@jetthai/cuora 1.1.485-dev.0 → 1.1.485-dev.2

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 (87) hide show
  1. package/.github/copilot-instructions.md +69 -32
  2. package/AGENTS.md +69 -32
  3. package/AI_PROMPT_SOURCE.md +69 -32
  4. package/CHANGELOG.md +9 -0
  5. package/CLAUDE.md +69 -32
  6. package/GEMINI.md +69 -32
  7. package/package.json +1 -1
  8. package/src/machine/auth.js +5 -18
  9. package/src/machine/game_v2_1.js +15 -0
  10. package/src/request/request.js +44 -4
  11. package/src/util/constant.js +5 -1
  12. package/src/util/tokenStore.js +44 -0
  13. package/tests/session.test.mjs +177 -0
  14. package/e2e/feature-map.md +0 -61
  15. package/prepare-for-pr/JT-1776243420.md +0 -85
  16. package/prepare-for-pr/TI-16026/STATE.md +0 -17
  17. package/prepare-for-pr/TI-16026/after-prepare-authorization.md +0 -3
  18. package/prepare-for-pr/TI-16026/analysis.md +0 -38
  19. package/prepare-for-pr/TI-16026/answer-analyze-01.md +0 -1
  20. package/prepare-for-pr/TI-16026/answer-commit-01.md +0 -2
  21. package/prepare-for-pr/TI-16026/answer-commit-02.md +0 -1
  22. package/prepare-for-pr/TI-16026/bundle.json +0 -18
  23. package/prepare-for-pr/TI-16026/checklist.md +0 -39
  24. package/prepare-for-pr/TI-16026/claude-after-model +0 -1
  25. package/prepare-for-pr/TI-16026/claude-commit-session +0 -1
  26. package/prepare-for-pr/TI-16026/claude-harvest-session +0 -1
  27. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.err +0 -1
  28. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.out +0 -2
  29. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.err +0 -1
  30. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.out +0 -4
  31. package/prepare-for-pr/TI-16026/claude-hops/03-dev.err +0 -1
  32. package/prepare-for-pr/TI-16026/claude-hops/03-dev.out +0 -4
  33. package/prepare-for-pr/TI-16026/claude-hops/04-dev.err +0 -1
  34. package/prepare-for-pr/TI-16026/claude-hops/04-dev.out +0 -4
  35. package/prepare-for-pr/TI-16026/claude-hops/05-dev.err +0 -1
  36. package/prepare-for-pr/TI-16026/claude-hops/05-dev.out +0 -3
  37. package/prepare-for-pr/TI-16026/claude-hops/06-after.err +0 -1
  38. package/prepare-for-pr/TI-16026/claude-hops/06-after.out +0 -2
  39. package/prepare-for-pr/TI-16026/claude-hops/07-commit.err +0 -1
  40. package/prepare-for-pr/TI-16026/claude-hops/07-commit.out +0 -2
  41. package/prepare-for-pr/TI-16026/claude-hops/08-commit.err +0 -1
  42. package/prepare-for-pr/TI-16026/claude-hops/08-commit.out +0 -2
  43. package/prepare-for-pr/TI-16026/claude-hops/09-commit.err +0 -1
  44. package/prepare-for-pr/TI-16026/claude-hops/09-commit.out +0 -8
  45. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.err +0 -1
  46. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.out +0 -3
  47. package/prepare-for-pr/TI-16026/commit-note.md +0 -5
  48. package/prepare-for-pr/TI-16026/feature-map.before.md +0 -61
  49. package/prepare-for-pr/TI-16026/harvest-redaction.out +0 -1
  50. package/prepare-for-pr/TI-16026/harvest.md +0 -37
  51. package/prepare-for-pr/TI-16026/lessons.md +0 -5
  52. package/prepare-for-pr/TI-16026/open-questions.md +0 -6
  53. package/prepare-for-pr/TI-16026/publish.md +0 -28
  54. package/prepare-for-pr/TI-16026/review-convergence-response.md +0 -3
  55. package/prepare-for-pr/TI-16026/review-input/scope.md +0 -18
  56. package/prepare-for-pr/TI-16026/review-log.md +0 -57
  57. package/prepare-for-pr/TI-16026/review-notes.md +0 -97
  58. package/prepare-for-pr/TI-16026/review-response-r1.md +0 -7
  59. package/prepare-for-pr/TI-16026/spec-proposal.md +0 -34
  60. package/prepare-for-pr/TI-16026/spec-snapshot.md +0 -291
  61. package/prepare-for-pr/TI-16026/state-log.md +0 -35
  62. package/prepare-for-pr/TI-16026/user-messages/01.md +0 -12
  63. package/prepare-for-pr/TI-16026/user-messages/02.md +0 -20
  64. package/prepare-for-pr/TI-16026/user-messages/03.md +0 -1
  65. package/prepare-for-pr/TI-16026/user-messages/04.md +0 -1
  66. package/prepare-for-pr/TI-16026/user-messages/05.md +0 -1
  67. package/prepare-for-pr/TI-16026/user-messages/06.md +0 -1
  68. package/prepare-for-pr/TI-16026/user-messages/07.md +0 -1
  69. package/prepare-for-pr/TI-16026/user-messages/08.md +0 -1
  70. package/prepare-for-pr/TI-16026/user-messages/09.md +0 -1
  71. package/prepare-for-pr/TI-16026/user-messages/10.md +0 -1
  72. package/prepare-for-pr/TI-16026/user-messages/11.md +0 -1
  73. package/prepare-for-pr/TI-16026/user-messages/12.md +0 -1
  74. package/prepare-for-pr/TI-16026/user-messages/13.md +0 -1
  75. package/prepare-for-pr/TI-16026/user-messages/14.md +0 -1
  76. package/prepare-for-pr/TI-16026/user-messages/15.md +0 -1
  77. package/prepare-for-pr/TI-16026/user-messages/16.md +0 -1
  78. package/prepare-for-pr/TI-16026/user-messages/17.md +0 -1
  79. package/prepare-for-pr/TI-16026/user-messages/18.md +0 -10
  80. package/prepare-for-pr/TI-16026/user-messages/19.md +0 -1
  81. package/prepare-for-pr/TI-16026/user-messages/20.md +0 -1
  82. package/prepare-for-pr/TI-16026/user-messages/21.md +0 -1
  83. package/prepare-for-pr/TI-16026/user-messages/22.md +0 -1
  84. package/prepare-for-pr/TI-16026/user-messages/23.md +0 -8
  85. package/prepare-for-pr/TI-16026/user-question.md +0 -24
  86. package/prepare-for-pr/TI-16026/verify-after.md +0 -15
  87. package/prepare-for-pr/TI-16026.md +0 -408
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`
@@ -144,7 +144,7 @@ State machines **do not directly reference each other**; they communicate indire
144
144
  | `ERR_F108` | System under maintenance (**dual interception**: `request.js` sets `isBlocked` to block subsequent non-config requests; `error.js` routes to logout) |
145
145
  | `ERR_A103` | Missing auth token |
146
146
  | `ERR_A104` / `ERR_A113` / `ERR_A201` / `ERR_A204` | Auth invalidation / logout class |
147
- | `ERR_A108` | OTP auth related |
147
+ | `ERR_A108` | Token expired (`send()` renews via `/self` first, and only on success resends the original request once; see item 15 of 2.9) |
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 |
@@ -161,16 +161,17 @@ This section explains how each module actually operates, its non-obvious behavio
161
161
 
162
162
  ### 2.1 Authentication & Token Lifecycle
163
163
 
164
- **Token survival strategy**: the token TTL is only 5 minutes (`maxAge: 300`), kept alive by continuous `fetchUserInfo` polling. On each successful poll, `extendToken` rewrites storage and resets the TTL. **Tokens are never auto-renewed** — if `fetchUserInfo` fails, the token expires naturally and the session terminates on its own.
164
+ **Token survival strategy**: the token TTL is only 5 minutes (`maxAge: 300`), kept alive by continuous `fetchUserInfo` polling. On each successful poll, `extendToken` rewrites the cookie and resets the TTL. **Tokens are never auto-renewed** — if `fetchUserInfo` fails, the token expires naturally and the session terminates on its own.
165
165
 
166
166
  ```
