@jetthai/cuora 1.1.485-dev.1 → 1.1.485

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.
@@ -6,96 +6,9 @@
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
-
96
9
  ## Step 1 — 讀取來源檔
97
10
 
98
- 讀取 `AI_PROMPT_SOURCE.md` 完整內容(此時已是 Step 0 更新後的最新版本)。
11
+ 讀取 `AI_PROMPT_SOURCE.md` 完整內容。
99
12
 
100
13
  ---
101
14
 
@@ -17,9 +17,7 @@
17
17
  "mcp__sentry__get_issue_details",
18
18
  "mcp__sentry__search_issues",
19
19
  "Bash(git add:*)",
20
- "Bash(git commit:*)",
21
- "Bash(git branch:*)",
22
- "Bash(git merge:*)"
20
+ "Bash(git commit:*)"
23
21
  ]
24
22
  }
25
23
  }
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
59
59
  - [ ] **Memory safety**: `setInterval` / `socket.on()` / `addEventListener` registered inside an XState callback service **must return a cleanup function** (e.g. `() => clientSocket.off(event, handler)`) to avoid accumulating listeners across reconnects; listeners registered inside a Promise must also be cleaned up after resolve / reject
60
60
  - [ ] **Token lifecycle**: token operations go through `getToken()` and the `extendToken` action, never bypass the interceptor to inject manually; prefer the existing TTL constants; when `fetchUserInfo` fails, let the session terminate naturally rather than retrying on your own
61
61
  - [ ] **Error handling**: forward through `request.errorHandler` to the error machine, with correct branches for each special code (see "Error Code System")
62
- - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the next step after a disconnect / failure is always decided by `decideNextStep` in `util/socketPolicy.js` — never write a separate reconnect condition in `websocket.js`; new listeners are always registered through `on()` in `bindSocket` (that is what gets them cleaned up and guarded against stale sessions)
62
+ - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the reconnect strategy only triggers on `'io server disconnect'`
63
63
  - [ ] **Performance impact**: avoid adding per-second self-referencing `after: { 1000 }` transitions (consider a callback + `setInterval` + computing elapsed time); don't eagerly import large dependencies at module top level; evaluate whether new high-frequency APIs need caching or backoff
64
64
  - [ ] **Consistent import paths**: cross-layer imports use relative paths (`'../../api/payment.js'`), never the `@jetthai/cuora` package name as a self-reference; lodash imports consistently omit the `.js` extension
65
65
  - [ ] **Magic numbers and strings**: activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'` / `'WITHDRAW'`, `receiveStatus` numbers, etc. should prefer the constants in `util/constant.js`
@@ -200,8 +200,6 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
200
200
 
201
201
  **OTP / bind-bank flow**: after a successful login it enters `otpChecking`; `OTP_VERIFIED` or `OTP_SKIP` moves it to `bindBankChecking`, and only `BIND_BANK_DONE` or `BIND_BANK_SKIP` proceeds to `loginSuccess` (either gate accepts `LOGOUT` to abort). Whether binding is required is decided by the downstream frontend; the machine only waits — **downstream must send one of these events in `bindBankChecking`, or the session stalls there**. The `tokenAuthenticated` path skips both gates.
202
202
 
203
- **OTP auto-verification** (`auth_otp_v3.js`): when `verify` / `sendPhone` / `sendEmail` respond with `needAcknowledge === false`, the machine skips OTP input and goes to `autoVerifying`. But **`needAcknowledge: false` by itself does not count as verified** — the `phone_verification_status` / `email_verification_status` from `/self` is always the basis, and the contact data must be non-empty (phone accepts `phone` or `tel`; when the data is empty, input is required even if the status is truthy). There is a delay between the backend writing the verification status and `/self` reflecting it; when the machine's own `/self` call does not pass, it enters `autoVerifyWaiting` — **the machine does not poll by itself**; instead it waits for downstream to forward the `/self` results of auth's routine polling as `USER_INFO_UPDATED` (`data` is the userInfo), for at most 2 updates or 5 seconds (`AUTO_VERIFY_*` in `util/constant.js`; receiving a stale value does not reset the timer), and if still not verified → `fail`. **When downstream does not forward this event, auto-verification simply falls to `fail` after 5 seconds.** The 5 seconds is sized against auth's `tick: 2000` so that two polls can come back in time; changing `tick` requires adjusting it in lockstep.
204
-
205
203
  **Account persistence**: the most recently used login account is stored in localStorage (31-day TTL) for form auto-fill. **Token expiration does not affect the account record.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
