@jetthai/cuora 1.1.487 → 1.1.488-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 (114) 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 +17 -6
  4. package/.husky/post-checkout +3 -3
  5. package/.husky/pre-push +1 -1
  6. package/.prettierignore +2 -1
  7. package/AGENTS.md +17 -6
  8. package/AI_PROMPT_SOURCE.md +17 -6
  9. package/CHANGELOG.md +422 -23
  10. package/CLAUDE.md +17 -6
  11. package/GEMINI.md +17 -6
  12. package/e2e/feature-map.md +19 -0
  13. package/package.json +1 -1
  14. package/prepare-for-pr/JT-1776243420.md +85 -0
  15. package/prepare-for-pr/TI-16026/STATE.md +18 -0
  16. package/prepare-for-pr/TI-16026/after-prepare-authorization.md +3 -0
  17. package/prepare-for-pr/TI-16026/analysis.md +38 -0
  18. package/prepare-for-pr/TI-16026/answer-analyze-01.md +1 -0
  19. package/prepare-for-pr/TI-16026/answer-commit-01.md +2 -0
  20. package/prepare-for-pr/TI-16026/answer-commit-02.md +1 -0
  21. package/prepare-for-pr/TI-16026/bundle.json +18 -0
  22. package/prepare-for-pr/TI-16026/checklist.md +196 -0
  23. package/prepare-for-pr/TI-16026/checklist.unit-test-original.md +39 -0
  24. package/prepare-for-pr/TI-16026/claude-after-model +1 -0
  25. package/prepare-for-pr/TI-16026/claude-commit-session +1 -0
  26. package/prepare-for-pr/TI-16026/claude-harvest-session +1 -0
  27. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.err +1 -0
  28. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.out +2 -0
  29. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.err +1 -0
  30. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.out +4 -0
  31. package/prepare-for-pr/TI-16026/claude-hops/03-dev.err +1 -0
  32. package/prepare-for-pr/TI-16026/claude-hops/03-dev.out +4 -0
  33. package/prepare-for-pr/TI-16026/claude-hops/04-dev.err +1 -0
  34. package/prepare-for-pr/TI-16026/claude-hops/04-dev.out +4 -0
  35. package/prepare-for-pr/TI-16026/claude-hops/05-dev.err +1 -0
  36. package/prepare-for-pr/TI-16026/claude-hops/05-dev.out +3 -0
  37. package/prepare-for-pr/TI-16026/claude-hops/06-after.err +1 -0
  38. package/prepare-for-pr/TI-16026/claude-hops/06-after.out +2 -0
  39. package/prepare-for-pr/TI-16026/claude-hops/07-commit.err +1 -0
  40. package/prepare-for-pr/TI-16026/claude-hops/07-commit.out +2 -0
  41. package/prepare-for-pr/TI-16026/claude-hops/08-commit.err +1 -0
  42. package/prepare-for-pr/TI-16026/claude-hops/08-commit.out +2 -0
  43. package/prepare-for-pr/TI-16026/claude-hops/09-commit.err +1 -0
  44. package/prepare-for-pr/TI-16026/claude-hops/09-commit.out +8 -0
  45. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.err +1 -0
  46. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.out +3 -0
  47. package/prepare-for-pr/TI-16026/claude-hops/11-harvest.err +1 -0
  48. package/prepare-for-pr/TI-16026/claude-hops/11-harvest.out +3 -0
  49. package/prepare-for-pr/TI-16026/commit-note.md +5 -0
  50. package/prepare-for-pr/TI-16026/evidence-index.json +215 -0
  51. package/prepare-for-pr/TI-16026/feature-map.before.md +61 -0
  52. package/prepare-for-pr/TI-16026/harvest-redaction.json +34 -0
  53. package/prepare-for-pr/TI-16026/harvest-redaction.out +37 -0
  54. package/prepare-for-pr/TI-16026/harvest.md +46 -0
  55. package/prepare-for-pr/TI-16026/lessons.md +5 -0
  56. package/prepare-for-pr/TI-16026/note-harvest-redaction.md +1 -0
  57. package/prepare-for-pr/TI-16026/open-questions.md +6 -0
  58. package/prepare-for-pr/TI-16026/publish.md +32 -0
  59. package/prepare-for-pr/TI-16026/review-convergence-response.md +3 -0
  60. package/prepare-for-pr/TI-16026/review-input/scope.md +18 -0
  61. package/prepare-for-pr/TI-16026/review-log.md +57 -0
  62. package/prepare-for-pr/TI-16026/review-notes.md +97 -0
  63. package/prepare-for-pr/TI-16026/review-response-r1.md +7 -0
  64. package/prepare-for-pr/TI-16026/self-test-report.md +67 -0
  65. package/prepare-for-pr/TI-16026/spec-proposal.md +34 -0
  66. package/prepare-for-pr/TI-16026/spec-snapshot.md +291 -0
  67. package/prepare-for-pr/TI-16026/state-log.md +57 -0
  68. package/prepare-for-pr/TI-16026/user-messages/01.md +12 -0
  69. package/prepare-for-pr/TI-16026/user-messages/02.md +20 -0
  70. package/prepare-for-pr/TI-16026/user-messages/03.md +1 -0
  71. package/prepare-for-pr/TI-16026/user-messages/04.md +1 -0
  72. package/prepare-for-pr/TI-16026/user-messages/05.md +1 -0
  73. package/prepare-for-pr/TI-16026/user-messages/06.md +1 -0
  74. package/prepare-for-pr/TI-16026/user-messages/07.md +1 -0
  75. package/prepare-for-pr/TI-16026/user-messages/08.md +1 -0
  76. package/prepare-for-pr/TI-16026/user-messages/09.md +1 -0
  77. package/prepare-for-pr/TI-16026/user-messages/10.md +1 -0
  78. package/prepare-for-pr/TI-16026/user-messages/11.md +1 -0
  79. package/prepare-for-pr/TI-16026/user-messages/12.md +1 -0
  80. package/prepare-for-pr/TI-16026/user-messages/13.md +1 -0
  81. package/prepare-for-pr/TI-16026/user-messages/14.md +1 -0
  82. package/prepare-for-pr/TI-16026/user-messages/15.md +1 -0
  83. package/prepare-for-pr/TI-16026/user-messages/16.md +1 -0
  84. package/prepare-for-pr/TI-16026/user-messages/17.md +1 -0
  85. package/prepare-for-pr/TI-16026/user-messages/18.md +10 -0
  86. package/prepare-for-pr/TI-16026/user-messages/19.md +1 -0
  87. package/prepare-for-pr/TI-16026/user-messages/20.md +1 -0
  88. package/prepare-for-pr/TI-16026/user-messages/21.md +1 -0
  89. package/prepare-for-pr/TI-16026/user-messages/22.md +1 -0
  90. package/prepare-for-pr/TI-16026/user-messages/23.md +8 -0
  91. package/prepare-for-pr/TI-16026/user-messages/24.md +24 -0
  92. package/prepare-for-pr/TI-16026/user-question.md +24 -0
  93. package/prepare-for-pr/TI-16026/verify/metrics-check.json +13 -0
  94. package/prepare-for-pr/TI-16026/verify/redaction.json +38 -0
  95. package/prepare-for-pr/TI-16026/verify/row-closure.json +45 -0
  96. package/prepare-for-pr/TI-16026/verify/s04-ws-capture.md +23 -0
  97. package/prepare-for-pr/TI-16026/verify-after.md +23 -0
  98. package/prepare-for-pr/TI-16026/verify.json +80 -0
  99. package/prepare-for-pr/TI-16026.md +408 -0
  100. package/scripts/auto-version.js +1 -0
  101. package/scripts/branch-auto-npm-publish.js +9 -2
  102. package/src/api/payment.js +1 -0
  103. package/src/machine/auth.js +36 -33
  104. package/src/machine/game_v2_1.js +15 -0
  105. package/src/machine/reward_cash.js +2 -2
  106. package/src/machine/user_sign_up.js +3 -0
  107. package/src/machine/withdraw/withdraw_manual_cash.js +17 -7
  108. package/src/request/request.js +103 -4
  109. package/src/util/constant.js +6 -0
  110. package/src/util/tokenStore.js +44 -0
  111. package/test/auth_self_timeout.test.js +171 -0
  112. package/test/request_self.test.js +288 -0
  113. package/test/withdraw_manual_cash.test.js +149 -0
  114. package/tests/session.test.mjs +177 -0
