@jetthai/cuora 1.1.487 → 1.1.488-dev.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/.claude/commands/sync-ai-prompts.md +88 -1
- package/.claude/settings.local.json +3 -1
- package/.github/copilot-instructions.md +17 -6
- package/.husky/post-checkout +3 -3
- package/.husky/pre-push +1 -1
- package/.prettierignore +2 -1
- package/AGENTS.md +17 -6
- package/AI_PROMPT_SOURCE.md +17 -6
- package/CHANGELOG.md +415 -23
- package/CLAUDE.md +17 -6
- package/GEMINI.md +17 -6
- package/package.json +1 -1
- package/scripts/auto-version.js +1 -0
- package/scripts/branch-auto-npm-publish.js +9 -2
- package/src/api/payment.js +1 -0
- package/src/machine/auth.js +36 -33
- package/src/machine/game_v2_1.js +15 -0
- package/src/machine/reward_cash.js +2 -2
- package/src/machine/user_sign_up.js +3 -0
- package/src/machine/withdraw/withdraw_manual_cash.js +7 -4
- package/src/request/request.js +103 -4
- package/src/util/constant.js +6 -0
- package/src/util/tokenStore.js +44 -0
- package/test/auth_self_timeout.test.js +171 -0
- package/test/request_self.test.js +288 -0
- package/test/withdraw_manual_cash.test.js +149 -0
- package/tests/session.test.mjs +177 -0
package/GEMINI.md
CHANGED
|
@@ -144,7 +144,7 @@ State machines **do not directly reference each other**; they communicate indire
|
|
|
144
144
|
| `ERR_F108` | System under maintenance (**dual interception**: `request.js` sets `isBlocked` to block subsequent non-config requests; `error.js` routes to logout) |
|
|
145
145
|
| `ERR_A103` | Missing auth token |
|
|
146
146
|
| `ERR_A104` / `ERR_A113` / `ERR_A201` / `ERR_A204` | Auth invalidation / logout class |
|
|
147
|
-
| `ERR_A108` |
|
|
147
|
+
| `ERR_A108` | Token expired (`send()` renews via `/self` first, and only on success resends the original request once; see item 15 of 2.9) |
|
|
148
148
|
| `ERR_F106` | OTP verification failed |
|
|
149
149
|
| `ERR_G106` | Insufficient balance (→ deposit state) |
|
|
150
150
|
| `ERR_G124` / `ERR_G125` | Free game settlement / forfeit |
|
|
@@ -161,16 +161,25 @@ This section explains how each module actually operates, its non-obvious behavio
|
|
|
161
161
|
|
|
162
162
|
### 2.1 Authentication & Token Lifecycle
|
|
163
163
|
|
|
164
|
-
**Token survival strategy**: the token TTL is only 5 minutes (`maxAge: 300`), kept alive by continuous `fetchUserInfo` polling. On each successful poll, `extendToken` rewrites
|
|
164
|
+
**Token survival strategy**: the token TTL is only 5 minutes (`maxAge: 300`), kept alive by continuous `fetchUserInfo` polling. On each successful poll, `extendToken` rewrites the cookie and resets the TTL. **Tokens are never auto-renewed** — if `fetchUserInfo` fails, the token expires naturally and the session terminates on its own.
|
|
165
165
|
|
|
166
166
|
```
|
|
167
167
|
Token 5min TTL → fetchUserInfo success → extendToken resets TTL → poll again
|
|
168
168
|
fetchUserInfo failure → leaving state → logout
|
|
169
169
|
```
|
|
170
170
|
|
|
171
|
-
- **
|
|
171
|
+
**`/self` single-flight and its dedicated timeout** (`request.js`, TI-16263): for `GET self` (`_isSelfRead`: non-public, url is `'self'` after stripping the query) `send()` shares one in-flight promise keyed by `[channel, token, url, params, headers, silent]` — shared only when all of them are identical; a different identity or different params each get their own request. `channel` is a classification field on the descriptor (never sent to the backend): `polling` (`pollUserInfo` in `auth.js`, used by `inline.fetching` / `login.fetching`), `freeGame` (the downstream wait after claiming a free game), and `standalone` by default (every other entry); the three channels each send their own request and never share or skip one another; calls passing their own `customToken` are not shared. Every `/self` read has a `SELF_REQUEST_TIMEOUT_MS` deadline (15 seconds, `util/constant.js`); when it expires the request is cancelled and rejects with `{ code: 'ERR_998', endpoint, isTimeout: true }`.
|
|
172
|
+
|
|
173
|
+
- **Single-flight must be paired with a timeout**: without one, a `/self` that never answers permanently stops the polling that shares it. Do the same when adding single-flight to another endpoint.
|
|
174
|
+
- **The read timeout must not be switched to axios's `timeout`**: `ECONNABORTED` gets re-sent by the downstream axios-retry; a cancelled error carries no `config` and is not retried. `POST self` (`_isSelfWrite`) is deliberately the opposite: each attempt gets 15 seconds and is retried per the downstream's existing settings, so it uses axios's `timeout` plus `'axios-retry': { shouldResetTimeout: true }`; when the retries are exhausted and it still times out, the error becomes `{ code: 'ERR_998', isTimeout: true }` and does not reach `errorHandler`.
|
|
175
|
+
- **A successful `GET /self` extends the token**: on a successful read (all three channels count), `_extendToken` resets the token's TTL to 5 minutes (only while the token sent is still the current one). While the main polling keeps timing out, a single successful read from another channel keeps the TTL from logging the user out. A successful `POST self` does **not** extend it: the backend renews the token only on `GET /self`.
|
|
176
|
+
- **A `/self` timeout never logs out**: the `isSelfTimeout` guard in `auth.js` only accepts `event.data.isTimeout === true`, and a timeout re-sends instead — `authenticated` → `userInfoRetrying`, `tokenAuthenticated` re-enters itself, `inline.fetching` / `login.checkDeviceTokenDone` / `login.fetching` → `pending` (wait for the next tick). A plain `ERR_998` (a network error that fails immediately) and authentication failures still go to `leaving`. Only once the token's 5-minute TTL has expired does `send()` return `ERR_A103` and the flow naturally reaches `leaving`.
|
|
177
|
+
- **`userInfoRetrying` is an externally visible state**: when the first `/self` after login times out, the machine stays here re-sending and moves to `otpChecking` on success. It deliberately does not re-enter `authenticated` — downstream fires one-off side effects on `state.matches('authenticated')` (saving credentials, registration conversion tracking), and re-entering would fire them again. Downstream code that enumerates auth states (loading checks, etc.) must treat it as a continuation of `authenticated`.
|
|
178
|
+
|
|
179
|
+
- **Storage location**: a cookie named `cuora_{clientId}`, with no `Domain` attribute (not shared across subdomains), `SameSite=Lax`, plus `Secure` under https. It is read and written only through `Request`'s `getToken()` / `setToken()` / `extendToken()` / `removeToken()` (implemented in `util/tokenStore.js`); **downstream frontends must not read or write this cookie themselves, and must no longer use `storage.get('cuora_{clientId}')` to determine login state** — `storage` is still localStorage, and the token no longer lives there. When `Request` is constructed, it clears any leftover same-named value from localStorage rather than reusing the old token
|
|
180
|
+
- **Unreadable in cross-site iframes**: a `SameSite=Lax` cookie cannot be read or written inside a cross-site iframe (e.g. a Mini App embedded in Telegram Web), so login state cannot be maintained in that context; this is an accepted limitation
|
|
172
181
|
- **Injection**: the request interceptor automatically adds `Authorization: Bearer {token}`
|
|
173
|
-
- **TTL**: token 300 seconds, account info 31 days, cookie data 7 days
|
|
182
|
+
- **TTL**: token 300 seconds (`TOKEN_MAX_AGE`; on expiry the browser removes the cookie), account info 31 days, cookie data 7 days
|
|
174
183
|
|
|
175
184
|
**Token revocation & foreground gate** (`request.js`): `revokeToken(token)` and `beginTokenGate(promise, timeoutMs = 3000)` are public `Request` methods with **no caller inside this package** — the downstream frontends call them on logout-class errors and when the app returns to the foreground; changing their signatures or semantics is a public-interface change.
|
|
176
185
|
|
|
@@ -281,6 +290,7 @@ There are only 4 guards: `hasNoBank` (`REFRESH` only reloads when no account is
|
|
|
281
290
|
- **Parallel architecture** (`game_v2_1.js`): `flow` (UI interaction and game loading) and `timer` (auto-update every 20 seconds) run simultaneously
|
|
282
291
|
- **Static-data fallback**: when logged out, `staticData` is used, slicing 20 entries per page from cache with **no API call**
|
|
283
292
|
- **Game-switching mechanism**: when switching to another game while in one, `connectSwitching` disconnects the old game first, then `connecting` connects to the new one
|
|
293
|
+
- **Two ways to leave a game**: `EXIT_GAME` goes through `disconnect`, which calls `game/logout`; `ABANDON_GAME` returns straight to `idle` and clears the game URL, **without calling `game/logout`**. The latter is only for when "the session has been replaced (re-login) and the game page must be left" — logging the old session out of the game no longer serves any purpose. Once `ABANDON_GAME` has been sent, the `EXIT_GAME` that is still sent as usual when the page unloads is not handled in `idle`
|
|
284
294
|
- **Provider-specific behavior**: some providers use `${origin}${base}return` as the returnURL, while the rest use `window.location.href` (with the query string stripped). The allowlist is `returnProviders` in `game_v2_1.js`
|
|
285
295
|
- **Response mapping**: backend `redirect_url` → `gameURL`, `wallet_type` → `gameWalletType`; some games return embedded `gameHtml` instead of a URL
|
|
286
296
|
|
|
@@ -382,14 +392,14 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
|
|
|
382
392
|
8. Custom paramsSerializer: special encoding for the q parameter (avoids double-encoding)
|
|
383
393
|
9. axios.request(config)
|
|
384
394
|
10. Response interceptor: response.data.error present → reject; Network Error / 404 → ERR_998 + Sentry
|
|
385
|
-
11. Error handling (in order): cancellation → reject ERR_800 (never reaches errorHandler); token-carrying requests get a non-enumerable requestToken attached to the error; ERR_F108 → isBlocked + errorHandler; stale-identity error → thrown directly (see item 14 of 2.9); ERR_998 → thrown directly; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown); non-cancellation error whose code is already ERR_800 → resolves undefined
|
|
395
|
+
11. Error handling (in order): cancellation → reject ERR_800 (never reaches errorHandler); ERR_A108 → renew via /self first, and only on success resend the original request once (see item 15 of 2.9); token-carrying requests get a non-enumerable requestToken attached to the error; ERR_F108 → isBlocked + errorHandler; stale-identity error → thrown directly (see item 14 of 2.9); ERR_998 → thrown directly; everything else → errorHandler (skipped when the descriptor carries silent: true, still thrown); non-cancellation error whose code is already ERR_800 → resolves undefined
|
|
386
396
|
```
|
|
387
397
|
|
|
388
398
|
**V1→V2 conversion**: `supportVersion2List` supports dynamic paths (e.g. `payment/v2/:paymentType/transaction`, where `:param` is replaced by `[^/]+`); special paths are hard-coded in `specifyingPath`, and the rest are auto-converted via `/([a-z])([A-Z])/g`. **When adding an endpoint that needs V2 conversion, it must be added to the list manually.**
|
|
389
399
|
|
|
390
400
|
### 2.9 Critical Design Constraints & Gotchas
|
|
391
401
|
|
|
392
|
-
1. **Token extension only happens when `
|
|
402
|
+
1. **Token extension only happens when `/self` succeeds**: tokens are never auto-renewed and depend on a successful `/self` (polling, a read from any other entry, or `POST self`). API failure → the session terminates. The only exception is the 15-second `/self` timeout — no logout, it re-sends instead (see 2.1).
|
|
393
403
|
2. **A leading slash changes routing**: `/payment/v2/...` (the withdrawal OTP endpoints) **deliberately** bypasses `url-join`'s baseURL composition and starts from the API root. Regular endpoints should not have a leading slash.
|
|
394
404
|
3. **`register` mixes parameter passing**: `channel`/`subchannel`/`ac`/`fc` are appended to the URL query string while the rest go in the body. **This is the only endpoint using this pattern.**
|
|
395
405
|
4. **OTP endpoints marked `isPublic`**: the withdrawal OTP `acknowledge`/`reset` endpoints are `isPublic: true` even though the operations are sensitive — this is because the token may already have expired during the OTP flow, and is **not a security oversight**.
|
|
@@ -403,6 +413,7 @@ A `CONNECT_ERROR` / `DISCONNECT` sent in by downstream itself, without `internal
|
|
|
403
413
|
12. **`silent: true` only skips errorHandler**: the error is still thrown to the caller's `onError`, and `ERR_F108` is still routed as usual; but every other error code — **including logout-class codes such as `ERR_A104`, and `ERR_G106` insufficient balance** — never reaches the error machine. Use it only for background requests whose session invalidation is already covered by `fetchUserInfo` polling; never add it to user-initiated requests.
|
|
404
414
|
13. **`send()` does not guarantee an object, and `assign()` must never throw**: non-config requests during maintenance (`isBlocked`) and non-cancellation errors that already carry `code: 'ERR_800'` make `send()` **resolve `undefined`** (they never reach `onError`); a 200 response with a non-JSON body resolves a string, so destructuring `{ data }` yields `undefined`. Cancellations (`customToken` cancellation, `revokeToken` revocation), by contrast, reject with `ERR_800` and **do reach `onError`** — they never resolve `undefined`. When an `assign()` throws, XState v4 clears the event queue and the state is not updated — the machine stays in the current invoke state and `after`-based polling stops until an external event (e.g. `REFRESH`) moves it out. **Validate response shapes inside the service and `throw` there (reject → `onError`)**; every assign in `onDone` must handle every value the service can resolve, including deliberate `return null` early exits.
|
|
405
415
|
14. **Late errors from a stale identity never reach errorHandler**: when the token a request was sent with differs from the current token (and a current token exists), the error is only thrown to the caller's `onError` and not forwarded to errorHandler — so a late logout-class error from an old session can't log out a newly logged-in identity. When there is no current token (TTL expired or already cleared), routing is unchanged so that `ERR_A204`-style popups aren't swallowed; the `ERR_F108` check comes before this one and still routes as usual.
|
|
416
|
+
15. **`ERR_A108` is resent only once, and only after asking `/self`**: when a token-carrying non-public request receives `ERR_A108`, `send()` first sends a single `silent` `/self`; only if that succeeds and the token has not changed is the original request resent, once. `/self` itself, an already-resent request, and a request whose identity changed during the renewal are never resent; if the renewal fails or the resent request still gets `ERR_A108`, the original error follows the existing routing into errorHandler. **Never turn this into a retry loop** — a failed `/self` means the session has really ended, and downstream relies on this error to log out.
|
|
406
417
|
|
|
407
418
|
---
|
|
408
419
|
|
package/package.json
CHANGED
package/scripts/auto-version.js
CHANGED
|
@@ -14,8 +14,15 @@ const { version } = JSON.parse(readFileSync('package.json', 'utf8'))
|
|
|
14
14
|
console.log(`Branch: ${branch}`)
|
|
15
15
|
console.log(`Version: ${version}`)
|
|
16
16
|
|
|
17
|
-
// 推送 commit
|
|
18
|
-
execSync(`git push --no-verify
|
|
17
|
+
// 推送 commit 到遠端(--no-verify 避免觸發 pre-push hook 造成無限迴圈)
|
|
18
|
+
execSync(`git push --no-verify ${remote} ${branch}`, { stdio: 'inherit' })
|
|
19
|
+
|
|
20
|
+
// 單獨推送 tag;tag 已存在於 remote 時視為成功(不中斷 npm publish)
|
|
21
|
+
try {
|
|
22
|
+
execSync(`git push --no-verify ${remote} refs/tags/v${version}`, { stdio: 'inherit' })
|
|
23
|
+
} catch {
|
|
24
|
+
console.warn(`⚠ tag v${version} push 失敗(可能已存在),繼續 npm publish`)
|
|
25
|
+
}
|
|
19
26
|
|
|
20
27
|
// 發布到 npm,使用分支名稱作為 dist-tag(例如 npm install @jetthai/cuora@dev)
|
|
21
28
|
try {
|
package/src/api/payment.js
CHANGED
package/src/machine/auth.js
CHANGED
|
@@ -8,8 +8,7 @@ import pickBy from 'lodash/pickBy.js'
|
|
|
8
8
|
import { readParamFromLocation, writeParam, normalize, AC_KEYS, FC_KEYS } from '../util/paramStore.js'
|
|
9
9
|
|
|
10
10
|
export default function (request) {
|
|
11
|
-
const { appSecret,
|
|
12
|
-
const tokenKey = `cuora_${clientId}`
|
|
11
|
+
const { appSecret, sentry } = request.config
|
|
13
12
|
const phoneCountryCode = 'phone_countrycode'
|
|
14
13
|
const accountPhoneKey = 'account_phone'
|
|
15
14
|
const accountEmailKey = 'account_email'
|
|
@@ -85,7 +84,22 @@ export default function (request) {
|
|
|
85
84
|
target: 'otpChecking',
|
|
86
85
|
actions: ['setUserInfo', 'extendToken'],
|
|
87
86
|
},
|
|
88
|
-
onError: {
|
|
87
|
+
onError: [{ target: 'userInfoRetrying', cond: 'isSelfTimeout' }, { target: 'leaving' }],
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
// 登入後第一筆 /self 逾時的重發。獨立成一個狀態而不重進 authenticated:
|
|
91
|
+
// 下游以 state.matches('authenticated') 觸發一次性副作用(存帳密、註冊轉換追蹤),重進會重複觸發
|
|
92
|
+
userInfoRetrying: {
|
|
93
|
+
invoke: {
|
|
94
|
+
src: 'fetchUserInfo',
|
|
95
|
+
onDone: {
|
|
96
|
+
target: 'otpChecking',
|
|
97
|
+
actions: ['setUserInfo', 'extendToken'],
|
|
98
|
+
},
|
|
99
|
+
onError: [{ target: 'userInfoRetrying', cond: 'isSelfTimeout' }, { target: 'leaving' }],
|
|
100
|
+
},
|
|
101
|
+
on: {
|
|
102
|
+
LOGOUT: {
|
|
89
103
|
target: 'leaving',
|
|
90
104
|
},
|
|
91
105
|
},
|
|
@@ -176,9 +190,8 @@ export default function (request) {
|
|
|
176
190
|
target: 'inline',
|
|
177
191
|
actions: ['setUserInfo', 'extendToken'],
|
|
178
192
|
},
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
},
|
|
193
|
+
// /self 逾時不登出:重進本狀態再發一筆;token 的 5 分鐘 TTL 到期後 send() 改回 ERR_A103,自然走 leaving
|
|
194
|
+
onError: [{ target: 'tokenAuthenticated', cond: 'isSelfTimeout' }, { target: 'leaving' }],
|
|
182
195
|
},
|
|
183
196
|
},
|
|
184
197
|
inline: {
|
|
@@ -194,14 +207,12 @@ export default function (request) {
|
|
|
194
207
|
},
|
|
195
208
|
fetching: {
|
|
196
209
|
invoke: {
|
|
197
|
-
src: '
|
|
210
|
+
src: 'pollUserInfo',
|
|
198
211
|
onDone: {
|
|
199
212
|
target: 'pending',
|
|
200
213
|
actions: ['setUserInfo', 'extendToken'],
|
|
201
214
|
},
|
|
202
|
-
onError: {
|
|
203
|
-
target: '#auth.leaving',
|
|
204
|
-
},
|
|
215
|
+
onError: [{ target: 'pending', cond: 'isSelfTimeout' }, { target: '#auth.leaving' }],
|
|
205
216
|
},
|
|
206
217
|
},
|
|
207
218
|
},
|
|
@@ -236,21 +247,17 @@ export default function (request) {
|
|
|
236
247
|
target: 'pending',
|
|
237
248
|
actions: ['setUserInfo', 'extendToken'],
|
|
238
249
|
},
|
|
239
|
-
onError: {
|
|
240
|
-
target: '#auth.leaving',
|
|
241
|
-
},
|
|
250
|
+
onError: [{ target: 'pending', cond: 'isSelfTimeout' }, { target: '#auth.leaving' }],
|
|
242
251
|
},
|
|
243
252
|
},
|
|
244
253
|
fetching: {
|
|
245
254
|
invoke: {
|
|
246
|
-
src: '
|
|
255
|
+
src: 'pollUserInfo',
|
|
247
256
|
onDone: {
|
|
248
257
|
target: 'pending',
|
|
249
258
|
actions: ['setUserInfo', 'extendToken'],
|
|
250
259
|
},
|
|
251
|
-
onError: {
|
|
252
|
-
target: '#auth.leaving',
|
|
253
|
-
},
|
|
260
|
+
onError: [{ target: 'pending', cond: 'isSelfTimeout' }, { target: '#auth.leaving' }],
|
|
254
261
|
},
|
|
255
262
|
},
|
|
256
263
|
pending: {
|
|
@@ -343,6 +350,10 @@ export default function (request) {
|
|
|
343
350
|
isNotInline: (context, event) => {
|
|
344
351
|
return !(context.userInfo?.rank >= 0)
|
|
345
352
|
},
|
|
353
|
+
// 只認請求層 15 秒逾時(request.js 的 isTimeout);一般 ERR_998 與驗證失敗維持原路由
|
|
354
|
+
isSelfTimeout: (context, event) => {
|
|
355
|
+
return event.data?.isTimeout === true
|
|
356
|
+
},
|
|
346
357
|
},
|
|
347
358
|
actions: {
|
|
348
359
|
setSiteConfig: assign((context, event) => {
|
|
@@ -415,16 +426,12 @@ export default function (request) {
|
|
|
415
426
|
}
|
|
416
427
|
}),
|
|
417
428
|
fetchToken: assign((context, event) => {
|
|
418
|
-
const token = storage.get(tokenKey)
|
|
419
429
|
return {
|
|
420
|
-
token,
|
|
430
|
+
token: request.getToken(),
|
|
421
431
|
}
|
|
422
432
|
}),
|
|
423
433
|
setToken: assign((context, event) => {
|
|
424
|
-
|
|
425
|
-
path: '/',
|
|
426
|
-
maxAge: 300,
|
|
427
|
-
})
|
|
434
|
+
request.setToken(event.data)
|
|
428
435
|
return {
|
|
429
436
|
token: event.data,
|
|
430
437
|
}
|
|
@@ -466,19 +473,11 @@ export default function (request) {
|
|
|
466
473
|
}
|
|
467
474
|
}),
|
|
468
475
|
removeToken: assign((context, event) => {
|
|
469
|
-
|
|
470
|
-
path: '/',
|
|
471
|
-
maxAge: 300,
|
|
472
|
-
})
|
|
476
|
+
request.removeToken()
|
|
473
477
|
return { token: null, dt: null }
|
|
474
478
|
}),
|
|
475
479
|
extendToken: assign((context, event) => {
|
|
476
|
-
|
|
477
|
-
storage.set(tokenKey, token, {
|
|
478
|
-
path: '/',
|
|
479
|
-
maxAge: 300,
|
|
480
|
-
})
|
|
481
|
-
return { token }
|
|
480
|
+
return { token: request.extendToken() }
|
|
482
481
|
}),
|
|
483
482
|
redirectTo3Party: async (context, event) => {
|
|
484
483
|
const { provider, fc } = event.data
|
|
@@ -566,6 +565,10 @@ export default function (request) {
|
|
|
566
565
|
fetchUserInfo: async (context, event) => {
|
|
567
566
|
return await request.send(user.getUserInfo())
|
|
568
567
|
},
|
|
568
|
+
// 例行輪詢的 /self 自成一類(channel),與各處單獨發的 /self 互不共用在途、互不影響
|
|
569
|
+
pollUserInfo: async (context, event) => {
|
|
570
|
+
return await request.send({ ...user.getUserInfo(), channel: 'polling' })
|
|
571
|
+
},
|
|
569
572
|
checkDeviceToken: async (context, event) => {
|
|
570
573
|
const deviceTokenEnable = context.siteConfig?.dtVerify
|
|
571
574
|
if (!deviceTokenEnable) return { dt: null }
|
package/src/machine/game_v2_1.js
CHANGED
|
@@ -6,6 +6,8 @@ import { GAME_SEARCH } from '../util/constant.js'
|
|
|
6
6
|
// 對應 intersectionObserver 版本
|
|
7
7
|
export default function (request) {
|
|
8
8
|
const { appSecret } = request.config
|
|
9
|
+
// 不呼叫 game/logout 直接回 idle:session 已換新時,舊 session 的遊戲登出沒有意義
|
|
10
|
+
const abandonGame = { target: 'idle', actions: 'clearGameURL' }
|
|
9
11
|
return createMachine(
|
|
10
12
|
{
|
|
11
13
|
id: 'game',
|
|
@@ -160,6 +162,7 @@ export default function (request) {
|
|
|
160
162
|
EXIT_GAME: {
|
|
161
163
|
target: 'disconnect',
|
|
162
164
|
},
|
|
165
|
+
ABANDON_GAME: abandonGame,
|
|
163
166
|
},
|
|
164
167
|
},
|
|
165
168
|
demoGame: {
|
|
@@ -178,6 +181,7 @@ export default function (request) {
|
|
|
178
181
|
EXIT_GAME: {
|
|
179
182
|
target: 'disconnect',
|
|
180
183
|
},
|
|
184
|
+
ABANDON_GAME: abandonGame,
|
|
181
185
|
},
|
|
182
186
|
},
|
|
183
187
|
connectSwitching: {
|
|
@@ -196,6 +200,7 @@ export default function (request) {
|
|
|
196
200
|
EXIT_GAME: {
|
|
197
201
|
target: 'disconnect',
|
|
198
202
|
},
|
|
203
|
+
ABANDON_GAME: abandonGame,
|
|
199
204
|
},
|
|
200
205
|
},
|
|
201
206
|
playing: {
|
|
@@ -203,6 +208,7 @@ export default function (request) {
|
|
|
203
208
|
EXIT_GAME: {
|
|
204
209
|
target: 'disconnect',
|
|
205
210
|
},
|
|
211
|
+
ABANDON_GAME: abandonGame,
|
|
206
212
|
REFRESH: {
|
|
207
213
|
target: 'refreshing',
|
|
208
214
|
},
|
|
@@ -224,6 +230,7 @@ export default function (request) {
|
|
|
224
230
|
EXIT_GAME: {
|
|
225
231
|
target: 'disconnect',
|
|
226
232
|
},
|
|
233
|
+
ABANDON_GAME: abandonGame,
|
|
227
234
|
EXIT_DEMO_GAME: {
|
|
228
235
|
target: 'idle',
|
|
229
236
|
},
|
|
@@ -245,6 +252,9 @@ export default function (request) {
|
|
|
245
252
|
actions: 'setGameURL',
|
|
246
253
|
},
|
|
247
254
|
},
|
|
255
|
+
on: {
|
|
256
|
+
ABANDON_GAME: abandonGame,
|
|
257
|
+
},
|
|
248
258
|
},
|
|
249
259
|
refreshPending: {
|
|
250
260
|
after: {
|
|
@@ -252,6 +262,9 @@ export default function (request) {
|
|
|
252
262
|
target: 'connecting',
|
|
253
263
|
},
|
|
254
264
|
},
|
|
265
|
+
on: {
|
|
266
|
+
ABANDON_GAME: abandonGame,
|
|
267
|
+
},
|
|
255
268
|
},
|
|
256
269
|
disconnect: {
|
|
257
270
|
invoke: {
|
|
@@ -266,6 +279,7 @@ export default function (request) {
|
|
|
266
279
|
},
|
|
267
280
|
},
|
|
268
281
|
on: {
|
|
282
|
+
ABANDON_GAME: abandonGame,
|
|
269
283
|
LOAD: {
|
|
270
284
|
target: 'routing',
|
|
271
285
|
actions: 'setLoadable',
|
|
@@ -426,6 +440,7 @@ export default function (request) {
|
|
|
426
440
|
return event.data.gameWalletType
|
|
427
441
|
},
|
|
428
442
|
}),
|
|
443
|
+
clearGameURL: assign({ type: undefined, gameToken: undefined, gameHtml: undefined, gameURL: undefined, gameWalletType: undefined }),
|
|
429
444
|
setGameInfo: assign((context, event) => {
|
|
430
445
|
const { providerId, gameId, gameTypeId, mappingId, portrait, gameCode, name, gameName } = event.data.game
|
|
431
446
|
return { game: { providerId, gameId, gameTypeId, mappingId, portrait: portrait ? 1 : 0, gameCode, name, gameName } }
|
|
@@ -197,7 +197,7 @@ export default function (request, context) {
|
|
|
197
197
|
)
|
|
198
198
|
const getOtherRewardAPI = request.send(
|
|
199
199
|
activity.getRewardList({
|
|
200
|
-
rewardType: 'CASH,FREE,PRIZE',
|
|
200
|
+
rewardType: 'CASH,FREE,PRIZE,GAME',
|
|
201
201
|
count: 30,
|
|
202
202
|
appSecret,
|
|
203
203
|
orderColumn,
|
|
@@ -212,7 +212,7 @@ export default function (request, context) {
|
|
|
212
212
|
const lang = context.lang
|
|
213
213
|
const getOtherRewardAPI = request.send(
|
|
214
214
|
activity.getRewardList({
|
|
215
|
-
rewardType: 'CASH,FREE,PRIZE',
|
|
215
|
+
rewardType: 'CASH,FREE,PRIZE,GAME',
|
|
216
216
|
count: 30,
|
|
217
217
|
appSecret,
|
|
218
218
|
orderColumn,
|
|
@@ -107,6 +107,7 @@ export default function (request) {
|
|
|
107
107
|
return {
|
|
108
108
|
signUpData: {
|
|
109
109
|
provider: 'local',
|
|
110
|
+
birthday,
|
|
110
111
|
...pickBindData(event.data),
|
|
111
112
|
birthday,
|
|
112
113
|
email,
|
|
@@ -130,6 +131,7 @@ export default function (request) {
|
|
|
130
131
|
return {
|
|
131
132
|
signUpData: {
|
|
132
133
|
provider: 'phone',
|
|
134
|
+
birthday,
|
|
133
135
|
...pickBindData(event.data),
|
|
134
136
|
birthday,
|
|
135
137
|
email,
|
|
@@ -152,6 +154,7 @@ export default function (request) {
|
|
|
152
154
|
return {
|
|
153
155
|
signUpData: {
|
|
154
156
|
provider: 'email',
|
|
157
|
+
birthday,
|
|
155
158
|
...pickBindData(event.data),
|
|
156
159
|
birthday,
|
|
157
160
|
email,
|
|
@@ -36,9 +36,8 @@ export default function (request, context) {
|
|
|
36
36
|
target: 'checking',
|
|
37
37
|
actions: 'setInitData',
|
|
38
38
|
},
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
},
|
|
39
|
+
// submitted 的 REFRESH 失敗時無法確認訂單已結束,保留原 Pending 畫面讓下次 REFRESH 可重試
|
|
40
|
+
onError: [{ target: 'submitted', cond: 'isProcessing' }, { target: 'loaded' }],
|
|
42
41
|
},
|
|
43
42
|
},
|
|
44
43
|
checking: {
|
|
@@ -96,7 +95,11 @@ export default function (request, context) {
|
|
|
96
95
|
},
|
|
97
96
|
},
|
|
98
97
|
},
|
|
99
|
-
submitted: {
|
|
98
|
+
submitted: {
|
|
99
|
+
on: {
|
|
100
|
+
REFRESH: { target: 'loading', internal: false },
|
|
101
|
+
},
|
|
102
|
+
},
|
|
100
103
|
otp: {
|
|
101
104
|
type: 'parallel',
|
|
102
105
|
states: {
|
package/src/request/request.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import pickBy from 'lodash/pickBy.js'
|
|
2
|
-
import
|
|
2
|
+
import createTokenStore from '../util/tokenStore.js'
|
|
3
3
|
import { getErr998SentryExtra } from '../util/err998SentryExtra.js'
|
|
4
|
+
import { SELF_REQUEST_TIMEOUT_MS } from '../util/constant.js'
|
|
4
5
|
|
|
5
6
|
// 暫停 ERR_998 上報:在組裝 Sentry 資料之前就中止,不建立事件;仍照常 reject ERR_998 給呼叫端。恢復時改回 false 即可
|
|
6
7
|
const IS_ERR_998_REPORT_PAUSED = true
|
|
7
8
|
|
|
8
9
|
const CANCELLED_MESSAGE = 'Requests Cancelled'
|
|
9
10
|
|
|
11
|
+
const SELF_URL = 'self'
|
|
12
|
+
const TOKEN_EXPIRED_CODE = 'ERR_A108'
|
|
13
|
+
|
|
10
14
|
// const pickBy = require('lodash/pickBy')
|
|
11
15
|
const supportVersion2List = [
|
|
12
16
|
// 04-09 Update
|
|
@@ -159,10 +163,12 @@ export default class Request {
|
|
|
159
163
|
this.config = config
|
|
160
164
|
this.sentry = config.sentry
|
|
161
165
|
this.key = `cuora_${config.clientId}`
|
|
166
|
+
this.tokenStore = createTokenStore(this.key)
|
|
162
167
|
this.errorHandler = null
|
|
163
168
|
this.hosts = []
|
|
164
169
|
this.isBlocked = false
|
|
165
170
|
this.activeRequests = new Set() // { source, token }:僅追蹤非 public 且帶 token 的在途請求,供 revokeToken 取消
|
|
171
|
+
this.selfFlights = new Map() // 在途的 /self 讀取:同類別(channel)、同 token、同 descriptor 共用同一筆,結束即移除
|
|
166
172
|
this.revokedToken = null
|
|
167
173
|
this.tokenGate = null
|
|
168
174
|
this.clientIp = '' // 由外部 plugin(如 clientIp.client.js)非同步寫入,用於 ERR_998 Sentry 回報
|
|
@@ -281,7 +287,69 @@ export default class Request {
|
|
|
281
287
|
return !!this.axios.isCancel?.(error) || error?.message === CANCELLED_MESSAGE
|
|
282
288
|
}
|
|
283
289
|
|
|
290
|
+
_isSelf(req) {
|
|
291
|
+
return req.url.split('?')[0] === SELF_URL
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
_isSelfRead(req) {
|
|
295
|
+
return !req.isPublic && this._isSelf(req) && req.method.toUpperCase() === 'GET'
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
_isSelfWrite(req) {
|
|
299
|
+
return !req.isPublic && this._isSelf(req) && req.method.toUpperCase() === 'POST'
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// GET /self 成功(任何類別)即證明 token 仍有效:比照 auth machine 的 extendToken 續 5 分鐘。
|
|
303
|
+
// 主輪詢連續逾時期間,只要其他類別的 GET /self 有一筆成功就不該被 TTL 登出。
|
|
304
|
+
// POST /self 不續:後端只在 GET /self 續期 token
|
|
305
|
+
_extendToken(requestToken) {
|
|
306
|
+
if (requestToken && requestToken === this.getToken()) this.extendToken()
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// /self 讀取分三類(descriptor 的 channel):主輪詢 polling/免費遊戲輪詢 freeGame/單獨呼叫 standalone(預設)。
|
|
310
|
+
// 類別之間各發各的,不共用在途;同一類別內單一在途:在途期間相同的呼叫共用同一筆結果不另發。
|
|
311
|
+
// key 含 channel、token 與 descriptor:換身分或參數不同(錯誤處理不同)各自獨立;自帶 customToken 者由呼叫端管理,不共用
|
|
284
312
|
async send(req, customToken) {
|
|
313
|
+
const token = !customToken && this._isSelfRead(req) ? this.getToken() : null
|
|
314
|
+
if (!token) return this._send(req, customToken)
|
|
315
|
+
|
|
316
|
+
const key = JSON.stringify([req.channel || 'standalone', token, req.url, req.params ?? null, req.headers ?? null, !!req.silent])
|
|
317
|
+
const inFlight = this.selfFlights.get(key)
|
|
318
|
+
if (inFlight) return inFlight
|
|
319
|
+
|
|
320
|
+
const flight = this._send(req).finally(() => {
|
|
321
|
+
if (this.selfFlights.get(key) === flight) this.selfFlights.delete(key)
|
|
322
|
+
})
|
|
323
|
+
this.selfFlights.set(key, flight)
|
|
324
|
+
return flight
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// 逾時視同網路失敗(ERR_998:不進 errorHandler、不彈窗),並取消請求。
|
|
328
|
+
// 不用 axios 的 timeout:ECONNABORTED 會被下游 axios-retry 重試;取消的錯誤不帶 config,不會被重試
|
|
329
|
+
_requestWithTimeout(requestConfig, tracked, timeoutMs) {
|
|
330
|
+
let timer
|
|
331
|
+
const timeout = new Promise((resolve, reject) => {
|
|
332
|
+
timer = setTimeout(() => {
|
|
333
|
+
reject({ code: 'ERR_998', endpoint: requestConfig.url, isTimeout: true })
|
|
334
|
+
tracked?.source.cancel(CANCELLED_MESSAGE)
|
|
335
|
+
}, timeoutMs)
|
|
336
|
+
})
|
|
337
|
+
return Promise.race([this.axios.request(requestConfig), timeout]).finally(() => clearTimeout(timer))
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// ERR_A108 多半是續期的短暫落差:先以 /self 確認 session 仍在,成功才把原請求重送一次。
|
|
341
|
+
// /self 自己、已重送過的請求、送出後身分已變的請求都不重送
|
|
342
|
+
async _renewSession(req, requestToken) {
|
|
343
|
+
if (!requestToken || this._isSelf(req) || this.getToken() !== requestToken) return false
|
|
344
|
+
try {
|
|
345
|
+
await this._send({ url: SELF_URL, method: 'get', silent: true }, undefined, true)
|
|
346
|
+
} catch (error) {
|
|
347
|
+
return false
|
|
348
|
+
}
|
|
349
|
+
return this.getToken() === requestToken
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async _send(req, customToken, isRetry) {
|
|
285
353
|
let tracked = null
|
|
286
354
|
let requestToken = null
|
|
287
355
|
try {
|
|
@@ -292,7 +360,7 @@ export default class Request {
|
|
|
292
360
|
if (!req.isPublic) this._throwIfRevoked()
|
|
293
361
|
|
|
294
362
|
// /self 是 gate 自己的探測請求,不可等待 gate,否則死鎖
|
|
295
|
-
if (this.tokenGate && !req.isPublic &&
|
|
363
|
+
if (this.tokenGate && !req.isPublic && !this._isSelf(req)) {
|
|
296
364
|
await this.tokenGate
|
|
297
365
|
this._throwIfRevoked()
|
|
298
366
|
if (!this.getToken()) return Promise.reject({ code: 'ERR_A103' })
|
|
@@ -317,15 +385,33 @@ export default class Request {
|
|
|
317
385
|
if (this.isBlocked && !configUrls.includes(requestConfig.url)) {
|
|
318
386
|
// 狀態是維護中&請求非siteConfig,終止所有的請求,除了維護頁需要的資料(siteConfig)
|
|
319
387
|
} else {
|
|
320
|
-
|
|
388
|
+
// 單一在途必須配逾時釋放:請求卡住不回時,共用它的輪詢會跟著永久停止
|
|
389
|
+
const isSelfWrite = this._isSelfWrite(req)
|
|
390
|
+
if (isSelfWrite) {
|
|
391
|
+
// 寫入與讀取相反:每次嘗試各 15 秒,逾時(ECONNABORTED)交給下游 axios-retry 照現行設定重試;
|
|
392
|
+
// shouldResetTimeout 讓每次重試各有完整期限,否則期限由所有嘗試共用
|
|
393
|
+
requestConfig.timeout = SELF_REQUEST_TIMEOUT_MS
|
|
394
|
+
requestConfig['axios-retry'] = { shouldResetTimeout: true }
|
|
395
|
+
}
|
|
396
|
+
const { data } = await (this._isSelfRead(req)
|
|
397
|
+
? this._requestWithTimeout(requestConfig, tracked, SELF_REQUEST_TIMEOUT_MS)
|
|
398
|
+
: this.axios.request(requestConfig))
|
|
399
|
+
if (this._isSelfRead(req)) this._extendToken(requestToken)
|
|
321
400
|
return data
|
|
322
401
|
}
|
|
323
402
|
} catch (error) {
|
|
324
403
|
if (this._isCancelled(error)) throw this._cancelledError()
|
|
404
|
+
if (error?.code === TOKEN_EXPIRED_CODE && !isRetry && (await this._renewSession(req, requestToken))) {
|
|
405
|
+
return await this._send(req, customToken, true)
|
|
406
|
+
}
|
|
325
407
|
// 不可列舉:避免 Bearer token 隨 JSON.stringify/Sentry 序列化外洩,但 error.requestToken 仍可讀取
|
|
326
408
|
if (requestToken && error && typeof error === 'object' && Object.isExtensible(error)) {
|
|
327
409
|
Object.defineProperty(error, 'requestToken', { value: requestToken, enumerable: false, configurable: true })
|
|
328
410
|
}
|
|
411
|
+
// POST /self 重試用完仍逾時:比照讀取的逾時(ERR_998:不進 errorHandler、不彈窗)
|
|
412
|
+
if (error?.code === 'ECONNABORTED' && this._isSelfWrite(req)) {
|
|
413
|
+
throw { code: 'ERR_998', endpoint: req.url, isTimeout: true }
|
|
414
|
+
}
|
|
329
415
|
if (error.code === 'ERR_F108') {
|
|
330
416
|
this.isBlocked = true
|
|
331
417
|
this.errorHandler && this.errorHandler(error)
|
|
@@ -421,6 +507,19 @@ export default class Request {
|
|
|
421
507
|
}
|
|
422
508
|
|
|
423
509
|
getToken() {
|
|
424
|
-
return
|
|
510
|
+
return this.tokenStore.get()
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
setToken(token) {
|
|
514
|
+
this.tokenStore.set(token)
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// 回傳續期當下的 token;已不存在時回傳 null
|
|
518
|
+
extendToken() {
|
|
519
|
+
return this.tokenStore.extend()
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
removeToken() {
|
|
523
|
+
this.tokenStore.clear()
|
|
425
524
|
}
|
|
426
525
|
}
|
package/src/util/constant.js
CHANGED
|
@@ -22,3 +22,9 @@ export const GAME_TYPE_LIST = [
|
|
|
22
22
|
// OTP 自動驗證:主動打的 /self 未通過後,最多再等幾次 auth 例行輪詢的 /self、等待上限多久
|
|
23
23
|
export const AUTO_VERIFY_MAX_USER_INFO_UPDATES = 2
|
|
24
24
|
export const AUTO_VERIFY_WAIT_MS = 5000
|
|
25
|
+
|
|
26
|
+
// 登入 token 的存活秒數:每次 /self 成功續期一次,逾時由瀏覽器自行移除 cookie
|
|
27
|
+
export const TOKEN_MAX_AGE = 300
|
|
28
|
+
|
|
29
|
+
// /self 讀取的逾時上限:後端 5 分鐘沒收到 /self 會移除 token,逾時釋放在途後由下一輪輪詢重發
|
|
30
|
+
export const SELF_REQUEST_TIMEOUT_MS = 15000
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import storage from './storage.js'
|
|
2
|
+
import { TOKEN_MAX_AGE } from './constant.js'
|
|
3
|
+
|
|
4
|
+
// document.cookie 在受限的環境(sandbox iframe、停用 cookie)會直接拋錯:讀不到視為沒有,寫不進去就算了
|
|
5
|
+
function read(name) {
|
|
6
|
+
const prefix = `${name}=`
|
|
7
|
+
try {
|
|
8
|
+
const pair = document.cookie.split('; ').find((item) => item.startsWith(prefix))
|
|
9
|
+
return pair ? decodeURIComponent(pair.slice(prefix.length)) || null : null
|
|
10
|
+
} catch (error) {
|
|
11
|
+
return null
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// 不帶 Domain:cookie 只屬於寫入它的網域,不跨子網域
|
|
16
|
+
function write(name, value, maxAge) {
|
|
17
|
+
try {
|
|
18
|
+
const secure = location.protocol === 'https:' ? '; Secure' : ''
|
|
19
|
+
document.cookie = `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}; SameSite=Lax${secure}`
|
|
20
|
+
} catch (error) {
|
|
21
|
+
console.error(`Error writing cookie: ${error}`)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export default function createTokenStore(key) {
|
|
26
|
+
// token 原本存在 localStorage;改放 cookie 後不沿用舊值,殘留的一併清掉
|
|
27
|
+
storage.remove(key)
|
|
28
|
+
|
|
29
|
+
const store = {
|
|
30
|
+
get: () => read(key),
|
|
31
|
+
set(token) {
|
|
32
|
+
if (token) write(key, token, TOKEN_MAX_AGE)
|
|
33
|
+
else store.clear()
|
|
34
|
+
},
|
|
35
|
+
// 以現有的值重寫一次,讓存活時間重新起算
|
|
36
|
+
extend() {
|
|
37
|
+
const token = read(key)
|
|
38
|
+
if (token) write(key, token, TOKEN_MAX_AGE)
|
|
39
|
+
return token
|
|
40
|
+
},
|
|
41
|
+
clear: () => write(key, '', 0),
|
|
42
|
+
}
|
|
43
|
+
return store
|
|
44
|
+
}
|