206
204
 
207
205
  ### 2.2 Canonical Deposit Pattern
@@ -300,62 +298,29 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
300
298
 
301
299
  ### 2.6 Real-Time Communication (WebSocket)
302
300
 
303
- **Single owner**: connecting, retrying, and cleanup all live inside the closure of the `socketLifecycle` callback service invoked at the root. States such as `idle` / `fetchSocket` / `connecting` / `connected` are **display-only states for downstream**, driven by the `_SOCKET_STATUS` (`phase`) the service emits; they have no invoke and no guard of their own — to change behavior, change the service; don't add `invoke` / `after` to a state. Before switching to a new instance, the old listeners are always `off`'d and the old instance `disconnect`ed first (including an instance that never connected).
304
-
305
- **Host selection**: `selectSocket` fetches multiple hosts from `target/target.json` on GCS and hits `/ping/status` on all of them simultaneously with `Promise.any()` — the fastest responder wins; when the list can't be fetched or every host fails, it falls back to `request.config.socketURL`. **Without a token, no host is selected and no connection is created.**
301
+ **SocketTester race mechanism**: the `fetchSocket` service fetches multiple socket URLs from `/target/target.json` and pings them all simultaneously with `Promise.any()` — the fastest responder wins.
306
302
 
307
303
  ```js
308
- io(frontendURL(host), {
304
+ io(`${socketURL}/frontend`, {
309
305
  withCredentials: true,
310
306
  forceNew: true,
311
- transports: ['websocket'], // websocket only, no polling fallback
312
- auth: (done) => done({ Authorization: request.getToken() }), // callback form: reads the latest token at each (re)connect
307
+ transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
308
+ auth: { Authorization: authToken },
313
309
  })
314
310
  ```
315
311
 