@@ -6,9 +6,96 @@
6
6
 
7
7
  ---
8
8
 
9
+ ## Step 0 — 分析專案並更新 AI_PROMPT_SOURCE.md
10
+
11
+ 在同步之前,先掃描專案的實際狀態,確保 `AI_PROMPT_SOURCE.md` 中的數據與程式碼一致。
12
+
13
+ ### Part A — 數據校準
14
+
15
+ 驗證並更新文件中的統計數據,確保與程式碼一致:
16
+
17
+ 1. **版本號**:讀取 `package.json` 的 `version` 欄位,更新文件中的版本號
18
+ 2. **檔案數量統計**:
19
+ - `src/` 下的 `.js` 檔案總數
20
+ - `src/api/` 檔案數
21
+ - `src/machine/` 檔案總數(含子目錄),以及狀態機數量(= 總數 - index 檔案數)
22
+ - `src/machine/activity/`、`src/machine/deposit/`、`src/machine/withdraw/` 各自檔案數
23
+ - `src/util/` 檔案數
24
+ 3. **API 函式數量**:對每個 `src/api/*.js` 模組,計算 `=>` 的出現次數以統計函式數
25
+ 4. **行數驗證**:驗證以下檔案的實際行數:
26
+ - `src/request/request.js`、`src/request/config.js`
27
+ - 所有超過 300 行的狀態機檔案(用於「大型狀態機檔案」表格)
28
+ 5. **supportVersion2List 端點數**:計算 `request.js` 中 `supportVersion2List` 陣列的實際項目數
29
+ 6. **specifyingPath 映射數**:計算 `_convertUrlToKebabCase` 中 `specifyingPath` 的 key 數量
30
+ 7. **關鍵行號參照**:驗證文件中引用的行號(如 `request.js:207`、`request.js:254` 等)是否仍然正確,若偏移則更新
31
+ 8. **依賴套件版本**:讀取 `package.json` 的 `dependencies`,更新版本號
32
+
33
+ ### Part B — Know-How 與架構驗證
34
+
35
+ 檢查 `1.7 核心業務流程與關鍵 Know-How` 章節的內容是否仍然反映程式碼的實際行為:
36
+
37
+ 1. **認證流程**:讀取 `src/machine/auth.js`,驗證:
38
+
39
+ - Token TTL、輪詢間隔、延展機制是否有變
40
+ - inline vs login 狀態判斷邏輯(`rank >= 0`)是否有變
41
+ - 登入方式是否有新增或移除(檢查全域 `on:` 事件列表)
42
+ - OTP 流程是否有調整
43
+
44
+ 2. **存款流程**:抽樣讀取 2-3 個 deposit 狀態機,驗證:
45
+
46
+ - canonical 流程(loading → promotion → loaded → debouncing → calculating → submitting → submitted)是否有變
47
+ - Cash vs Non-Cash 變體的差異描述是否仍然正確
48
+ - 是否有新增的存款類型或支付方式
49
+
50
+ 3. **提款流程**:讀取 `src/machine/withdraw/withdraw_manual.js`,驗證:
51
+
52
+ - 五步驟資格驗證鏈是否有調整
53
+ - OTP 平行狀態是否有變
54
+
55
+ 4. **WebSocket**:讀取 `src/machine/websocket.js`,驗證:
56
+
57
+ - 連線參數、重連策略是否有變
58
+ - 事件轉發映射表是否有新增事件
59
+
60
+ 5. **Error Machine**:讀取 `src/machine/error.js`,驗證:
61
+
62
+ - 錯誤代碼分類是否有新增
63
+ - 路由邏輯是否有調整
64
+
65
+ 6. **Common Machine**:讀取 `src/machine/common.js`,驗證:
66
+
67
+ - 4 個平行子機器的結構是否有變
68
+ - siteConfig 解碼方式是否有變
69
+
70
+ 7. **API 請求生命週期**:讀取 `src/request/request.js`,驗證:
71
+
72
+ - 攔截器邏輯、V2 轉換流程是否有變
73
+ - isBlocked 維護模式機制是否有變
74
+
75
+ 8. **新增狀態機**:比對 `src/machine/` 目錄與文件中的狀態機分類表,若有新增檔案:
76
+ - 判斷歸類(核心/存款/提款/活動/遊戲/使用者/UI)
77
+ - 更新分類表中的數量與代表檔案
78
+
79
+ ### Part C — Clean Code 規範驗證
80
+
81
+ 檢查「二、程式碼品質標準」中列出的問題是否已修正:
82
+
83
+ 1. **已修正的問題**:若問題已被修正(如 HTTP 方法大小寫已統一),將該項標記為已修正或移除
84
+ 2. **新增的問題**:若發現新的程式碼品質問題,添加到對應章節
85
+
86
+ ### 執行方式
87
+
88
+ - 使用 shell 指令(`wc -l`、`grep -c`、`find` 等)取得實際數據
89
+ - 使用 Agent subagent 平行分析多個核心檔案
90
+ - 將每項差異直接修正到 `AI_PROMPT_SOURCE.md` 中
91
+ - 若無差異則跳過,不做無意義修改
92
+ - 完成後簡短回報哪些項目有更新
93
+
94
+ ---
95
+
9
96
  ## Step 1 — 讀取來源檔
