@jetthai/cuora 1.1.485 → 1.1.487-otp.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/.github/copilot-instructions.md +61 -27
  2. package/AGENTS.md +61 -27
  3. package/AI_PROMPT_SOURCE.md +61 -27
  4. package/CHANGELOG.md +14 -0
  5. package/CLAUDE.md +61 -27
  6. package/GEMINI.md +61 -27
  7. package/e2e/feature-map.md +19 -0
  8. package/package.json +3 -3
  9. package/prepare-for-pr/JT-1776243420.md +85 -0
  10. package/prepare-for-pr/TI-16026/STATE.md +18 -0
  11. package/prepare-for-pr/TI-16026/after-prepare-authorization.md +3 -0
  12. package/prepare-for-pr/TI-16026/analysis.md +38 -0
  13. package/prepare-for-pr/TI-16026/answer-analyze-01.md +1 -0
  14. package/prepare-for-pr/TI-16026/answer-commit-01.md +2 -0
  15. package/prepare-for-pr/TI-16026/answer-commit-02.md +1 -0
  16. package/prepare-for-pr/TI-16026/bundle.json +18 -0
  17. package/prepare-for-pr/TI-16026/checklist.md +196 -0
  18. package/prepare-for-pr/TI-16026/checklist.unit-test-original.md +39 -0
  19. package/prepare-for-pr/TI-16026/claude-after-model +1 -0
  20. package/prepare-for-pr/TI-16026/claude-commit-session +1 -0
  21. package/prepare-for-pr/TI-16026/claude-harvest-session +1 -0
  22. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.err +1 -0
  23. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.out +2 -0
  24. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.err +1 -0
  25. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.out +4 -0
  26. package/prepare-for-pr/TI-16026/claude-hops/03-dev.err +1 -0
  27. package/prepare-for-pr/TI-16026/claude-hops/03-dev.out +4 -0
  28. package/prepare-for-pr/TI-16026/claude-hops/04-dev.err +1 -0
  29. package/prepare-for-pr/TI-16026/claude-hops/04-dev.out +4 -0
  30. package/prepare-for-pr/TI-16026/claude-hops/05-dev.err +1 -0
  31. package/prepare-for-pr/TI-16026/claude-hops/05-dev.out +3 -0
  32. package/prepare-for-pr/TI-16026/claude-hops/06-after.err +1 -0
  33. package/prepare-for-pr/TI-16026/claude-hops/06-after.out +2 -0
  34. package/prepare-for-pr/TI-16026/claude-hops/07-commit.err +1 -0
  35. package/prepare-for-pr/TI-16026/claude-hops/07-commit.out +2 -0
  36. package/prepare-for-pr/TI-16026/claude-hops/08-commit.err +1 -0
  37. package/prepare-for-pr/TI-16026/claude-hops/08-commit.out +2 -0
  38. package/prepare-for-pr/TI-16026/claude-hops/09-commit.err +1 -0
  39. package/prepare-for-pr/TI-16026/claude-hops/09-commit.out +8 -0
  40. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.err +1 -0
  41. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.out +3 -0
  42. package/prepare-for-pr/TI-16026/claude-hops/11-harvest.err +1 -0
  43. package/prepare-for-pr/TI-16026/claude-hops/11-harvest.out +3 -0
  44. package/prepare-for-pr/TI-16026/commit-note.md +5 -0
  45. package/prepare-for-pr/TI-16026/evidence-index.json +215 -0
  46. package/prepare-for-pr/TI-16026/feature-map.before.md +61 -0
  47. package/prepare-for-pr/TI-16026/harvest-redaction.json +34 -0
  48. package/prepare-for-pr/TI-16026/harvest-redaction.out +37 -0
  49. package/prepare-for-pr/TI-16026/harvest.md +46 -0
  50. package/prepare-for-pr/TI-16026/lessons.md +5 -0
  51. package/prepare-for-pr/TI-16026/note-harvest-redaction.md +1 -0
  52. package/prepare-for-pr/TI-16026/open-questions.md +6 -0
  53. package/prepare-for-pr/TI-16026/publish.md +32 -0
  54. package/prepare-for-pr/TI-16026/review-convergence-response.md +3 -0
  55. package/prepare-for-pr/TI-16026/review-input/scope.md +18 -0
  56. package/prepare-for-pr/TI-16026/review-log.md +57 -0
  57. package/prepare-for-pr/TI-16026/review-notes.md +97 -0
  58. package/prepare-for-pr/TI-16026/review-response-r1.md +7 -0
  59. package/prepare-for-pr/TI-16026/self-test-report.md +67 -0
  60. package/prepare-for-pr/TI-16026/spec-proposal.md +34 -0
  61. package/prepare-for-pr/TI-16026/spec-snapshot.md +291 -0
  62. package/prepare-for-pr/TI-16026/state-log.md +57 -0
  63. package/prepare-for-pr/TI-16026/user-messages/01.md +12 -0
  64. package/prepare-for-pr/TI-16026/user-messages/02.md +20 -0
  65. package/prepare-for-pr/TI-16026/user-messages/03.md +1 -0
  66. package/prepare-for-pr/TI-16026/user-messages/04.md +1 -0
  67. package/prepare-for-pr/TI-16026/user-messages/05.md +1 -0
  68. package/prepare-for-pr/TI-16026/user-messages/06.md +1 -0
  69. package/prepare-for-pr/TI-16026/user-messages/07.md +1 -0
  70. package/prepare-for-pr/TI-16026/user-messages/08.md +1 -0
  71. package/prepare-for-pr/TI-16026/user-messages/09.md +1 -0
  72. package/prepare-for-pr/TI-16026/user-messages/10.md +1 -0
  73. package/prepare-for-pr/TI-16026/user-messages/11.md +1 -0
  74. package/prepare-for-pr/TI-16026/user-messages/12.md +1 -0
  75. package/prepare-for-pr/TI-16026/user-messages/13.md +1 -0
  76. package/prepare-for-pr/TI-16026/user-messages/14.md +1 -0
  77. package/prepare-for-pr/TI-16026/user-messages/15.md +1 -0
  78. package/prepare-for-pr/TI-16026/user-messages/16.md +1 -0
  79. package/prepare-for-pr/TI-16026/user-messages/17.md +1 -0
  80. package/prepare-for-pr/TI-16026/user-messages/18.md +10 -0
  81. package/prepare-for-pr/TI-16026/user-messages/19.md +1 -0
  82. package/prepare-for-pr/TI-16026/user-messages/20.md +1 -0
  83. package/prepare-for-pr/TI-16026/user-messages/21.md +1 -0
  84. package/prepare-for-pr/TI-16026/user-messages/22.md +1 -0
  85. package/prepare-for-pr/TI-16026/user-messages/23.md +8 -0
  86. package/prepare-for-pr/TI-16026/user-messages/24.md +24 -0
  87. package/prepare-for-pr/TI-16026/user-question.md +24 -0
  88. package/prepare-for-pr/TI-16026/verify/metrics-check.json +13 -0
  89. package/prepare-for-pr/TI-16026/verify/redaction.json +38 -0
  90. package/prepare-for-pr/TI-16026/verify/row-closure.json +45 -0
  91. package/prepare-for-pr/TI-16026/verify/s04-ws-capture.md +23 -0
  92. package/prepare-for-pr/TI-16026/verify-after.md +23 -0
  93. package/prepare-for-pr/TI-16026/verify.json +80 -0
  94. package/prepare-for-pr/TI-16026.md +408 -0
  95. package/src/machine/withdraw/withdraw_manual_cash.js +10 -3
  96. package/src/util/constant.js +2 -1
