@jetthai/cuora 1.1.483 → 1.1.485-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/.claude/commands/sync-ai-prompts.md +88 -1
  2. package/.claude/settings.local.json +3 -1
  3. package/.github/copilot-instructions.md +80 -37
  4. package/.husky/post-checkout +3 -3
  5. package/.husky/pre-push +1 -1
  6. package/.prettierignore +2 -1
  7. package/AGENTS.md +80 -37
  8. package/AI_PROMPT_SOURCE.md +80 -37
  9. package/CHANGELOG.md +393 -23
  10. package/CLAUDE.md +80 -37
  11. package/GEMINI.md +80 -37
  12. package/docs/my-claude/feat-sharon-JT-1790247240-socket/branch-transfer.md +14 -0
  13. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-preparation.json +40 -0
  14. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-verification.md +41 -0
  15. package/docs/my-claude/feat-sharon-JT-1790247240-socket/implementation-ledger.md +87 -0
  16. package/docs/my-claude/feat-sharon-JT-1790247240-socket/module-report.md +73 -0
  17. package/docs/my-claude/feat-sharon-JT-1790247240-socket/plan.md +309 -0
  18. package/docs/my-claude/feat-sharon-JT-1790247240-socket/test-cases.md +245 -0
  19. package/docs/my-claude/feat-sharon-JT-1791180540-onesignal/transfer.md +9 -0
  20. package/package.json +1 -1
  21. package/scripts/auto-version.js +1 -0
  22. package/scripts/branch-auto-npm-publish.js +9 -2
  23. package/src/api/payment.js +1 -0
  24. package/src/machine/auth_otp_v3.js +59 -20
  25. package/src/machine/honor_board_cash.js +15 -18
  26. package/src/machine/reward_cash.js +2 -2
  27. package/src/machine/user_sign_up.js +3 -0
  28. package/src/machine/websocket.js +380 -311
  29. package/src/machine/withdraw/withdraw_manual_cash.js +7 -4
  30. package/src/util/constant.js +6 -1
  31. package/src/util/socketPolicy.js +57 -0
  32. package/test/auth_otp_v3.test.js +323 -0
  33. package/test/withdraw_manual_cash.test.js +149 -0
  34. package/tests/websocket.test.mjs +779 -0
package/CLAUDE.md CHANGED
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
59
59
  - [ ] **Memory safety**: `setInterval` / `socket.on()` / `addEventListener` registered inside an XState callback service **must return a cleanup function** (e.g. `() => clientSocket.off(event, handler)`) to avoid accumulating listeners across reconnects; listeners registered inside a Promise must also be cleaned up after resolve / reject
60
60
  - [ ] **Token lifecycle**: token operations go through `getToken()` and the `extendToken` action, never bypass the interceptor to inject manually; prefer the existing TTL constants; when `fetchUserInfo` fails, let the session terminate naturally rather than retrying on your own
61
61
  - [ ] **Error handling**: forward through `request.errorHandler` to the error machine, with correct branches for each special code (see "Error Code System")
62
- - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the reconnect strategy only triggers on `'io server disconnect'`
62
+ - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the next step after a disconnect / failure is always decided by `decideNextStep` in `util/socketPolicy.js` — never write a separate reconnect condition in `websocket.js`; new listeners are always registered through `on()` in `bindSocket` (that is what gets them cleaned up and guarded against stale sessions)
63
63
  - [ ] **Performance impact**: avoid adding per-second self-referencing `after: { 1000 }` transitions (consider a callback + `setInterval` + computing elapsed time); don't eagerly import large dependencies at module top level; evaluate whether new high-frequency APIs need caching or backoff
64
64
  - [ ] **Consistent import paths**: cross-layer imports use relative paths (`'../../api/payment.js'`), never the `@jetthai/cuora` package name as a self-reference; lodash imports consistently omit the `.js` extension
65
65
  - [ ] **Magic numbers and strings**: activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'` / `'WITHDRAW'`, `receiveStatus` numbers, etc. should prefer the constants in `util/constant.js`
@@ -148,7 +148,7 @@ State machines **do not directly reference each other**; they communicate indire
148
148
  | `ERR_F106` | OTP verification failed |
149
149
  | `ERR_G106` | Insufficient balance (→ deposit state) |
150
150
  | `ERR_G124` / `ERR_G125` | Free game settlement / forfeit |