10
97
 
11
- 讀取 `AI_PROMPT_SOURCE.md` 完整內容。
98
+ 讀取 `AI_PROMPT_SOURCE.md` 完整內容(此時已是 Step 0 更新後的最新版本)。
12
99
 
13
100
  ---
14
101
 
@@ -17,7 +17,9 @@
17
17
  "mcp__sentry__get_issue_details",
18
18
  "mcp__sentry__search_issues",
19
19
  "Bash(git add:*)",
20
- "Bash(git commit:*)"
20
+ "Bash(git commit:*)",
21
+ "Bash(git branch:*)",
22
+ "Bash(git merge:*)"
21
23
  ]
22
24
  }
23
25
  }
@@ -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,25 @@ 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
+ **`/self` single-flight and its dedicated timeout** (`request.js`, TI-16263): for `GET self` (`_isSelfRead`: non-public, url is `'self'` after stripping the query) `send()` shares one in-flight promise keyed by `[channel, token, url, params, headers, silent]` — shared only when all of them are identical; a different identity or different params each get their own request. `channel` is a classification field on the descriptor (never sent to the backend): `polling` (`pollUserInfo` in `auth.js`, used by `inline.fetching` / `login.fetching`), `freeGame` (the downstream wait after claiming a free game), and `standalone` by default (every other entry); the three channels each send their own request and never share or skip one another; calls passing their own `customToken` are not shared. Every `/self` read has a `SELF_REQUEST_TIMEOUT_MS` deadline (15 seconds, `util/constant.js`); when it expires the request is cancelled and rejects with `{ code: 'ERR_998', endpoint, isTimeout: true }`.
172
+
173
+ - **Single-flight must be paired with a timeout**: without one, a `/self` that never answers permanently stops the polling that shares it. Do the same when adding single-flight to another endpoint.
174
+ - **The read timeout must not be switched to axios's `timeout`**: `ECONNABORTED` gets re-sent by the downstream axios-retry; a cancelled error carries no `config` and is not retried. `POST self` (`_isSelfWrite`) is deliberately the opposite: each attempt gets 15 seconds and is retried per the downstream's existing settings, so it uses axios's `timeout` plus `'axios-retry': { shouldResetTimeout: true }`; when the retries are exhausted and it still times out, the error becomes `{ code: 'ERR_998', isTimeout: true }` and does not reach `errorHandler`.
175
+ - **A successful `GET /self` extends the token**: on a successful read (all three channels count), `_extendToken` resets the token's TTL to 5 minutes (only while the token sent is still the current one). While the main polling keeps timing out, a single successful read from another channel keeps the TTL from logging the user out. A successful `POST self` does **not** extend it: the backend renews the token only on `GET /self`.
176
+ - **A `/self` timeout never logs out**: the `isSelfTimeout` guard in `auth.js` only accepts `event.data.isTimeout === true`, and a timeout re-sends instead — `authenticated` → `userInfoRetrying`, `tokenAuthenticated` re-enters itself, `inline.fetching` / `login.checkDeviceTokenDone` / `login.fetching` → `pending` (wait for the next tick). A plain `ERR_998` (a network error that fails immediately) and authentication failures still go to `leaving`. Only once the token's 5-minute TTL has expired does `send()` return `ERR_A103` and the flow naturally reaches `leaving`.
177
+ - **`userInfoRetrying` is an externally visible state**: when the first `/self` after login times out, the machine stays here re-sending and moves to `otpChecking` on success. It deliberately does not re-enter `authenticated` — downstream fires one-off side effects on `state.matches('authenticated')` (saving credentials, registration conversion tracking), and re-entering would fire them again. Downstream code that enumerates auth states (loading checks, etc.) must treat it as a continuation of `authenticated`.
178
+
179
+ - **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
180
+ - **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
181
  - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