package/CLAUDE.md CHANGED
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
59
59
  - [ ] **Memory safety**: `setInterval` / `socket.on()` / `addEventListener` registered inside an XState callback service **must return a cleanup function** (e.g. `() => clientSocket.off(event, handler)`) to avoid accumulating listeners across reconnects; listeners registered inside a Promise must also be cleaned up after resolve / reject
60
60
  - [ ] **Token lifecycle**: token operations go through `getToken()` and the `extendToken` action, never bypass the interceptor to inject manually; prefer the existing TTL constants; when `fetchUserInfo` fails, let the session terminate naturally rather than retrying on your own
61
61
  - [ ] **Error handling**: forward through `request.errorHandler` to the error machine, with correct branches for each special code (see "Error Code System")
62
- - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the reconnect strategy only triggers on `'io server disconnect'`
62
+ - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the next step after a disconnect / failure is always decided by `decideNextStep` in `util/socketPolicy.js` — never write a separate reconnect condition in `websocket.js`; new listeners are always registered through `on()` in `bindSocket` (that is what gets them cleaned up and guarded against stale sessions)
63
63
  - [ ] **Performance impact**: avoid adding per-second self-referencing `after: { 1000 }` transitions (consider a callback + `setInterval` + computing elapsed time); don't eagerly import large dependencies at module top level; evaluate whether new high-frequency APIs need caching or backoff