316
- **The next step after a failure** is always decided by `decideNextStep` in `util/socketPolicy.js`:
317
-
318
- | Result | Trigger | Behavior |
319
- | ---------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
320
- | `socketio` | A `disconnect` not initiated by the server, or a `connect_error` while the socket is still `active` | Stay on the same instance and leave it to Socket.IO's built-in reconnect; not recovered within 120 seconds of the first loss → `exhausted` |
321
- | `retry` | Every other failure (including `io server disconnect` **before the session is ready**) | Re-select a host; at most 3 times beyond the initial attempt, 1 / 2 / 4 second exponential backoff × 0.5–1.5 jitter, with the server-provided `retryAfterMs` as the floor; budget used up → `exhausted` |
322
- | `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | Reconnect immediately once (only one allowance before becoming ready), then treated as `retry` |
323
- | `kicked` | The `kicked` event, `MAX_CONNECTIONS`, or `io server disconnect` **after the session is ready** | Stop |
324
- | `stop` | A rejection carrying `retryable: false` | Stop |
325
- | `none` | `io client disconnect` (disconnected by ourselves) | Ignored |
326
-
327
- **`io server disconnect` no longer means "reconnect"**: being disconnected by the server after the session is ready is treated as being kicked, with no automatic reconnect. After stopping, `context.blocked` decides who may resume (`canResume`): `kicked` only accepts `source: 'user'`; `exhausted` accepts user at any time and `auto` only once ≥ 15 seconds have passed since the last attempt; `stop` has to wait for a token change. A `DISCONNECT_SOCKET` without `preserveSession` clears `blocked`.
328
-
329
- **Downstream contracts** (the other end of these events and context fields lives in the downstream frontends; there is no caller inside this package):
330
-
331
- | Interface | Contract |
332
- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
333
- | `CONNECT` / `CHECK_SOCKET` | May carry `source: 'user' \| 'auto'` (default `user`), which decides whether it can resume after `blocked` |
334
- | `AUTH_CHECKED` | `{ token, uidSite }`; may only come from a successful `/self`, and `token` must equal the current `getToken()`; for the obligation after sending it once, see below |
335
- | `DISCONNECT_SOCKET` | Default = logout / destroy, clearing the session, dedupe records, and retry state; `{ preserveSession: true }` = background release, keeping all of them |
336
- | `SESSION_READY` | `{ resync, generation }`. **Readiness is based on the server's `session-ready` (or `socket.recovered === true`), not on `connect`** — `SET_CONNECTED` only means the transport is up. `resync: true` means a session was ready before and this one is a fresh, non-recovered session, so downstream must catch up via REST |
337
- | `ACTIVITY_INFO` | `{ data, eventName, generation }`; `payment-info` is **no longer limited to `windowType === 'toast'`** — any filtering is up to downstream |
338
- | `context.generation` | Incremented when the connection is invalidated, on a new attempt, and on the first loss; downstream can use it to discard REST responses from an older generation |
339
- | `context.claimPaymentEvent(event, orderData)` | GA dedupe shared by REST and socket: `true` = first time, may report; `false` = duplicate, or the current session can't be trusted. `purchase` and `first_deposit` are counted separately, and `applyId` / `transactionId` are treated as aliases of the same order; with no ID at all it returns `true` |
340
-
341
- **Once `AUTH_CHECKED` has been sent, it must be sent again after every token rotation**: when a verified session switches directly to another token, until the `AUTH_CHECKED` for the new token arrives, `CONNECT` / `CHECK_SOCKET` are only recorded and do not connect, and `claimPaymentEvent` always returns `false`; the dedupe records are restored only when the UID is the same as before. Downstreams that have never sent `AUTH_CHECKED` are unaffected.
342
-
343
- **Push dedupe**: the four push events are deduplicated before being forwarded (`createPushDedupe`) — `_meta.messageId` is preferred; without it, only `payment-info` is keyed by "business event + `applyId` / `transactionId`"; with neither, no dedupe is applied.
312
+ **Reconnect strategy**: **reconnect only when `connectError === 'io server disconnect'`** (the server actively disconnected), at most 3 times with a 2-second interval. Client-side network errors do not trigger it (they are left to Socket.IO's built-in auto-reconnect).
344
313
 
345
314
  **Event forwarding map**:
346
315
 
347
- | Socket event | State machine event |
348
- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
349
- | `activity-info` / `payment-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
350
- | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
351
- | `connect` | `SET_CONNECTED` |
352
- | `session-ready` (or `socket.recovered === true` on `connect`) | `SESSION_READY` |
353
- | `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT` (carrying `internalSocket: true`, after going through the failure decision) |
354
- | `auth-rejected` / `kicked` | Not forwarded; they only enter the failure decision |
355
-
356
- A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internalSocket`, is treated as a failure report and enters the failure decision as well.
316
+ | Socket event | State machine event |
317
+ | ---------------------------------------------- | ----------------------------------------------------------------------------------- |
318
+ | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
319
+ | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
320
+ | `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
321
+ | `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
357
322
 
358
- **First-deposit detection**: `PUSH_ANALYTICS` (only when `isTracking` is truthy) reports the original event first; if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **additionally pushed** (Facebook Pixel / conversion tracking). Both must first pass `claimPaymentEvent`, and if the token or `generation` changes while reporting, `first_deposit` is not sent.
323
+ **First-deposit detection**: while handling `PUSH_ANALYTICS`, if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **automatically pushed as well** (Facebook Pixel / conversion tracking).
359
324
 
360
325
  ### 2.7 Configuration & Live Info (Common Machine)
361
326
 
@@ -410,19 +375,19 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
410
375
 
411
376
  > Every item below exists in the code in **two competing forms** — exploring the code cannot tell you which one is the standard, so it must be written down explicitly. New code always follows the "Target" column; existing code is not proactively refactored en masse (scope discipline).
412
377
 
413
- | Item | Current state | Target |
414
- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
415
- | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
416
- | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
417
- | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
418
- | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
419
- | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
420
- | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
421
- | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around, and `util/constant.js` does not hold any of these categories yet | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
422
- | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
423
- | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
424
- | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
425
- | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
378
+ | Item | Current state | Target |
379
+ | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
380
+ | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
381
+ | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
382
+ | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
383
+ | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
384
+ | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
385
+ | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
386
+ | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around; `util/constant.js` currently holds **only** `GAME_SEARCH` / `GAME_TYPE_LIST`, two game-category constants | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
387
+ | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
388
+ | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
389
+ | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
390
+ | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
426
391
 
427
392
  ---
428
393
 
@@ -430,6 +395,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
430
395
 
431
396
  > These issues **have already been surveyed**; there is no need to re-report them in every code review. When you want to address one, open a separate ticket — don't bundle it into a feature change.
432
397
 
398
+ - **WebSocket listener leak (severity: high)** — the `listenToSocketEvents` callback service in `machine/websocket.js` registers several `.on()` listeners but **never returns a cleanup function**, so they accumulate on every reconnect. Fix: extract the handlers into named variables and return `() => clientSocket.off(event, handler)`. The `connect` / `connect_error` listeners registered inside `connectSocket`'s Promise are likewise never cleaned up. **Newly written callback services must always return a cleanup function (see the DoD).**
433
399
  - **No request caching** — high-frequency endpoints (`fetchUserInfo` every 2–10 seconds, `getConfig` on every state machine initialization, `getPaymentDetail` on every entry to a deposit/withdrawal page, `getActivityList` every 20 seconds) all hit the server directly. Consider TTL caching or `stale-while-revalidate`.
434
400
  - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
435
401
  - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
@@ -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 "You have $LOCAL_AHEAD unpushed commit(s) on '$CURRENT_BRANCH'. Skipping auto-pull."
22
+ echo "分支 '$CURRENT_BRANCH' 有 $LOCAL_AHEAD 個尚未推送的 commit,略過自動拉取。"
23
23
  exit 0
24
24
  fi
25
25
 
26
26
  # 自動從遠端拉取最新程式碼(使用 rebase 保持線性歷史)
27
- echo "Auto pulling '$CURRENT_BRANCH' from remote..."
27
+ echo "正在從遠端自動拉取 '$CURRENT_BRANCH'..."
28
28
  git pull --rebase origin "$CURRENT_BRANCH" || {
29
- echo "Failed to pull '$CURRENT_BRANCH'. Please resolve manually."
29
+ echo "拉取 '$CURRENT_BRANCH' 失敗,請手動處理。"
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 "Force push detected on $BRANCH, skipping pre-push hooks."
24
+ echo "偵測到在 $BRANCH 分支上強制推送,略過 pre-push hooks。"
25
25
  exit 0
26
26
  fi
27
27
 
package/.prettierignore CHANGED
@@ -1,2 +1 @@
1
- dist/
2
- CHANGELOG.md
1
+ dist/
package/AGENTS.md CHANGED
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
59
59
  - [ ] **Memory safety**: `setInterval` / `socket.on()` / `addEventListener` registered inside an XState callback service **must return a cleanup function** (e.g. `() => clientSocket.off(event, handler)`) to avoid accumulating listeners across reconnects; listeners registered inside a Promise must also be cleaned up after resolve / reject
60
60
  - [ ] **Token lifecycle**: token operations go through `getToken()` and the `extendToken` action, never bypass the interceptor to inject manually; prefer the existing TTL constants; when `fetchUserInfo` fails, let the session terminate naturally rather than retrying on your own
61
61
  - [ ] **Error handling**: forward through `request.errorHandler` to the error machine, with correct branches for each special code (see "Error Code System")
62
- - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the next step after a disconnect / failure is always decided by `decideNextStep` in `util/socketPolicy.js` — never write a separate reconnect condition in `websocket.js`; new listeners are always registered through `on()` in `bindSocket` (that is what gets them cleaned up and guarded against stale sessions)
62
+ - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the reconnect strategy only triggers on `'io server disconnect'`
63
63
  - [ ] **Performance impact**: avoid adding per-second self-referencing `after: { 1000 }` transitions (consider a callback + `setInterval` + computing elapsed time); don't eagerly import large dependencies at module top level; evaluate whether new high-frequency APIs need caching or backoff
64
64
  - [ ] **Consistent import paths**: cross-layer imports use relative paths (`'../../api/payment.js'`), never the `@jetthai/cuora` package name as a self-reference; lodash imports consistently omit the `.js` extension
65
65
  - [ ] **Magic numbers and strings**: activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'` / `'WITHDRAW'`, `receiveStatus` numbers, etc. should prefer the constants in `util/constant.js`