173
- - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
182
+ - **TTL**: token 300 seconds (`TOKEN_MAX_AGE`; on expiry the browser removes the cookie), account info 31 days, cookie data 7 days
174
183
 
175
184
  **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
185
 
@@ -281,6 +290,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
281
290
  - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
282
291
  - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
283
292
  - **Game-switching mechanism**: when switching to another game while in one, `connectSwitching` disconnects the old game first, then `connecting` connects to the new one
293
+ - **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`
284
294
  - **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`
285
295
  - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
286
296
 
@@ -382,14 +392,14 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
382
392
  8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
393
  9. axios.request(config)
384
394
  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
395
+ 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
386
396
  ```
387
397
 
388
398
  **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.**
389
399
 
390
400
  ### 2.9 Critical Design Constraints & Gotchas
391
401
 
392
- 1. **Token extension only happens when `fetchUserInfo` succeeds**: tokens are never auto-renewed and depend on successful polling. API failure → the session terminates.
402
+ 1. **Token extension only happens when `/self` succeeds**: tokens are never auto-renewed and depend on a successful `/self` (polling, a read from any other entry, or `POST self`). API failure → the session terminates. The only exception is the 15-second `/self` timeout — no logout, it re-sends instead (see 2.1).
393
403
  2. **A leading slash changes routing**: `/payment/v2/...` (the withdrawal OTP endpoints) **deliberately** bypasses `url-join`'s baseURL composition and starts from the API root. Regular endpoints should not have a leading slash.
394
404
  3. **`register` mixes parameter passing**: `channel`/`subchannel`/`ac`/`fc` are appended to the URL query string while the rest go in the body. **This is the only endpoint using this pattern.**
395
405
  4. **OTP endpoints marked `isPublic`**: the withdrawal OTP `acknowledge`/`reset` endpoints are `isPublic: true` even though the operations are sensitive — this is because the token may already have expired during the OTP flow, and is **not a security oversight**.
@@ -403,6 +413,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
403
413
  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.
404
414
  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
415
  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.
416
+ 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.
406
417
 
407
418
  ---
408
419
 
@@ -19,14 +19,14 @@ if [ "$match" = "1" ]; then
19
19
  # 檢查本地是否有尚未推送的 commit,有的話跳過自動拉取(避免覆蓋本地變更)
20
20
  LOCAL_AHEAD=$(git rev-list --count origin/"$CURRENT_BRANCH"..HEAD 2>/dev/null || echo 0)
21
21
  if [ "$LOCAL_AHEAD" -gt 0 ]; then
22
- echo "分支 '$CURRENT_BRANCH' 有 $LOCAL_AHEAD 個尚未推送的 commit,略過自動拉取。"
22
+ echo "You have $LOCAL_AHEAD unpushed commit(s) on '$CURRENT_BRANCH'. Skipping auto-pull."
23
23
  exit 0
24
24
  fi
25
25
 
26
26
  # 自動從遠端拉取最新程式碼(使用 rebase 保持線性歷史)
27
- echo "正在從遠端自動拉取 '$CURRENT_BRANCH'..."
27
+ echo "Auto pulling '$CURRENT_BRANCH' from remote..."
28
28
  git pull --rebase origin "$CURRENT_BRANCH" || {
29
- echo "拉取 '$CURRENT_BRANCH' 失敗,請手動處理。"
29
+ echo "Failed to pull '$CURRENT_BRANCH'. Please resolve manually."
30
30
  exit 1
31
31
  }
32
32
  fi
package/.husky/pre-push CHANGED
@@ -21,7 +21,7 @@ BRANCH=$(git rev-parse --abbrev-ref HEAD)
21
21
 
22
22
  # 在 dev/qa 分支的 force push 跳過所有 pre-push hook(避免干擾強制推送)
23
23
  if [ "$IS_FORCE" = true ] && { [ "$BRANCH" = "dev" ] || [ "$BRANCH" = "qa" ]; }; then
24
- echo "偵測到在 $BRANCH 分支上強制推送,略過 pre-push hooks。"
24
+ echo "Force push detected on $BRANCH, skipping pre-push hooks."
25
25
  exit 0
26
26
  fi
27
27
 
package/.prettierignore CHANGED
@@ -1 +1,2 @@
1
- dist/
1
+ dist/
2
+ CHANGELOG.md
package/AGENTS.md CHANGED
@@ -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,25 @@ 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
+ **`/self` single-flight and its dedicated timeout** (`request.js`, TI-16263): for `GET self` (`_isSelfRead`: non-public, url is `'self'` after stripping the query) `send()` shares one in-flight promise keyed by `[channel, token, url, params, headers, silent]` — shared only when all of them are identical; a different identity or different params each get their own request. `channel` is a classification field on the descriptor (never sent to the backend): `polling` (`pollUserInfo` in `auth.js`, used by `inline.fetching` / `login.fetching`), `freeGame` (the downstream wait after claiming a free game), and `standalone` by default (every other entry); the three channels each send their own request and never share or skip one another; calls passing their own `customToken` are not shared. Every `/self` read has a `SELF_REQUEST_TIMEOUT_MS` deadline (15 seconds, `util/constant.js`); when it expires the request is cancelled and rejects with `{ code: 'ERR_998', endpoint, isTimeout: true }`.
172
+
173
+ - **Single-flight must be paired with a timeout**: without one, a `/self` that never answers permanently stops the polling that shares it. Do the same when adding single-flight to another endpoint.
174
+ - **The read timeout must not be switched to axios's `timeout`**: `ECONNABORTED` gets re-sent by the downstream axios-retry; a cancelled error carries no `config` and is not retried. `POST self` (`_isSelfWrite`) is deliberately the opposite: each attempt gets 15 seconds and is retried per the downstream's existing settings, so it uses axios's `timeout` plus `'axios-retry': { shouldResetTimeout: true }`; when the retries are exhausted and it still times out, the error becomes `{ code: 'ERR_998', isTimeout: true }` and does not reach `errorHandler`.
175
+ - **A successful `GET /self` extends the token**: on a successful read (all three channels count), `_extendToken` resets the token's TTL to 5 minutes (only while the token sent is still the current one). While the main polling keeps timing out, a single successful read from another channel keeps the TTL from logging the user out. A successful `POST self` does **not** extend it: the backend renews the token only on `GET /self`.
176
+ - **A `/self` timeout never logs out**: the `isSelfTimeout` guard in `auth.js` only accepts `event.data.isTimeout === true`, and a timeout re-sends instead — `authenticated` → `userInfoRetrying`, `tokenAuthenticated` re-enters itself, `inline.fetching` / `login.checkDeviceTokenDone` / `login.fetching` → `pending` (wait for the next tick). A plain `ERR_998` (a network error that fails immediately) and authentication failures still go to `leaving`. Only once the token's 5-minute TTL has expired does `send()` return `ERR_A103` and the flow naturally reaches `leaving`.
177
+ - **`userInfoRetrying` is an externally visible state**: when the first `/self` after login times out, the machine stays here re-sending and moves to `otpChecking` on success. It deliberately does not re-enter `authenticated` — downstream fires one-off side effects on `state.matches('authenticated')` (saving credentials, registration conversion tracking), and re-entering would fire them again. Downstream code that enumerates auth states (loading checks, etc.) must treat it as a continuation of `authenticated`.
178
+
179
+ - **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
180
+ - **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
181
  - **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
173
- - **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
182
+ - **TTL**: token 300 seconds (`TOKEN_MAX_AGE`; on expiry the browser removes the cookie), account info 31 days, cookie data 7 days
174
183
 
175
184
  **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
185
 
@@ -281,6 +290,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
281
290
  - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
282
291
  - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
283
292
  - **Game-switching mechanism**: when switching to another game while in one, `connectSwitching` disconnects the old game first, then `connecting` connects to the new one
293
+ - **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`
284
294
  - **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`
285
295
  - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
286
296
 
@@ -382,14 +392,14 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
382
392
  8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
393
  9. axios.request(config)
384
394
  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
395
+ 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
386
396
  ```