167
167
  Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll again
168
168
  fetchUserInfo failure → leaving state → logout
169
169
  ```
170
170
 
171
- - **Storage location**: localStorage, key `cuora_{clientId}` (a contract shared with the downstream frontends)
171
+ - **Storage location**: a cookie named `cuora_{clientId}`, with no `Domain` attribute (not shared across subdomains), `SameSite=Lax`, plus `Secure` under https. It is read and written only through `Request`'s `getToken()` / `setToken()` / `extendToken()` / `removeToken()` (implemented in `util/tokenStore.js`); **downstream frontends must not read or write this cookie themselves, and must no longer use `storage.get('cuora_{clientId}')` to determine login state** — `storage` is still localStorage, and the token no longer lives there. When `Request` is constructed, it clears any leftover same-named value from localStorage rather than reusing the old token
172
+ - **Unreadable in cross-site iframes**: a `SameSite=Lax` cookie cannot be read or written inside a cross-site iframe (e.g. a Mini App embedded in Telegram Web), so login state cannot be maintained in that context; this is an accepted limitation
172
173
  - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
173
- - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
174
+ - **TTL**: token 300 seconds (`TOKEN_MAX_AGE`; on expiry the browser removes the cookie), account info 31 days, cookie data 7 days
174
175
 
175
176
  **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
 
@@ -200,6 +201,8 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
200
201
 
201
202
  **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.
202
203
 
204
+ **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.
205
+
203
206
  **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.
204
207
 
205
208
  ### 2.2 Canonical Deposit Pattern
@@ -279,6 +282,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
279
282
  - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
280
283
  - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
281
284
  - **Game-switching mechanism**: when switching to another game while in one, `connectSwitching` disconnects the old game first, then `connecting` connects to the new one
285
+ - **Two ways to leave a game**: `EXIT_GAME` goes through `disconnect`, which calls `game/logout`; `ABANDON_GAME` returns straight to `idle` and clears the game URL, **without calling `game/logout`**. The latter is only for when "the session has been replaced (re-login) and the game page must be left" — logging the old session out of the game no longer serves any purpose. Once `ABANDON_GAME` has been sent, the `EXIT_GAME` that is still sent as usual when the page unloads is not handled in `idle`
282
286
  - **Provider-specific behavior**: some providers use `${origin}${base}return` as the returnURL, while the rest use `window.location.href` (with the query string stripped). The allowlist is `returnProviders` in `game_v2_1.js`
283
287
  - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
284
288
 
@@ -298,29 +302,62 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
298
302
 
299
303
  ### 2.6 Real-Time Communication (WebSocket)
300
304
 
301
- **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.
305
+ **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).
306
+
307
+ **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.**
302
308
 
303
309
  ```js
