@jetthai/cuora 1.1.483-dev.4 → 1.1.485-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.
Files changed (89) hide show
  1. package/CHANGELOG.md +42 -2
  2. package/docs/my-claude/feat-sharon-JT-1790247240-socket/branch-transfer.md +14 -0
  3. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-preparation.json +40 -0
  4. package/docs/my-claude/feat-sharon-JT-1790247240-socket/cash-module-verification.md +41 -0
  5. package/docs/my-claude/feat-sharon-JT-1790247240-socket/implementation-ledger.md +87 -0
  6. package/docs/my-claude/feat-sharon-JT-1790247240-socket/module-report.md +73 -0
  7. package/docs/my-claude/feat-sharon-JT-1790247240-socket/plan.md +309 -0
  8. package/docs/my-claude/feat-sharon-JT-1790247240-socket/test-cases.md +245 -0
  9. package/docs/my-claude/feat-sharon-JT-1791180540-onesignal/transfer.md +9 -0
  10. package/e2e/feature-map.md +61 -0
  11. package/package.json +1 -1
  12. package/prepare-for-pr/JT-1776243420.md +85 -0
  13. package/prepare-for-pr/TI-16026/STATE.md +17 -0
  14. package/prepare-for-pr/TI-16026/after-prepare-authorization.md +3 -0
  15. package/prepare-for-pr/TI-16026/analysis.md +38 -0
  16. package/prepare-for-pr/TI-16026/answer-analyze-01.md +1 -0
  17. package/prepare-for-pr/TI-16026/answer-commit-01.md +2 -0
  18. package/prepare-for-pr/TI-16026/answer-commit-02.md +1 -0
  19. package/prepare-for-pr/TI-16026/bundle.json +18 -0
  20. package/prepare-for-pr/TI-16026/checklist.md +39 -0
  21. package/prepare-for-pr/TI-16026/claude-after-model +1 -0
  22. package/prepare-for-pr/TI-16026/claude-commit-session +1 -0
  23. package/prepare-for-pr/TI-16026/claude-harvest-session +1 -0
  24. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.err +1 -0
  25. package/prepare-for-pr/TI-16026/claude-hops/01-analyze.out +2 -0
  26. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.err +1 -0
  27. package/prepare-for-pr/TI-16026/claude-hops/02-analyze.out +4 -0
  28. package/prepare-for-pr/TI-16026/claude-hops/03-dev.err +1 -0
  29. package/prepare-for-pr/TI-16026/claude-hops/03-dev.out +4 -0
  30. package/prepare-for-pr/TI-16026/claude-hops/04-dev.err +1 -0
  31. package/prepare-for-pr/TI-16026/claude-hops/04-dev.out +4 -0
  32. package/prepare-for-pr/TI-16026/claude-hops/05-dev.err +1 -0
  33. package/prepare-for-pr/TI-16026/claude-hops/05-dev.out +3 -0
  34. package/prepare-for-pr/TI-16026/claude-hops/06-after.err +1 -0
  35. package/prepare-for-pr/TI-16026/claude-hops/06-after.out +2 -0
  36. package/prepare-for-pr/TI-16026/claude-hops/07-commit.err +1 -0
  37. package/prepare-for-pr/TI-16026/claude-hops/07-commit.out +2 -0
  38. package/prepare-for-pr/TI-16026/claude-hops/08-commit.err +1 -0
  39. package/prepare-for-pr/TI-16026/claude-hops/08-commit.out +2 -0
  40. package/prepare-for-pr/TI-16026/claude-hops/09-commit.err +1 -0
  41. package/prepare-for-pr/TI-16026/claude-hops/09-commit.out +8 -0
  42. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.err +1 -0
  43. package/prepare-for-pr/TI-16026/claude-hops/10-harvest.out +3 -0
  44. package/prepare-for-pr/TI-16026/commit-note.md +5 -0
  45. package/prepare-for-pr/TI-16026/feature-map.before.md +61 -0
  46. package/prepare-for-pr/TI-16026/harvest-redaction.out +1 -0
  47. package/prepare-for-pr/TI-16026/harvest.md +37 -0
  48. package/prepare-for-pr/TI-16026/lessons.md +5 -0
  49. package/prepare-for-pr/TI-16026/open-questions.md +6 -0
  50. package/prepare-for-pr/TI-16026/publish.md +28 -0
  51. package/prepare-for-pr/TI-16026/review-convergence-response.md +3 -0
  52. package/prepare-for-pr/TI-16026/review-input/scope.md +18 -0
  53. package/prepare-for-pr/TI-16026/review-log.md +57 -0
  54. package/prepare-for-pr/TI-16026/review-notes.md +97 -0
  55. package/prepare-for-pr/TI-16026/review-response-r1.md +7 -0
  56. package/prepare-for-pr/TI-16026/spec-proposal.md +34 -0
  57. package/prepare-for-pr/TI-16026/spec-snapshot.md +291 -0
  58. package/prepare-for-pr/TI-16026/state-log.md +35 -0
  59. package/prepare-for-pr/TI-16026/user-messages/01.md +12 -0
  60. package/prepare-for-pr/TI-16026/user-messages/02.md +20 -0
  61. package/prepare-for-pr/TI-16026/user-messages/03.md +1 -0
  62. package/prepare-for-pr/TI-16026/user-messages/04.md +1 -0
  63. package/prepare-for-pr/TI-16026/user-messages/05.md +1 -0
  64. package/prepare-for-pr/TI-16026/user-messages/06.md +1 -0
  65. package/prepare-for-pr/TI-16026/user-messages/07.md +1 -0
  66. package/prepare-for-pr/TI-16026/user-messages/08.md +1 -0
  67. package/prepare-for-pr/TI-16026/user-messages/09.md +1 -0
  68. package/prepare-for-pr/TI-16026/user-messages/10.md +1 -0
  69. package/prepare-for-pr/TI-16026/user-messages/11.md +1 -0
  70. package/prepare-for-pr/TI-16026/user-messages/12.md +1 -0
  71. package/prepare-for-pr/TI-16026/user-messages/13.md +1 -0
  72. package/prepare-for-pr/TI-16026/user-messages/14.md +1 -0
  73. package/prepare-for-pr/TI-16026/user-messages/15.md +1 -0
  74. package/prepare-for-pr/TI-16026/user-messages/16.md +1 -0
  75. package/prepare-for-pr/TI-16026/user-messages/17.md +1 -0
  76. package/prepare-for-pr/TI-16026/user-messages/18.md +10 -0
  77. package/prepare-for-pr/TI-16026/user-messages/19.md +1 -0
  78. package/prepare-for-pr/TI-16026/user-messages/20.md +1 -0
  79. package/prepare-for-pr/TI-16026/user-messages/21.md +1 -0
  80. package/prepare-for-pr/TI-16026/user-messages/22.md +1 -0
  81. package/prepare-for-pr/TI-16026/user-messages/23.md +8 -0
  82. package/prepare-for-pr/TI-16026/user-question.md +24 -0
  83. package/prepare-for-pr/TI-16026/verify-after.md +15 -0
  84. package/prepare-for-pr/TI-16026.md +408 -0
  85. package/src/machine/websocket.js +380 -311
  86. package/src/machine/withdraw/withdraw_manual_cash.js +7 -4
  87. package/src/util/socketPolicy.js +57 -0
  88. package/test/withdraw_manual_cash.test.js +149 -0
  89. package/tests/websocket.test.mjs +779 -0