@@ -200,8 +200,6 @@ Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll aga
200
200
 
201
201
  **OTP / bind-bank flow**: after a successful login it enters `otpChecking`; `OTP_VERIFIED` or `OTP_SKIP` moves it to `bindBankChecking`, and only `BIND_BANK_DONE` or `BIND_BANK_SKIP` proceeds to `loginSuccess` (either gate accepts `LOGOUT` to abort). Whether binding is required is decided by the downstream frontend; the machine only waits — **downstream must send one of these events in `bindBankChecking`, or the session stalls there**. The `tokenAuthenticated` path skips both gates.
202
202
 
203
- **OTP auto-verification** (`auth_otp_v3.js`): when `verify` / `sendPhone` / `sendEmail` respond with `needAcknowledge === false`, the machine skips OTP input and goes to `autoVerifying`. But **`needAcknowledge: false` by itself does not count as verified** — the `phone_verification_status` / `email_verification_status` from `/self` is always the basis, and the contact data must be non-empty (phone accepts `phone` or `tel`; when the data is empty, input is required even if the status is truthy). There is a delay between the backend writing the verification status and `/self` reflecting it; when the machine's own `/self` call does not pass, it enters `autoVerifyWaiting` — **the machine does not poll by itself**; instead it waits for downstream to forward the `/self` results of auth's routine polling as `USER_INFO_UPDATED` (`data` is the userInfo), for at most 2 updates or 5 seconds (`AUTO_VERIFY_*` in `util/constant.js`; receiving a stale value does not reset the timer), and if still not verified → `fail`. **When downstream does not forward this event, auto-verification simply falls to `fail` after 5 seconds.** The 5 seconds is sized against auth's `tick: 2000` so that two polls can come back in time; changing `tick` requires adjusting it in lockstep.
204
-
205
203
  **Account persistence**: the most recently used login account is stored in localStorage (31-day TTL) for form auto-fill. **Token expiration does not affect the account record.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