151
- | `ERR_800` | Cancelled request (handled silently) |
151
+ | `ERR_800` | Cancelled request (never forwarded to errorHandler, but still rejects to the caller's `onError`) |
152
152
  | `ERR_998` | Network error / 404 (reported to Sentry) |
153
153
 
154
154
  When `error.extend` contains `unfinished_` → unfinished game; the gameCode is everything after the first underscore, taken via `error.extend.split(/_(.+)/)[1]`.
@@ -172,6 +172,13 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
172
172
  - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
173
173
  - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
174
174
 
175
+ **Token revocation & foreground gate** (`request.js`): `revokeToken(token)` and `beginTokenGate(promise, timeoutMs = 3000)` are public `Request` methods with **no caller inside this package** — the downstream frontends call them on logout-class errors and when the app returns to the foreground; changing their signatures or semantics is a public-interface change.
176
+
177
+ - **Only the current identity can be revoked**: `revokeToken` only takes effect when `token === getToken()`, so a late error from a previous identity cannot revoke a newly logged-in token. Once in effect, it cancels in-flight requests carrying that token (for the scope, see item 11 of 2.9), and any later non-public `send()` still carrying it rejects `ERR_800` immediately without hitting the network; public requests are unaffected (the token stays in storage while revoked, and `getConfig` around autoLogin must not be wrongly rejected). There is no "un-revoke" API — logging in again changes the token, which lifts the revocation naturally.
178
+ - **The token to revoke comes from the error object**: when a token-carrying request fails, `send()` attaches a **non-enumerable** `error.requestToken` (the Bearer token at send time). It is non-enumerable so it doesn't leak through `JSON.stringify` / Sentry serialization — **never make it enumerable, and never copy it into enumerable fields, logs, or Sentry extra**. Cancellation `ERR_800` errors and the missing-token `ERR_A103` don't carry this field.
179
+ - **While a gate is active**: non-public requests first wait for the probe promise to settle (success and failure both release it) or for the timeout; once released, they re-check whether the token has been revoked and whether it still exists (missing → `ERR_A103`).
180
+ - **Hard-coded `'self'` coupling**: `send()` decides which request skips the gate by checking whether the descriptor's raw `url` (query stripped, before V2 conversion) is `'self'`, which corresponds to `getUserInfo` in `api/user.js` (`updateUserInfo`, sharing the same url, skips it too). Changing `getUserInfo`'s url (adding a leading slash, changing the path) requires updating this check in lockstep, otherwise `/self` gets blocked by the gate as well — a probe sent after the gate is created would then wait on its own gate until the timeout.
181
+
175
182
  **inline vs login states** (the most central concept in `auth.js`):
176
183
 
177
184
  - `inline`: authenticated but `rank < 0` (the account has not finished ranking/activation); polling continues until rank takes effect
@@ -193,6 +200,8 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
193
200
 
194
201
  **OTP / bind-bank flow**: after a successful login it enters `otpChecking`; `OTP_VERIFIED` or `OTP_SKIP` moves it to `bindBankChecking`, and only `BIND_BANK_DONE` or `BIND_BANK_SKIP` proceeds to `loginSuccess` (either gate accepts `LOGOUT` to abort). Whether binding is required is decided by the downstream frontend; the machine only waits — **downstream must send one of these events in `bindBankChecking`, or the session stalls there**. The `tokenAuthenticated` path skips both gates.
195
202
 
203
+ **OTP auto-verification** (`auth_otp_v3.js`): when `verify` / `sendPhone` / `sendEmail` respond with `needAcknowledge === false`, the machine skips OTP input and goes to `autoVerifying`. But **`needAcknowledge: false` by itself does not count as verified** — the `phone_verification_status` / `email_verification_status` from `/self` is always the basis, and the contact data must be non-empty (phone accepts `phone` or `tel`; when the data is empty, input is required even if the status is truthy). There is a delay between the backend writing the verification status and `/self` reflecting it; when the machine's own `/self` call does not pass, it enters `autoVerifyWaiting` — **the machine does not poll by itself**; instead it waits for downstream to forward the `/self` results of auth's routine polling as `USER_INFO_UPDATED` (`data` is the userInfo), for at most 2 updates or 5 seconds (`AUTO_VERIFY_*` in `util/constant.js`; receiving a stale value does not reset the timer), and if still not verified → `fail`. **When downstream does not forward this event, auto-verification simply falls to `fail` after 5 seconds.** The 5 seconds is sized against auth's `tick: 2000` so that two polls can come back in time; changing `tick` requires adjusting it in lockstep.
204
+
196
205
  **Account persistence**: the most recently used login account is stored in localStorage (31-day TTL) for form auto-fill. **Token expiration does not affect the account record.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
197
206
 
198
207
  ### 2.2 Canonical Deposit Pattern
@@ -291,29 +300,62 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
291
300
 
292
301
  ### 2.6 Real-Time Communication (WebSocket)
293
302
 
294
- **SocketTester race mechanism**: the `fetchSocket` service fetches multiple socket URLs from `/target/target.json` and pings them all simultaneously with `Promise.any()` — the fastest responder wins.
303
+ **Single owner**: connecting, retrying, and cleanup all live inside the closure of the `socketLifecycle` callback service invoked at the root. States such as `idle` / `fetchSocket` / `connecting` / `connected` are **display-only states for downstream**, driven by the `_SOCKET_STATUS` (`phase`) the service emits; they have no invoke and no guard of their own — to change behavior, change the service; don't add `invoke` / `after` to a state. Before switching to a new instance, the old listeners are always `off`'d and the old instance `disconnect`ed first (including an instance that never connected).
304
+
305
+ **Host selection**: `selectSocket` fetches multiple hosts from `target/target.json` on GCS and hits `/ping/status` on all of them simultaneously with `Promise.any()` — the fastest responder wins; when the list can't be fetched or every host fails, it falls back to `request.config.socketURL`. **Without a token, no host is selected and no connection is created.**
295
306
 
296
307
  ```js
297
- io(`${socketURL}/frontend`, {
308
+ io(frontendURL(host), {
298
309
  withCredentials: true,
299
310
  forceNew: true,
300
- transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
301
- auth: { Authorization: authToken },
311
+ transports: ['websocket'], // websocket only, no polling fallback
312
+ auth: (done) => done({ Authorization: request.getToken() }), // callback form: reads the latest token at each (re)connect
302
313
  })
303
314
  ```
304
315
 
305
- **Reconnect strategy**: **reconnect only when `connectError === 'io server disconnect'`** (the server actively disconnected), at most 3 times with a 2-second interval. Client-side network errors do not trigger it (they are left to Socket.IO's built-in auto-reconnect).
316
+ **The next step after a failure** is always decided by `decideNextStep` in `util/socketPolicy.js`:
317
+
318
+ | Result | Trigger | Behavior |
319
+ | ---------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
320
+ | `socketio` | A `disconnect` not initiated by the server, or a `connect_error` while the socket is still `active` | Stay on the same instance and leave it to Socket.IO's built-in reconnect; not recovered within 120 seconds of the first loss → `exhausted` |
321
+ | `retry` | Every other failure (including `io server disconnect` **before the session is ready**) | Re-select a host; at most 3 times beyond the initial attempt, 1 / 2 / 4 second exponential backoff × 0.5–1.5 jitter, with the server-provided `retryAfterMs` as the floor; budget used up → `exhausted` |
322
+ | `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | Reconnect immediately once (only one allowance before becoming ready), then treated as `retry` |
323
+ | `kicked` | The `kicked` event, `MAX_CONNECTIONS`, or `io server disconnect` **after the session is ready** | Stop |
324
+ | `stop` | A rejection carrying `retryable: false` | Stop |
325
+ | `none` | `io client disconnect` (disconnected by ourselves) | Ignored |
326
+
327
+ **`io server disconnect` no longer means "reconnect"**: being disconnected by the server after the session is ready is treated as being kicked, with no automatic reconnect. After stopping, `context.blocked` decides who may resume (`canResume`): `kicked` only accepts `source: 'user'`; `exhausted` accepts user at any time and `auto` only once ≥ 15 seconds have passed since the last attempt; `stop` has to wait for a token change. A `DISCONNECT_SOCKET` without `preserveSession` clears `blocked`.
328
+
329
+ **Downstream contracts** (the other end of these events and context fields lives in the downstream frontends; there is no caller inside this package):
330
+
331
+ | Interface | Contract |
332
+ | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
333
+ | `CONNECT` / `CHECK_SOCKET` | May carry `source: 'user' \| 'auto'` (default `user`), which decides whether it can resume after `blocked` |
334
+ | `AUTH_CHECKED` | `{ token, uidSite }`; may only come from a successful `/self`, and `token` must equal the current `getToken()`; for the obligation after sending it once, see below |
335
+ | `DISCONNECT_SOCKET` | Default = logout / destroy, clearing the session, dedupe records, and retry state; `{ preserveSession: true }` = background release, keeping all of them |
336
+ | `SESSION_READY` | `{ resync, generation }`. **Readiness is based on the server's `session-ready` (or `socket.recovered === true`), not on `connect`** — `SET_CONNECTED` only means the transport is up. `resync: true` means a session was ready before and this one is a fresh, non-recovered session, so downstream must catch up via REST |
337
+ | `ACTIVITY_INFO` | `{ data, eventName, generation }`; `payment-info` is **no longer limited to `windowType === 'toast'`** — any filtering is up to downstream |
338
+ | `context.generation` | Incremented when the connection is invalidated, on a new attempt, and on the first loss; downstream can use it to discard REST responses from an older generation |
339
+ | `context.claimPaymentEvent(event, orderData)` | GA dedupe shared by REST and socket: `true` = first time, may report; `false` = duplicate, or the current session can't be trusted. `purchase` and `first_deposit` are counted separately, and `applyId` / `transactionId` are treated as aliases of the same order; with no ID at all it returns `true` |
340
+
341
+ **Once `AUTH_CHECKED` has been sent, it must be sent again after every token rotation**: when a verified session switches directly to another token, until the `AUTH_CHECKED` for the new token arrives, `CONNECT` / `CHECK_SOCKET` are only recorded and do not connect, and `claimPaymentEvent` always returns `false`; the dedupe records are restored only when the UID is the same as before. Downstreams that have never sent `AUTH_CHECKED` are unaffected.
342
+
343
+ **Push dedupe**: the four push events are deduplicated before being forwarded (`createPushDedupe`) — `_meta.messageId` is preferred; without it, only `payment-info` is keyed by "business event + `applyId` / `transactionId`"; with neither, no dedupe is applied.
306
344
 
307
345
  **Event forwarding map**:
308
346
 
309
- | Socket event | State machine event |
310
- | ---------------------------------------------- | ----------------------------------------------------------------------------------- |
311
- | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
312
- | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
313
- | `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
314
- | `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
347
+ | Socket event | State machine event |
348
+ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
349
+ | `activity-info` / `payment-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
350
+ | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
351
+ | `connect` | `SET_CONNECTED` |
352
+ | `session-ready` (or `socket.recovered === true` on `connect`) | `SESSION_READY` |
353
+ | `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT` (carrying `internalSocket: true`, after going through the failure decision) |
354
+ | `auth-rejected` / `kicked` | Not forwarded; they only enter the failure decision |
355
+
356
+ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internalSocket`, is treated as a failure report and enters the failure decision as well.
315
357
 
316
- **First-deposit detection**: while handling `PUSH_ANALYTICS`, if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **automatically pushed as well** (Facebook Pixel / conversion tracking).
358
+ **First-deposit detection**: `PUSH_ANALYTICS` (only when `isTracking` is truthy) reports the original event first; if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **additionally pushed** (Facebook Pixel / conversion tracking). Both must first pass `claimPaymentEvent`, and if the token or `generation` changes while reporting, `first_deposit` is not sent.
317
359
 
318
360
  ### 2.7 Configuration & Live Info (Common Machine)
319
361
 
@@ -327,19 +369,20 @@ io(`${socketURL}/frontend`, {
327
369
  ```
328
370
  1. A state machine service calls request.send(api.xxx(params))
329
371
  2. api.xxx(params) returns a descriptor object
330
- 3. _checkToken(req): non-public endpoints check the token; if missing, throw ERR_A103
331
- 4. isBlocked check: under maintenance and not a config request → silently blocked
372
+ 3. Identity pre-checks (non-public only): no token → reject ERR_A103; token revoked via revokeToken → reject ERR_800; gate active and url is not 'self' → wait for the gate, then re-check (see 2.1)
373
+ 4. Token-carrying request without customToken → attach a one-time CancelToken source and register it in activeRequests, removed in finally (see item 11 of 2.9)
332
374
  5. _createConfig(req):
333
375
  a. Strip the query string from the URL
334
376
  b. Match against supportVersion2List (supports :param dynamic-path regex matching)
335
377
  c. If matched → _convertUrlToKebabCase() (look up the specifyingPath mapping first, otherwise auto-convert)
336
378
  d. GET → params goes in the params field; POST → params goes in the data field
337
379
  e. pickBy filters out null/undefined values
338
- 6. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
339
- 7. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
340
- 8. axios.request(config)
341
- 9. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
342
- 10. Error handling: ERR_F108 → isBlocked + errorHandler; ERR_998 → thrown directly; ERR_800 (cancelled) → silent; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown)
380
+ 6. isBlocked check: under maintenance and not a config request → no request is sent, resolves undefined
381
+ 7. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
382
+ 8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
+ 9. axios.request(config)
384
+ 10. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
385
+ 11. Error handling (in order): cancellation → reject ERR_800 (never reaches errorHandler); token-carrying requests get a non-enumerable requestToken attached to the error; ERR_F108 → isBlocked + errorHandler; stale-identity error → thrown directly (see item 14 of 2.9); ERR_998 → thrown directly; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown); non-cancellation error whose code is already ERR_800 → resolves undefined
343
386
  ```
344
387
 
345
388
  **V1→V2 conversion**: `supportVersion2List` supports dynamic paths (e.g. `payment/v2/:paymentType/transaction`, where `:param` is replaced by `[^/]+`); special paths are hard-coded in `specifyingPath`, and the rest are auto-converted via `/([a-z])([A-Z])/g`. **When adding an endpoint that needs V2 conversion, it must be added to the list manually.**
@@ -356,9 +399,10 @@ io(`${socketURL}/frontend`, {
356
399
  8. **`appSecret` marks public endpoints**: nearly all `isPublic: true` endpoints require an `appSecret` parameter, **but the auth endpoints do not**.
357
400
  9. **Unfinished-game infinite retry**: the `unfinishedGame` state in `error.js` returns to itself on `onError`, with **no backoff strategy and no retry cap** (a known issue, see "Known Technical Debt").
358
401
  10. **`isMobile` is a string, not a boolean**: in `common.js`, `isMobile = userAgent?.device?.type` returns `'mobile'`/`'tablet'`/`undefined`, so comparisons must be string-based (e.g. `isMobile === 'mobile' ? 'y' : null`).
359
- 11. **Requests carry no CancelToken by default**: the cancellation feature of `send(req, customToken)` is **opt-in**. In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not "helpfully" add the CancelToken back onto the shared path.**
402
+ 11. **CancelTokens must be one-time, never shared**: a token-carrying non-public request that passes no `customToken` gets its own **one-time** `CancelToken.source()` (registered in `activeRequests`, removed in `finally`, collected along with the request) so that `revokeToken` can cancel in-flight requests; when `customToken` is passed, it is used instead, the caller manages its lifecycle, and it is not registered (`revokeToken` cannot cancel it). In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not turn the one-time source into a shared token.** The one-time source is only created when the injected `axios` exposes `CancelToken` (axios's default export and `@nuxtjs/axios`'s `$axios` do; instances produced by `axios.create()` don't); without it, `revokeToken` cannot abort in-flight requests and only blocks subsequent `send()` calls.
360
403
  12. **`silent: true` only skips errorHandler**: the error is still thrown to the caller's `onError`, and `ERR_F108` is still routed as usual; but every other error code — **including logout-class codes such as `ERR_A104`, and `ERR_G106` insufficient balance** — never reaches the error machine. Use it only for background requests whose session invalidation is already covered by `fetchUserInfo` polling; never add it to user-initiated requests.
361
- 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and `ERR_800` cancellations make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
404
+ 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and non-cancellation errors that already carry `code: 'ERR_800'` make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. Cancellations (`customToken` cancellation, `revokeToken` revocation), by contrast, reject with `ERR_800` and **do reach `onError`** — they never resolve `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
405
+ 14. **Late errors from a stale identity never reach errorHandler**: when the token a request was sent with differs from the current token (and a current token exists), the error is only thrown to the caller's `onError` and not forwarded to errorHandler — so a late logout-class error from an old session can't log out a newly logged-in identity. When there is no current token (TTL expired or already cleared), routing is unchanged so that `ERR_A204`-style popups aren't swallowed; the `ERR_F108` check comes before this one and still routes as usual.
362
406
 