@@ -0,0 +1,779 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { readFile } from 'node:fs/promises'
4
+ import { interpret } from 'xstate'
5
+ import { canResume, createPushDedupe, decideNextStep, nextRetryDelay } from '../src/util/socketPolicy.js'
6
+
7
+ const sourceURL = new URL('../src/machine/websocket.js', import.meta.url)
8
+ const source = (await readFile(sourceURL, 'utf8'))
9
+ .replace("import { io } from 'socket.io-client'", 'const io = (...args) => globalThis.__socketTestIo(...args)')
10
+ .replace("from 'xstate'", `from '${new URL('../node_modules/xstate/lib/index.js', import.meta.url).href}'`)
11
+ .replace("from '../util/socketPolicy.js'", `from '${new URL('../src/util/socketPolicy.js', import.meta.url).href}'`)
12
+ const { default: websocket } = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`)
13
+
14
+ class Socket {
15
+ constructor(url, options) {
16
+ this.url = url
17
+ this.options = options
18
+ this.handlers = new Map()
19
+ this.connected = false
20
+ this.active = true
21
+ this.recovered = false
22
+ this.closed = 0
23
+ }
24
+ on(name, handler) {
25
+ if (!this.handlers.has(name)) this.handlers.set(name, new Set())
26
+ this.handlers.get(name).add(handler)
27
+ return this
28
+ }
29
+ off(name, handler) {
30
+ this.handlers.get(name)?.delete(handler)
31
+ return this
32
+ }
33
+ disconnect() {
34
+ this.closed++
35
+ this.connected = false
36
+ this.active = false
37
+ this.emit('disconnect', 'io client disconnect')
38
+ return this
39
+ }
40
+ emit(name, data) {
41
+ if (name === 'connect') this.connected = true
42
+ if (name === 'disconnect') this.connected = false
43
+ for (const handler of [...(this.handlers.get(name) || [])]) handler(data)
44
+ }
45
+ }
46
+
47
+ const flush = async () => {
48
+ for (let i = 0; i < 30; i++) await Promise.resolve()
49
+ }
50
+ function setup(t, token = 'T1') {
51
+ const saved = {
52
+ fetch: globalThis.fetch,
53
+ io: globalThis.__socketTestIo,
54
+ timeout: globalThis.setTimeout,
55
+ clear: globalThis.clearTimeout,
56
+ now: Date.now,
57
+ random: Math.random,
58
+ }
59
+ let now = 100000,
60
+ next = 1
61
+ const timers = new Map(),
62
+ sockets = [],
63
+ fetches = [],
64
+ pushes = [],
65
+ events = []
66
+ globalThis.setTimeout = (fn, delay = 0) => {
67
+ const id = next++
68
+ timers.set(id, { fn, at: now + delay })
69
+ return id
70
+ }
71
+ globalThis.clearTimeout = (id) => timers.delete(id)
72
+ Date.now = () => now
73
+ Math.random = () => 0.5
74
+ let fetchImpl = async (url) =>
75
+ url.includes('target.json') ? { ok: true, json: async () => ({ socket: ['https://selected/frontend/'] }) } : { ok: true }
76
+ globalThis.fetch = (...args) => {
77
+ fetches.push(args)
78
+ return fetchImpl(...args)
79
+ }
80
+ globalThis.__socketTestIo = (url, options) => {
81
+ const socket = new Socket(url, options)
82
+ sockets.push(socket)
83
+ return socket
84
+ }
85
+ const request = { config: { socketURL: 'https://fallback', bucketName: 'bucket', clientId: 'client' }, getToken: () => token }
86
+ const machine = websocket(request),
87
+ service = interpret(machine)
88
+ .onTransition((state) => events.push(state.event))
89
+ .start()
90
+ service.send({ type: 'SET_ANALYTICS', data: { push: (...args) => pushes.push(args) } })
91
+ const advance = async (ms) => {
92
+ const until = now + ms
93
+ while (true) {
94
+ const due = [...timers].filter(([, timer]) => timer.at <= until).sort((a, b) => a[1].at - b[1].at)[0]
95
+ if (!due) break
96
+ now = due[1].at
97
+ timers.delete(due[0])
98
+ due[1].fn()
99
+ await flush()
100
+ }
101
+ now = until
102
+ await flush()
103
+ }
104
+ t.after(() => {
105
+ service.stop()
106
+ globalThis.fetch = saved.fetch
107
+ globalThis.__socketTestIo = saved.io
108
+ globalThis.setTimeout = saved.timeout
109
+ globalThis.clearTimeout = saved.clear
110
+ Date.now = saved.now
111
+ Math.random = saved.random
112
+ })
113
+ return {
114
+ service,
115
+ sockets,
116
+ fetches,
117
+ pushes,
118
+ events,
119
+ timers,
120
+ advance,
121
+ setToken: (value) => {
122
+ token = value
123
+ },
124
+ setFetch: (fn) => {
125
+ fetchImpl = fn
126
+ },
127
+ async connect(source = 'user') {
128
+ service.send({ type: 'CHECK_SOCKET', source })
129
+ await flush()
130
+ return sockets.at(-1)
131
+ },
132
+ }
133
+ }
134
+ const fail = (socket) => {
135
+ socket.active = false
136
+ socket.emit('connect_error', { message: 'temporary', data: { retryable: true } })
137
+ }
138
+
139
+ test('anonymous triggers perform no selection or socket construction', async (t) => {
140
+ const h = setup(t, '')
141
+ await h.connect()
142
+ assert.equal(h.fetches.length, 0)
143
+ assert.equal(h.sockets.length, 0)
144
+ })
145
+ test('websocket only namespace and synchronous current RAW auth callback', async (t) => {
146
+ const h = setup(t)
147
+ const s = await h.connect()
148
+ assert.equal(s.url, 'https://selected/frontend')
149
+ assert.deepEqual(s.options.transports, ['websocket'])
150
+ h.setToken('RAW2')
151
+ let auth
152
+ s.options.auth((value) => {
153
+ auth = value
154
+ })
155
+ assert.deepEqual(auth, { Authorization: 'RAW2' })
156
+ })
157
+ test('selection lock prevents overlapping external attempts', async (t) => {
158
+ const h = setup(t)
159
+ let resolve
160
+ h.setFetch(
161
+ () =>
162
+ new Promise((r) => {
163
+ resolve = r
164
+ })
165
+ )
166
+ h.service.send('CONNECT')
167
+ h.service.send('CHECK_SOCKET')
168
+ assert.equal(h.fetches.length, 1)
169
+ resolve({ json: async () => ({ socket: [] }) })
170
+ await flush()
171
+ assert.equal(h.sockets.length, 1)
172
+ })
173
+ test('active network reconnect retains instance and has a first-loss 120 second giveup', async (t) => {
174
+ const h = setup(t)
175
+ const s = await h.connect()
176
+ s.emit('connect')
177
+ s.emit('disconnect', 'transport close')
178
+ await h.advance(119000)
179
+ await h.connect()
180
+ assert.equal(h.sockets.length, 1)
181
+ s.emit('connect_error', { message: 'network' })
182
+ await h.advance(1000)
183
+ assert.equal(s.closed, 1)
184
+ assert.equal(h.service.state.context.blocked, 'exhausted')
185
+ await h.connect()
186
+ assert.equal(h.sockets.length, 2)
187
+ })
188
+ test('initial plus three automatic retries closes every failed instance', async (t) => {
189
+ const h = setup(t)
190
+ await h.connect()
191
+ for (const delay of [1000, 2000, 4000]) {
192
+ fail(h.sockets.at(-1))
193
+ await h.advance(delay)
194
+ }
195
+ fail(h.sockets.at(-1))
196
+ await h.advance(100000)
197
+ assert.equal(h.sockets.length, 4)
198
+ assert.ok(h.sockets.every((s) => s.closed === 1))
199
+ assert.equal(h.service.state.context.blocked, 'exhausted')
200
+ })
201
+ test('connect alone does not reset finite retry budget', async (t) => {
202
+ const h = setup(t)
203
+ await h.connect()
204
+ for (const delay of [1000, 2000, 4000]) {
205
+ h.sockets.at(-1).emit('connect')
206
+ fail(h.sockets.at(-1))
207
+ await h.advance(delay)
208
+ }
209
+ h.sockets.at(-1).emit('connect')
210
+ fail(h.sockets.at(-1))
211
+ await h.advance(10000)
212
+ assert.equal(h.sockets.length, 4)
213
+ })
214
+ test('pending server floor blocks both user and auto external attempts', async (t) => {
215
+ const h = setup(t)
216
+ const s = await h.connect()
217
+ s.active = false
218
+ s.emit('connect_error', { data: { retryable: true, retryAfterMs: 10000 } })
219
+ await h.connect('user')
220
+ await h.connect('auto')
221
+ await h.advance(9999)
222
+ assert.equal(h.sockets.length, 1)
223
+ await h.advance(1)
224
+ assert.equal(h.sockets.length, 2)
225
+ })
226
+ test('renew once immediately then finite retry and exhausted extra cannot renew', async (t) => {
227
+ const h = setup(t)
228
+ await h.connect()
229
+ const reject = () => {
230
+ const s = h.sockets.at(-1)
231
+ s.active = false
232
+ s.emit('connect_error', { data: { code: 'SESSION_TOKEN_INVALID' } })
233
+ }
234
+ reject()
235
+ await flush()
236
+ assert.equal(h.sockets.length, 2)
237
+ for (const delay of [1000, 2000, 4000]) {
238
+ reject()
239
+ await h.advance(delay)
240
+ }
241
+ reject()
242
+ await h.advance(50000)
243
+ assert.equal(h.sockets.length, 5)
244
+ await h.connect()
245
+ reject()
246
+ await h.advance(10000)
247
+ assert.equal(h.sockets.length, 6)
248
+ assert.equal(h.service.state.context.blocked, 'exhausted')
249
+ })
250
+ test('exhausted auto uses actual last attempt time and user extra failures stay exhausted', async (t) => {
251
+ const h = setup(t)
252
+ await h.connect()
253
+ for (const delay of [1000, 2000, 4000]) {
254
+ fail(h.sockets.at(-1))
255
+ await h.advance(delay)
256
+ }
257
+ fail(h.sockets.at(-1))
258
+ await h.advance(14999)
259
+ await h.connect('auto')
260
+ assert.equal(h.sockets.length, 4)
261
+ await h.advance(1)
262
+ await h.connect('auto')
263
+ assert.equal(h.sockets.length, 5)
264
+ fail(h.sockets.at(-1))
265
+ await h.advance(14999)
266
+ await h.connect('auto')
267
+ assert.equal(h.sockets.length, 5)
268
+ await h.connect('user')
269
+ assert.equal(h.sockets.length, 6)
270
+ })
271
+ test('stop only resumes for new token and kicked only resumes from user', async (t) => {
272
+ const h = setup(t)
273
+ let s = await h.connect()
274
+ s.active = false
275
+ s.emit('connect_error', { data: { retryable: false } })
276
+ await h.connect()
277
+ assert.equal(h.sockets.length, 1)
278
+ h.setToken('T2')
279
+ s = await h.connect()
280
+ s.emit('kicked', { message: 'old payload' })
281
+ await h.connect('auto')
282
+ assert.equal(h.sockets.length, 2)
283
+ assert.equal(h.service.state.context.connectError.code, 'MAX_CONNECTIONS')
284
+ await h.connect('user')
285
+ assert.equal(h.sockets.length, 3)
286
+ })
287
+ test('stale selection after token change and logout cannot construct a socket', async (t) => {
288
+ const h = setup(t)
289
+ const resolves = []
290
+ h.setFetch(() => new Promise((r) => resolves.push(r)))
291
+ h.service.send('CONNECT')
292
+ h.setToken('T2')
293
+ h.service.send('CHECK_SOCKET')
294
+ resolves[0]({ json: async () => ({ socket: [] }) })
295
+ await flush()
296
+ assert.equal(h.sockets.length, 0)
297
+ h.service.send('DISCONNECT_SOCKET')
298
+ resolves[1]({ json: async () => ({ socket: [] }) })
299
+ await flush()
300
+ assert.equal(h.sockets.length, 0)
301
+ })
302
+ test('stop removes every listener, cancels selection and timers; restart works', async (t) => {
303
+ const h = setup(t)
304
+ const s = await h.connect()
305
+ s.emit('disconnect', 'transport close')
306
+ h.service.stop()
307
+ assert.equal(s.closed, 1)
308
+ assert.equal(
309
+ [...s.handlers.values()].reduce((n, v) => n + v.size, 0),
310
+ 0
311
+ )
312
+ assert.equal(h.timers.size, 0)
313
+ h.service.start()
314
+ await h.connect()
315
+ assert.equal(h.sockets.length, 2)
316
+ })
317
+ test('all four push channels dedupe global opaque message IDs before any side effect', async (t) => {
318
+ const h = setup(t)
319
+ const s = await h.connect()
320
+ const payment = { _meta: { messageId: 'm' }, event: 'purchase', isTracking: true, data: { transactionId: 'T', value: 2, isFirst: true } }
321
+ for (const channel of ['payment-info', 'activity-info', 'activity-reward-info', 'message-notice-info']) s.emit(channel, payment)
322
+ assert.equal(h.events.filter((e) => e.type === 'ACTIVITY_INFO').length, 1)
323
+ assert.deepEqual(
324
+ h.pushes.map((p) => p[0].event),
325
+ ['purchase', 'first_deposit']
326
+ )
327
+ })
328
+ test('same tick unique pushes are individually delivered before ready', async (t) => {
329
+ const h = setup(t)
330
+ const s = await h.connect()
331
+ for (const messageId of ['1', '2', '3']) s.emit('message-notice-info', { _meta: { messageId } })
332
+ assert.equal(h.events.filter((e) => e.type === 'ACTIVITY_INFO').length, 3)
333
+ })
334
+ test('first/repeated/recovered ready never resync; fresh later generation does', async (t) => {
335
+ const h = setup(t)
336
+ let s = await h.connect()
337
+ s.emit('connect')
338
+ assert.equal(h.events.filter((e) => e.type === 'SESSION_READY').length, 0)
339
+ s.emit('session-ready', 'ok')
340
+ s.emit('session-ready', {})
341
+ assert.deepEqual(
342
+ h.events.filter((e) => e.type === 'SESSION_READY').map((e) => e.resync),
343
+ [false]
344
+ )
345
+ h.service.send({ type: 'DISCONNECT_SOCKET', preserveSession: true })
346
+ s = await h.connect()
347
+ s.recovered = true
348
+ s.emit('connect')
349
+ assert.deepEqual(
350
+ h.events.filter((e) => e.type === 'SESSION_READY').map((e) => e.resync),
351
+ [false, false]
352
+ )
353
+ h.service.send({ type: 'DISCONNECT_SOCKET', preserveSession: true })
354
+ s = await h.connect()
355
+ s.emit('session-ready', {})
356
+ assert.deepEqual(
357
+ h.events.filter((e) => e.type === 'SESSION_READY').map((e) => e.resync),
358
+ [false, false, true]
359
+ )
360
+ })
361
+ test('stale instance callbacks cannot update replacement or send pushes', async (t) => {
362
+ const h = setup(t)
363
+ const old = await h.connect()
364
+ const handlers = [...old.handlers].map(([name, fns]) => [name, [...fns]])
365
+ h.setToken('T2')
366
+ const fresh = await h.connect()
367
+ const count = h.events.length
368
+ for (const [name, fns] of handlers)
369
+ if (['connect', 'session-ready', 'payment-info'].includes(name))
370
+ for (const fn of fns) fn({ event: 'purchase', isTracking: true, data: { transactionId: 'old' } })
371
+ assert.equal(h.service.state.context.clientSocket, fresh)
372
+ assert.equal(h.events.length, count)
373
+ assert.equal(h.pushes.length, 0)
374
+ })
375
+ test('shared payment claims link known order aliases and preserve GA eventID', async (t) => {
376
+ const h = setup(t)
377
+ const s = await h.connect()
378
+ const claim = h.service.state.context.claimPaymentEvent
379
+ assert.equal(claim('purchase', { applyId: 'A', transactionId: 'T' }), true)
380
+ assert.equal(claim('purchase', { transactionId: 'T' }), false)
381
+ s.emit('payment-info', {
382
+ event: 'purchase',
383
+ isTracking: true,
384
+ data: { applyId: 'A', transactionId: 'T', isFirst: true, currency: 'THB', value: 99, paymentMethod: 'manual' },
385
+ })
386
+ assert.deepEqual(
387
+ h.pushes.map((p) => p[0].event),
388
+ ['first_deposit']
389
+ )
390
+ assert.deepEqual(h.pushes[0][1], { eventID: 'T' })
391
+ assert.equal(claim('first_deposit', { applyId: 'A' }), false)
392
+ assert.equal(claim('purchase', { transactionId: 'OTHER' }), true)
393
+ })
394
+ test('verified same UID token rotation waits for captured proof and restores session claims', async (t) => {
395
+ const h = setup(t)
396
+ let s = await h.connect()
397
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T1', uidSite: 'U1' })
398
+ s.emit('session-ready', {})
399
+ h.service.state.context.claimPaymentEvent('purchase', { transactionId: 'T' })
400
+ h.setToken('T2')
401
+ await h.connect('user')
402
+ assert.equal(h.sockets.length, 1)
403
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T1', uidSite: 'U2' })
404
+ await flush()
405
+ assert.equal(h.sockets.length, 1)
406
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T2', uidSite: 'U1' })
407
+ await flush()
408
+ assert.equal(h.sockets.length, 2)
409
+ assert.equal(h.service.state.context.claimPaymentEvent('purchase', { transactionId: 'T' }), false)
410
+ h.sockets.at(-1).emit('session-ready', {})
411
+ assert.equal(h.events.filter((e) => e.type === 'SESSION_READY').at(-1).resync, true)
412
+ })
413
+ test('different UID rotation clears claims, dedupe and hadSession', async (t) => {
414
+ const h = setup(t)
415
+ let s = await h.connect()
416
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T1', uidSite: 'U1' })
417
+ s.emit('session-ready', {})
418
+ s.emit('message-notice-info', { _meta: { messageId: 'M' } })
419
+ h.service.state.context.claimPaymentEvent('purchase', { transactionId: 'T' })
420
+ h.setToken('T2')
421
+ await h.connect()
422
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T2', uidSite: 'U2' })
423
+ await flush()
424
+ s = h.sockets.at(-1)
425
+ s.emit('message-notice-info', { _meta: { messageId: 'M' } })
426
+ s.emit('session-ready', {})
427
+ assert.equal(h.service.state.context.claimPaymentEvent('purchase', { transactionId: 'T' }), true)
428
+ assert.equal(h.events.filter((e) => e.type === 'ACTIVITY_INFO').length, 2)
429
+ assert.equal(h.events.filter((e) => e.type === 'SESSION_READY').at(-1).resync, false)
430
+ })
431
+ test('legacy consumers retain connected/idle and public context events', async (t) => {
432
+ const h = setup(t)
433
+ const s = await h.connect()
434
+ s.emit('connect')
435
+ assert.equal(h.service.state.matches('connected'), true)
436
+ assert.equal(h.service.state.context.connectStatus, 2)
437
+ h.service.send({ type: 'ACTIVITY_INFO', data: { x: 1 } })
438
+ assert.deepEqual(h.service.state.context.socketData, { x: 1 })
439
+ h.service.send('CLEAR_SOCKET_DATA')
440
+ assert.deepEqual(h.service.state.context.socketData, {})
441
+ h.service.send('DISCONNECT_SOCKET')
442
+ assert.equal(h.service.state.matches('idle'), true)
443
+ assert.equal(h.service.state.context.clientSocket, null)
444
+ })
445
+ test('logout during push consumer prevents subsequent analytics from that stale push', async (t) => {
446
+ const h = setup(t)
447
+ const s = await h.connect()
448
+ h.service.onTransition((state) => {
449
+ if (state.event.type === 'ACTIVITY_INFO') {
450
+ h.service.send('DISCONNECT_SOCKET')
451
+ h.setToken('T2')
452
+ h.service.send('CHECK_SOCKET')
453
+ }
454
+ })
455
+ s.emit('payment-info', { event: 'purchase', isTracking: true, data: { transactionId: 'old' } })
456
+ await flush()
457
+ assert.equal(h.pushes.length, 0)
458
+ })
459
+ test('same-token different UID proof closes prior session and clears claims', async (t) => {
460
+ const h = setup(t)
461
+ const s = await h.connect()
462
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T1', uidSite: 'U1' })
463
+ s.emit('session-ready', {})
464
+ h.service.state.context.claimPaymentEvent('purchase', { transactionId: 'T' })
465
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T1', uidSite: 'U2' })
466
+ assert.equal(s.closed, 1)
467
+ assert.equal(h.service.state.context.claimPaymentEvent('purchase', { transactionId: 'T' }), true)
468
+ const fresh = await h.connect()
469
+ fresh.emit('session-ready', {})
470
+ assert.equal(h.events.filter((e) => e.type === 'SESSION_READY').at(-1).resync, false)
471
+ })
472
+ test('late stopped selection and saved callback cannot alter restarted service', async (t) => {
473
+ const h = setup(t)
474
+ const s = await h.connect()
475
+ const saved = [...s.handlers.get('connect')][0]
476
+ h.service.send('DISCONNECT_SOCKET')
477
+ let resolve
478
+ h.setFetch(
479
+ () =>
480
+ new Promise((r) => {
481
+ resolve = r
482
+ })
483
+ )
484
+ h.service.send('CHECK_SOCKET')
485
+ h.service.stop()
486
+ h.setToken('T2')
487
+ h.setFetch(async () => ({ json: async () => ({ socket: [] }) }))
488
+ h.service.start()
489
+ const fresh = await h.connect()
490
+ const count = h.events.length
491
+ resolve({ json: async () => ({ socket: [] }) })
492
+ saved()
493
+ await flush()
494
+ assert.equal(h.service.state.context.clientSocket, fresh)
495
+ assert.equal(h.events.length, count)
496
+ })
497
+ test('background preserves stop/kicked and claims; explicit logout clears all', async (t) => {
498
+ const h = setup(t)
499
+ const s = await h.connect()
500
+ h.service.state.context.claimPaymentEvent('purchase', { applyId: 0 })
501
+ s.emit('kicked', {})
502
+ h.service.send({ type: 'DISCONNECT_SOCKET', preserveSession: true })
503
+ await h.connect('auto')
504
+ assert.equal(h.sockets.length, 1)
505
+ assert.equal(h.service.state.context.claimPaymentEvent('purchase', { applyId: 0 }), false)
506
+ h.service.send('DISCONNECT_SOCKET')
507
+ await h.connect('auto')
508
+ assert.equal(h.sockets.length, 2)
509
+ assert.equal(h.service.state.context.claimPaymentEvent('purchase', { applyId: 0 }), true)
510
+ })
511
+ test('blocked exhausted survives different error codes on an extra attempt', async (t) => {
512
+ const h = setup(t)
513
+ await h.connect()
514
+ for (const delay of [1000, 2000, 4000]) {
515
+ fail(h.sockets.at(-1))
516
+ await h.advance(delay)
517
+ }
518
+ fail(h.sockets.at(-1))
519
+ let s = await h.connect()
520
+ s.active = false
521
+ s.emit('connect_error', { data: { retryable: false } })
522
+ assert.equal(h.service.state.context.blocked, 'exhausted')
523
+ s = await h.connect()
524
+ s.emit('kicked', {})
525
+ assert.equal(h.service.state.context.blocked, 'exhausted')
526
+ })
527
+ test('background release and foreground user trigger respect outstanding server retry floor', async (t) => {
528
+ const h = setup(t)
529
+ const s = await h.connect()
530
+ s.active = false
531
+ s.emit('connect_error', { data: { retryable: true, retryAfterMs: 20000 } })
532
+ h.service.send({ type: 'DISCONNECT_SOCKET', preserveSession: true })
533
+ await h.connect('user')
534
+ assert.equal(h.sockets.length, 1)
535
+ await h.advance(19999)
536
+ assert.equal(h.sockets.length, 1)
537
+ await h.advance(1)
538
+ assert.equal(h.sockets.length, 2)
539
+ })
540
+ test('synchronous socket construction error schedules bounded retry', async (t) => {
541
+ const h = setup(t)
542
+ const original = globalThis.__socketTestIo
543
+ let once = true
544
+ globalThis.__socketTestIo = (...args) => {
545
+ if (once) {
546
+ once = false
547
+ throw new Error('construction failed')
548
+ }
549
+ return original(...args)
550
+ }
551
+ await h.connect()
552
+ assert.equal(h.service.state.context.connectStatus, 0)
553
+ await h.advance(1000)
554
+ assert.equal(h.sockets.length, 1)
555
+ })
556
+ test('auth-rejected always handles structured server rejection even while socket is active', async (t) => {
557
+ const h = setup(t)
558
+ let s = await h.connect()
559
+ s.emit('auth-rejected', { retryable: false })
560
+ assert.equal(s.closed, 1)
561
+ assert.equal(h.service.state.context.blocked, 'stop')
562
+ h.setToken('T2')
563
+ s = await h.connect()
564
+ s.emit('auth-rejected', { code: 'SESSION_TOKEN_INVALID' })
565
+ await flush()
566
+ assert.equal(h.sockets.length, 3)
567
+ })
568
+ test('after active loss a legacy server disconnect is unready and retries rather than kicks', async (t) => {
569
+ const h = setup(t)
570
+ const s = await h.connect()
571
+ s.emit('session-ready', 'ok')
572
+ s.emit('disconnect', 'transport close')
573
+ s.active = false
574
+ s.emit('disconnect', 'io server disconnect')
575
+ await h.advance(1000)
576
+ assert.equal(h.sockets.length, 2)
577
+ assert.notEqual(h.service.state.context.blocked, 'kicked')
578
+ })
579
+ test('same instance fresh nonrecovered ready after loss resyncs once; recovered does not', async (t) => {
580
+ const h = setup(t)
581
+ const s = await h.connect()
582
+ s.emit('session-ready', 'ok')
583
+ s.emit('disconnect', 'transport close')
584
+ s.emit('connect')
585
+ s.emit('session-ready', 'ok')
586
+ s.emit('session-ready', 'again')
587
+ s.emit('disconnect', 'transport close')
588
+ s.recovered = true
589
+ s.emit('connect')
590
+ s.emit('session-ready', 'ok')
591
+ assert.deepEqual(
592
+ h.events.filter((e) => e.type === 'SESSION_READY').map((e) => e.resync),
593
+ [false, true, false]
594
+ )
595
+ })
596
+ test('equal opaque payment IDs share claims across REST applyId and socket transactionId', async (t) => {
597
+ const h = setup(t)
598
+ await h.connect()
599
+ const claim = h.service.state.context.claimPaymentEvent
600
+ assert.equal(claim('purchase', { applyId: 'SAME' }), true)
601
+ assert.equal(claim('purchase', { transactionId: 'SAME' }), false)
602
+ assert.equal(claim('purchase', { transactionId: 'UNRELATED' }), true)
603
+ assert.equal(claim('purchase', { applyId: 'A', transactionId: 'T' }), true)
604
+ assert.equal(claim('purchase', { transactionId: 'T' }), false)
605
+ })
606
+ test('loss and release advance public generation to invalidate old REST flight', async (t) => {
607
+ const h = setup(t)
608
+ const s = await h.connect()
609
+ s.emit('session-ready', 'ok')
610
+ const before = h.service.state.context.generation
611
+ s.emit('disconnect', 'transport close')
612
+ const lost = h.service.state.context.generation
613
+ assert.ok(lost > before)
614
+ s.emit('connect_error', { message: 'network' })
615
+ assert.equal(h.service.state.context.generation, lost)
616
+ s.emit('session-ready', {})
617
+ assert.equal(h.events.filter((e) => e.type === 'SESSION_READY').at(-1).generation, lost)
618
+ h.service.send({ type: 'DISCONNECT_SOCKET', preserveSession: true })
619
+ assert.ok(h.service.state.context.generation > lost)
620
+ })
621
+ test('policy prioritizes client loss and active Socket.IO over rejection codes', () => {
622
+ for (const [input, want] of [
623
+ [{ event: 'disconnect', reason: 'io client disconnect', rejection: { code: 'MAX_CONNECTIONS' } }, 'none'],
624
+ [{ event: 'connect_error', active: true, err: { data: { code: 'MAX_CONNECTIONS' } } }, 'socketio'],
625
+ [{ event: 'kicked', rejection: { retryable: true } }, 'kicked'],
626
+ [{ event: 'auth-rejected', rejection: { code: 'MAX_CONNECTIONS', retryable: true } }, 'kicked'],
627
+ [{ event: 'auth-rejected', rejection: { code: 'SESSION_TOKEN_INVALID', retryable: false } }, 'renew'],
628
+ [{ event: 'auth-rejected', rejection: { retryable: false } }, 'stop'],
629
+ [{ event: 'auth-rejected', rejection: { retryable: true } }, 'retry'],
630
+ [{ event: 'disconnect', reason: 'io server disconnect', ready: true }, 'kicked'],
631
+ [{ event: 'disconnect', reason: 'io server disconnect', ready: false }, 'retry'],
632
+ [{ event: 'connect_error', err: { message: 'session rejected' } }, 'renew'],
633
+ [{ event: 'connect_error', err: { message: 'temporary' } }, 'retry'],
634
+ ])
635
+ assert.equal(decideNextStep(input), want)
636
+ })
637
+ test('policy resume rejects anonymous and stop, bounds exhausted auto at fifteen seconds', () => {
638
+ assert.equal(canResume({ lastToken: 'T', blocked: 'stop' }, ''), false)
639
+ assert.equal(canResume({ lastToken: 'T', blocked: 'stop' }, 'T', 'user'), false)
640
+ assert.equal(canResume({ lastToken: 'T', blocked: 'stop' }, 'N', 'auto'), true)
641
+ assert.equal(canResume({ lastToken: 'T', blocked: 'kicked' }, 'T', 'auto'), false)
642
+ assert.equal(canResume({ lastToken: 'T', blocked: 'kicked' }, 'T', 'user'), true)
643
+ assert.equal(canResume({ lastToken: 'T', blocked: 'exhausted', lastAttemptAt: 1 }, 'T', 'auto', 15000), false)
644
+ assert.equal(canResume({ lastToken: 'T', blocked: 'exhausted', lastAttemptAt: 1 }, 'T', 'auto', 15001), true)
645
+ })
646
+ test('retry jitter applies to capped base while server floor remains absolute', (t) => {
647
+ const original = Math.random
648
+ t.after(() => {
649
+ Math.random = original
650
+ })
651
+ Math.random = () => 0
652
+ assert.equal(nextRetryDelay(1), 500)
653
+ assert.equal(nextRetryDelay(2), 1000)
654
+ assert.equal(nextRetryDelay(3), 2000)
655
+ Math.random = () => 0.999999
656
+ assert.equal(nextRetryDelay(40), 45000)
657
+ assert.equal(nextRetryDelay(1, 60000), 60000)
658
+ assert.equal(nextRetryDelay(NaN, -1), 1500)
659
+ })
660
+ test('legacy payment dedupe uses explicit event and first nonempty nested or top-level ID including zero', () => {
661
+ const duplicate = createPushDedupe()
662
+ assert.equal(duplicate('payment-info', { event: 'purchase', data: { applyId: '', transactionId: 0 } }, 0), false)
663
+ assert.equal(duplicate('payment-info', { event: 'purchase', transactionId: 0 }, 1), true)
664
+ assert.equal(duplicate('payment-info', { event: 'withdraw', transactionId: 0 }, 2), false)
665
+ assert.equal(duplicate('payment-info', { transactionId: 0 }, 3), false)
666
+ assert.equal(duplicate('payment-info', { transactionId: 0 }, 4), false)
667
+ assert.equal(duplicate('activity-info', { event: 'purchase', transactionId: 0 }, 5), false)
668
+ assert.equal(duplicate('payment-info', { event: 'purchase', data: { applyId: 'A', transactionId: 'T' } }, 6), false)
669
+ assert.equal(duplicate('payment-info', { event: 'purchase', applyId: 'A' }, 7), true)
670
+ })
671
+ test('opaque global message IDs expire at TTL and oldest is evicted at capacity', () => {
672
+ const duplicate = createPushDedupe({ max: 2, ttlMs: 10 })
673
+ assert.equal(duplicate('payment-info', { _meta: { messageId: 0 } }, 0), false)
674
+ assert.equal(duplicate('activity-info', { _meta: { messageId: 0 } }, 1), true)
675
+ assert.equal(duplicate('activity-info', { _meta: { messageId: '0' } }, 2), false)
676
+ assert.equal(duplicate('activity-info', { _meta: { messageId: '(opaque,x)' } }, 3), false)
677
+ assert.equal(duplicate('message-notice-info', { _meta: { messageId: 0 } }, 4), false)
678
+ assert.equal(duplicate('activity-info', { _meta: { messageId: 0 } }, 14), false)
679
+ })
680
+ test('server-shutting-down is informational and does not schedule or close', async (t) => {
681
+ const h = setup(t)
682
+ const s = await h.connect()
683
+ s.emit('server-shutting-down', { reconnectIn: 5000 })
684
+ await h.advance(6000)
685
+ assert.equal(s.closed, 0)
686
+ assert.equal(h.sockets.length, 1)
687
+ assert.equal(h.timers.size, 0)
688
+ })
689
+ test('fresh self proof can seed persisted payment claims before initial CONNECT', async (t) => {
690
+ const h = setup(t)
691
+ h.service.send({ type: 'AUTH_CHECKED', token: 'T1', uidSite: 'U1' })
692
+ const claim = h.service.state.context.claimPaymentEvent
693
+ assert.equal(claim('purchase', { applyId: 'A' }), true)
694
+ assert.equal(claim('first_deposit', { applyId: 'A' }), true)
695
+ const s = await h.connect()
696
+ s.emit('payment-info', { event: 'purchase', isTracking: true, data: { transactionId: 'A', isFirst: true } })
697
+ assert.equal(h.pushes.length, 0)
698
+ })
699
+ test('structured rejection details remain readable for UI when no code is provided', async (t) => {
700
+ const h = setup(t)
701
+ const s = await h.connect()
702
+ s.emit('auth-rejected', { retryable: false, message: 'denied' })
703
+ assert.deepEqual(h.service.state.context.connectError, { retryable: false, message: 'denied' })
704
+ })
705
+ test('synchronous status consumer cannot insert an attempt before retry is locked', async (t) => {
706
+ const h = setup(t)
707
+ const s = await h.connect()
708
+ let triggers = 0
709
+ h.service.onTransition((state) => {
710
+ if (state.event.type === 'CONNECT_ERROR') {
711
+ triggers++
712
+ h.service.send({ type: 'CHECK_SOCKET', source: 'user' })
713
+ }
714
+ })
715
+ fail(s)
716
+ await flush()
717
+ assert.equal(triggers, 1)
718
+ assert.equal(h.fetches.filter(([url]) => url.includes('target.json')).length, 1)
719
+ await h.advance(1000)
720
+ assert.equal(h.sockets.length, 2)
721
+ })
722
+ test('logout within ready-status observer prevents late SESSION_READY publication', async (t) => {
723
+ const h = setup(t)
724
+ const s = await h.connect()
725
+ h.service.onTransition((state) => {
726
+ if (state.event.type === '_SOCKET_STATUS' && state.event.data.ready) h.service.send('DISCONNECT_SOCKET')
727
+ })
728
+ s.emit('session-ready', {})
729
+ assert.equal(h.events.filter((e) => e.type === 'SESSION_READY').length, 0)
730
+ assert.equal(h.service.state.context.ready, false)
731
+ assert.equal(h.service.state.context.clientSocket, null)
732
+ })
733
+ test('token change inside purchase analytics prevents old first_deposit side effect', async (t) => {
734
+ const h = setup(t)
735
+ const s = await h.connect()
736
+ h.service.send({
737
+ type: 'SET_ANALYTICS',
738
+ data: {
739
+ push: (payload) => {
740
+ h.pushes.push([payload])
741
+ if (payload.event === 'purchase') h.setToken('T2')
742
+ },
743
+ },
744
+ })
745
+ s.emit('payment-info', { event: 'purchase', isTracking: true, data: { transactionId: 'old', isFirst: true } })
746
+ assert.deepEqual(
747
+ h.pushes.map((p) => p[0].event),
748
+ ['purchase']
749
+ )
750
+ })
751
+ for (const cleanup of ['background', 'logout', 'stop', 'token rotation']) {
752
+ test(`renew status observer ${cleanup} cancels the old immediate renewal continuation`, async (t) => {
753
+ const h = setup(t)
754
+ const s = await h.connect()
755
+ const initialFetchCount = h.fetches.length
756
+ let interrupted = false
757
+ h.service.onTransition((state) => {
758
+ if (interrupted || state.event.type !== '_SOCKET_STATUS' || state.event.data.connectError?.code !== 'SESSION_TOKEN_INVALID') return
759
+ interrupted = true
760
+ if (cleanup === 'background') h.service.send({ type: 'DISCONNECT_SOCKET', preserveSession: true })
761
+ else if (cleanup === 'logout') h.service.send('DISCONNECT_SOCKET')
762
+ else if (cleanup === 'stop') h.service.stop()
763
+ else h.setToken('T2')
764
+ })
765
+ s.emit('auth-rejected', { code: 'SESSION_TOKEN_INVALID' })
766
+ await flush()
767
+ assert.equal(interrupted, true)
768
+ assert.equal(s.closed, 1)
769
+ assert.equal(h.sockets.length, 1)
770
+ assert.equal(h.fetches.length, initialFetchCount)
771
+ assert.equal(h.service.state.context.clientSocket, null)
772
+ assert.equal(h.service.state.context.connectStatus, 0)
773
+ assert.equal(h.timers.size, 0)
774
+ if (cleanup !== 'stop') {
775
+ await h.connect('user')
776
+ assert.equal(h.sockets.length, 2)
777
+ }
778
+ })
779
+ }