206
204
 
207
205
  ### 2.2 Canonical Deposit Pattern
@@ -300,62 +298,29 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
300
298
 
301
299
  ### 2.6 Real-Time Communication (WebSocket)
302
300
 
303
- **Single owner**: connecting, retrying, and cleanup all live inside the closure of the `socketLifecycle` callback service invoked at the root. States such as `idle` / `fetchSocket` / `connecting` / `connected` are **display-only states for downstream**, driven by the `_SOCKET_STATUS` (`phase`) the service emits; they have no invoke and no guard of their own — to change behavior, change the service; don't add `invoke` / `after` to a state. Before switching to a new instance, the old listeners are always `off`'d and the old instance `disconnect`ed first (including an instance that never connected).
304
-
305
- **Host selection**: `selectSocket` fetches multiple hosts from `target/target.json` on GCS and hits `/ping/status` on all of them simultaneously with `Promise.any()` — the fastest responder wins; when the list can't be fetched or every host fails, it falls back to `request.config.socketURL`. **Without a token, no host is selected and no connection is created.**
301
+ **SocketTester race mechanism**: the `fetchSocket` service fetches multiple socket URLs from `/target/target.json` and pings them all simultaneously with `Promise.any()` — the fastest responder wins.
306
302
 
307
303
  ```js
308
- io(frontendURL(host), {
304
+ io(`${socketURL}/frontend`, {
309
305
  withCredentials: true,
310
306
  forceNew: true,
311
- transports: ['websocket'], // websocket only, no polling fallback
312
- auth: (done) => done({ Authorization: request.getToken() }), // callback form: reads the latest token at each (re)connect
307
+ transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
308
+ auth: { Authorization: authToken },
313
309
  })
314
310
  ```
315
311
 
