@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.
- package/.github/copilot-instructions.md +61 -27
- package/AGENTS.md +61 -27
- package/AI_PROMPT_SOURCE.md +61 -27
- package/CHANGELOG.md +14 -0
- package/CLAUDE.md +61 -27
- package/GEMINI.md +61 -27
- package/e2e/feature-map.md +19 -0
- package/package.json +3 -3
- package/prepare-for-pr/JT-1776243420.md +85 -0
- package/prepare-for-pr/TI-16026/STATE.md +18 -0
- package/prepare-for-pr/TI-16026/after-prepare-authorization.md +3 -0
- package/prepare-for-pr/TI-16026/analysis.md +38 -0
- package/prepare-for-pr/TI-16026/answer-analyze-01.md +1 -0
- package/prepare-for-pr/TI-16026/answer-commit-01.md +2 -0
- package/prepare-for-pr/TI-16026/answer-commit-02.md +1 -0
- package/prepare-for-pr/TI-16026/bundle.json +18 -0
- package/prepare-for-pr/TI-16026/checklist.md +196 -0
- package/prepare-for-pr/TI-16026/checklist.unit-test-original.md +39 -0
- package/prepare-for-pr/TI-16026/claude-after-model +1 -0
- package/prepare-for-pr/TI-16026/claude-commit-session +1 -0
- package/prepare-for-pr/TI-16026/claude-harvest-session +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/01-analyze.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/01-analyze.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/02-analyze.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/02-analyze.out +4 -0
- package/prepare-for-pr/TI-16026/claude-hops/03-dev.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/03-dev.out +4 -0
- package/prepare-for-pr/TI-16026/claude-hops/04-dev.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/04-dev.out +4 -0
- package/prepare-for-pr/TI-16026/claude-hops/05-dev.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/05-dev.out +3 -0
- package/prepare-for-pr/TI-16026/claude-hops/06-after.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/06-after.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/07-commit.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/07-commit.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/08-commit.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/08-commit.out +2 -0
- package/prepare-for-pr/TI-16026/claude-hops/09-commit.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/09-commit.out +8 -0
- package/prepare-for-pr/TI-16026/claude-hops/10-harvest.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/10-harvest.out +3 -0
- package/prepare-for-pr/TI-16026/claude-hops/11-harvest.err +1 -0
- package/prepare-for-pr/TI-16026/claude-hops/11-harvest.out +3 -0
- package/prepare-for-pr/TI-16026/commit-note.md +5 -0
- package/prepare-for-pr/TI-16026/evidence-index.json +215 -0
- package/prepare-for-pr/TI-16026/feature-map.before.md +61 -0
- package/prepare-for-pr/TI-16026/harvest-redaction.json +34 -0
- package/prepare-for-pr/TI-16026/harvest-redaction.out +37 -0
- package/prepare-for-pr/TI-16026/harvest.md +46 -0
- package/prepare-for-pr/TI-16026/lessons.md +5 -0
- package/prepare-for-pr/TI-16026/note-harvest-redaction.md +1 -0
- package/prepare-for-pr/TI-16026/open-questions.md +6 -0
- package/prepare-for-pr/TI-16026/publish.md +32 -0
- package/prepare-for-pr/TI-16026/review-convergence-response.md +3 -0
- package/prepare-for-pr/TI-16026/review-input/scope.md +18 -0
- package/prepare-for-pr/TI-16026/review-log.md +57 -0
- package/prepare-for-pr/TI-16026/review-notes.md +97 -0
- package/prepare-for-pr/TI-16026/review-response-r1.md +7 -0
- package/prepare-for-pr/TI-16026/self-test-report.md +67 -0
- package/prepare-for-pr/TI-16026/spec-proposal.md +34 -0
- package/prepare-for-pr/TI-16026/spec-snapshot.md +291 -0
- package/prepare-for-pr/TI-16026/state-log.md +57 -0
- package/prepare-for-pr/TI-16026/user-messages/01.md +12 -0
- package/prepare-for-pr/TI-16026/user-messages/02.md +20 -0
- package/prepare-for-pr/TI-16026/user-messages/03.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/04.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/05.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/06.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/07.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/08.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/09.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/10.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/11.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/12.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/13.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/14.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/15.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/16.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/17.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/18.md +10 -0
- package/prepare-for-pr/TI-16026/user-messages/19.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/20.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/21.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/22.md +1 -0
- package/prepare-for-pr/TI-16026/user-messages/23.md +8 -0
- package/prepare-for-pr/TI-16026/user-messages/24.md +24 -0
- package/prepare-for-pr/TI-16026/user-question.md +24 -0
- package/prepare-for-pr/TI-16026/verify/metrics-check.json +13 -0
- package/prepare-for-pr/TI-16026/verify/redaction.json +38 -0
- package/prepare-for-pr/TI-16026/verify/row-closure.json +45 -0
- package/prepare-for-pr/TI-16026/verify/s04-ws-capture.md +23 -0
- package/prepare-for-pr/TI-16026/verify-after.md +23 -0
- package/prepare-for-pr/TI-16026/verify.json +80 -0
- package/prepare-for-pr/TI-16026.md +408 -0
- package/src/machine/withdraw/withdraw_manual_cash.js +10 -3
- package/src/util/constant.js +2 -1
|
@@ -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
|
|
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
|
-
**
|
|
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(
|
|
308
|
+
io(frontendURL(host), {
|
|
305
309
|
withCredentials: true,
|
|
306
310
|
forceNew: true,
|
|
307
|
-
transports: ['websocket'
|
|
308
|
-
auth: { Authorization:
|
|
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
|
-
**
|
|
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
|
|
317
|
-
|
|
|
318
|
-
| `activity-info`
|
|
319
|
-
| `activity-reward-info` / `message-notice-info`
|
|
320
|
-
| `
|
|
321
|
-
| `
|
|
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**:
|
|
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
|
|
379
|
-
| ------------------------- |
|
|
380
|
-
| HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected)
|
|
381
|
-
| Import paths | Some files self-reference via the `@jetthai/cuora` package name
|
|
382
|
-
| lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist
|
|
383
|
-
| URL leading slash | A few APIs carry a leading slash
|
|
384
|
-
| Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization
|
|
385
|
-
| Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably
|
|
386
|
-
| Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around
|
|
387
|
-
| Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry
|
|
388
|
-
| Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear
|
|
389
|
-
| Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL)
|
|
390
|
-
| Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment
|
|
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/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 reconnect
|
|
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
|
-
**
|
|
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(
|
|
308
|
+
io(frontendURL(host), {
|
|
305
309
|
withCredentials: true,
|
|
306
310
|
forceNew: true,
|
|
307
|
-
transports: ['websocket'
|
|
308
|
-
auth: { Authorization:
|
|
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
|
-
**
|
|
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
|
|
317
|
-
|
|
|
318
|
-
| `activity-info`
|
|
319
|
-
| `activity-reward-info` / `message-notice-info`
|
|
320
|
-
| `
|
|
321
|
-
| `
|
|
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**:
|
|
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
|
|
379
|
-
| ------------------------- |
|
|
380
|
-
| HTTP method casing | `'GET'` and `'get'` coexist (`request.js` calls `toUpperCase()` internally, so behavior is unaffected)
|
|
381
|
-
| Import paths | Some files self-reference via the `@jetthai/cuora` package name
|
|
382
|
-
| lodash extension | `'lodash/pickBy.js'` and `'lodash/pickBy'` coexist
|
|
383
|
-
| URL leading slash | A few APIs carry a leading slash
|
|
384
|
-
| Query parameter placement | A few write them straight into the URL (`register?${qs}`, `mail?include=cl`), bypassing serialization
|
|
385
|
-
| Initial state naming | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` and others used interchangeably
|
|
386
|
-
| Magic numbers and strings | Activity type IDs, error codes, TTLs, polling ticks, `'DEPOSIT'`/`'WITHDRAW'`, `receiveStatus`, `connectStatus` are scattered around
|
|
387
|
-
| Error handling | Three forms coexist: silent fallback to `idle` (most common, loses error info), transition to `fail`, infinite retry
|
|
388
|
-
| Parameter naming | e.g. `getFreeGameReward(code)` is semantically unclear
|
|
389
|
-
| Parameter validation | The API layer has no validation at all (e.g. the dynamic path following `checkDt()` is injected straight into the URL)
|
|
390
|
-
| Deprecated APIs | `getPaymentInfo` in `api/payment.js` only carries a "deprecated" comment
|
|
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/AI_PROMPT_SOURCE.md
CHANGED
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
- [ ] **記憶體安全**:XState callback service 註冊的 `setInterval` / `socket.on()` / `addEventListener` 等,**必須回傳清理函式**(如 `() => clientSocket.off(event, handler)`),避免重連時累積監聽器;Promise 內註冊的監聽器在 resolve / reject 後也要清理
|
|
58
58
|
- [ ] **Token 生命週期**:Token 操作走 `getToken()` 與 `extendToken` action,不繞過攔截器自行注入;TTL 常數優先用既有定義;`fetchUserInfo` 失敗時讓 session 自然終止,不自行重試
|
|
59
59
|
- [ ] **錯誤處理**:透過 `request.errorHandler` 轉發至 error machine,各特殊碼有正確分支(見「錯誤代碼系統」)
|
|
60
|
-
- [ ] **WebSocket 事件路由**:新事件依既有映射表轉發;首充事件額外推送 `first_deposit
|
|
60
|
+
- [ ] **WebSocket 事件路由**:新事件依既有映射表轉發;首充事件額外推送 `first_deposit`;斷線/失敗後的下一步一律交給 `util/socketPolicy.js` 的 `decideNextStep`,不在 `websocket.js` 另寫重連條件;新 listener 一律經 `bindSocket` 的 `on()` 註冊(才會被清理、才有過期 session 的防護)
|
|
61
61
|
- [ ] **效能影響**:避免新增每秒級的 `after: { 1000 }` 自我引用轉換(考慮 callback + `setInterval` + 計算經過時間);不要在模組頂層即時匯入大型依賴;新增高頻 API 須評估是否需快取或退避
|
|
62
62
|
- [ ] **匯入路徑一致**:跨層匯入用相對路徑(`'../../api/payment.js'`),不用 `@jetthai/cuora` 套件名自我引用;lodash 統一不帶 `.js` 副檔名
|
|
63
63
|
- [ ] **魔法數字與字串**:活動類型 ID、錯誤碼、TTL、輪詢 tick、`'DEPOSIT'` / `'WITHDRAW'`、`receiveStatus` 數字等優先用 `util/constant.js` 的常數
|
|
@@ -198,6 +198,8 @@ Token 5min TTL → fetchUserInfo 成功 → extendToken 重設 TTL → 再次輪
|
|
|
198
198
|
|
|
199
199
|
**OTP/綁銀行流程**:登入成功後進入 `otpChecking`,等待 `OTP_VERIFIED` 或 `OTP_SKIP` 後進入 `bindBankChecking`,再等待 `BIND_BANK_DONE` 或 `BIND_BANK_SKIP` 才進入 `loginSuccess`(兩關都可送 `LOGOUT` 中止)。是否需要綁定由下游前端判斷,machine 只負責等待;**下游必須在 `bindBankChecking` 送出其中一個事件,否則會停在這一關**。`tokenAuthenticated` 路徑不經過這兩關。
|
|
200
200
|
|
|
201
|
+
**OTP 自動驗證**(`auth_otp_v3.js`):`verify` / `sendPhone` / `sendEmail` 回應 `needAcknowledge === false` 時不進 OTP 輸入,改走 `autoVerifying`。但 **`needAcknowledge: false` 本身不算驗證通過**,一律以 `/self` 的 `phone_verification_status` / `email_verification_status` 為準,且聯絡資料必須非空(phone 接受 `phone` 或 `tel`;資料為空時即使 status 為真也要求輸入)。後端寫入驗證狀態到 `/self` 反映之間有延遲,主動打的那次未通過時進入 `autoVerifyWaiting`——**machine 不自己輪詢**,而是等下游把 auth 例行輪詢的 `/self` 結果以 `USER_INFO_UPDATED`(`data` 為 userInfo)轉送進來,最多等 2 次或 5 秒(`util/constant.js` 的 `AUTO_VERIFY_*`;收到舊值不會重置計時),仍未通過 → `fail`。**下游沒轉送這個事件時,自動驗證只會在 5 秒後落到 `fail`。** 5 秒是配合 auth 的 `tick: 2000` 讓兩次輪詢來得及回來,改 `tick` 要一起調整。
|
|
202
|
+
|
|
201
203
|
**帳號持久化**:最後使用的登入帳號存 localStorage(31 天 TTL)供表單自動填入。**Token 過期不影響帳號記錄。**但 `fetchSiteConfig` 成功後的 `pruneRememberedAccounts` 會**比對 `siteConfig.loginMethods` 清掉已停用登入方式的殘留帳號**(`phone` 連同國碼一起刪)——拉設定這個看似唯讀的動作帶有刪 localStorage 的副作用,目的是避免後台關掉某種登入方式後,下游把舊值回填進已改型別的輸入框。`loginMethods` 整包缺失時不清除,以免誤刪全部。
|
|
202
204
|
|
|
203
205
|
### 2.2 存款流程模式(Canonical Deposit Pattern)
|
|
@@ -296,29 +298,62 @@ loading(fetchInitData:雙錢包規則閘門 + getBindingPaymentInfo + getPen
|
|
|
296
298
|
|
|
297
299
|
### 2.6 即時通訊(WebSocket)
|
|
298
300
|
|
|
299
|
-
|
|
301
|
+
**單一 owner**:連線、重試、清理全部在掛於 root 的 `socketLifecycle` callback service 的 closure 內。`idle` / `fetchSocket` / `connecting` / `connected` 等 state **只是給下游看的顯示狀態**,由 service 送出的 `_SOCKET_STATUS`(`phase`)驅動,本身沒有 invoke 也沒有 guard——要改行為改 service,不要往 state 加 `invoke` / `after`。換 instance 前一律先 `off` 舊 listener 再 `disconnect`(含尚未連上的 instance)。
|
|
302
|
+
|
|
303
|
+
**線路選擇**:`selectSocket` 從 GCS 的 `target/target.json` 取得多個 host,用 `Promise.any()` 同時打 `/ping/status`,最快回應者勝出;取不到或全部失敗時退回 `request.config.socketURL`。**沒有 token 不選線也不建立連線。**
|
|
300
304
|
|
|
301
305
|
```js
|
|
302
|
-
io(
|
|
306
|
+
io(frontendURL(host), {
|
|
303
307
|
withCredentials: true,
|
|
304
308
|
forceNew: true,
|
|
305
|
-
transports: ['websocket'
|
|
306
|
-
auth: { Authorization:
|
|
309
|
+
transports: ['websocket'], // 只走 websocket,沒有 polling 備援
|
|
310
|
+
auth: (done) => done({ Authorization: request.getToken() }), // callback 形式:每次(重)連線當下才讀最新 token
|
|
307
311
|
})
|
|
308
312
|
```
|
|
309
313
|
|
|
310
|
-
|
|
314
|
+
**失敗後的下一步**一律由 `util/socketPolicy.js` 的 `decideNextStep` 決定:
|
|
315
|
+
|
|
316
|
+
| 結果 | 觸發 | 行為 |
|
|
317
|
+
| ---------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
318
|
+
| `socketio` | 非 server 主動的 `disconnect`,或 `connect_error` 時 socket 仍 `active` | 留在同一個 instance 交給 Socket.IO 內建重連;從第一次斷線起 120 秒沒恢復 → `exhausted` |
|
|
319
|
+
| `retry` | 其餘失敗(含**尚未就緒**時的 `io server disconnect`) | 重新選線;首次之外最多 3 次,1 / 2 / 4 秒指數退避 × 0.5–1.5 jitter,並以 server 給的 `retryAfterMs` 為下限;用完 → `exhausted` |
|
|
320
|
+
| `renew` | `SESSION_TOKEN_INVALID` / `session rejected` | 立即重連一次(就緒前只有一次額度),之後比照 `retry` |
|
|
321
|
+
| `kicked` | `kicked` 事件、`MAX_CONNECTIONS`、**已就緒後**的 `io server disconnect` | 停止 |
|
|
322
|
+
| `stop` | 拒絕訊息帶 `retryable: false` | 停止 |
|
|
323
|
+
| `none` | `io client disconnect`(自己斷的) | 不處理 |
|
|
324
|
+
|
|
325
|
+
**`io server disconnect` 不再等於「重連」**:就緒後被 server 斷開視為被踢,不自動重連。停止後由 `context.blocked` 決定誰能恢復(`canResume`):`kicked` 只接受 `source: 'user'`;`exhausted` 是 user 隨時、`auto` 需距上次嘗試 ≥ 15 秒;`stop` 要等換 token。非 `preserveSession` 的 `DISCONNECT_SOCKET` 會清掉 `blocked`。
|
|
326
|
+
|
|
327
|
+
**下游契約**(這些事件與 context 欄位的另一端在下游前端,本 package 內沒有 caller):
|
|
328
|
+
|
|
329
|
+
| 介面 | 契約 |
|
|
330
|
+
| --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
331
|
+
| `CONNECT` / `CHECK_SOCKET` | 可帶 `source: 'user' \| 'auto'`(預設 `user`),決定 `blocked` 後能否恢復 |
|
|
332
|
+
| `AUTH_CHECKED` | `{ token, uidSite }`,只能來自成功的 `/self`,`token` 必須等於當下的 `getToken()`;送過一次之後的義務見下方 |
|
|
333
|
+
| `DISCONNECT_SOCKET` | 預設=登出/銷毀,清掉 session、去重紀錄與重試狀態;`{ preserveSession: true }`=背景釋放,全部保留 |
|
|
334
|
+
| `SESSION_READY` | `{ resync, generation }`。**就緒的依據是 server 的 `session-ready`(或 `socket.recovered === true`),不是 `connect`**——`SET_CONNECTED` 只代表傳輸層連上。`resync: true` 表示曾就緒過、這次是未恢復的新 session,下游要用 REST 補抓 |
|
|
335
|
+
| `ACTIVITY_INFO` | `{ data, eventName, generation }`;`payment-info` **不再限 `windowType === 'toast'`**,要過濾由下游自己做 |
|
|
336
|
+
| `context.generation` | 連線失效、重新嘗試、第一次斷線時遞增,下游可用來作廢舊世代的 REST 回應 |
|
|
337
|
+
| `context.claimPaymentEvent(event, orderData)` | REST 與 socket 共用的 GA 去重:`true`=第一次、可上報;`false`=重複或當下 session 不可信。`purchase` 與 `first_deposit` 分開計,`applyId` / `transactionId` 視為同一張單的別名;完全沒有 ID 時回 `true` |
|
|
338
|
+
|
|
339
|
+
**`AUTH_CHECKED` 一旦送過,之後每次 token 輪替都要再送**:已驗證的 session 直接換成另一個 token 時,在收到新 token 的 `AUTH_CHECKED` 之前,`CONNECT` / `CHECK_SOCKET` 只會被記下、不會連線,`claimPaymentEvent` 一律回 `false`;UID 與先前相同才還原去重紀錄。從未送過 `AUTH_CHECKED` 的下游不受影響。
|
|
340
|
+
|
|
341
|
+
**推播去重**:四種推播在轉發前先去重(`createPushDedupe`)——優先用 `_meta.messageId`;沒有時只有 `payment-info` 以「業務 event + `applyId` / `transactionId`」為鍵;兩者皆無則不去重。
|
|
311
342
|
|
|
312
343
|
**事件轉發映射**:
|
|
313
344
|
|
|
314
|
-
| Socket 事件
|
|
315
|
-
|
|
|
316
|
-
| `activity-info`
|
|
317
|
-
| `activity-reward-info` / `message-notice-info`
|
|
318
|
-
| `
|
|
319
|
-
| `
|
|
345
|
+
| Socket 事件 | 狀態機事件 |
|
|
346
|
+
| -------------------------------------------------------------- | --------------------------------------------------------------------------- |
|
|
347
|
+
| `activity-info` / `payment-info` | `ACTIVITY_INFO` + `PUSH_ANALYTICS` |
|
|
348
|
+
| `activity-reward-info` / `message-notice-info` | `ACTIVITY_INFO` |
|
|
349
|
+
| `connect` | `SET_CONNECTED` |
|
|
350
|
+
| `session-ready`(或 `connect` 時 `socket.recovered === true`) | `SESSION_READY` |
|
|
351
|
+
| `connect_error` / `disconnect` | `CONNECT_ERROR` / `DISCONNECT`(帶 `internalSocket: true`,先經過失敗決策) |
|
|
352
|
+
| `auth-rejected` / `kicked` | 不轉發,只進失敗決策 |
|
|
353
|
+
|
|
354
|
+
下游自行送入、不帶 `internalSocket` 的 `CONNECT_ERROR` / `DISCONNECT` 會被當成失敗回報,同樣進失敗決策。
|
|
320
355
|
|
|
321
|
-
**首充偵測**:`PUSH_ANALYTICS`
|
|
356
|
+
**首充偵測**:`PUSH_ANALYTICS`(僅 `isTracking` 為真時)先上報原事件;若 `event === 'purchase'` 且 `data.isFirst === true`,**再額外推送 `first_deposit`**(Facebook Pixel / 轉換追蹤)。兩者都要先通過 `claimPaymentEvent`,且上報途中 token 或 `generation` 變了就不補送 `first_deposit`。
|
|
322
357
|
|
|
323
358
|
### 2.7 設定與即時資訊(Common Machine)
|
|
324
359
|
|
|
@@ -373,19 +408,19 @@ io(`${socketURL}/frontend`, {
|
|
|
373
408
|
|
|
374
409
|
> 以下每一項在程式碼中都是**兩種寫法並存**——探索程式碼無法判斷哪個才是規範,因此必須明文記錄。新寫的程式碼一律採用「目標」欄;既有程式碼不主動大規模重構(範圍自律)。
|
|
375
410
|
|
|
376
|
-
| 項目 | 現況
|
|
377
|
-
| ------------------ |
|
|
378
|
-
| HTTP method 大小寫 | `'GET'` 與 `'get'` 並存(`request.js` 內部 `toUpperCase()`,功能不受影響)
|
|
379
|
-
| 匯入路徑 | 部分檔案用 `@jetthai/cuora` 套件名自我引用
|
|
380
|
-
| lodash 副檔名 | `'lodash/pickBy.js'` 與 `'lodash/pickBy'` 並存
|
|
381
|
-
| URL 前導斜線 | 少數 API 帶前導斜線
|
|
382
|
-
| 查詢參數位置 | 少數直接寫入 URL(`register?${qs}`、`mail?include=cl`),繞過序列化
|
|
383
|
-
| 初始狀態命名 | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` 等混用
|
|
384
|
-
| 魔法數字與字串 | 活動類型 ID、錯誤碼、TTL、輪詢 tick、`'DEPOSIT'`/`'WITHDRAW'`、`receiveStatus`、`connectStatus`
|
|
385
|
-
| 錯誤處理 | 三種並存:靜默轉 `idle`(多數,錯誤資訊遺失)、轉 `fail`、無限重試
|
|
386
|
-
| 參數命名 | 如 `getFreeGameReward(code)` 語意不明
|
|
387
|
-
| 參數驗證 | API 層無任何驗證(如 `checkDt()` 之後的動態路徑直接注入 URL)
|
|
388
|
-
| 已棄用 API | `api/payment.js` 的 `getPaymentInfo` 只標了「棄用」註解
|
|
411
|
+
| 項目 | 現況 | 目標 |
|
|
412
|
+
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
413
|
+
| HTTP method 大小寫 | `'GET'` 與 `'get'` 並存(`request.js` 內部 `toUpperCase()`,功能不受影響) | 統一小寫 `'get'`/`'post'`/`'put'`/`'delete'` |
|
|
414
|
+
| 匯入路徑 | 部分檔案用 `@jetthai/cuora` 套件名自我引用 | 統一相對路徑(`'../../api/payment.js'`) |
|
|
415
|
+
| lodash 副檔名 | `'lodash/pickBy.js'` 與 `'lodash/pickBy'` 並存 | 統一**不帶**副檔名 |
|
|
416
|
+
| URL 前導斜線 | 少數 API 帶前導斜線 | 不加(除非刻意繞過 `url-join`,須註解原因) |
|
|
417
|
+
| 查詢參數位置 | 少數直接寫入 URL(`register?${qs}`、`mail?include=cl`),繞過序列化 | 一律用 `params` 欄位 |
|
|
418
|
+
| 初始狀態命名 | `idle` / `loading` / `fetching` / `pending` / `checking` / `init` 等混用 | 依語意:`idle`(等待操作)、`loading`(初始載入)、`fetching`(重新取得)、`submitting` / `submitted` |
|
|
419
|
+
| 魔法數字與字串 | 活動類型 ID、錯誤碼、TTL、輪詢 tick、`'DEPOSIT'`/`'WITHDRAW'`、`receiveStatus`、`connectStatus` 散佈各處,`util/constant.js` 尚未收錄這些類別 | 集中至 `util/constant.js`(`ERROR_CODES` / `TTL` / `INTERVAL` / `TRANSFER_TYPE` / `RECEIVE_STATUS`) |
|
|
420
|
+
| 錯誤處理 | 三種並存:靜默轉 `idle`(多數,錯誤資訊遺失)、轉 `fail`、無限重試 | `onError` 搭配 `actions: 'setError'` 保存錯誤至 context;區分可恢復 / 不可恢復;重試須設上限 |
|
|
421
|
+
| 參數命名 | 如 `getFreeGameReward(code)` 語意不明 | 具體命名(`gameCode`) |
|
|
422
|
+
| 參數驗證 | API 層無任何驗證(如 `checkDt()` 之後的動態路徑直接注入 URL) | 在系統邊界驗證:路徑參數非 undefined 且無路徑遍歷字元、金額為正數 |
|
|
423
|
+
| 已棄用 API | `api/payment.js` 的 `getPaymentInfo` 只標了「棄用」註解 | 先補 `@deprecated`,確認無引用後再移除 |
|
|
389
424
|
|
|
390
425
|
---
|
|
391
426
|
|
|
@@ -393,7 +428,6 @@ io(`${socketURL}/frontend`, {
|
|
|
393
428
|
|
|
394
429
|
> 這些問題**已經被盤點過**,不需要在每次 code review 重新回報。要處理時請開獨立工單,不要夾帶在功能異動裡。
|
|
395
430
|
|
|
396
|
-
- **WebSocket 監聽器洩漏(嚴重度:高)** — `machine/websocket.js` 的 `listenToSocketEvents` callback service 註冊多個 `.on()` 監聽器但**從未回傳清理函式**,每次重連都累積。修法:handler 抽為具名變數並回傳 `() => clientSocket.off(event, handler)`。`connectSocket` 的 Promise 內註冊的 `connect` / `connect_error` 監聽器同樣未清理。**新寫的 callback service 一律要回傳清理函式(見 DoD)。**
|
|
397
431
|
- **無請求快取** — 高頻端點(`fetchUserInfo` 每 2–10 秒、`getConfig` 每次狀態機初始化、`getPaymentDetail` 每次進入存提款頁、`getActivityList` 每 20 秒)皆直打伺服器。可考慮 TTL 快取或 `stale-while-revalidate`。
|
|
398
432
|
- **無速率限制與退避** — 輪詢為固定間隔,錯誤時不變。可考慮錯誤時指數退避。
|
|
399
433
|
- **無 Token 自動刷新** — `request.js` 回應攔截器不處理 401,Token 過期即失敗。
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
|
|
4
4
|
|
|
5
|
+
### [1.1.487-otp.0](https://github.com/jetthai/cuora-module/compare/v1.1.487...v1.1.487-otp.0) (2026-11-26)
|
|
6
|
+
|
|
7
|
+
### Bug Fixes
|
|
8
|
+
|
|
9
|
+
- **withdraw:** keep OTP open on ERR_M129 ([4ca19f0](https://github.com/jetthai/cuora-module/commit/4ca19f05a8bb576c9baa2bc60ef43c63808ffdfb))
|
|
10
|
+
|
|
11
|
+
### [1.1.487](https://github.com/jetthai/cuora-module/compare/v1.1.486...v1.1.487) (2026-11-22)
|
|
12
|
+
|
|
13
|
+
### [1.1.486](https://github.com/jetthai/cuora-module/compare/v1.1.485...v1.1.486) (2026-11-22)
|
|
14
|
+
|
|
15
|
+
### Features
|
|
16
|
+
|
|
17
|
+
- **constant:** 新增 Prediction 遊戲類別取代 Ball(gameTypeMappingId 12) ([6f861e2](https://github.com/jetthai/cuora-module/commit/6f861e28afd9fdd8a39c286420b4d328aab56f7b))
|
|
18
|
+
|
|
5
19
|
### [1.1.485](https://github.com/jetthai/cuora-module/compare/v1.1.484...v1.1.485) (2026-11-16)
|
|
6
20
|
|
|
7
21
|
### Features
|