ApiCryptoTest.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Constants\StepStatus;
  4. use App\Http\Controllers\api\TelegramWebHook;
  5. use App\Services\ApiCryptoService;
  6. use App\Services\QianBaoWithdrawService;
  7. use App\Services\UserService;
  8. use App\Services\WithdrawService;
  9. use Illuminate\Contracts\Http\Kernel;
  10. use Illuminate\Database\Schema\Blueprint;
  11. use Illuminate\Foundation\Application;
  12. use Illuminate\Http\JsonResponse;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Cache;
  16. use Illuminate\Support\Facades\Facade;
  17. use Illuminate\Support\Facades\Route;
  18. use Illuminate\Support\Facades\Schema;
  19. use PHPUnit\Framework\TestCase;
  20. use Symfony\Component\HttpFoundation\Response;
  21. class ApiCryptoTest extends TestCase
  22. {
  23. private Application $app;
  24. private Kernel $kernel;
  25. private ApiCryptoService $crypto;
  26. private int $errorReporting;
  27. private string $displayErrors;
  28. private const TOKEN = 'fixture-member-token';
  29. protected function setUp(): void
  30. {
  31. Facade::clearResolvedInstances();
  32. $this->errorReporting = error_reporting();
  33. $this->displayErrors = ini_get('display_errors');
  34. $this->app = require dirname(__DIR__, 2) . '/bootstrap/app.php';
  35. $this->kernel = $this->app->make(Kernel::class);
  36. $this->kernel->bootstrap();
  37. $key = base64_encode(str_repeat('k', 32));
  38. $this->crypto = new ApiCryptoService($key);
  39. config([
  40. 'app.env' => 'testing',
  41. 'app.debug' => false,
  42. 'app.key' => 'base64:' . $key,
  43. 'api_crypto.enabled' => true,
  44. 'api_crypto.key' => $key,
  45. 'api_crypto.allow_plaintext' => false,
  46. 'api_crypto.timestamp_tolerance' => 300,
  47. 'api_crypto.max_payload_bytes' => 2097152,
  48. 'cache.default' => 'array',
  49. 'database.default' => 'sqlite',
  50. 'database.connections.sqlite.url' => null,
  51. 'database.connections.sqlite.database' => ':memory:',
  52. 'database.connections.sqlite.prefix' => 'bot_',
  53. 'logging.default' => 'null',
  54. 'logging.channels.dblog' => config('logging.channels.null'),
  55. 'app.tree_payment_merchant_id' => '',
  56. 'app.tree_pay_mch_id' => '',
  57. 'app.jd_pay_mch_id' => '',
  58. ]);
  59. }
  60. protected function tearDown(): void
  61. {
  62. DB::disconnect();
  63. Facade::clearResolvedInstances();
  64. $this->app->flush();
  65. restore_error_handler();
  66. restore_exception_handler();
  67. error_reporting($this->errorReporting);
  68. ini_set('display_errors', $this->displayErrors);
  69. parent::tearDown();
  70. }
  71. public function test_real_wallet_and_lottery_routes_keep_the_original_business_response(): void
  72. {
  73. $this->createWalletFixture();
  74. Schema::create('pc_issues', function (Blueprint $table) {
  75. $table->id();
  76. $table->integer('status');
  77. $table->string('issue_no');
  78. });
  79. $response = $this->sendEncrypted('/api/wallet/withdrawChannel?lang=zh', 'GET', ['lang' => 'en'], true);
  80. $body = $this->unwrap($response);
  81. self::assertSame(0, $body['code']);
  82. self::assertSame(['code', 'timestamp', 'msg', 'data'], array_keys($body));
  83. self::assertSame('Bank card', array_column($body['data'], 'label', 'value')['DF001']);
  84. $channels = array_column($body['data'], null, 'value');
  85. self::assertTrue($channels['DF001']['requires_bank_name']);
  86. self::assertTrue($channels['NOwithdraw']['requires_real_name']);
  87. self::assertTrue($channels['ZIMUwithdraw']['requires_real_name']);
  88. self::assertFalse($channels['JDpay']['requires_real_name']);
  89. self::assertSame(['bank', 'wechat', 'alipay'], array_column($channels['rgtx']['payout_methods'], 'value'));
  90. self::assertSame([true, false, true], array_column($channels['rgtx']['payout_methods'], 'requires_card_no'));
  91. $lottery = $this->unwrap($this->sendEncrypted('/api/newPc/yuanTou', 'GET', (object) []));
  92. self::assertSame(0, $lottery['code'] ?? null, json_encode($lottery));
  93. self::assertSame([], $lottery['data']);
  94. DB::table('users')->where('member_id', '42')->update(['real_name' => 'Fixture Name']);
  95. $response = $this->sendEncrypted('/api/wallet/payout?amount=900', 'POST', [
  96. 'channel' => 'NOwithdraw', 'amount' => 100, 'card_no' => ' no_fixture ', 'safe_word' => 'fixture-password',
  97. ], true, ['card_no' => 'outer-account']);
  98. $body = $this->unwrap($response);
  99. self::assertSame(0, $body['code'] ?? null, json_encode($body));
  100. $order = DB::table('payment_orders')->sole();
  101. self::assertSame('NOwithdraw', $order->channel);
  102. self::assertSame('no_fixture', $order->card_no);
  103. self::assertSame(100, (int) $order->amount);
  104. self::assertSame('Fixture Name', $order->account);
  105. DB::table('user_session')->where('token', self::TOKEN)->update(['expire_time' => time() - 1]);
  106. $expiredSession = $this->sendEncrypted('/api/wallet/withdrawChannel', 'GET', (object) [], true);
  107. self::assertSame(401, $expiredSession->getStatusCode());
  108. self::assertSame(401, $this->unwrap($expiredSession)['code']);
  109. }
  110. public function test_authentication_and_maintenance_errors_remain_encrypted(): void
  111. {
  112. $this->createMaintenanceFixture();
  113. $response = $this->sendEncrypted('/api/wallet/withdrawChannel', 'GET', (object) []);
  114. self::assertSame(401, $response->getStatusCode());
  115. self::assertSame(401, $this->unwrap($response)['code']);
  116. DB::table('maintenance_settings')->where('scope_code', 'site')->update(['enabled' => 1, 'platforms' => '["H5"]']);
  117. $response = $this->sendEncrypted('/api/wallet/withdrawChannel?platform=PC', 'GET', ['platform' => 'H5']);
  118. self::assertSame(200, $response->getStatusCode());
  119. self::assertSame(11001, $this->unwrap($response)['code']);
  120. }
  121. public function test_registered_real_name_is_used_for_binding_and_payout(): void
  122. {
  123. $this->createWalletFixture();
  124. DB::table('users')->where('member_id', '42')->update(['real_name' => 'Registered Name']);
  125. $binding = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [
  126. 'channel' => 'DF001', 'bank_name' => 'Fixture Bank', 'card_no' => '12345', 'account' => 'Different Name',
  127. ], true));
  128. self::assertSame('Registered Name', $binding['data']['real_name']);
  129. self::assertSame('Registered Name', DB::table('banks')->sole()->account);
  130. $payout = $this->unwrap($this->sendEncrypted('/api/wallet/payout', 'POST', [
  131. 'channel' => 'DF001', 'bank_name' => 'Fixture Bank', 'card_no' => '12345',
  132. 'amount' => 100, 'safe_word' => 'fixture-password', 'account' => 'Another Name',
  133. ], true));
  134. self::assertSame(0, $payout['code'], $payout['msg']);
  135. self::assertSame('Registered Name', DB::table('payment_orders')->sole()->account);
  136. $zimu = $this->unwrap($this->sendEncrypted('/api/wallet/payout', 'POST', [
  137. 'channel' => 'ZIMUwithdraw', 'card_no' => 'zimu-wallet-fixture',
  138. 'amount' => 100, 'safe_word' => 'fixture-password', 'account' => 'Another Name',
  139. ], true));
  140. self::assertSame(0, $zimu['code'], $zimu['msg']);
  141. self::assertSame('Registered Name', DB::table('payment_orders')->where('channel', 'ZIMUwithdraw')->value('account'));
  142. self::assertSame('Registered Name', UserService::paginate()['data']->first()->toArray()['real_name']);
  143. self::assertArrayNotHasKey('real_name', \App\Models\User::first()->toArray());
  144. }
  145. public function test_only_the_first_successful_named_binding_can_set_a_missing_real_name(): void
  146. {
  147. $this->createWalletFixture();
  148. $params = ['channel' => 'DF001', 'bank_name' => 'Fixture Bank', 'card_no' => '12345'];
  149. $payout = $this->unwrap($this->sendEncrypted('/api/wallet/payout', 'POST', $params + [
  150. 'amount' => 100, 'safe_word' => 'fixture-password', 'account' => 'Unbound Name',
  151. ], true));
  152. self::assertSame('请先绑定收款账户并填写真实姓名', $payout['msg']);
  153. self::assertSame(0, DB::table('payment_orders')->count());
  154. $invalid = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', $params + [
  155. 'id' => 999, 'account' => 'Invalid Binding',
  156. ], true));
  157. self::assertNotSame(0, $invalid['code']);
  158. self::assertNull(DB::table('users')->value('real_name'));
  159. DB::unprepared("CREATE TRIGGER reject_bank BEFORE INSERT ON bot_banks
  160. WHEN NEW.card_no = 'reject-fixture' BEGIN SELECT RAISE(ABORT, 'fixture failure'); END");
  161. $failedSave = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [
  162. 'card_no' => 'reject-fixture', 'account' => 'Failed Name',
  163. ] + $params, true));
  164. self::assertNotSame(0, $failedSave['code']);
  165. self::assertNull(DB::table('users')->value('real_name'));
  166. foreach (['NOwithdraw', 'ZIMUwithdraw'] as $channel) {
  167. $noName = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [
  168. 'channel' => $channel, 'card_no' => 'wallet-fixture',
  169. ], true));
  170. self::assertSame('请输入真实姓名', $noName['msg']);
  171. $payout = $this->unwrap($this->sendEncrypted('/api/wallet/payout', 'POST', [
  172. 'channel' => $channel, 'card_no' => 'wallet-fixture', 'amount' => 100,
  173. 'safe_word' => 'fixture-password', 'account' => 'Unbound Name',
  174. ], true));
  175. self::assertSame('请先绑定收款账户并填写真实姓名', $payout['msg']);
  176. }
  177. $binding = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', $params + [
  178. 'account' => " First Bound Name ",
  179. ], true));
  180. self::assertSame('First Bound Name', $binding['data']['real_name']);
  181. $id = DB::table('banks')->where('channel', 'DF001')->value('id');
  182. $update = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', $params + [
  183. 'id' => $id, 'account' => 'Replacement Name',
  184. ], true));
  185. self::assertSame('First Bound Name', $update['data']['real_name']);
  186. self::assertSame('First Bound Name', DB::table('banks')->where('id', $id)->value('account'));
  187. $noBinding = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [
  188. 'channel' => 'NOwithdraw', 'card_no' => 'no_fixture',
  189. ], true));
  190. self::assertSame(0, $noBinding['code']);
  191. $deleted = $this->unwrap($this->sendEncrypted('/api/wallet/delBank', 'GET', ['id' => $id], true));
  192. self::assertSame(0, $deleted['code']);
  193. $list = $this->unwrap($this->sendEncrypted('/api/wallet/bankList', 'GET', (object) [], true));
  194. self::assertSame('First Bound Name', $list['data']['real_name']);
  195. self::assertSame('First Bound Name', $list['data']['list'][0]['account']);
  196. }
  197. public function test_manual_payout_uses_bank_details_or_wallet_payment_qr_and_shares_the_pending_limit(): void
  198. {
  199. $this->createWalletFixture();
  200. $common = ['channel' => 'rgtx', 'amount' => 100, 'safe_word' => 'fixture-password'];
  201. $payout = fn (array $params) => $this->unwrap($this->sendEncrypted('/api/wallet/payout', 'POST', $params, true));
  202. $qr = 'https://uploads.example.test/fixture.png';
  203. $alipayAccount = 'cash@example.test';
  204. $wechat = ['payout_method' => 'wechat', 'qr_image' => $qr];
  205. $alipay = ['payout_method' => 'alipay', 'card_no' => $alipayAccount, 'qr_image' => $qr];
  206. foreach ([$wechat, $alipay] as $wallet) {
  207. self::assertSame('请先绑定收款账户并填写真实姓名', $payout($common + $wallet + ['account' => 'Injected Name'])['msg']);
  208. }
  209. DB::table('users')->update(['real_name' => 'Fixture Name']);
  210. self::assertSame('请输入开户行名称', $payout($common + ['card_no' => '12345'])['msg']);
  211. self::assertSame('请输入开户行名称', $payout(['channel' => 'DF001', 'card_no' => '12345'] + $common)['msg']);
  212. self::assertSame('请上传有效的收款码图片', $payout($common + ['payout_method' => 'wechat', 'qr_image' => 'javascript:alert(1)'])['msg']);
  213. self::assertSame('请上传有效的收款码图片', $payout($common + ['payout_method' => 'alipay', 'card_no' => $alipayAccount])['msg']);
  214. self::assertSame('请输入支付宝账号', $payout($common + ['payout_method' => 'alipay', 'qr_image' => $qr])['msg']);
  215. self::assertSame('请输入支付宝账号', $payout($common + ['card_no' => $qr] + $alipay)['msg']);
  216. $bank = $payout($common + ['bank_name' => 'Fixture Bank Branch', 'card_no' => '12345']);
  217. self::assertSame(0, $bank['code'], $bank['msg']);
  218. self::assertSame('bank', $bank['data']['payout_method']);
  219. self::assertSame('Fixture Bank Branch', $bank['data']['bank_name']);
  220. self::assertSame('您已有1笔提现订单正常处理中!', $payout($common + $wechat)['msg']);
  221. self::assertSame(1, DB::table('payment_orders')->count());
  222. self::assertSame(900, (int) DB::table('wallets')->value('available_balance'));
  223. foreach ([[$wechat, '微信', ''], [$alipay, '支付宝', $alipayAccount]] as [$wallet, $bankName, $cardNo]) {
  224. DB::table('payment_orders')->update(['status' => 2]);
  225. $result = $payout($common + $wallet + ['account' => 'Injected Name']);
  226. self::assertSame(0, $result['code'], $result['msg']);
  227. self::assertSame($wallet['payout_method'], $result['data']['payout_method']);
  228. self::assertSame($qr, $result['data']['qr_image']);
  229. $stored = DB::table('payment_orders')->where('id', $result['data']['id'])->first();
  230. self::assertSame(4, (int) $stored->type);
  231. self::assertSame($bankName, $stored->bank_name);
  232. self::assertSame('Fixture Name', $stored->account);
  233. self::assertSame($cardNo, $stored->card_no);
  234. self::assertSame($qr, $stored->qr_image);
  235. }
  236. // Legacy WeChat rows stored the QR URL in the account column.
  237. DB::table('payment_orders')->where('bank_name', '微信')->update(['card_no' => $qr, 'qr_image' => null]);
  238. $this->app->instance('request', Request::create('/admin/withdraw/rmb?type=4'));
  239. $admin = (new \App\Http\Controllers\admin\Withdraw())->rmb()->getData(true);
  240. self::assertSame(0, $admin['code'], $admin['msg']);
  241. $rows = array_column($admin['data']['data'], null, 'payout_method');
  242. self::assertSame('Fixture Name', $rows['wechat']['recipient_name']);
  243. self::assertSame('fixture-login', $rows['wechat']['account']);
  244. self::assertSame($qr, $rows['wechat']['qr_image']);
  245. self::assertSame('', $rows['wechat']['card_no']);
  246. self::assertSame($alipayAccount, $rows['alipay']['card_no']);
  247. self::assertSame($qr, $rows['alipay']['qr_image']);
  248. $bind = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', ['channel' => 'rgtx'] + $alipay, true));
  249. self::assertSame(0, $bind['code'], $bind['msg']);
  250. $bankList = $this->unwrap($this->sendEncrypted('/api/wallet/bankList', 'GET', ['channel' => 'rgtx'], true));
  251. self::assertSame($alipayAccount, $bankList['data']['list'][0]['card_no']);
  252. self::assertSame($qr, $bankList['data']['list'][0]['qr_image']);
  253. self::assertSame('Fixture Name', $bankList['data']['list'][0]['account']);
  254. }
  255. public function test_protocol_errors_and_rollout_flags(): void
  256. {
  257. Route::get('api/wallet/probe', fn () => response()->json(['code' => 0]));
  258. foreach (['/api/wallet/probe', '/api/newPc', '/api/issue', '/api/pcissue'] as $path) {
  259. $response = $this->send($path);
  260. self::assertSame(400, $response->getStatusCode());
  261. self::assertSame(4001, $this->unwrap($response)['code']);
  262. }
  263. $payload = $this->crypto->encrypt(['amount' => 100], 'request');
  264. $envelope = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
  265. $envelope['tag'][0] = $envelope['tag'][0] === 'A' ? 'B' : 'A';
  266. $tampered = rtrim(strtr(base64_encode(json_encode($envelope)), '+/', '-_'), '=');
  267. $expired = $this->crypto->encrypt((object) [], 'request', (time() - 301) * 1000);
  268. $wrongDirection = $this->crypto->encrypt((object) [], 'response');
  269. foreach (['', $tampered, $expired, $wrongDirection, $this->crypto->encrypt([], 'request')] as $invalid) {
  270. $response = $this->send('/api/wallet/probe?payload=' . $invalid, 'GET', ['HTTP_X_API_ENCRYPTED' => '1']);
  271. self::assertSame(400, $response->getStatusCode());
  272. self::assertSame(4002, $this->unwrap($response)['code']);
  273. }
  274. Route::get('api/wallet/large-response', fn () => response()->json(['data' => str_repeat('x', 1024)]));
  275. config(['api_crypto.max_payload_bytes' => 1024]);
  276. $response = $this->sendEncrypted('/api/wallet/large-response', 'GET', (object) []);
  277. self::assertSame(500, $response->getStatusCode());
  278. self::assertSame(5002, json_decode($response->getContent(), true)['code']);
  279. config(['api_crypto.allow_plaintext' => true]);
  280. self::assertSame('{"code":0}', $this->send('/api/wallet/probe')->getContent());
  281. self::assertSame(0, $this->unwrap($this->sendEncrypted('/api/wallet/probe', 'GET', (object) []))['code']);
  282. config(['api_crypto.key' => 'invalid']);
  283. $response = $this->send('/api/wallet/probe');
  284. self::assertSame(500, $response->getStatusCode());
  285. self::assertSame(5001, json_decode($response->getContent(), true)['code']);
  286. config(['api_crypto.enabled' => false]);
  287. self::assertSame('{"code":0}', $this->send('/api/wallet/probe')->getContent());
  288. }
  289. public function test_withdrawal_account_and_address_apis_ignore_and_hide_aliases(): void
  290. {
  291. $this->createWalletFixture();
  292. $bank = $this->unwrap($this->sendEncrypted('/api/wallet/addBank', 'POST', [
  293. 'channel' => 'DF001', 'bank_name' => 'Fixture Bank', 'card_no' => '12345', 'account' => 'Fixture Name',
  294. 'alias' => 'ignored bank alias',
  295. ], true));
  296. self::assertSame(0, $bank['code']);
  297. self::assertSame('', DB::table('banks')->value('alias'));
  298. DB::table('banks')->update(['alias' => 'old bank alias']);
  299. $bankList = $this->unwrap($this->sendEncrypted('/api/wallet/bankList', 'GET', (object) [], true));
  300. self::assertSame('12345', $bankList['data']['list'][0]['card_no']);
  301. self::assertArrayNotHasKey('alias', $bankList['data']['list'][0]);
  302. $address = 'T' . str_repeat('A', 33);
  303. $saved = $this->unwrap($this->sendEncrypted('/api/wallet/addAddress', 'POST', [
  304. 'address' => $address, 'alias' => 'ignored address alias',
  305. ], true));
  306. self::assertSame(0, $saved['code']);
  307. self::assertNull(DB::table('address')->value('alias'));
  308. DB::table('address')->update(['alias' => 'old address alias']);
  309. $addresses = $this->unwrap($this->sendEncrypted('/api/wallet/address', 'GET', (object) [], true));
  310. self::assertSame($address, $addresses['data']['list'][0]['address']);
  311. self::assertArrayNotHasKey('alias', $addresses['data']['list'][0]);
  312. }
  313. public function test_telegram_saves_withdrawal_destinations_without_prompting_for_aliases(): void
  314. {
  315. $this->createWalletFixture();
  316. Cache::put('42_QB_WITHDRAW_CHANNEL', 'DF001');
  317. Cache::put('42_QB_WITHDRAW_BANK_NAME', 'Fixture Bank');
  318. QianBaoWithdrawService::onMessage(42, '12345', 1, StepStatus::QB_INPUT_CARD_NO);
  319. self::assertSame(StepStatus::QB_INPUT_ACCOUNT, Cache::get(get_step_key(42)));
  320. $saved = QianBaoWithdrawService::onMessage(42, 'Fixture Name', 2, StepStatus::QB_INPUT_ACCOUNT);
  321. $keyboard = json_decode($saved['reply_markup'], true)['inline_keyboard'];
  322. self::assertSame('12345', $keyboard[0][0]['text']);
  323. self::assertSame('', DB::table('banks')->where('card_no', '12345')->value('alias'));
  324. self::assertNull(Cache::get(get_step_key(42)));
  325. Cache::put('42_QB_WITHDRAW_CARD_NO', '67890');
  326. Cache::put('42_QB_ACCOUNT', 'Fixture Name');
  327. QianBaoWithdrawService::onMessage(42, 'ignored', 3, StepStatus::LEGACY_QB_INPUT_ALIAS);
  328. self::assertSame('', DB::table('banks')->where('card_no', '67890')->value('alias'));
  329. $address = 'T' . str_repeat('A', 33);
  330. $saved = WithdrawService::onMessage(42, $address, 4, StepStatus::INPUT_ADDRESS_TRC20);
  331. $keyboard = json_decode($saved['reply_markup'], true)['inline_keyboard'];
  332. self::assertSame($address, $keyboard[0][0]['text']);
  333. self::assertNull(Cache::get(get_step_key(42)));
  334. $oldAddress = 'T' . str_repeat('B', 33);
  335. Cache::put('42_address', $oldAddress);
  336. WithdrawService::onMessage(42, 'ignored', 5, StepStatus::LEGACY_INPUT_ADDRESS_ALIAS);
  337. self::assertTrue(DB::table('address')->where('address', $oldAddress)->exists());
  338. self::assertSame(0, DB::table('address')->whereNotNull('alias')->count());
  339. }
  340. public function test_cors_preflight_and_head(): void
  341. {
  342. Route::get('api/wallet/probe', fn () => response()->json(['code' => 0]));
  343. $response = $this->send('/api/wallet/probe', 'OPTIONS', [
  344. 'HTTP_ORIGIN' => 'https://frontend.example',
  345. 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
  346. 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'content-type,x-api-encrypted',
  347. ]);
  348. self::assertSame(204, $response->getStatusCode());
  349. self::assertStringContainsString('x-api-encrypted', strtolower($response->headers->get('Access-Control-Allow-Headers')));
  350. self::assertFalse($response->headers->has('X-Api-Encrypted'));
  351. $response = $this->sendEncrypted('/api/wallet/probe', 'HEAD', (object) []);
  352. self::assertSame(200, $response->getStatusCode());
  353. self::assertSame('1', $response->headers->get('X-Api-Encrypted'));
  354. self::assertStringContainsString('X-Api-Encrypted', $response->headers->get('Access-Control-Expose-Headers'));
  355. self::assertSame('', $response->getContent());
  356. }
  357. public function test_excluded_routes_keep_plaintext_input_and_response(): void
  358. {
  359. $this->createMaintenanceFixture();
  360. (require dirname(__DIR__, 2) . '/database/migrations/2026_09_08_160000_add_payment_provider_status_and_channel_soft_deletes.php')->up();
  361. $this->app->instance(TelegramWebHook::class, new class extends TelegramWebHook {
  362. public function __construct() {}
  363. public function handle(Request $request): JsonResponse
  364. {
  365. return response()->json(['update_id' => $request->input('update_id')]);
  366. }
  367. });
  368. $telegram = $this->send('/api/onMessage', 'POST', ['CONTENT_TYPE' => 'application/json'], '{"update_id":123}');
  369. self::assertSame('{"update_id":123}', $telegram->getContent());
  370. self::assertFalse($telegram->headers->has('X-Api-Encrypted'));
  371. foreach (['notify', 'harvest'] as $callback) {
  372. $response = $this->send('/api/pay/' . $callback, 'POST', ['CONTENT_TYPE' => 'application/json'],
  373. '{"appId":"unmatched-fixture","merchantNum":"unmatched-fixture","userCode":"unmatched-fixture","mchId":"unmatched-fixture"}');
  374. self::assertSame(200, $response->getStatusCode(), $callback . ': ' . $response->getContent());
  375. self::assertSame('success', $response->getContent());
  376. self::assertFalse($response->headers->has('X-Api-Encrypted'));
  377. }
  378. Schema::create('config', function (Blueprint $table) {
  379. $table->id();
  380. $table->string('field');
  381. $table->string('val');
  382. });
  383. DB::table('config')->insert([
  384. ['field' => 'activity_rule', 'val' => 'Telegram rule fixture'],
  385. ['field' => 'benefits_service_customer', 'val' => 'customer fixture'],
  386. ]);
  387. $activity = $this->send('/api/ActivityReward/rule');
  388. self::assertSame(200, $activity->getStatusCode());
  389. self::assertSame('Telegram rule fixture', json_decode($activity->getContent(), true)['data']['rule']);
  390. self::assertFalse($activity->headers->has('X-Api-Encrypted'));
  391. $admin = $this->send('/admin/maintenance/options');
  392. self::assertFalse($admin->headers->has('X-Api-Encrypted'));
  393. }
  394. private function send(string $url, string $method = 'GET', array $headers = [], ?string $body = null): Response
  395. {
  396. return $this->kernel->handle(Request::create($url, $method, [], [], [], $headers + [
  397. 'HTTP_ORIGIN' => 'https://frontend.example',
  398. 'HTTP_ACCEPT' => 'application/json',
  399. ], $body));
  400. }
  401. private function sendEncrypted(string $url, string $method, array|object $parameters, bool $authenticated = false, array $outerBody = []): Response
  402. {
  403. $payload = $this->crypto->encrypt($parameters, 'request');
  404. $headers = ['HTTP_X_API_ENCRYPTED' => '1'];
  405. if ($authenticated) {
  406. $headers['HTTP_AUTHORIZATION'] = self::TOKEN;
  407. }
  408. if ($method === 'POST') {
  409. return $this->send($url, $method, $headers + ['CONTENT_TYPE' => 'application/json'], json_encode(['payload' => $payload] + $outerBody));
  410. }
  411. return $this->send($url . (str_contains($url, '?') ? '&' : '?') . 'payload=' . $payload, $method, $headers);
  412. }
  413. private function unwrap(Response $response): array
  414. {
  415. self::assertSame('1', $response->headers->get('X-Api-Encrypted'), (string) $response->getContent());
  416. self::assertStringContainsString('no-store', $response->headers->get('Cache-Control'));
  417. $envelope = json_decode($response->getContent(), true, 512, JSON_THROW_ON_ERROR);
  418. self::assertTrue($envelope['encrypted']);
  419. return $this->crypto->decrypt($envelope['payload'], 'response');
  420. }
  421. private function createMaintenanceFixture(): void
  422. {
  423. (require dirname(__DIR__, 2) . '/database/migrations/2026_10_26_120000_create_maintenance_settings.php')->up();
  424. }
  425. private function createWalletFixture(): void
  426. {
  427. DB::connection()->getPdo()->sqliteCreateCollation('utf8mb4_general_ci', 'strcasecmp');
  428. $this->createMaintenanceFixture();
  429. Schema::create('users', function (Blueprint $table) {
  430. $table->id();
  431. $table->string('user_id');
  432. $table->string('member_id');
  433. $table->string('account')->default('fixture-login');
  434. $table->string('first_name')->nullable();
  435. $table->string('admin_note')->nullable();
  436. $table->integer('from');
  437. $table->bigInteger('last_active_time')->default(0);
  438. $table->integer('recharge_channel_group_id');
  439. $table->string('payment_password');
  440. $table->integer('level')->default(1);
  441. $table->string('agent_user_code')->nullable();
  442. $table->timestamps();
  443. });
  444. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_06_120000_add_real_name_to_users.php')->up();
  445. Schema::create('level', function (Blueprint $table) {
  446. $table->id();
  447. $table->integer('level');
  448. $table->string('level_name');
  449. $table->string('img');
  450. $table->decimal('recharge');
  451. });
  452. Schema::create('user_session', function (Blueprint $table) {
  453. $table->id();
  454. $table->string('user_id');
  455. $table->string('token');
  456. $table->bigInteger('expire_time');
  457. $table->bigInteger('create_time');
  458. $table->bigInteger('update_time');
  459. });
  460. Schema::create('recharge_channel_group', function (Blueprint $table) {
  461. $table->id();
  462. $table->string('withdraw_type');
  463. $table->softDeletes();
  464. });
  465. Schema::create('recharge_channel', function (Blueprint $table) {
  466. $table->id();
  467. $table->integer('data_type');
  468. $table->integer('status');
  469. $table->integer('sort');
  470. $table->string('name');
  471. $table->string('type');
  472. $table->decimal('rate');
  473. $table->decimal('min');
  474. $table->decimal('max');
  475. $table->string('fixed')->nullable();
  476. $table->string('logo')->nullable();
  477. });
  478. (require dirname(__DIR__, 2) . '/database/migrations/2026_09_08_160000_add_payment_provider_status_and_channel_soft_deletes.php')->up();
  479. Schema::create('wallets', function (Blueprint $table) {
  480. $table->id();
  481. $table->string('member_id');
  482. $table->decimal('available_balance');
  483. $table->decimal('frozen_balance')->default(0);
  484. $table->timestamps();
  485. });
  486. Schema::create('payment_orders', function (Blueprint $table) {
  487. $table->id();
  488. $table->integer('type');
  489. $table->integer('status');
  490. foreach (['member_id', 'order_no', 'channel', 'bank_name', 'account', 'card_no'] as $field) {
  491. $table->string($field);
  492. }
  493. $table->string('callback_url')->nullable();
  494. $table->string('remark')->nullable();
  495. $table->decimal('amount');
  496. $table->decimal('fee');
  497. $table->timestamps();
  498. });
  499. Schema::create('backflow', function (Blueprint $table) {
  500. $table->id();
  501. $table->string('member_id');
  502. $table->string('date');
  503. $table->integer('status')->default(0);
  504. $table->decimal('withdrawal_amount')->default(0);
  505. $table->timestamps();
  506. });
  507. Schema::create('balance_logs', function (Blueprint $table) {
  508. $table->id();
  509. $table->integer('type')->default(1);
  510. $table->string('member_id');
  511. $table->string('change_type');
  512. $table->integer('related_id');
  513. $table->string('remark');
  514. $table->decimal('amount');
  515. $table->decimal('before_balance');
  516. $table->decimal('after_balance');
  517. $table->timestamps();
  518. });
  519. Schema::create('banks', function (Blueprint $table) {
  520. $table->id();
  521. foreach (['member_id', 'channel', 'bank_name', 'account', 'card_no'] as $field) {
  522. $table->string($field);
  523. }
  524. $table->string('alias')->default('');
  525. $table->timestamps();
  526. });
  527. Schema::create('address', function (Blueprint $table) {
  528. $table->id();
  529. $table->string('member_id');
  530. $table->string('address');
  531. $table->string('alias')->nullable();
  532. $table->timestamps();
  533. });
  534. (require dirname(__DIR__, 2) . '/database/migrations/2026_11_06_140000_add_qr_image_to_withdrawal_destinations.php')->up();
  535. DB::table('users')->insert(['user_id' => '42', 'member_id' => '42', 'from' => 1, 'recharge_channel_group_id' => 1,
  536. 'payment_password' => password_hash('fixture-password', PASSWORD_DEFAULT)]);
  537. DB::table('user_session')->insert(['user_id' => '42', 'token' => self::TOKEN,
  538. 'expire_time' => time() + 3600, 'create_time' => time(), 'update_time' => time()]);
  539. DB::table('wallets')->insert(['member_id' => '42', 'available_balance' => 1000]);
  540. DB::table('recharge_channel_group')->insert(['id' => 1, 'withdraw_type' => 'DF001,NOwithdraw,ZIMUwithdraw,JDpay,rgtx']);
  541. foreach (['DF001' => '银行卡', 'NOwithdraw' => 'NO快捷提现', 'ZIMUwithdraw' => '808账户提现', 'JDpay' => 'JD钱包', 'rgtx' => '人工提现'] as $type => $name) {
  542. DB::table('recharge_channel')->insert(['data_type' => 2, 'status' => 1, 'sort' => 0,
  543. 'name' => $name, 'type' => $type, 'rate' => 0, 'min' => 10, 'max' => 5000]);
  544. }
  545. }
  546. }