@jetthai/cuora 1.1.485-dev.1 → 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.
@@ -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
 
@@ -281,6 +282,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
281
282
  - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
282
283
  - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
283
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`
284
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`
285
287
  - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
286
288
 
@@ -382,7 +384,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
382
384
  8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
385
  9. axios.request(config)
384
386
  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
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
386
388
  ```
387
389
 
388
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.**
@@ -403,6 +405,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
403
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.
404
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.
405
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.
406
409
 
407
410
  ---
408
411
 
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,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
 
@@ -281,6 +282,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
281
282
  - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
282
283
  - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
283
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`
284
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`
285
287
  - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
286
288
 
@@ -382,7 +384,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
382
384
  8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
385
  9. axios.request(config)
384
386
  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
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
386
388
  ```
387
389
 
388
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.**
@@ -403,6 +405,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
403
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.
404
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.
405
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.
406
409
 
407
410
  ---
408
411
 
@@ -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,17 @@ 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
+ - **儲存位置**: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
170
+ - **跨站 iframe 讀不到**:`SameSite=Lax` 的 cookie 在跨站 iframe(例如 Telegram 網頁版內嵌的 Mini App)無法讀寫,該情境下登入狀態無法維持;這是已接受的限制
170
171
  - **注入方式**:請求攔截器自動添加 `Authorization: Bearer {token}`
171
- - **TTL**:Token 300 秒、帳號資訊 31 天、Cookie 資料 7 天
172
+ - **TTL**:Token 300 秒(`TOKEN_MAX_AGE`,到期由瀏覽器移除 cookie)、帳號資訊 31 天、Cookie 資料 7 天
172
173
 
173
174
  **Token 作廢與回前景閘門**(`request.js`):`revokeToken(token)` 與 `beginTokenGate(promise, timeoutMs = 3000)` 是 `Request` 的公開方法,**本套件內沒有呼叫端**,由下游前端在收到登出類錯誤、App 回前景時呼叫;改簽名或語意屬對外介面變動。
174
175
 