64
64
  - [ ] **Consistent import paths**: cross-layer imports use relative paths (`'../../api/payment.js'`), never the `@jetthai/cuora` package name as a self-reference; lodash imports consistently omit the `.js` extension
65
65
  - [ ] **Magic numbers and strings**: activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'` / `'WITHDRAW'`, `receiveStatus` numbers, etc. should prefer the constants in `util/constant.js`
@@ -200,6 +200,8 @@ 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
+
203
205
  **Account persistence**: the most recently used login account is stored in localStorage (31-day TTL) for form auto-fill. **Token expiration does not affect the account record.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
204
206
 
205
207
  ### 2.2 Canonical Deposit Pattern
@@ -298,29 +300,62 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
298
300
 
299
301
  ### 2.6 Real-Time Communication (WebSocket)
300
302
 
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.
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.**
302
306
 
303
307
  ```js
304
- io(`${socketURL}/frontend`, {
308
+ io(frontendURL(host), {
305
309
  withCredentials: true,
306
310
  forceNew: true,
307
- transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
308
- auth: { Authorization: authToken },
311
+ transports: ['websocket'], // websocket only, no polling fallback
312
+ auth: (done) => done({ Authorization: request.getToken() }), // callback form: reads the latest token at each (re)connect
309
313
  })
310
314
  ```
311
315
 
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).
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.
313
344
 
314
345
  **Event forwarding map**:
315
346
 
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` |
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.
322
357
 
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).
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.
324
359
 
325
360
  ### 2.7 Configuration & Live Info (Common Machine)
326
361
 
@@ -375,19 +410,19 @@ io(`${socketURL}/frontend`, {
375
410
 
376
411
  > Every item below exists in the code in **two competing forms** — exploring the code cannot tell you which one is the standard, so it must be written down explicitly. New code always follows the "Target" column; existing code is not proactively refactored en masse (scope discipline).
377
412
 
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 |
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 |
391
426
 
392
427
  ---
393
428
 
@@ -395,7 +430,6 @@ io(`${socketURL}/frontend`, {
395
430
 
396
431
  > These issues **have already been surveyed**; there is no need to re-report them in every code review. When you want to address one, open a separate ticket — don't bundle it into a feature change.
397
432
 
398
- - **WebSocket listener leak (severity: high)** — the `listenToSocketEvents` callback service in `machine/websocket.js` registers several `.on()` listeners but **never returns a cleanup function**, so they accumulate on every reconnect. Fix: extract the handlers into named variables and return `() => clientSocket.off(event, handler)`. The `connect` / `connect_error` listeners registered inside `connectSocket`'s Promise are likewise never cleaned up. **Newly written callback services must always return a cleanup function (see the DoD).**
399
433
  - **No request caching** — high-frequency endpoints (`fetchUserInfo` every 2–10 seconds, `getConfig` on every state machine initialization, `getPaymentDetail` on every entry to a deposit/withdrawal page, `getActivityList` every 20 seconds) all hit the server directly. Consider TTL caching or `stale-while-revalidate`.
400
434
  - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
401
435
  - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
package/GEMINI.md CHANGED
@@ -59,7 +59,7 @@ Before delivering any code change, verify each of the following yourself:
59
59
  - [ ] **Memory safety**: `setInterval` / `socket.on()` / `addEventListener` registered inside an XState callback service **must return a cleanup function** (e.g. `() => clientSocket.off(event, handler)`) to avoid accumulating listeners across reconnects; listeners registered inside a Promise must also be cleaned up after resolve / reject
60
60
  - [ ] **Token lifecycle**: token operations go through `getToken()` and the `extendToken` action, never bypass the interceptor to inject manually; prefer the existing TTL constants; when `fetchUserInfo` fails, let the session terminate naturally rather than retrying on your own
61
61
  - [ ] **Error handling**: forward through `request.errorHandler` to the error machine, with correct branches for each special code (see "Error Code System")
62
- - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the reconnect strategy only triggers on `'io server disconnect'`
62
+ - [ ] **WebSocket event routing**: forward new events per the existing mapping; first-deposit events additionally push `first_deposit`; the next step after a disconnect / failure is always decided by `decideNextStep` in `util/socketPolicy.js` — never write a separate reconnect condition in `websocket.js`; new listeners are always registered through `on()` in `bindSocket` (that is what gets them cleaned up and guarded against stale sessions)
63
63
  - [ ] **Performance impact**: avoid adding per-second self-referencing `after: { 1000 }` transitions (consider a callback + `setInterval` + computing elapsed time); don't eagerly import large dependencies at module top level; evaluate whether new high-frequency APIs need caching or backoff
64
64
  - [ ] **Consistent import paths**: cross-layer imports use relative paths (`'../../api/payment.js'`), never the `@jetthai/cuora` package name as a self-reference; lodash imports consistently omit the `.js` extension
65
65
  - [ ] **Magic numbers and strings**: activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'` / `'WITHDRAW'`, `receiveStatus` numbers, etc. should prefer the constants in `util/constant.js`