304
- io(`${socketURL}/frontend`, {
310
+ io(frontendURL(host), {
305
311
  withCredentials: true,
306
312
  forceNew: true,
307
- transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
308
- auth: { Authorization: authToken },
313
+ transports: ['websocket'], // websocket only, no polling fallback
314
+ auth: (done) => done({ Authorization: request.getToken() }), // callback form: reads the latest token at each (re)connect
309
315
  })
310
316
  ```
311
317
 
312
- **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).
318
+ **The next step after a failure** is always decided by `decideNextStep` in `util/socketPolicy.js`:
319
+
320
+ | Result | Trigger | Behavior |
321
+ | ---------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
322
+ | `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` |
323
+ | `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` |
324
+ | `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | Reconnect immediately once (only one allowance before becoming ready), then treated as `retry` |
325
+ | `kicked` | The `kicked` event, `MAX_CONNECTIONS`, or `io server disconnect` **after the session is ready** | Stop |
326
+ | `stop` | A rejection carrying `retryable: false` | Stop |
327
+ | `none` | `io client disconnect` (disconnected by ourselves) | Ignored |
328
+
329
+ **`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`.
330
+
331
+ **Downstream contracts** (the other end of these events and context fields lives in the downstream frontends; there is no caller inside this package):
332
+
333
+ | Interface | Contract |
334
+ | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
335
+ | `CONNECT` / `CHECK_SOCKET` | May carry `source: 'user' \| 'auto'` (default `user`), which decides whether it can resume after `blocked` |
336
+ | `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 |
337
+ | `DISCONNECT_SOCKET` | Default = logout / destroy, clearing the session, dedupe records, and retry state; `{ preserveSession: true }` = background release, keeping all of them |
338
+ | `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 |
339
+ | `ACTIVITY_INFO` | `{ data, eventName, generation }`; `payment-info` is **no longer limited to `windowType === 'toast'`** — any filtering is up to downstream |
340
+ | `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 |
341
+ | `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` |
342
+
343
+ **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.
344
+
345
+ **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.
313
346
 
314
347
  **Event forwarding map**:
315
348
 
316
- | Socket event | State machine event |
317
- | ---------------------------------------------- | ----------------------------------------------------------------------------------- |
318
- | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
319
- | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
320
- | `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
321
- | `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
349
+ | Socket event | State machine event |
350
+ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
351
+ | `activity-info` / `payment-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
352
+ | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
353
+ | `connect` | `SET_CONNECTED` |
354
+ | `session-ready` (or `socket.recovered === true` on `connect`) | `SESSION_READY` |
355
+ | `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT` (carrying `internalSocket: true`, after going through the failure decision) |
356
+ | `auth-rejected` / `kicked` | Not forwarded; they only enter the failure decision |
357
+
358
+ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internalSocket`, is treated as a failure report and enters the failure decision as well.
322
359
 
323
- **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).
360
+ **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.
324
361
 
325
362
  ### 2.7 Configuration & Live Info (Common Machine)
326
363
 
@@ -347,7 +384,7 @@ io(`${socketURL}/frontend`, {
347
384
  8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
348
385
  9. axios.request(config)
349
386
  10. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
350
- 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
387
+ 11. Error handling (in order): cancellation → reject ERR_800 (never reaches errorHandler); ERR_A108 → renew via /self first, and only on success resend the original request once (see item 15 of 2.9); 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
351
388
  ```
352
389
 
353
390
  **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.**
@@ -368,6 +405,7 @@ io(`${socketURL}/frontend`, {
368
405
  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.
369
406
  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.
370
407
  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.
408
+ 15. **`ERR_A108` is resent only once, and only after asking `/self`**: when a token-carrying non-public request receives `ERR_A108`, `send()` first sends a single `silent` `/self`; only if that succeeds and the token has not changed is the original request resent, once. `/self` itself, an already-resent request, and a request whose identity changed during the renewal are never resent; if the renewal fails or the resent request still gets `ERR_A108`, the original error follows the existing routing into errorHandler. **Never turn this into a retry loop** — a failed `/self` means the session has really ended, and downstream relies on this error to log out.
371
409
 
372
410
  ---
373
411
 
@@ -375,19 +413,19 @@ io(`${socketURL}/frontend`, {
375
413
 
376
414
  > 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).
377
415
 
378
- | Item | Current state | Target |
379
- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
380
- | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
381
- | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
382
- | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
383
- | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
384
- | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
385
- | 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` |
386
- | 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`) |
387
- | 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 |
388
- | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
389
- | 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 |
390
- | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
416
+ | Item | Current state | Target |
417
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
418
+ | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
419
+ | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
420
+ | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
421
+ | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
422
+ | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
423
+ | 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` |
424
+ | 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`) |
425
+ | 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 |
426
+ | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
427
+ | 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 |
428
+ | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
391
429
 
392
430
  ---
393
431
 
@@ -395,7 +433,6 @@ io(`${socketURL}/frontend`, {
395
433
 
396
434
  > 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.
397
435
 
398
- - **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).**
399
436
  - **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`.
400
437
  - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
401
438
  - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jetthai/cuora",
3
- "version": "1.1.485-dev.0",
3
+ "version": "1.1.485-dev.2",
4
4
  "description": "",
5
5
  "main": "./src/index.js",
6
6
  "type": "module",
@@ -8,8 +8,7 @@ import pickBy from 'lodash/pickBy.js'
8
8
  import { readParamFromLocation, writeParam, normalize, AC_KEYS, FC_KEYS } from '../util/paramStore.js'
9
9
 
10
10
  export default function (request) {
11
- const { appSecret, clientId, sentry } = request.config
12
- const tokenKey = `cuora_${clientId}`
11
+ const { appSecret, sentry } = request.config
13
12
  const phoneCountryCode = 'phone_countrycode'
14
13
  const accountPhoneKey = 'account_phone'
15
14
  const accountEmailKey = 'account_email'
@@ -415,16 +414,12 @@ export default function (request) {
415
414
  }
416
415
  }),
417
416
  fetchToken: assign((context, event) => {
418
- const token = storage.get(tokenKey)
419
417
  return {
420
- token,
418
+ token: request.getToken(),
421
419
  }
422
420
  }),
423
421
  setToken: assign((context, event) => {
424
- storage.set(tokenKey, event.data, {
425
- path: '/',
426
- maxAge: 300,
427
- })
422
+ request.setToken(event.data)
428
423
  return {
429
424
  token: event.data,
430
425
  }
@@ -466,19 +461,11 @@ export default function (request) {
466
461
  }
467
462
  }),
468
463
  removeToken: assign((context, event) => {
469
- storage.remove(tokenKey, {
470
- path: '/',
471
- maxAge: 300,
472
- })
464
+ request.removeToken()
473
465
  return { token: null, dt: null }
474
466
  }),
475
467
  extendToken: assign((context, event) => {
476
- const token = storage.get(tokenKey)
477
- storage.set(tokenKey, token, {
478
- path: '/',
479
- maxAge: 300,
480
- })
481
- return { token }
468
+ return { token: request.extendToken() }
482
469
  }),
483
470
  redirectTo3Party: async (context, event) => {
484
471
  const { provider, fc } = event.data
@@ -6,6 +6,8 @@ import { GAME_SEARCH } from '../util/constant.js'
6
6
  // 對應 intersectionObserver 版本
7
7
  export default function (request) {
8
8
  const { appSecret } = request.config
9
+ // 不呼叫 game/logout 直接回 idle:session 已換新時,舊 session 的遊戲登出沒有意義
10
+ const abandonGame = { target: 'idle', actions: 'clearGameURL' }
9
11
  return createMachine(
10
12
  {
11
13
  id: 'game',
@@ -160,6 +162,7 @@ export default function (request) {
160
162
  EXIT_GAME: {
161
163
  target: 'disconnect',
162
164
  },
165
+ ABANDON_GAME: abandonGame,
163
166
  },
164
167
  },
165
168
  demoGame: {
@@ -178,6 +181,7 @@ export default function (request) {
178
181
  EXIT_GAME: {
179
182
  target: 'disconnect',
180
183
  },
184
+ ABANDON_GAME: abandonGame,
181
185
  },
182
186
  },
183
187
  connectSwitching: {
@@ -196,6 +200,7 @@ export default function (request) {
196
200
  EXIT_GAME: {
197
201
  target: 'disconnect',
198
202
  },
203
+ ABANDON_GAME: abandonGame,
199
204
  },
200
205
  },
201
206
  playing: {
@@ -203,6 +208,7 @@ export default function (request) {
203
208
  EXIT_GAME: {
204
209
  target: 'disconnect',
205
210
  },
211
+ ABANDON_GAME: abandonGame,
206
212
  REFRESH: {
207
213
  target: 'refreshing',
208
214
  },
@@ -224,6 +230,7 @@ export default function (request) {
224
230
  EXIT_GAME: {
225
231
  target: 'disconnect',
226
232
  },
233
+ ABANDON_GAME: abandonGame,
227
234
  EXIT_DEMO_GAME: {
228
235
  target: 'idle',
229
236
  },
@@ -245,6 +252,9 @@ export default function (request) {
245
252
  actions: 'setGameURL',
246
253
  },
247
254
  },
255
+ on: {
256
+ ABANDON_GAME: abandonGame,
257
+ },
248
258
  },
249
259
  refreshPending: {
250
260
  after: {
@@ -252,6 +262,9 @@ export default function (request) {
252
262
  target: 'connecting',
253
263
  },
254
264
  },
265
+ on: {
266
+ ABANDON_GAME: abandonGame,
267
+ },
255
268
  },
256
269
  disconnect: {
257
270
  invoke: {
@@ -266,6 +279,7 @@ export default function (request) {
266
279
  },
267
280
  },
268
281
  on: {
282
+ ABANDON_GAME: abandonGame,
269
283
  LOAD: {
270
284
  target: 'routing',
271
285
  actions: 'setLoadable',
@@ -426,6 +440,7 @@ export default function (request) {
426
440
  return event.data.gameWalletType
427
441
  },
428
442
  }),
443
+ clearGameURL: assign({ type: undefined, gameToken: undefined, gameHtml: undefined, gameURL: undefined, gameWalletType: undefined }),
429
444
  setGameInfo: assign((context, event) => {
430
445
  const { providerId, gameId, gameTypeId, mappingId, portrait, gameCode, name, gameName } = event.data.game
431
446
  return { game: { providerId, gameId, gameTypeId, mappingId, portrait: portrait ? 1 : 0, gameCode, name, gameName } }
@@ -1,5 +1,5 @@
1
1
  import pickBy from 'lodash/pickBy.js'
2
- import storage from '../util/storage.js'
2
+ import createTokenStore from '../util/tokenStore.js'
3
3
  import { getErr998SentryExtra } from '../util/err998SentryExtra.js'
4
4
 
5
5
  // 暫停 ERR_998 上報:在組裝 Sentry 資料之前就中止,不建立事件;仍照常 reject ERR_998 給呼叫端。恢復時改回 false 即可
@@ -7,6 +7,9 @@ const IS_ERR_998_REPORT_PAUSED = true
7
7
 
8
8
  const CANCELLED_MESSAGE = 'Requests Cancelled'
9
9
 
10
+ const SELF_URL = 'self'
11
+ const TOKEN_EXPIRED_CODE = 'ERR_A108'
12
+
10
13
  // const pickBy = require('lodash/pickBy')
11
14
  const supportVersion2List = [
12
15
  // 04-09 Update
@@ -159,6 +162,7 @@ export default class Request {
159
162
  this.config = config
160
163
  this.sentry = config.sentry
161
164
  this.key = `cuora_${config.clientId}`
165
+ this.tokenStore = createTokenStore(this.key)
162
166
  this.errorHandler = null
163
167
  this.hosts = []
164
168
  this.isBlocked = false
@@ -281,7 +285,27 @@ export default class Request {
281
285
  return !!this.axios.isCancel?.(error) || error?.message === CANCELLED_MESSAGE
282
286
  }
283
287
 
284
- async send(req, customToken) {
288
+ send(req, customToken) {
289
+ return this._send(req, customToken, false)
290
+ }
291
+
292
+ _isSelf(req) {
293
+ return req.url.split('?')[0] === SELF_URL
294
+ }
295
+
296
+ // ERR_A108 多半是續期的短暫落差:先以 /self 確認 session 仍在,成功才把原請求重送一次。
297
+ // /self 自己、已重送過的請求、送出後身分已變的請求都不重送
298
+ async _renewSession(req, requestToken) {
299
+ if (!requestToken || this._isSelf(req) || this.getToken() !== requestToken) return false
300
+ try {
301
+ await this._send({ url: SELF_URL, method: 'get', silent: true }, undefined, true)
302
+ } catch (error) {
303
+ return false
304
+ }
305
+ return this.getToken() === requestToken
306
+ }
307
+
308
+ async _send(req, customToken, isRetry) {
285
309
  let tracked = null
286
310
  let requestToken = null
287
311
  try {
@@ -292,7 +316,7 @@ export default class Request {
292
316
  if (!req.isPublic) this._throwIfRevoked()
293
317
 
294
318
  // /self 是 gate 自己的探測請求,不可等待 gate,否則死鎖
295
- if (this.tokenGate && !req.isPublic && req.url.split('?')[0] !== 'self') {
319
+ if (this.tokenGate && !req.isPublic && !this._isSelf(req)) {
296
320
  await this.tokenGate
297
321
  this._throwIfRevoked()
298
322
  if (!this.getToken()) return Promise.reject({ code: 'ERR_A103' })
@@ -322,6 +346,9 @@ export default class Request {
322
346
  }
323
347
  } catch (error) {
324
348
  if (this._isCancelled(error)) throw this._cancelledError()
349
+ if (error?.code === TOKEN_EXPIRED_CODE && !isRetry && (await this._renewSession(req, requestToken))) {
350
+ return await this._send(req, customToken, true)
351
+ }
325
352
  // 不可列舉:避免 Bearer token 隨 JSON.stringify/Sentry 序列化外洩,但 error.requestToken 仍可讀取
326
353
  if (requestToken && error && typeof error === 'object' && Object.isExtensible(error)) {
327
354
  Object.defineProperty(error, 'requestToken', { value: requestToken, enumerable: false, configurable: true })
@@ -421,6 +448,19 @@ export default class Request {
421
448
  }
422
449
 
423
450
  getToken() {
424
- return storage.get(this.key)
451
+ return this.tokenStore.get()
452
+ }
453
+
454
+ setToken(token) {
455
+ this.tokenStore.set(token)
456
+ }
457
+
458
+ // 回傳續期當下的 token;已不存在時回傳 null
459
+ extendToken() {
460
+ return this.tokenStore.extend()
461
+ }
462
+
463
+ removeToken() {
464
+ this.tokenStore.clear()
425
465
  }
426
466
  }
@@ -11,13 +11,17 @@ export const GAME_TYPE_LIST = [
11
11
  { typeId: 'SCRATCHCARDS', name: 'Scratch Cards', gameTypeMappingId: 9 },
12
12
  { typeId: 'EGAME', name: 'E-Game', gameTypeMappingId: 10 },
13
13
  { typeId: 'BONUS', name: 'Bonus', gameTypeMappingId: 11 },
14
- { typeId: 'BALL', name: 'Ball', gameTypeMappingId: 12 },
14
+ // { typeId: 'BALL', name: 'Ball', gameTypeMappingId: 12 }, 已經沒有此類別,由 Prediction 取代。但暫不移除
15
15
  { typeId: 'PACHINKO', name: 'Pachinko', gameTypeMappingId: 13 },
16
16
  { typeId: 'GRAPH', name: 'Graph', gameTypeMappingId: 14 },
17
17
  { typeId: 'TURBO', name: 'Turbo', gameTypeMappingId: 15 },
18
18
  { typeId: 'SPORT', name: 'Sports', gameTypeMappingId: 16 },
19
+ { typeId: 'PREDICTION', name: 'Prediction', gameTypeMappingId: 12 },
19
20
  ]
20
21
 
21
22
  // OTP 自動驗證:主動打的 /self 未通過後,最多再等幾次 auth 例行輪詢的 /self、等待上限多久
22
23
  export const AUTO_VERIFY_MAX_USER_INFO_UPDATES = 2
23
24
  export const AUTO_VERIFY_WAIT_MS = 5000
25
+
26
+ // 登入 token 的存活秒數:每次 /self 成功續期一次,逾時由瀏覽器自行移除 cookie
27
+ export const TOKEN_MAX_AGE = 300
@@ -0,0 +1,44 @@
1
+ import storage from './storage.js'
2
+ import { TOKEN_MAX_AGE } from './constant.js'
3
+
4
+ // document.cookie 在受限的環境(sandbox iframe、停用 cookie)會直接拋錯:讀不到視為沒有,寫不進去就算了
5
+ function read(name) {
6
+ const prefix = `${name}=`
7
+ try {
8
+ const pair = document.cookie.split('; ').find((item) => item.startsWith(prefix))
9
+ return pair ? decodeURIComponent(pair.slice(prefix.length)) || null : null
10
+ } catch (error) {
11
+ return null
12
+ }
13
+ }
14
+
15
+ // 不帶 Domain:cookie 只屬於寫入它的網域,不跨子網域
16
+ function write(name, value, maxAge) {
17
+ try {
18
+ const secure = location.protocol === 'https:' ? '; Secure' : ''
19
+ document.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}; SameSite=Lax${secure}`
20
+ } catch (error) {
21
+ console.error(`Error writing cookie: ${error}`)
22
+ }
23
+ }
24
+
25
+ export default function createTokenStore(key) {
26
+ // token 原本存在 localStorage;改放 cookie 後不沿用舊值,殘留的一併清掉
27
+ storage.remove(key)
28
+
29
+ const store = {
30
+ get: () => read(key),
31
+ set(token) {
32
+ if (token) write(key, token, TOKEN_MAX_AGE)
33
+ else store.clear()
34
+ },
35
+ // 以現有的值重寫一次,讓存活時間重新起算
36
+ extend() {
37
+ const token = read(key)
38
+ if (token) write(key, token, TOKEN_MAX_AGE)
39
+ return token
40
+ },
41
+ clear: () => write(key, '', 0),
42
+ }
43
+ return store
44
+ }