@@ -279,6 +280,7 @@ loading(fetchInitData:雙錢包規則閘門 + getBindingPaymentInfo + getPen
279
280
  - **平行架構**(`game_v2_1.js`):`flow`(UI 互動與遊戲載入)和 `timer`(每 20 秒自動更新)同時運作
280
281
  - **靜態資料 Fallback**:未登入時使用 `staticData`,每頁 20 筆從快取切片,**無 API 呼叫**
281
282
  - **遊戲切換機制**:遊戲中切換另一款,先經 `connectSwitching` 斷線舊遊戲,再 `connecting` 連線新遊戲
283
+ - **兩種離開方式**:`EXIT_GAME` 經 `disconnect` 呼叫 `game/logout`;`ABANDON_GAME` 直接回 `idle` 並清掉遊戲網址,**不呼叫 `game/logout`**。後者只給「session 已換新(重新登入)而必須離開遊戲頁」使用——舊 session 的遊戲登出已無意義。先送 `ABANDON_GAME` 後,頁面卸載時照常送的 `EXIT_GAME` 在 `idle` 不會被處理
282
284
  - **Provider 特定行為**:部分 provider 使用 `${origin}${base}return` 作為 returnURL,其餘使用 `window.location.href`(去除 query string)。白名單以 `game_v2_1.js` 的 `returnProviders` 為準
283
285
  - **回應映射**:後端 `redirect_url` → `gameURL`、`wallet_type` → `gameWalletType`;部分遊戲回傳內嵌 `gameHtml` 而非 URL
284
286
 
@@ -380,7 +382,7 @@ io(frontendURL(host), {
380
382
  8. 自訂 paramsSerializer:q 參數特殊編碼(避免雙重編碼)
381
383
  9. axios.request(config)
382
384
  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
385
+ 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
386
  ```
385
387
 
386
388
  **V1→V2 轉換**:`supportVersion2List` 支援動態路徑(如 `payment/v2/:paymentType/transaction`,`:param` 替換為 `[^/]+`);特殊路徑由 `specifyingPath` 硬編碼映射,其餘用 `/([a-z])([A-Z])/g` 自動轉換。**新增需要 V2 轉換的端點時必須手動加入清單。**
@@ -401,6 +403,7 @@ io(frontendURL(host), {
401
403
  12. **`silent: true` 只略過 errorHandler**:錯誤仍會 throw 給呼叫端的 `onError`,`ERR_F108` 也照常路由;但其餘錯誤碼——**包含 `ERR_A104` 等登出類、`ERR_G106` 餘額不足**——都不會進 error machine。只用於背景呼叫、且 session 失效另有 `fetchUserInfo` 輪詢兜底的請求;使用者主動觸發的請求不可加。
402
404
  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
405
  14. **舊身分遲到的錯誤不進 errorHandler**:請求送出時的 Token 與目前 Token 不同(且目前仍有 Token)時,錯誤只 throw 給呼叫端的 `onError`、不轉 errorHandler——避免舊 session 遲到的登出類錯誤把新登入的身分登出。目前沒有 Token(TTL 過期或已清除)時照原路由,`ERR_A204` 等彈窗才不會被吞;`ERR_F108` 的判斷在此之前,照常路由。
406
+ 15. **`ERR_A108` 只重送一次,且先問 `/self`**:帶 Token 的非 public 請求收到 `ERR_A108` 時,`send()` 先送一次 `silent` 的 `/self`;成功且 Token 沒換,才把原請求重送一次。`/self` 自己、重送後的請求、續期期間身分已變的請求都不重送;續期失敗或重送後仍是 `ERR_A108`,原錯誤照既有路由進 errorHandler。**不可改成迴圈重試**——`/self` 失敗代表 session 真的結束了,下游靠這個錯誤登出。
404
407
 
405
408
  ---
406
409
 
package/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [1.1.485-dev.2](https://github.com/jetthai/cuora-module/compare/v1.1.485-dev.1...v1.1.485-dev.2) (2026-11-19)
6
+
5
7
  ### [1.1.485-dev.1](https://github.com/jetthai/cuora-module/compare/v1.1.485-dev.0...v1.1.485-dev.1) (2026-11-18)
6
8
 
7
9
 
package/CLAUDE.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,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
 
@@ -281,6 +282,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
281
282
  - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
282
283
  - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
283
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`
284
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`
285
287
  - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
286
288
 
@@ -382,7 +384,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
382
384
  8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
385
  9. axios.request(config)
384
386
  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
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
386
388
  ```
387
389
 
388
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.**
@@ -403,6 +405,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
403
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.
404
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.
405
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.
406
409
 
407
410
  ---
408
411
 
package/GEMINI.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,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
 
@@ -281,6 +282,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
281
282
  - **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
282
283
  - **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
283
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`
284
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`
285
287
  - **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
286
288
 
@@ -382,7 +384,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
382
384
  8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
383
385
  9. axios.request(config)
384
386
  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
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
386
388
  ```
387
389
 
388
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.**
@@ -403,6 +405,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
403
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.
404
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.
405
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.
406
409
 
407
410
  ---
408
411
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jetthai/cuora",
3
- "version": "1.1.485-dev.1",
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
  }
@@ -22,3 +22,6 @@ export const GAME_TYPE_LIST = [
22
22
  // OTP 自動驗證:主動打的 /self 未通過後,最多再等幾次 auth 例行輪詢的 /self、等待上限多久
23
23
  export const AUTO_VERIFY_MAX_USER_INFO_UPDATES = 2
24
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
+ }
@@ -0,0 +1,177 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { interpret } from 'xstate'
4
+ import Request from '../src/request/request.js'
5
+ import createTokenStore from '../src/util/tokenStore.js'
6
+ import { TOKEN_MAX_AGE } from '../src/util/constant.js'
7
+ import game from '../src/machine/game_v2_1.js'
8
+
9
+ globalThis.localStorage = { getItem: () => null, setItem() {}, removeItem() {} }
10
+ globalThis.location = { protocol: 'http:' }
11
+
12
+ // 只模擬 tokenStore 用到的行為:以 name 覆寫、Max-Age=0 即刪除
13
+ function installDocument() {
14
+ const jar = new Map()
15
+ const writes = []
16
+ globalThis.document = {
17
+ get cookie() {
18
+ return [...jar].map(([name, value]) => `${name}=${value}`).join('; ')
19
+ },
20
+ set cookie(text) {
21
+ writes.push(text)
22
+ const [pair, ...attributes] = text.split('; ')
23
+ const index = pair.indexOf('=')
24
+ const name = pair.slice(0, index)
25
+ const maxAge = attributes.find((item) => item.startsWith('Max-Age='))
26
+ if (maxAge && Number(maxAge.slice(8)) <= 0) jar.delete(name)
27
+ else jar.set(name, pair.slice(index + 1))
28
+ },
29
+ }
30
+ return { jar, writes }
31
+ }
32
+
33
+ function createRequest(respond) {
34
+ const calls = []
35
+ const axios = {
36
+ defaults: {},
37
+ interceptors: { request: { use() {} }, response: { use() {} } },
38
+ isCancel: () => false,
39
+ async request(config) {
40
+ calls.push(config.url)
41
+ return respond(config, calls.length)
42
+ },
43
+ }
44
+ const request = new Request(axios, { clientId: 'SITE', fullURL: 'https://api.test/v1/SITE' })
45
+ const handled = []
46
+ request.setErrorHandler((error) => handled.push(error.code))
47
+ return { request, calls, handled }
48
+ }
49
+
50
+ const expired = () => Promise.reject({ code: 'ERR_A108' })
51
+ const ok = (data = {}) => Promise.resolve({ data })
52
+
53
+ test('token lives in a host-only cookie with a 300 second lifetime', () => {
54
+ const { jar, writes } = installDocument()
55
+ const store = createTokenStore('cuora_SITE')
56
+
57
+ assert.equal(store.get(), null)
58
+ store.set('token.a')
59
+ assert.equal(store.get(), 'token.a')
60
+ assert.equal(writes.at(-1), `cuora_SITE=token.a; Path=/; Max-Age=${TOKEN_MAX_AGE}; SameSite=Lax`)
61
+ assert.ok(!/Domain=/i.test(writes.at(-1)))
62
+
63
+ jar.set('cuora_SITE-cred', 'sealed')
64
+ assert.equal(store.get(), 'token.a')
65
+
66
+ const before = writes.length
67
+ assert.equal(store.extend(), 'token.a')
68
+ assert.equal(writes.length, before + 1)
69
+
70
+ store.clear()
71
+ assert.equal(store.get(), null)
72
+ assert.equal(store.extend(), null)
73
+ })
74
+
75
+ test('request reads and writes the token through the cookie', () => {
76
+ installDocument()
77
+ const { request } = createRequest(() => ok())
78
+
79
+ request.setToken('token.a')
80
+ assert.equal(request.getToken(), 'token.a')
81
+ assert.equal(request.extendToken(), 'token.a')
82
+ request.removeToken()
83
+ assert.equal(request.getToken(), null)
84
+ })
85
+
86
+ test('ERR_A108 renews through /self and resends the request once', async () => {
87
+ installDocument()
88
+ const { request, calls, handled } = createRequest((config, count) => (count === 1 ? expired() : ok({ url: config.url })))
89
+ request.setToken('token.a')
90
+
91
+ const result = await request.send({ url: 'payment/v2/setting', method: 'get' })
92
+
93
+ assert.deepEqual(calls, ['payment/v2/setting', 'self', 'payment/v2/setting'])
94
+ assert.deepEqual(result, { url: 'payment/v2/setting' })
95
+ assert.deepEqual(handled, [])
96
+ })
97
+
98
+ test('a resent request that still fails with ERR_A108 is routed as before', async () => {
99
+ installDocument()
100
+ const { request, calls, handled } = createRequest((config) => (config.url === 'self' ? ok() : expired()))
101
+ request.setToken('token.a')
102
+
103
+ await assert.rejects(request.send({ url: 'payment/v2/setting', method: 'get' }), { code: 'ERR_A108' })
104
+
105
+ assert.deepEqual(calls, ['payment/v2/setting', 'self', 'payment/v2/setting'])
106
+ assert.deepEqual(handled, ['ERR_A108'])
107
+ })
108
+
109
+ test('ERR_A108 is not resent when /self cannot renew the session', async () => {
110
+ installDocument()
111
+ const { request, calls, handled } = createRequest(() => expired())
112
+ request.setToken('token.a')
113
+
114
+ await assert.rejects(request.send({ url: 'payment/v2/setting', method: 'get' }), { code: 'ERR_A108' })
115
+
116
+ assert.deepEqual(calls, ['payment/v2/setting', 'self'])
117
+ assert.deepEqual(handled, ['ERR_A108'])
118
+ })
119
+
120
+ test('/self itself and public requests are never resent', async () => {
121
+ installDocument()
122
+ const { request, calls } = createRequest(() => expired())
123
+ request.setToken('token.a')
124
+
125
+ await assert.rejects(request.send({ url: 'self', method: 'get' }), { code: 'ERR_A108' })
126
+ await assert.rejects(request.send({ url: 'getConfig', method: 'get', isPublic: true }), { code: 'ERR_A108' })
127
+
128
+ assert.deepEqual(calls, ['self', 'get-config'])
129
+ })
130
+
131
+ test('a request whose identity changed while renewing is not resent', async () => {
132
+ installDocument()
133
+ let request
134
+ const created = createRequest((config, count) => {
135
+ if (count === 1) return expired()
136
+ request.setToken('token.b')
137
+ return ok()
138
+ })
139
+ request = created.request
140
+ request.setToken('token.a')
141
+
142
+ await assert.rejects(request.send({ url: 'payment/v2/setting', method: 'get' }), { code: 'ERR_A108' })
143
+
144
+ assert.deepEqual(created.calls, ['payment/v2/setting', 'self'])
145
+ assert.deepEqual(created.handled, [])
146
+ })
147
+
148
+ test('ABANDON_GAME leaves a game without calling game/logout', async () => {
149
+ installDocument()
150
+ const sent = []
151
+ const request = {
152
+ config: { appSecret: 'secret' },
153
+ async send(descriptor) {
154
+ sent.push(descriptor.url)
155
+ return { type: 'url', redirect_url: 'https://game.test', wallet_type: 'CASH' }
156
+ },
157
+ }
158
+ globalThis.window = { location: { origin: 'https://site.test', href: 'https://site.test/play', search: '' } }
159
+ const service = interpret(game(request)).start()
160
+
161
+ service.send({
162
+ type: 'ENTER_GAME',
163
+ data: { game: { providerId: 'P', gameId: 'G', gameTypeId: 'SLOT', mappingId: 1 }, locale: 'en-US' },
164
+ })
165
+ await new Promise((resolve) => setTimeout(resolve, 0))
166
+ assert.ok(service.state.matches('flow.playing'))
167
+ assert.equal(service.state.context.gameURL, 'https://game.test')
168
+
169
+ service.send({ type: 'ABANDON_GAME' })
170
+ assert.ok(service.state.matches('flow.idle'))
171
+ assert.equal(service.state.context.gameURL, undefined)
172
+
173
+ service.send({ type: 'EXIT_GAME', data: 'uid' })
174
+ assert.ok(service.state.matches('flow.idle'))
175
+ assert.ok(!sent.includes('game/logout'))
176
+ service.stop()
177
+ })