387
397
 
388
398
  **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.**
389
399
 
390
400
  ### 2.9 Critical Design Constraints & Gotchas
391
401
 
392
- 1. **Token extension only happens when `fetchUserInfo` succeeds**: tokens are never auto-renewed and depend on successful polling. API failure → the session terminates.
402
+ 1. **Token extension only happens when `/self` succeeds**: tokens are never auto-renewed and depend on a successful `/self` (polling, a read from any other entry, or `POST self`). API failure → the session terminates. The only exception is the 15-second `/self` timeout — no logout, it re-sends instead (see 2.1).
393
403
  2. **A leading slash changes routing**: `/payment/v2/...` (the withdrawal OTP endpoints) **deliberately** bypasses `url-join`'s baseURL composition and starts from the API root. Regular endpoints should not have a leading slash.
394
404
  3. **`register` mixes parameter passing**: `channel`/`subchannel`/`ac`/`fc` are appended to the URL query string while the rest go in the body. **This is the only endpoint using this pattern.**
395
405
  4. **OTP endpoints marked `isPublic`**: the withdrawal OTP `acknowledge`/`reset` endpoints are `isPublic: true` even though the operations are sensitive — this is because the token may already have expired during the OTP flow, and is **not a security oversight**.
@@ -403,6 +413,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
403
413
  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.