316
- **The next step after a failure** is always decided by `decideNextStep` in `util/socketPolicy.js`:
317
-
318
- | Result | Trigger | Behavior |
319
- | ---------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
320
- | `socketio` | A `disconnect` not initiated by the server, or a `connect_error` while the socket is still `active` | Stay on the same instance and leave it to Socket.IO's built-in reconnect; not recovered within 120 seconds of the first loss → `exhausted` |
321
- | `retry` | Every other failure (including `io server disconnect` **before the session is ready**) | Re-select a host; at most 3 times beyond the initial attempt, 1 / 2 / 4 second exponential backoff × 0.5–1.5 jitter, with the server-provided `retryAfterMs` as the floor; budget used up → `exhausted` |
322
- | `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | Reconnect immediately once (only one allowance before becoming ready), then treated as `retry` |
323
- | `kicked` | The `kicked` event, `MAX_CONNECTIONS`, or `io server disconnect` **after the session is ready** | Stop |
324
- | `stop` | A rejection carrying `retryable: false` | Stop |
325
- | `none` | `io client disconnect` (disconnected by ourselves) | Ignored |
326
-
327
- **`io server disconnect` no longer means "reconnect"**: being disconnected by the server after the session is ready is treated as being kicked, with no automatic reconnect. After stopping, `context.blocked` decides who may resume (`canResume`): `kicked` only accepts `source: 'user'`; `exhausted` accepts user at any time and `auto` only once ≥ 15 seconds have passed since the last attempt; `stop` has to wait for a token change. A `DISCONNECT_SOCKET` without `preserveSession` clears `blocked`.
328
-
329
- **Downstream contracts** (the other end of these events and context fields lives in the downstream frontends; there is no caller inside this package):
330
-
331
- | Interface | Contract |
332
- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
333
- | `CONNECT` / `CHECK_SOCKET` | May carry `source: 'user' \| 'auto'` (default `user`), which decides whether it can resume after `blocked` |
334
- | `AUTH_CHECKED` | `{ token, uidSite }`; may only come from a successful `/self`, and `token` must equal the current `getToken()`; for the obligation after sending it once, see below |
335
- | `DISCONNECT_SOCKET` | Default = logout / destroy, clearing the session, dedupe records, and retry state; `{ preserveSession: true }` = background release, keeping all of them |
336
- | `SESSION_READY` | `{ resync, generation }`. **Readiness is based on the server's `session-ready` (or `socket.recovered === true`), not on `connect`** — `SET_CONNECTED` only means the transport is up. `resync: true` means a session was ready before and this one is a fresh, non-recovered session, so downstream must catch up via REST |
337
- | `ACTIVITY_INFO` | `{ data, eventName, generation }`; `payment-info` is **no longer limited to `windowType === 'toast'`** — any filtering is up to downstream |
338
- | `context.generation` | Incremented when the connection is invalidated, on a new attempt, and on the first loss; downstream can use it to discard REST responses from an older generation |
339
- | `context.claimPaymentEvent(event, orderData)` | GA dedupe shared by REST and socket: `true` = first time, may report; `false` = duplicate, or the current session can't be trusted. `purchase` and `first_deposit` are counted separately, and `applyId` / `transactionId` are treated as aliases of the same order; with no ID at all it returns `true` |
340
-
341
- **Once `AUTH_CHECKED` has been sent, it must be sent again after every token rotation**: when a verified session switches directly to another token, until the `AUTH_CHECKED` for the new token arrives, `CONNECT` / `CHECK_SOCKET` are only recorded and do not connect, and `claimPaymentEvent` always returns `false`; the dedupe records are restored only when the UID is the same as before. Downstreams that have never sent `AUTH_CHECKED` are unaffected.
342
-
343
- **Push dedupe**: the four push events are deduplicated before being forwarded (`createPushDedupe`) — `_meta.messageId` is preferred; without it, only `payment-info` is keyed by "business event + `applyId` / `transactionId`"; with neither, no dedupe is applied.
312
+ **Reconnect strategy**: **reconnect only when `connectError === 'io server disconnect'`** (the server actively disconnected), at most 3 times with a 2-second interval. Client-side network errors do not trigger it (they are left to Socket.IO's built-in auto-reconnect).
344
313
 
345
314
  **Event forwarding map**:
346
315
 
347
- | Socket event | State machine event |
348
- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
349
- | `activity-info` / `payment-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
350
- | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
351
- | `connect` | `SET_CONNECTED` |
352
- | `session-ready` (or `socket.recovered === true` on `connect`) | `SESSION_READY` |
353
- | `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT` (carrying `internalSocket: true`, after going through the failure decision) |
354
- | `auth-rejected` / `kicked` | Not forwarded; they only enter the failure decision |
355
-
356
- A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internalSocket`, is treated as a failure report and enters the failure decision as well.
316
+ | Socket event | State machine event |
317
+ | ---------------------------------------------- | ----------------------------------------------------------------------------------- |
318
+ | `activity-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
319
+ | `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
320
+ | `payment-info` | Conditional: sends `ACTIVITY_INFO` + `PUSH_ANALYTICS` when `windowType === 'toast'` |
321
+ | `connect` / `connect_error` / `disconnect` | `SET_CONNECTED` / `CONNECT_ERROR` / `DISCONNECT` |
357
322
 
358
- **First-deposit detection**: `PUSH_ANALYTICS` (only when `isTracking` is truthy) reports the original event first; if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **additionally pushed** (Facebook Pixel / conversion tracking). Both must first pass `claimPaymentEvent`, and if the token or `generation` changes while reporting, `first_deposit` is not sent.
323
+ **First-deposit detection**: while handling `PUSH_ANALYTICS`, if `event === 'purchase'` and `data.isFirst === true`, a `first_deposit` event is **automatically pushed as well** (Facebook Pixel / conversion tracking).
359
324
 
360
325
  ### 2.7 Configuration & Live Info (Common Machine)
361
326
 
@@ -410,19 +375,19 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
410
375
 
411
376
  > Every item below exists in the code in **two competing forms** — exploring the code cannot tell you which one is the standard, so it must be written down explicitly. New code always follows the "Target" column; existing code is not proactively refactored en masse (scope discipline).
412
377
 
413
- | Item | Current state | Target |
414
- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
415
- | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
416
- | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
417
- | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
418
- | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
419
- | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
420
- | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
421
- | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around, and `util/constant.js` does not hold any of these categories yet | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
422
- | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
423
- | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
424
- | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
425
- | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
378
+ | Item | Current state | Target |
379
+ | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
380
+ | HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected) | Consistently lowercase `'get'`/`'post'`/`'put'`/`'delete'` |
381
+ | Import paths | Some files self-reference via the `@jetthai/cuora` package name | Consistently relative paths (`'../../api/payment.js'`) |
382
+ | lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist | Consistently **without** the extension |
383
+ | URL leading slash | A few APIs carry a leading slash | Omit it (unless deliberately bypassing `url-join`, in which case comment the reason) |
384
+ | Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization | Always use the `params` field |
385
+ | Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably | By semantics: `idle` (awaiting action), `loading` (initial load), `fetching` (re-fetch), `submitting` / `submitted` |
386
+ | Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around; `util/constant.js` currently holds **only** `GAME_SEARCH` / `GAME_TYPE_LIST`, two game-category constants | Centralize in `util/constant.js` (`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
387
+ | Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry | `onError` with `actions: 'setError'` to preserve the error in context; distinguish recoverable from unrecoverable; retries must have a cap |
388
+ | Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear | Concrete names (`gameCode`) |
389
+ | Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL) | Validate at the system boundary: path parameters non-undefined and free of path-traversal characters, amounts positive |
390
+ | Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment | Add `@deprecated` first, then remove once confirmed unreferenced |
426
391
 
427
392
  ---
428
393
 
@@ -430,6 +395,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
430
395
 
431
396
  > These issues **have already been surveyed**; there is no need to re-report them in every code review. When you want to address one, open a separate ticket — don't bundle it into a feature change.
432
397
 
398
+ - **WebSocket listener leak (severity: high)** — the `listenToSocketEvents` callback service in `machine/websocket.js` registers several `.on()` listeners but **never returns a cleanup function**, so they accumulate on every reconnect. Fix: extract the handlers into named variables and return `() => clientSocket.off(event, handler)`. The `connect` / `connect_error` listeners registered inside `connectSocket`'s Promise are likewise never cleaned up. **Newly written callback services must always return a cleanup function (see the DoD).**
433
399
  - **No request caching** — high-frequency endpoints (`fetchUserInfo` every 2–10 seconds, `getConfig` on every state machine initialization, `getPaymentDetail` on every entry to a deposit/withdrawal page, `getActivityList` every 20 seconds) all hit the server directly. Consider TTL caching or `stale-while-revalidate`.
434
400
  - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
435
401
  - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.