@@ -200,6 +200,8 @@ 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
+
203
205
  **Account persistence**: the most recently used login account is stored in localStorage (31-day TTL) for form auto-fill. **Token expiration does not affect the account record.** However, `pruneRememberedAccounts`, which runs after `fetchSiteConfig` succeeds, **compares against `siteConfig.loginMethods` and clears the leftover account for any disabled login method** (`phone` clears the country code along with it) — fetching configuration, an apparently read-only action, carries the side effect of deleting from localStorage. The purpose is to prevent downstream frontends from back-filling a stale value into an input whose type has since changed after the backend disables a login method. When `loginMethods` is missing entirely, nothing is cleared, to avoid wiping everything by mistake.
204
206
 
205
207
  ### 2.2 Canonical Deposit Pattern
@@ -298,29 +300,62 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
298
300
 
299
301
  ### 2.6 Real-Time Communication (WebSocket)
300
302
 
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.
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.**
302
306
 
303
307
  ```js
304
- io(`${socketURL}/frontend`, {
308
+ io(frontendURL(host), {
305
309
  withCredentials: true,
306
310
  forceNew: true,
307
- transports: ['websocket', 'polling'], // WebSocket preferred, polling as fallback
308
- auth: { Authorization: authToken },
311
+ transports: ['websocket'], // websocket only, no polling fallback
312
+ auth: (done) => done({ Authorization: request.getToken() }), // callback form: reads the latest token at each (re)connect
309
313
  })
310
314
  ```
311
315
 
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).
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.
313
344
 
314
345
  **Event forwarding map**:
315
346
 
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` |
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.
322
357
 
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).
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.
324
359
 
325
360
  ### 2.7 Configuration & Live Info (Common Machine)
326
361
 
@@ -375,19 +410,19 @@ io(`${socketURL}/frontend`, {
375
410
 
376
411
  > Every item below exists in the code in **two competing forms** — exploring the code cannot tell you which one is the standard, so it must be written down explicitly. New code always follows the "Target" column; existing code is not proactively refactored en masse (scope discipline).
377
412
 
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 |
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 |
391
426
 
392
427
  ---
393
428
 
@@ -395,7 +430,6 @@ io(`${socketURL}/frontend`, {
395
430
 
396
431
  > These issues **have already been surveyed**; there is no need to re-report them in every code review. When you want to address one, open a separate ticket — don't bundle it into a feature change.
397
432
 
398
- - **WebSocket listener leak (severity: high)** — the `listenToSocketEvents` callback service in `machine/websocket.js` registers several `.on()` listeners but **never returns a cleanup function**, so they accumulate on every reconnect. Fix: extract the handlers into named variables and return `() => clientSocket.off(event, handler)`. The `connect` / `connect_error` listeners registered inside `connectSocket`'s Promise are likewise never cleaned up. **Newly written callback services must always return a cleanup function (see the DoD).**
399
433
  - **No request caching** — high-frequency endpoints (`fetchUserInfo` every 2–10 seconds, `getConfig` on every state machine initialization, `getPaymentDetail` on every entry to a deposit/withdrawal page, `getActivityList` every 20 seconds) all hit the server directly. Consider TTL caching or `stale-while-revalidate`.
400
434
  - **No rate limiting or backoff** — polling runs at a fixed interval and does not change on errors. Consider exponential backoff on errors.
401
435
  - **No automatic token refresh** — the response interceptor in `request.js` does not handle 401, so an expired token simply fails.
@@ -0,0 +1,19 @@
1
+ # Feature map — cuora-module
2
+
3
+ Hints, not facts: verify any line you rely on with this task's own check.
4
+ Each line ends with (observed YYYY-MM-DD <TASK-id>) = the last task that confirmed it.
5
+
6
+ ## Repo-wide
7
+
8
+ - SDK with no UI and no `e2e/review-playbook.md`: no browser captures; evidence is `node --test test/*.test.js` (no `test` script in `package.json`) plus code review (observed 2026-11-17 TI-16026)
9
+ - Commit hook runs `npm run format` (`prettier --write .`) even with `HUSKY=0`, so ignored `prepare-for-pr/` files (review reports included) get reformatted → re-check a protected report before relying on it (observed 2026-11-17 TI-16026)
10
+ - Claude's `Bash(git commit:*)` allow pattern does not match an env-prefixed `HUSKY=0 git commit` → allow the prefixed form explicitly (observed 2026-11-17 TI-16026)
11
+ - `NPM_TOKEN_WRITE` set but `npm whoami` returned E401 → run `npm whoami` before starting a release flow (observed 2026-11-17 TI-16026)
12
+
13
+ ## withdraw_manual_cash machine
14
+
15
+ - Entry: `src/machine/withdraw/withdraw_manual_cash.js`; unit test pattern in `test/auth_otp_v3.test.js` (`node:test`, `interpret`, stubbed `request.send` keyed by `descriptor.url`) (observed 2026-11-17 TI-16026)
16
+ - Preconditions: context `doubleWalletWithdrawLimitCheck: '0'` and a `paymentDetail` entry `{ category: 'manual', transferType: 'withdraw', minimum, maximum, method }`; stub URLs come from `src/api/payment.js` (observed 2026-11-17 TI-16026)
17
+ - Selectors: `loading.onError` — `src/machine/withdraw/withdraw_manual_cash.js:40`; `submitted.on.REFRESH` — `:100`; root `REFRESH` with `hasNoBank` — `:159` (observed 2026-11-17 TI-16026)
18
+ - States: `submitted` with a pending order is reached via `loading` → `checking` → `isProcessing` guard; REFRESH there is unconditional because the state-level handler wins over the root one (observed 2026-11-17 TI-16026)
19
+ - Gotchas: a failed REFRESH inside `submitted` must return to `submitted` (guard `isProcessing`), not `loaded`, or the user leaves Pending; `setInitData` resets `selectedUserBank` to `userBanks[0]` and leaves OTP fields stale (observed 2026-11-17 TI-16026)
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@jetthai/cuora",
3
- "version": "1.1.485",
3
+ "version": "1.1.487-otp.0",
4
4
  "description": "",
5
5
  "main": "./src/index.js",
6
6
  "type": "module",
7
7
  "scripts": {
8
- "release": "standard-version && git push --follow-tags origin master && npm publish",
9
- "release:latest": "standard-version && git push --follow-tags origin master && npm publish && npm dist-tag add @jetthai/cuora@$(node -p \"require('./package.json').version\") latest",
8
+ "release": "standard-version && git push --follow-tags origin master && npm publish --tag latest",
9
+ "release:latest": "standard-version && git push --follow-tags origin master && npm publish --tag latest && npm dist-tag add @jetthai/cuora@$(node -p \"require('./package.json').version\") latest",
10
10
  "release:dev": "node scripts/branch-auto-npm-publish.js",
11
11
  "release:qa": "node scripts/branch-auto-npm-publish.js",
12
12
  "format": "prettier --write .",
@@ -0,0 +1,85 @@
1
+ # JT-1776243420: Third-Party Register Carry Phone / Email Payload
2
+
3
+ ## Key Changes
4
+
5
+ 1. Extended third-party redirect payload assembly to read `tp_phone`, `tp_countryCode`, and `tp_email` from storage.
6
+ 2. Preserved existing affiliate code / nickname behavior and appended new fields only when values are valid.
7
+ 3. Cleans the temporary third-party storage keys after composing the redirect query.
8
+
9
+ ---
10
+
11
+ ## Key Findings
12
+
13
+ ### Strengths
14
+
15
+ 1. The change is tightly scoped to the third-party auth redirect builder in `src/machine/auth.js:477-520`.
16
+ 2. Existing affiliate code and nickname logic remains unchanged while phone / email are additive only.
17
+ 3. Temporary keys are removed after payload composition, reducing leakage into later unrelated auth flows.
18
+
19
+ ---
20
+
21
+ ### Behavior Observed
22
+
23
+ 1. Static review confirms `phone`, `countryCode`, and `email` are appended only when storage values are not `undefined` / `null`.
24
+ 2. Channel and subchannel fallback logic stays intact after the new fields are added.
25
+ 3. No unrelated file changes were present in this repo for the review scope.
26
+
27
+ ---
28
+
29
+ ## 🔧 Change Type
30
+
31
+ - [ ] 🐛 Bug fix
32
+ - [x] ✨ New feature
33
+ - [ ] 💄 Style
34
+ - [ ] ♻️ Refactor
35
+ - [ ] ⚡ Performance
36
+ - [ ] 🔧 Chore
37
+
38
+ ---
39
+
40
+ ## 📱 Impact Scope
41
+
42
+ - Third-party register / login redirect query assembly in cuora shared auth machine.
43
+ - Downstream PWA clients that store `tp_phone`, `tp_countryCode`, and `tp_email` before `LOGIN_3PARTY`.
44
+
45
+ ---
46
+
47
+ ## Test Completion Status
48
+
49
+ | Item | Validation Tested | Status |
50
+ | -------------------------- | --------------------------------------------------------------------- | ------- |
51
+ | Diff hygiene | `git diff --check` in `cuora-module` | PASS |
52
+ | Shared auth payload review | Reviewed `src/machine/auth.js:477-520` against ticket intent | PASS |
53
+ | Runtime redirect execution | Not run in this repo directly; validated through client repos instead | NOT RUN |
54
+
55
+ ---
56
+
57
+ ## 📋 Spec Validation (Aligned with review-playbook)
58
+
59
+ | Spec Item | Evidence (File/Line/Result) | Status |
60
+ | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------ |
61
+ | Third-party flow can carry phone when client stored it | `src/machine/auth.js:479-520` reads `tp_phone` / `tp_countryCode` and appends them to `referralObj` | PASS |
62
+ | Third-party flow can carry email when client stored it | `src/machine/auth.js:481-520` reads `tp_email` and appends it to `referralObj` | PASS |
63
+ | Affiliate code and nickname keep original logic | `src/machine/auth.js:477-500` keeps `ac` / `nick_name` handling unchanged | PASS |
64
+ | Temporary third-party data does not leak into later unrelated flows | `src/machine/auth.js:518-520` removes the temporary storage keys after composing the redirect URL | PASS |
65
+
66
+ ---
67
+
68
+ ## 📋 Standards Checklist (Summary)
69
+
70
+ | Category | Result | Notes |
71
+ | ---------------------- | ------- | --------------------------------------------------------------------------- |
72
+ | Memory Safety | PASS | Simple storage reads and object assembly only. |
73
+ | Rendering Performance | PASS | No rendering code touched. |
74
+ | Network Requests | PASS | Existing redirect flow only; no extra requests added. |
75
+ | Bundle Optimization | PASS | No new imports or heavy logic added. |
76
+ | Code Quality | PASS | Scope is narrow and branch contains only the required file change. |
77
+ | Vue / Nuxt Standards | NOT RUN | Shared module; not a Vue / Nuxt surface. |
78
+ | SSR Security Standards | PASS | Query parameters are assembled from existing client-side storage path only. |
79
+ | Project Conventions | PASS | Matches existing storage-guard pattern used for affiliate / nickname. |
80
+
81
+ ## Conclusion
82
+
83
+ This repo’s shared auth-machine change matches the ticket intent and is internally consistent. Runtime behavior was not executed in `cuora-module` directly, but both client repos now pass the new storage keys into this shared payload path.
84
+
85
+ **Overall Result:** PASS (PARTIAL)
@@ -0,0 +1,18 @@
1
+ phase: done
2
+ caller: codex
3
+ round: none
4
+ pendingCaptureIds: none
5
+ deliveryRef: null
6
+ guardHash: status=" M src/machine/withdraw/withdraw_manual_cash.js | ?? test/withdraw_manual_cash.test.js"; tracked diff sha256=013984d028fdf138d1240c9fc4d4ba247a310d8c0595ef2c1da759ea44720c09; untracked test/withdraw_manual_cash.test.js sha256=fecacc81d718bc118f791d125768c0ee0204d89b9d3762d0ca15c45725c29268
7
+ claudeSessions: analyze=94FC61FD-8DD5-41F5-B1F5-C3E6C55E71A9 before=none dev=00904264-E71A-4E07-8723-3F15A8D7B64C after=FC2E4263-D2A2-4BCF-8BE7-EDDA430DA18F
8
+ blockedOn: none
9
+ updatedAt: 2026-11-18T17:22:00+08:00
10
+
11
+ ## Current
12
+
13
+ - Committed 219a415070e8c9ee23615b60a9942d6c4dc1b02c on feat/stone/JT-1791856380-ws-refresh: `src/machine/withdraw/withdraw_manual_cash.js` + `test/withdraw_manual_cash.test.js` only (2 files, +156/-4). `git status --porcelain` clean after the commit.
14
+ - Hook finding: with `HUSKY=0` the pre-commit hook still ran `npm run format` (`prettier --write .`), so the globally ignored files under `prepare-for-pr/` (including the protected review report `prepare-for-pr/TI-16026.md` and `prepare-for-pr/JT-1776243420.md`) were probably rewritten by prettier. Content changes, if any, are formatting only; Codex should check the review report before relying on it.
15
+ - Harvest completed successfully on 2026-11-18 (`NEXT: harvested`). The wrapper redaction check passed using a temporary ignored symlink to the existing client-pwa-cash test-account config; the symlink was removed immediately after the hop. The current `e2e/feature-map.md` contains the harvested repo knowledge. The user declined the shared call-claude permission-pattern proposal; recorded verbatim in `harvest.md`, and no proposal was applied.
16
+ - Codex did not push, merge or publish. The user later confirmed the cuora dev package was published and installed in cash. The earlier `npm whoami` E401 is historical; no registry operation was performed in this turn.
17
+ - Authorization in force: the user approved the commit and shared-dev release flow, then reported that cuora was published and installed. This resumed turn only verified the installed version and wrote local evidence; no publish or push occurred.
18
+ - User approved the one-time no-UI exception verbatim: 「採一次性例外:報告列出 22/22 測試與獨立 review,明列截圖檢查不適用」. `self-test-report.md`, `evidence-index.json`, `verify.json`, and row-closure/redaction reports now record the unit-test proof and screenshot-check exception; top-level verification result is `ok`.
@@ -0,0 +1,3 @@
1
+ The user reported the publish-token setup complete after receiving the requested NPM_TOKEN_WRITE setup instructions. Their exact authorization was: 「A,不過修改後需要 publish cash 才有辦法驗證,而且 publish token 有改,有需要 publish 再叫我,或是先給我指令,我更新之後你就可以直接走到底」. Codex gave the token setup instructions and the user replied 「完成」.
2
+
3
+ Interpret this as authorization to complete the remaining task flow, including the feature commit, the repository's documented merge/push to the shared dev branch, and publishing the dev package, after verifying the publishing account. Do not ask for redundant permission at the publish gate. Do not expose the token. This cuora SDK is in the user's choice A mode: local delivery with unit-test/review proof and no UI captures or Notion self-test page. The visible UI evidence will be collected in client-pwa-cash.
@@ -0,0 +1,38 @@
1
+ # Analysis — TI-16026 (cuora-module)
2
+
3
+ Mode: user choice A (2026-11-17, `open-questions.md` Q1). No BEFORE/AFTER captures in this repo; proof is unit tests (`checklist.md`) plus Codex review. Size: 4 items, 0 captures.
4
+
5
+ ## Change
6
+
7
+ `src/machine/withdraw/withdraw_manual_cash.js`
8
+
9
+ - `submitted: {}` (line 99) gets its own handler: `on: { REFRESH: { target: 'loading', internal: false } }`.
10
+ - State-level `on` takes precedence over the root `on.REFRESH` (line 156, `cond: 'hasNoBank'`), so in `submitted` the refresh is unconditional; everywhere else the root rule is unchanged.
11
+ - `loading` re-runs `fetchInitData` (rule gate + `getBindingPaymentInfo` + `getPendingOrder({ transferType: 'WITHDRAW' })`) → `setInitData` → `checking`: `isProcessing` → `submitted` (with the new `processing`), else `loaded` (the withdraw form). This is exactly spec flow step 3.
12
+ - Nothing else in the machine changes. `websocket.js` needs no change (`open-questions.md`).
13
+
14
+ Alternatives rejected:
15
+
16
+ - Removing `cond: 'hasNoBank'` from the root REFRESH: would let REFRESH reset `loaded` / `calculated` / `otp` too — changes behavior the spec does not ask for, and downstream may already send REFRESH elsewhere expecting a no-op.
17
+ - A new event name (e.g. `PAYMENT_UPDATED`): the spec names `REFRESH`; cash's L4 sends `REFRESH`.
18
+ - Doing the applyId match inside the machine: spec L4 puts the match in client-pwa-cash; the machine has no socket input.
19
+
20
+ ## Unit test
21
+
22
+ New `test/withdraw_manual_cash.test.js`, same pattern as `test/auth_otp_v3.test.js` (`node:test`, `interpret`, stubbed `request.send` keyed by `descriptor.url`, `waitForState`). Run: `node --test test/withdraw_manual_cash.test.js` (no `test` script in `package.json`; do not add one — scope). Read the URLs the stub must answer from `src/api/payment.js` (`getBindingPaymentInfo`, `getDoubleWalletWithdrawRule`, `getPendingOrder`); use context `doubleWalletWithdrawLimitCheck: '0'` and a `paymentDetail` entry `{ category: 'manual', transferType: 'withdraw', minimum, maximum, method }`.
23
+
24
+ ## Constraints and risks
25
+
26
+ - Public-interface impact: additive only (a new accepted event in one state). No export, signature or context-field change. Downstream: client-pwa-cash must send `REFRESH` (its own bundle); client-pwa-ssr does not use this machine.
27
+ - `loading.onError → loaded` (line 39-41) is silent: if the refresh request fails, the user sees the form even if the order is still pending. Pre-existing behavior for the first load; not changed here (scope). Mention in the change description.
28
+ - `setInitData` reads `paymentInfo.bankList` inside `assign` (line 170-171): if `send()` resolves `undefined` (maintenance), the assign throws (CLAUDE.md §2.9 item 13). Pre-existing, same on first load; not changed.
29
+ - Context kept across the refresh: `selectedAmount`, `selectedUserBank` is reset by `setInitData` to `userBanks[0]`, OTP fields stay stale. Harmless for the form (`isSubmittable` only runs after `SET_AMOUNT`), but note it for cash review.
30
+ - Formatting: `.prettierrc`; the pre-commit hook runs `npm run format && git add .` — note `git add .` would also stage `prepare-for-pr/` if it is not ignored; check `.gitignore` before the commit step.
31
+
32
+ ## Delivery
33
+
34
+ Cash cannot verify until a cuora version with this change is published (user, Q1). Publish plan and the command for the user: `publish.md`.
35
+
36
+ ## Feature map lines used
37
+
38
+ None (no `e2e/feature-map.md` in this repo).
@@ -0,0 +1 @@
1
+ A,不過修改後需要 publish cash 才有辦法驗證,而且 publish token 有改,有需要 publish 再叫我,或是先給我指令,我更新之後你就可以直接走到底
@@ -0,0 +1,2 @@
1
+ A,不過修改後需要 publish cash 才有辦法驗證,而且 publish token 有改,有需要 publish 再叫我,或是先給我指令,我更新之後你就可以直接走到底
2
+ 完成
@@ -0,0 +1 @@
1
+ A:允許 Claude CLI 提交
@@ -0,0 +1,18 @@
1
+ {
2
+ "formatVersion": 2,
3
+ "taskId": "TI-16026",
4
+ "title": "[優化][前台] 存出款 Pending 畫面依 WebSocket 即時刷新狀態",
5
+ "spec": { "source": "notion", "ref": "https://app.notion.com/p/3f8b399ad8b5801d81e9fb0675e50907", "externalId": "TI-16026" },
6
+ "delivery": { "target": "local", "ref": null },
7
+ "repo": "cuora-module",
8
+ "adapter": "none",
9
+ "branch": "feat/stone/JT-1791856380-ws-refresh",
10
+ "baseCommit": "c9186b6b3f424d74a9fe1363e64b17eb63809b58",
11
+ "submodules": {},
12
+ "runtime": [],
13
+ "viewports": [],
14
+ "locales": [],
15
+ "dataSource": "none: SDK without UI; proved by node:test unit tests with a stubbed request (user choice A, 2026-11-17). Screen evidence lives in the client-pwa-cash and client-pwa-ssr TI-16026 bundles. The user approved a one-time exception for screenshot-only checks on 2026-11-18.",
16
+ "createdBy": "claude /ui-baseline-codex",
17
+ "createdAt": "2026-11-17T00:00:00+08:00"
18
+ }