404
414
  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
415
  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.
416
+ 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.
406
417
 
407
418
  ---
408
419
 
@@ -142,7 +142,7 @@ export default function (request) {
142
142
  | `ERR_F108` | 系統維護中(**雙重攔截**:`request.js` 設 `isBlocked` 擋掉後續非 config 請求;`error.js` 路由至 logout) |
143
143
  | `ERR_A103` | 缺少認證 Token |
144
144
  | `ERR_A104` / `ERR_A113` / `ERR_A201` / `ERR_A204` | 認證失效 / 登出類 |
145
- | `ERR_A108` | OTP 認證相關 |
145
+ | `ERR_A108` | Token 過期(`send()` 先以 `/self` 續期,成功才重送原請求一次,見 2.9 第 15 點) |
146
146
  | `ERR_F106` | OTP 驗證失敗 |
147
147
  | `ERR_G106` | 餘額不足(→ deposit 狀態) |
148
148
  | `ERR_G124` / `ERR_G125` | 免費遊戲結算 / 放棄 |
@@ -159,16 +159,25 @@ export default function (request) {
159
159
 
160
160
  ### 2.1 認證與 Token 生命週期
161
161
 
162
- **Token 存活策略**:Token TTL 僅 5 分鐘(`maxAge: 300`),靠 `fetchUserInfo` 輪詢不斷延展。每次輪詢成功,`extendToken` 重新寫入 storage 並重設 TTL。**Token 不會自動續期**——若 `fetchUserInfo` 失敗,Token 自然過期,session 自動終止。
162
+ **Token 存活策略**:Token TTL 僅 5 分鐘(`maxAge: 300`),靠 `fetchUserInfo` 輪詢不斷延展。每次輪詢成功,`extendToken` 重寫 cookie 並重設 TTL。**Token 不會自動續期**——若 `fetchUserInfo` 失敗,Token 自然過期,session 自動終止。
163
163
 
164
164
  ```
165
165
  Token 5min TTL → fetchUserInfo 成功 → extendToken 重設 TTL → 再次輪詢
166
166
  fetchUserInfo 失敗 → leaving 狀態 → 登出
167
167
  ```
168
168
 
169
- - **儲存位置**:localStorage,key 為 `cuora_{clientId}`(與下游前端共用契約)
169
+ **`/self` 單一在途與專屬逾時**(`request.js`,TI-16263):`send()` 對 `GET self`(`_isSelfRead`:非 public、去掉 query 後 url 為 `'self'`)以 `[channel, token, url, params, headers, silent]` 為 key 共用同一筆在途 promise——完全相同才共用,換身分或參數不同各自獨立。`channel` 是 descriptor 上的分類欄位(不送給後端):`polling`(`auth.js` 的 `pollUserInfo`,用於 `inline.fetching`/`login.fetching`)、`freeGame`(下游領取免費遊戲後的等待)、預設 `standalone`(其餘所有入口);三類之間各發各的,不共用在途、不互相略過;自帶 `customToken` 的呼叫不共用。每筆 `/self` 讀取有 `SELF_REQUEST_TIMEOUT_MS`(15 秒,`util/constant.js`)期限,到期取消請求並 reject `{ code: 'ERR_998', endpoint, isTimeout: true }`。
170
+
171
+ - **單一在途必須配逾時**:沒有逾時,一筆卡住的 `/self` 會讓共用它的輪詢永久停止。新增其他單一在途的端點時比照辦理。
172
+ - **讀取的逾時不可改用 axios 的 `timeout`**:`ECONNABORTED` 會被下游的 axios-retry 重送;取消的錯誤不帶 `config`,不會被重試。`POST self`(`_isSelfWrite`)刻意相反:每次嘗試各 15 秒並照下游現行設定重試,所以用 axios 的 `timeout` 加 `'axios-retry': { shouldResetTimeout: true }`;重試用完仍逾時時轉成 `{ code: 'ERR_998', isTimeout: true }`,不進 `errorHandler`。
173
+ - **`GET /self` 成功即續期 token**:讀取(三個類別都算)成功時 `_extendToken` 把 token 的 TTL 重設為 5 分鐘(僅限送出時的 token 仍是目前的 token)。主輪詢連續逾時期間,其他類別的讀取有一筆成功就不會被 TTL 登出。`POST self` 成功**不續期**:後端只在 `GET /self` 續期 token。
174
+ - **`/self` 逾時一律不登出**:`auth.js` 的 guard `isSelfTimeout` 只認 `event.data.isTimeout === true`,逾時改為重發——`authenticated` → `userInfoRetrying`、`tokenAuthenticated` 重進自己、`inline.fetching`/`login.checkDeviceTokenDone`/`login.fetching` → `pending`(等下一個 tick)。一般 `ERR_998`(立即失敗的網路錯誤)與驗證失敗維持走 `leaving`。Token 的 5 分鐘 TTL 到期後 `send()` 改回 `ERR_A103`,才自然走 `leaving`。
175
+ - **`userInfoRetrying` 是對外可見的狀態**:登入後第一筆 `/self` 逾時時停在這裡重發,成功後進 `otpChecking`。刻意不重進 `authenticated`——下游以 `state.matches('authenticated')` 觸發一次性副作用(存帳密、註冊轉換追蹤),重進會重複觸發。下游若列舉 auth 狀態(loading 判斷等)需把它視同 `authenticated` 的延續。
176
+
177
+ - **儲存位置**:cookie,名稱為 `cuora_{clientId}`,不帶 `Domain`(不跨子網域)、`SameSite=Lax`、https 下加 `Secure`。讀寫只經 `Request` 的 `getToken()` / `setToken()` / `extendToken()` / `removeToken()`(實作在 `util/tokenStore.js`);**下游前端不得自行讀寫這顆 cookie,也不得再用 `storage.get('cuora_{clientId}')` 判斷登入**——`storage` 仍是 localStorage,那裡已經沒有 token。`Request` 建構時會清掉 localStorage 的同名殘值,不沿用舊 token
178
+ - **跨站 iframe 讀不到**:`SameSite=Lax` 的 cookie 在跨站 iframe(例如 Telegram 網頁版內嵌的 Mini App)無法讀寫,該情境下登入狀態無法維持;這是已接受的限制
170
179
  - **注入方式**:請求攔截器自動添加 `Authorization: Bearer {token}`
171
- - **TTL**:Token 300 秒、帳號資訊 31 天、Cookie 資料 7 天
180
+ - **TTL**:Token 300 秒(`TOKEN_MAX_AGE`,到期由瀏覽器移除 cookie)、帳號資訊 31 天、Cookie 資料 7 天
172
181
 
173
182
  **Token 作廢與回前景閘門**(`request.js`):`revokeToken(token)` 與 `beginTokenGate(promise, timeoutMs = 3000)` 是 `Request` 的公開方法,**本套件內沒有呼叫端**,由下游前端在收到登出類錯誤、App 回前景時呼叫;改簽名或語意屬對外介面變動。
174
183
 
@@ -279,6 +288,7 @@ loading(fetchInitData:雙錢包規則閘門 + getBindingPaymentInfo + getPen
279
288
  - **平行架構**(`game_v2_1.js`):`flow`(UI 互動與遊戲載入)和 `timer`(每 20 秒自動更新)同時運作
280
289
  - **靜態資料 Fallback**:未登入時使用 `staticData`,每頁 20 筆從快取切片,**無 API 呼叫**
281
290
  - **遊戲切換機制**:遊戲中切換另一款,先經 `connectSwitching` 斷線舊遊戲,再 `connecting` 連線新遊戲
291
+ - **兩種離開方式**:`EXIT_GAME` 經 `disconnect` 呼叫 `game/logout`;`ABANDON_GAME` 直接回 `idle` 並清掉遊戲網址,**不呼叫 `game/logout`**。後者只給「session 已換新(重新登入)而必須離開遊戲頁」使用——舊 session 的遊戲登出已無意義。先送 `ABANDON_GAME` 後,頁面卸載時照常送的 `EXIT_GAME` 在 `idle` 不會被處理
282
292
  - **Provider 特定行為**:部分 provider 使用 `${origin}${base}return` 作為 returnURL,其餘使用 `window.location.href`(去除 query string)。白名單以 `game_v2_1.js` 的 `returnProviders` 為準
283
293
  - **回應映射**:後端 `redirect_url` → `gameURL`、`wallet_type` → `gameWalletType`;部分遊戲回傳內嵌 `gameHtml` 而非 URL
284
294
 
@@ -380,14 +390,14 @@ io(frontendURL(host), {
380
390
  8. 自訂 paramsSerializer:q 參數特殊編碼(避免雙重編碼)
381
391
  9. axios.request(config)
382
392
  10. 回應攔截器:response.data.error 存在 → reject;Network Error / 404 → ERR_998 + Sentry
383
- 11. 錯誤處理(依序):取消類 → reject ERR_800(不進 errorHandler);帶 Token 的請求在錯誤上掛不可列舉的 requestToken;ERR_F108 → isBlocked + errorHandler;舊身分的錯誤 → 直接 throw(見 2.9 第 14 點);ERR_998 → 直接 throw;其餘 → errorHandler(描述物件帶 silent: true 則略過,仍 throw);非取消但 code 已是 ERR_800 → resolve undefined
393
+ 11. 錯誤處理(依序):取消類 → reject ERR_800(不進 errorHandler);ERR_A108 → 先以 /self 續期,成功才重送原請求一次(見 2.9 第 15 點);帶 Token 的請求在錯誤上掛不可列舉的 requestToken;ERR_F108 → isBlocked + errorHandler;舊身分的錯誤 → 直接 throw(見 2.9 第 14 點);ERR_998 → 直接 throw;其餘 → errorHandler(描述物件帶 silent: true 則略過,仍 throw);非取消但 code 已是 ERR_800 → resolve undefined
384
394
  ```
385
395
 
386
396
  **V1→V2 轉換**:`supportVersion2List` 支援動態路徑(如 `payment/v2/:paymentType/transaction`,`:param` 替換為 `[^/]+`);特殊路徑由 `specifyingPath` 硬編碼映射,其餘用 `/([a-z])([A-Z])/g` 自動轉換。**新增需要 V2 轉換的端點時必須手動加入清單。**
387
397
 
388
398
  ### 2.9 關鍵設計約束與 Gotcha
389
399
 
390
- 1. **Token 延展僅在 `fetchUserInfo` 成功時**:Token 不會自動續期,必須依賴輪詢成功。API 失敗 → session 終止。
400
+ 1. **Token 延展僅在 `/self` 成功時**:Token 不會自動續期,必須依賴 `/self`(輪詢、其他入口的讀取或 `POST self`)成功。API 失敗 → session 終止;唯一例外是 `/self` 的 15 秒逾時——不登出、改為重發(見 2.1)。
391
401
  2. **前導斜線影響路由**:`/payment/v2/...`(提款 OTP 端點)**刻意**繞過 `url-join` 的 baseURL 拼接,直接從 API 根目錄開始。一般端點不應加前導斜線。
392
402
  3. **`register` 混合參數傳遞**:`channel`/`subchannel`/`ac`/`fc` 拼入 URL query string,其餘放 body。**這是唯一使用此模式的端點。**
393
403
  4. **OTP 端點標記 `isPublic`**:提款 OTP 的 `acknowledge`/`reset` 為 `isPublic: true`,但實際操作敏感——這是因為 OTP 流程中 Token 可能已過期,**不是安全疏漏**。
@@ -401,6 +411,7 @@ io(frontendURL(host), {
401
411
  12. **`silent: true` 只略過 errorHandler**:錯誤仍會 throw 給呼叫端的 `onError`,`ERR_F108` 也照常路由;但其餘錯誤碼——**包含 `ERR_A104` 等登出類、`ERR_G106` 餘額不足**——都不會進 error machine。只用於背景呼叫、且 session 失效另有 `fetchUserInfo` 輪詢兜底的請求;使用者主動觸發的請求不可加。
402
412
  13. **`send()` 不保證回傳物件,`assign()` 內不可拋錯**:維護中(`isBlocked`)的非 config 請求、以及本身已帶 `code: 'ERR_800'` 的非取消錯誤會讓 `send()` **resolve `undefined`**(不進 `onError`);200 但 body 非 JSON 時 resolve 字串,解構 `{ data }` 得到 `undefined`。取消類(`customToken` 取消、`revokeToken` 作廢)則是 reject `ERR_800`,**會進 `onError`**,不會 resolve `undefined`。XState v4 在 `assign()` 內拋錯會清空事件佇列且狀態不更新——machine 停在當前 invoke 狀態、`after` 輪詢中止,直到外部事件(如 `REFRESH`)才離開。**回應格式驗證放 service 內 `throw`(reject → `onError`)**;`onDone` 的每個 assign 都必須承受 service 所有可能的 resolve 值,含刻意 `return null` 的早退路徑。
403
413
  14. **舊身分遲到的錯誤不進 errorHandler**:請求送出時的 Token 與目前 Token 不同(且目前仍有 Token)時,錯誤只 throw 給呼叫端的 `onError`、不轉 errorHandler——避免舊 session 遲到的登出類錯誤把新登入的身分登出。目前沒有 Token(TTL 過期或已清除)時照原路由,`ERR_A204` 等彈窗才不會被吞;`ERR_F108` 的判斷在此之前,照常路由。
414
+ 15. **`ERR_A108` 只重送一次,且先問 `/self`**:帶 Token 的非 public 請求收到 `ERR_A108` 時,`send()` 先送一次 `silent` 的 `/self`;成功且 Token 沒換,才把原請求重送一次。`/self` 自己、重送後的請求、續期期間身分已變的請求都不重送;續期失敗或重送後仍是 `ERR_A108`,原錯誤照既有路由進 errorHandler。**不可改成迴圈重試**——`/self` 失敗代表 session 真的結束了,下游靠這個錯誤登出。
404
415
 
405
416
  ---
406
417