363
407
  ---
364
408
 
@@ -366,19 +410,19 @@ io(`${socketURL}/frontend`, {
366
410
 
367
411
  > Every item below exists in the code in **two competing forms** — exploring the code cannot tell you which one is the standard, so it must be written down explicitly. New code always follows the "Target" column; existing code is not proactively refactored en masse (scope discipline).
368
412
 
369
- | Item | Current state | Target |
370
- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
371
- | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
372
- | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
373
- | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
374
- | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
375
- | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
376
- | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
377
- | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around; `util/constant.js` currently holds **only** `GAME_SEARCH` / `GAME_TYPE_LIST`, two game-category constants | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
378
- | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
379
- | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
380
- | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
381
- | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
413
+ | Item | Current state | Target |
414
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
415
+ | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
416
+ | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
417
+ | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
418
+ | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
419
+ | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
420
+ | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
421
+ | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around, and `util/constant.js` does not hold any of these categories yet | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
422
+ | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
423
+ | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
424
+ | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
425
+ | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
382
426
 
383
427
  ---
384
428
 
@@ -386,7 +430,6 @@ io(`${socketURL}/frontend`, {
386
430
 
387
431
  > These issues **have already been surveyed**; there is no need to re-report them in every code review. When you want to address one, open a separate ticket — don't bundle it into a feature change.
388
432
 
389
- - **WebSocket listener leak (severity: high)** — the `listenToSocketEvents` callback service in `machine/websocket.js` registers several `.on()` listeners but **never returns a cleanup function**, so they accumulate on every reconnect. Fix: extract the handlers into named variables and return `() => clientSocket.off(event, handler)`. The `connect` / `connect_error` listeners registered inside `connectSocket`'s Promise are likewise never cleaned up. **Newly written callback services must always return a cleanup function (see the DoD).**
390
433
  - **No request caching** — high-frequency endpoints (`fetchUserInfo` every 2–10 seconds, `getConfig` on every state machine initialization, `getPaymentDetail` on every entry to a deposit/withdrawal page, `getActivityList` every 20 seconds) all hit the server directly. Consider TTL caching or `stale-while-revalidate`.
391
434
  - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
392
435
  - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
package/GEMINI.md CHANGED
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
59
59
  - [ ] **Memory safety**: `setInterval` / `socket.on()` / `addEventListener` registered inside an XState callback service **must return a cleanup function** (e.g. `() => clientSocket.off(event, handler)`) to avoid accumulating listeners across reconnects; listeners registered inside a Promise must also be cleaned up after resolve / reject
60
60
  - [ ] **Token lifecycle**: token operations go through `getToken()` and the `extendToken` action, never bypass the interceptor to inject manually; prefer the existing TTL constants; when `fetchUserInfo` fails, let the session terminate naturally rather than retrying on your own
61
61
  - [ ] **Error handling**: forward through `request.errorHandler` to the error machine, with correct branches for each special code (see "Error Code System")
62
- - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the reconnect strategy only triggers on `'io server disconnect'`
62
+ - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the next step after a disconnect / failure is always decided by `decideNextStep` in `util/socketPolicy.js` — never write a separate reconnect condition in `websocket.js`; new listeners are always registered through `on()` in `bindSocket` (that is what gets them cleaned up and guarded against stale sessions)
63
63
  - [ ] **Performance impact**: avoid adding per-second self-referencing `after: { 1000 }` transitions (consider a callback + `setInterval` + computing elapsed time); don't eagerly import large dependencies at module top level; evaluate whether new high-frequency APIs need caching or backoff
64
64
  - [ ] **Consistent import paths**: cross-layer imports use relative paths (`'../../api/payment.js'`), never the `@jetthai/cuora` package name as a self-reference; lodash imports consistently omit the `.js` extension
65
65
  - [ ] **Magic numbers and strings**: activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'` / `'WITHDRAW'`, `receiveStatus` numbers, etc. should prefer the constants in `util/constant.js`
@@ -148,7 +148,7 @@ State machines **do not directly reference each other**; they communicate indire
148
148
  | `ERR_F106` | OTP verification failed |
149
149
  | `ERR_G106` | Insufficient balance (→ deposit state) |
150
150
  | `ERR_G124` / `ERR_G125` | Free game settlement / forfeit |
151
- | `ERR_800` | Cancelled request (handled silently) |
151
+ | `ERR_800` | Cancelled request (never forwarded to errorHandler, but still rejects to the caller's `onError`) |
152
152
  | `ERR_998` | Network error / 404 (reported to Sentry) |
153
153
 
154
154
  When `error.extend` contains `unfinished_` → unfinished game; the gameCode is everything after the first underscore, taken via `error.extend.split(/_(.+)/)[1]`.
@@ -172,6 +172,13 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
172
172
  - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
173
173
  - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
174
174
 
175
+ **Token revocation & foreground gate** (`request.js`): `revokeToken(token)` and `beginTokenGate(promise, timeoutMs = 3000)` are public `Request` methods with **no caller inside this package** — the downstream frontends call them on logout-class errors and when the app returns to the foreground; changing their signatures or semantics is a public-interface change.
176
+
177
+ - **Only the current identity can be revoked**: `revokeToken` only takes effect when `token === getToken()`, so a late error from a previous identity cannot revoke a newly logged-in token. Once in effect, it cancels in-flight requests carrying that token (for the scope, see item 11 of 2.9), and any later non-public `send()` still carrying it rejects `ERR_800` immediately without hitting the network; public requests are unaffected (the token stays in storage while revoked, and `getConfig` around autoLogin must not be wrongly rejected). There is no "un-revoke" API — logging in again changes the token, which lifts the revocation naturally.
178
+ - **The token to revoke comes from the error object**: when a token-carrying request fails, `send()` attaches a **non-enumerable** `error.requestToken` (the Bearer token at send time). It is non-enumerable so it doesn't leak through `JSON.stringify` / Sentry serialization — **never make it enumerable, and never copy it into enumerable fields, logs, or Sentry extra**. Cancellation `ERR_800` errors and the missing-token `ERR_A103` don't carry this field.
179
+ - **While a gate is active**: non-public requests first wait for the probe promise to settle (success and failure both release it) or for the timeout; once released, they re-check whether the token has been revoked and whether it still exists (missing → `ERR_A103`).
180
+ - **Hard-coded `'self'` coupling**: `send()` decides which request skips the gate by checking whether the descriptor's raw `url` (query stripped, before V2 conversion) is `'self'`, which corresponds to `getUserInfo` in `api/user.js` (`updateUserInfo`, sharing the same url, skips it too). Changing `getUserInfo`'s url (adding a leading slash, changing the path) requires updating this check in lockstep, otherwise `/self` gets blocked by the gate as well — a probe sent after the gate is created would then wait on its own gate until the timeout.
181
+
175
182
  **inline vs login states** (the most central concept in `auth.js`):
176
183
 
177
184
  - `inline`: authenticated but `rank < 0` (the account has not finished ranking/activation); polling continues until rank takes effect
@@ -193,6 +200,8 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
193
200
 
194
201
  **OTP / bind-bank flow**: after a successful login it enters `otpChecking`; `OTP_VERIFIED` or `OTP_SKIP` moves it to `bindBankChecking`, and only `BIND_BANK_DONE` or `BIND_BANK_SKIP` proceeds to `loginSuccess` (either gate accepts `LOGOUT` to abort). Whether binding is required is decided by the downstream frontend; the machine only waits — **downstream must send one of these events in `bindBankChecking`, or the session stalls there**. The `tokenAuthenticated` path skips both gates.
195
202
 
203
+ **OTP auto-verification** (`auth_otp_v3.js`): when `verify` / `sendPhone` / `sendEmail` respond with `needAcknowledge === false`, the machine skips OTP input and goes to `autoVerifying`. But **`needAcknowledge: false` by itself does not count as verified** — the `phone_verification_status` / `email_verification_status` from `/self` is always the basis, and the contact data must be non-empty (phone accepts `phone` or `tel`; when the data is empty, input is required even if the status is truthy). There is a delay between the backend writing the verification status and `/self` reflecting it; when the machine's own `/self` call does not pass, it enters `autoVerifyWaiting` — **the machine does not poll by itself**; instead it waits for downstream to forward the `/self` results of auth's routine polling as `USER_INFO_UPDATED` (`data` is the userInfo), for at most 2 updates or 5 seconds (`AUTO_VERIFY_*` in `util/constant.js`; receiving a stale value does not reset the timer), and if still not verified → `fail`. **When downstream does not forward this event, auto-verification simply falls to `fail` after 5 seconds.** The 5 seconds is sized against auth's `tick: 2000` so that two polls can come back in time; changing `tick` requires adjusting it in lockstep.
204
+
196
205
  **Account persistence**: the most recently used login account is stored in localStorage (31-day TTL) for form auto-fill. **Token expiration does not affect the account record.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
197
206
 
198
207
  ### 2.2 Canonical Deposit Pattern
@@ -291,29 +300,62 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
291
300
 
292
301
  ### 2.6 Real-Time Communication (WebSocket)
293
302
 
294
- **SocketTester race mechanism**: the `fetchSocket` service fetches multiple socket URLs from `/target/target.json` and pings them all simultaneously with `Promise.any()` — the fastest responder wins.
303
+ **Single owner**: connecting, retrying, and cleanup all live inside the closure of the `socketLifecycle` callback service invoked at the root. States such as `idle` / `fetchSocket` / `connecting` / `connected` are **display-only states for downstream**, driven by the `_SOCKET_STATUS` (`phase`) the service emits; they have no invoke and no guard of their own — to change behavior, change the service; don't add `invoke` / `after` to a state. Before switching to a new instance, the old listeners are always `off`'d and the old instance `disconnect`ed first (including an instance that never connected).
304
+
305
+ **Host selection**: `selectSocket` fetches multiple hosts from `target/target.json` on GCS and hits `/ping/status` on all of them simultaneously with `Promise.any()` — the fastest responder wins; when the list can't be fetched or every host fails, it falls back to `request.config.socketURL`. **Without a token, no host is selected and no connection is created.**
295
306
 
296
307
  ```js
297
- io(`${socketURL}/frontend`, {
308
+ io(frontendURL(host), {
298
309
  withCredentials: true,
299
310
  forceNew: true,
300
- transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
301
- auth: { Authorization: authToken },
311
+ transports: ['websocket'], // websocket only, no polling fallback
312
+ auth: (done) => done({ Authorization: request.getToken() }), // callback form: reads the latest token at each (re)connect
302
313
  })
303
314
  ```
304
315
 
305
- **Reconnect strategy**: **reconnect only when `connectError === 'io server disconnect'`** (the server actively disconnected), at most 3 times with a 2-second interval. Client-side network errors do not trigger it (they are left to Socket.IO's built-in auto-reconnect).
316
+ **The next step after a failure** is always decided by `decideNextStep` in `util/socketPolicy.js`:
317
+
318
+ | Result | Trigger | Behavior |
319
+ | ---------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
320
+ | `socketio` | A `disconnect` not initiated by the server, or a `connect_error` while the socket is still `active` | Stay on the same instance and leave it to Socket.IO's built-in reconnect; not recovered within 120 seconds of the first loss → `exhausted` |
321
+ | `retry` | Every other failure (including `io server disconnect` **before the session is ready**) | Re-select a host; at most 3 times beyond the initial attempt, 1 / 2 / 4 second exponential backoff × 0.5–1.5 jitter, with the server-provided `retryAfterMs` as the floor; budget used up → `exhausted` |
322
+ | `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | Reconnect immediately once (only one allowance before becoming ready), then treated as `retry` |
323
+ | `kicked` | The `kicked` event, `MAX_CONNECTIONS`, or `io server disconnect` **after the session is ready** | Stop |
324
+ | `stop` | A rejection carrying `retryable: false` | Stop |
325
+ | `none` | `io client disconnect` (disconnected by ourselves) | Ignored |
326
+
327
+ **`io server disconnect` no longer means "reconnect"**: being disconnected by the server after the session is ready is treated as being kicked, with no automatic reconnect. After stopping, `context.blocked` decides who may resume (`canResume`): `kicked` only accepts `source: 'user'`; `exhausted` accepts user at any time and `auto` only once ≥ 15 seconds have passed since the last attempt; `stop` has to wait for a token change. A `DISCONNECT_SOCKET` without `preserveSession` clears `blocked`.
328
+
329
+ **Downstream contracts** (the other end of these events and context fields lives in the downstream frontends; there is no caller inside this package):
330
+
331
+ | Interface | Contract |
332
+ | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
333
+ | `CONNECT` / `CHECK_SOCKET` | May carry `source: 'user' \| 'auto'` (default `user`), which decides whether it can resume after `blocked` |
334
+ | `AUTH_CHECKED` | `{ token, uidSite }`; may only come from a successful `/self`, and `token` must equal the current `getToken()`; for the obligation after sending it once, see below |
335
+ | `DISCONNECT_SOCKET` | Default = logout / destroy, clearing the session, dedupe records, and retry state; `{ preserveSession: true }` = background release, keeping all of them |
336
+ | `SESSION_READY` | `{ resync, generation }`. **Readiness is based on the server's `session-ready` (or `socket.recovered === true`), not on `connect`** — `SET_CONNECTED` only means the transport is up. `resync: true` means a session was ready before and this one is a fresh, non-recovered session, so downstream must catch up via REST |
337
+ | `ACTIVITY_INFO` | `{ data, eventName, generation }`; `payment-info` is **no longer limited to `windowType === 'toast'`** — any filtering is up to downstream |
338
+ | `context.generation` | Incremented when the connection is invalidated, on a new attempt, and on the first loss; downstream can use it to discard REST responses from an older generation |
339
+ | `context.claimPaymentEvent(event, orderData)` | GA dedupe shared by REST and socket: `true` = first time, may report; `false` = duplicate, or the current session can't be trusted. `purchase` and `first_deposit` are counted separately, and `applyId` / `transactionId` are treated as aliases of the same order; with no ID at all it returns `true` |
340
+
341
+ **Once `AUTH_CHECKED` has been sent, it must be sent again after every token rotation**: when a verified session switches directly to another token, until the `AUTH_CHECKED` for the new token arrives, `CONNECT` / `CHECK_SOCKET` are only recorded and do not connect, and `claimPaymentEvent` always returns `false`; the dedupe records are restored only when the UID is the same as before. Downstreams that have never sent `AUTH_CHECKED` are unaffected.
342
+
343
+ **Push dedupe**: the four push events are deduplicated before being forwarded (`createPushDedupe`) — `_meta.messageId` is preferred; without it, only `payment-info` is keyed by "business event + `applyId` / `transactionId`"; with neither, no dedupe is applied.
306
344
 
307
345
  **Event forwarding map**:
308
346
 
309
- | Socket event | State machine event |
310
- | ---------------------------------------------- | ----------------------------------------------------------------------------------- |
311
- | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
312
- | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
313
- | `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
314
- | `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
347
+ | Socket event | State machine event |
348
+ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
349
+ | `activity-info` / `payment-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
350
+ | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
351
+ | `connect` | `SET_CONNECTED` |
352
+ | `session-ready` (or `socket.recovered === true` on `connect`) | `SESSION_READY` |
353
+ | `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT` (carrying `internalSocket: true`, after going through the failure decision) |
354
+ | `auth-rejected` / `kicked` | Not forwarded; they only enter the failure decision |
355
+
356
+ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internalSocket`, is treated as a failure report and enters the failure decision as well.
315
357
 
316
- **First-deposit detection**: while handling `PUSH_ANALYTICS`, if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **automatically pushed as well** (Facebook Pixel / conversion tracking).
358
+ **First-deposit detection**: `PUSH_ANALYTICS` (only when `isTracking` is truthy) reports the original event first; if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **additionally pushed** (Facebook Pixel / conversion tracking). Both must first pass `claimPaymentEvent`, and if the token or `generation` changes while reporting, `first_deposit` is not sent.
317
359
 
318
360
  ### 2.7 Configuration & Live Info (Common Machine)
319
361
 
@@ -327,19 +369,20 @@ io(`${socketURL}/frontend`, {
327
369
  ```
328
370
  1. A state machine service calls request.send(api.xxx(params))
329
371
  2. api.xxx(params) returns a descriptor object
330
- 3. _checkToken(req): non-public endpoints check the token; if missing, throw ERR_A103
331
- 4. isBlocked check: under maintenance and not a config request → silently blocked
372
+ 3. Identity pre-checks (non-public only): no token → reject ERR_A103; token revoked via revokeToken → reject ERR_800; gate active and url is not 'self' → wait for the gate, then re-check (see 2.1)
373
+ 4. Token-carrying request without customToken → attach a one-time CancelToken source and register it in activeRequests, removed in finally (see item 11 of 2.9)
332
374
  5. _createConfig(req):
333
375
  a. Strip the query string from the URL
334
376
  b. Match against supportVersion2List (supports :param dynamic-path regex matching)
335
377
  c. If matched → _convertUrlToKebabCase() (look up the specifyingPath mapping first, otherwise auto-convert)
336
378
  d. GET → params goes in the params field; POST → params goes in the data field
337
379
  e. pickBy filters out null/undefined values
338
- 6. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
339
- 7. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
340
- 8. axios.request(config)
341
- 9. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
342
- 10. Error handling: ERR_F108 → isBlocked + errorHandler; ERR_998 → thrown directly; ERR_800 (cancelled) → silent; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown)
380
+ 6. isBlocked check: under maintenance and not a config request → no request is sent, resolves undefined
381
+ 7. Request interceptor: injects X-TH1GAMES-VERSION, X-TH1GAMES-PLATFORM, Authorization
382
+ 8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
+ 9. axios.request(config)
384
+ 10. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
385
+ 11. Error handling (in order): cancellation → reject ERR_800 (never reaches errorHandler); token-carrying requests get a non-enumerable requestToken attached to the error; ERR_F108 → isBlocked + errorHandler; stale-identity error → thrown directly (see item 14 of 2.9); ERR_998 → thrown directly; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown); non-cancellation error whose code is already ERR_800 → resolves undefined
343
386
  ```
344
387
 
345
388
  **V1→V2 conversion**: `supportVersion2List` supports dynamic paths (e.g. `payment/v2/:paymentType/transaction`, where `:param` is replaced by `[^/]+`); special paths are hard-coded in `specifyingPath`, and the rest are auto-converted via `/([a-z])([A-Z])/g`. **When adding an endpoint that needs V2 conversion, it must be added to the list manually.**
@@ -356,9 +399,10 @@ io(`${socketURL}/frontend`, {
356
399
  8. **`appSecret` marks public endpoints**: nearly all `isPublic: true` endpoints require an `appSecret` parameter, **but the auth endpoints do not**.
357
400
  9. **Unfinished-game infinite retry**: the `unfinishedGame` state in `error.js` returns to itself on `onError`, with **no backoff strategy and no retry cap** (a known issue, see "Known Technical Debt").
358
401
  10. **`isMobile` is a string, not a boolean**: in `common.js`, `isMobile = userAgent?.device?.type` returns `'mobile'`/`'tablet'`/`undefined`, so comparisons must be string-based (e.g. `isMobile === 'mobile' ? 'y' : null`).
359
- 11. **Requests carry no CancelToken by default**: the cancellation feature of `send(req, customToken)` is **opt-in**. In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not "helpfully" add the CancelToken back onto the shared path.**
402
+ 11. **CancelTokens must be one-time, never shared**: a token-carrying non-public request that passes no `customToken` gets its own **one-time** `CancelToken.source()` (registered in `activeRequests`, removed in `finally`, collected along with the request) so that `revokeToken` can cancel in-flight requests; when `customToken` is passed, it is used instead, the caller manages its lifecycle, and it is not registered (`revokeToken` cannot cancel it). In axios <0.22 the cancel handler is never unsubscribed — a shared long-lived token accumulates one handler per request, causing overnight OOM when left running (TI-15555). **Do not turn the one-time source into a shared token.** The one-time source is only created when the injected `axios` exposes `CancelToken` (axios's default export and `@nuxtjs/axios`'s `$axios` do; instances produced by `axios.create()` don't); without it, `revokeToken` cannot abort in-flight requests and only blocks subsequent `send()` calls.
360
403
  12. **`silent: true` only skips errorHandler**: the error is still thrown to the caller's `onError`, and `ERR_F108` is still routed as usual; but every other error code — **including logout-class codes such as `ERR_A104`, and `ERR_G106` insufficient balance** — never reaches the error machine. Use it only for background requests whose session invalidation is already covered by `fetchUserInfo` polling; never add it to user-initiated requests.
361
- 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and `ERR_800` cancellations make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
404
+ 13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and non-cancellation errors that already carry `code: 'ERR_800'` make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. Cancellations (`customToken` cancellation, `revokeToken` revocation), by contrast, reject with `ERR_800` and **do reach `onError`** — they never resolve `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
405
+ 14. **Late errors from a stale identity never reach errorHandler**: when the token a request was sent with differs from the current token (and a current token exists), the error is only thrown to the caller's `onError` and not forwarded to errorHandler — so a late logout-class error from an old session can't log out a newly logged-in identity. When there is no current token (TTL expired or already cleared), routing is unchanged so that `ERR_A204`-style popups aren't swallowed; the `ERR_F108` check comes before this one and still routes as usual.
362
406
 
363
407
  ---
364
408
 
@@ -366,19 +410,19 @@ io(`${socketURL}/frontend`, {
366
410
 
367
411
  > Every item below exists in the code in **two competing forms** — exploring the code cannot tell you which one is the standard, so it must be written down explicitly. New code always follows the "Target" column; existing code is not proactively refactored en masse (scope discipline).
368
412
 
369
- | Item | Current state | Target |
370
- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
371
- | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
372
- | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
373
- | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
374
- | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
375
- | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
376
- | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
377
- | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around; `util/constant.js` currently holds **only** `GAME_SEARCH` / `GAME_TYPE_LIST`, two game-category constants | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
378
- | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
379
- | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
380
- | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
381
- | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
413
+ | Item | Current state | Target |
414
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
415
+ | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
416
+ | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
417
+ | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
418
+ | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
419
+ | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
420
+ | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
421
+ | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around, and `util/constant.js` does not hold any of these categories yet | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
422
+ | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
423
+ | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
424
+ | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
425
+ | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
382
426
 
383
427
  ---
384
428
 
@@ -386,7 +430,6 @@ io(`${socketURL}/frontend`, {
386
430
 
387
431
  > These issues **have already been surveyed**; there is no need to re-report them in every code review. When you want to address one, open a separate ticket — don't bundle it into a feature change.
388
432
 
389
- - **WebSocket listener leak (severity: high)** — the `listenToSocketEvents` callback service in `machine/websocket.js` registers several `.on()` listeners but **never returns a cleanup function**, so they accumulate on every reconnect. Fix: extract the handlers into named variables and return `() => clientSocket.off(event, handler)`. The `connect` / `connect_error` listeners registered inside `connectSocket`'s Promise are likewise never cleaned up. **Newly written callback services must always return a cleanup function (see the DoD).**
390
433
  - **No request caching** — high-frequency endpoints (`fetchUserInfo` every 2–10 seconds, `getConfig` on every state machine initialization, `getPaymentDetail` on every entry to a deposit/withdrawal page, `getActivityList` every 20 seconds) all hit the server directly. Consider TTL caching or `stale-while-revalidate`.
391
434
  - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
392
435
  - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
@@ -0,0 +1,14 @@
1
+ # cuora-module 分支轉移紀錄
2
+
3
+ - 日期:2026-10-14。
4
+ - 使用者指示:將原 worktree 的檔案複製到 `feat/sharon/JT-1790247240-socket` 並 push。
5
+ - 來源:`/Users/sharon/Documents/git-project/.worktrees/cuora-module/feat-sharon-JT-1790247240-socket`,當時分支為 `feat/sharon/JT-1791180540-onesignal`。
6
+ - 目的:`/Users/sharon/Documents/git-project/cuora-module`,分支為 `feat/sharon/JT-1790247240-socket`。
7
+ - 轉移:`src/machine/websocket.js`、`src/util/socketPolicy.js`、`tests/websocket.test.mjs` 與既有規劃/驗證文件;10 個來源檔案 SHA-256 一致。
8
+ - 原 worktree 保留;先前複製的 `feat-sharon-JT-1790247240-socket/` 子目錄不納入提交。
9
+ - OTP 原分支 `feat/sharon/JT-1789548840-otp` 保留;未提交的 `src/machine/auth_otp_v3.js`、`test/` 存於下列 stash,內容逐檔核對一致。
10
+ - OTP stash:`a3d753f7b4582da25dfa63a7e540dc18100d3b0b`,訊息為 `preserve OTP before JT-1790247240 socket transfer`。回到 OTP 分支後可使用 `git stash apply <stash hash>` 恢復,stash 目前保留。
11
+ - 目的目錄重新執行 `node --test tests/websocket.test.mjs`:47/47 通過;`git diff --check` 通過。
12
+ - 此次提交不變更套件版本,不執行 npm 套件發布。
13
+
14
+ 之前文件的「未 commit/push」是當時的歷史驗證狀態;本次另依使用者授權提交並推送上述 socket 分支。
@@ -0,0 +1,40 @@
1
+ [
2
+ {
3
+ "repo": "client-pwa-cash",
4
+ "path": "/Users/sharon/Documents/git-project/client-pwa-cash",
5
+ "branch": "feat/sharon/JT-1790247240-socket",
6
+ "base_branch": "release",
7
+ "base_sha": "f97917bdb3115161308bc4e5a71a0d8e45477a63",
8
+ "submodules": [
9
+ {
10
+ "path": "assets/map",
11
+ "before_gitlink": "3fb527ff8740f0b132df84014baaec31d4876155",
12
+ "after_sha": "3fb527ff8740f0b132df84014baaec31d4876155",
13
+ "remote_HEAD": "refs/remotes/origin/master",
14
+ "status": ""
15
+ },
16
+ {
17
+ "path": "configs",
18
+ "before_gitlink": "22e909731d1b1eb480ac3842c9a966e70707e0fa",
19
+ "after_sha": "22e909731d1b1eb480ac3842c9a966e70707e0fa",
20
+ "remote_HEAD": "refs/remotes/origin/master",
21
+ "status": ""
22
+ },
23
+ {
24
+ "path": "resources",
25
+ "before_gitlink": "9123ff5bb93e275ef1864ed1b43a97738725ecbe",
26
+ "after_sha": "9123ff5bb93e275ef1864ed1b43a97738725ecbe",
27
+ "remote_HEAD": "refs/remotes/origin/master",
28
+ "status": ""
29
+ }
30
+ ]
31
+ },
32
+ {
33
+ "repo": "cuora-module",
34
+ "path": "/Users/sharon/Documents/git-project/.worktrees/cuora-module/feat-sharon-JT-1790247240-socket",
35
+ "branch": "feat/sharon/JT-1790247240-socket",
36
+ "base_branch": "master",
37
+ "base_sha": "6b6cd8faf770a12257cf22235331efc85fb21e6a",
38
+ "submodules": []
39
+ }
40
+ ]