Repository navigation
Expand file tree
/
Copy pathauth-handler.test.ts
More file actions
571 lines (504 loc) · 18.6 KB
/
Copy pathauth-handler.test.ts
File metadata and controls
571 lines (504 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/* eslint-disable test/no-import-node-test */
import type { InitData } from '@telegram-apps/init-data-node'
import type { AuthHandlerDependencies } from '#root/backend/auth-handler'
import assert from 'node:assert/strict'
import test from 'node:test'
import fastify from 'fastify'
import { buildAuthHandler } from '#root/backend/auth-handler'
type ResolvedUser = NonNullable<
Awaited<ReturnType<AuthHandlerDependencies['findUserById']>>
>
interface StubUser {
id: number
language: string
name?: string
wallet?: string
referalId?: number
joinedViaChat?: boolean
firstLoginAt?: Date
votes: bigint
minted: boolean
state: string
pass?: { index: number, address: string, name: string, image: string, verifiedAt: Date }
saveCalls: number
save: () => Promise<void>
}
interface AuthTestContext {
app: ReturnType<typeof fastify>
users: Map<number, StubUser>
infoLogs: string[]
errorLogs: string[]
unhandledErrorLogs: string[]
verifyCalls: Array<{ passAddress: string, ownerAddress: string }>
setPassCalls: Array<{ userId: number, index: number, verifiedAt: Date }>
clearPassCalls: number[]
firstLogins: number[]
inviterCredits: number[]
}
function toResolvedUser(user: StubUser): ResolvedUser {
return user as unknown as ResolvedUser
}
function createStubUser(overrides: Partial<StubUser> = {}): StubUser {
const user: StubUser = {
id: 1001,
language: 'en',
votes: BigInt(200),
minted: false,
state: 'WaitNothing',
saveCalls: 0,
save: async () => {
user.saveCalls += 1
},
...overrides,
}
return user
}
async function createAuthTestContext(
overrides: Partial<AuthHandlerDependencies> = {},
): Promise<AuthTestContext> {
const users = new Map<number, StubUser>([
[1001, createStubUser()],
[2002, createStubUser({ id: 2002, votes: BigInt(999) })],
])
const infoLogs: string[] = []
const errorLogs: string[] = []
const unhandledErrorLogs: string[] = []
const verifyCalls: Array<{ passAddress: string, ownerAddress: string }> = []
const setPassCalls: Array<{ userId: number, index: number, verifiedAt: Date }> = []
const clearPassCalls: number[] = []
const firstLogins: number[] = []
const inviterCredits: number[] = []
const dependencies: AuthHandlerDependencies = {
validateInitData: () => {},
parseInitData: () => ({ user: { id: 1001, username: 'alice' } } as InitData),
findUserById: async (id: number) => {
const user = users.get(id)
return user ? toResolvedUser(user) : null
},
findOrCreateUser: async (id: number) => {
// Upsert: create-and-insert a fresh stub if the user is unknown.
let user = users.get(id)
if (!user) {
user = createStubUser({ id, votes: BigInt(0) })
users.set(id, user)
}
return toResolvedUser(user)
},
info: (message: string) => {
infoLogs.push(message)
},
error: (message: string) => {
errorLogs.push(message)
},
logError: (message: string) => {
unhandledErrorLogs.push(message)
},
verifyPassOwnership: async (passAddress: string, ownerAddress: string) => {
verifyCalls.push({ passAddress, ownerAddress })
return true
},
setUserPass: async (userId, pass, verifiedAt) => {
setPassCalls.push({ userId, index: pass.index, verifiedAt })
},
clearUserPass: async (userId) => {
clearPassCalls.push(userId)
},
setFirstLoginAt: async (userId: number) => {
const user = users.get(userId)
if (!user || user.firstLoginAt) return false
user.firstLoginAt = new Date()
firstLogins.push(userId)
return true
},
creditInviter: async (inviterId: number) => { inviterCredits.push(inviterId) },
...overrides,
}
const app = fastify()
await app.register(buildAuthHandler(dependencies), { prefix: '/api/auth' })
return {
app,
users,
infoLogs,
errorLogs,
unhandledErrorLogs,
verifyCalls,
setPassCalls,
clearPassCalls,
firstLogins,
inviterCredits,
}
}
test('POST /api/auth/login validates required initData', async (t) => {
const ctx = await createAuthTestContext()
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: {},
})
assert.equal(response.statusCode, 200)
assert.equal(response.json().error, 'No initData or hash provided')
})
test('POST /api/auth/login upserts a brand-new user (no "User not found")', async (t) => {
const ctx = await createAuthTestContext({
parseInitData: () => ({ user: { id: 404 } } as InitData),
})
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed-payload' },
})
const body = response.json()
assert.equal(response.statusCode, 200)
assert.equal(body.error, undefined, 'no error — the user is created on first login')
assert.equal(body.id, 404)
// freshly created → not minted, default mint state
assert.equal(body.minted, false)
assert.equal(body.mintState, 'WaitNothing')
// the upsert actually inserted the user
assert.ok(ctx.users.has(404), 'new user persisted')
})
test('POST /api/auth/login returns minted + mintState for an existing user', async (t) => {
const ctx = await createAuthTestContext()
ctx.users.get(1001)!.minted = true
ctx.users.get(1001)!.state = 'Submited'
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed-payload' },
})
const body = response.json()
assert.equal(body.id, 1001)
assert.equal(body.minted, true)
assert.equal(body.mintState, 'Submited')
})
test('POST /api/auth/login returns validation error for missing telegram user id', async (t) => {
const ctx = await createAuthTestContext({
parseInitData: () => ({ user: {} } as InitData),
})
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed-payload' },
})
assert.equal(response.statusCode, 200)
assert.equal(response.json().error, 'Invalid telegram user id')
})
test('POST /api/auth/login sanitizes unexpected catch-branch errors', async (t) => {
const ctx = await createAuthTestContext({
validateInitData: () => {
throw new Error('Invalid initData signature')
},
})
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'tampered' },
})
assert.equal(response.statusCode, 200)
assert.equal(response.json().error, 'Unable to process request')
assert.equal(ctx.unhandledErrorLogs.length, 1)
assert.match(ctx.unhandledErrorLogs[0], /Invalid initData signature/)
})
test('POST /api/auth/login logs referral error when referrer is the same user', async (t) => {
const ctx = await createAuthTestContext()
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed-payload', referId: '1001' },
})
const body = response.json()
assert.equal(body.id, 1001)
// referrer was self → not assigned, error logged
assert.equal(body.referalId, undefined)
assert.deepEqual(ctx.errorLogs, ['Referrer not found or same as user'])
assert.deepEqual(ctx.infoLogs, [])
})
test('POST /api/auth/login logs referral error when referrer does not exist', async (t) => {
const ctx = await createAuthTestContext()
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed-payload', referId: '99999' },
})
assert.equal(response.json().referalId, undefined)
assert.deepEqual(ctx.errorLogs, ['Referrer not found or same as user'])
})
test('POST /api/auth/login skips referral when user already has a wallet', async (t) => {
const ctx = await createAuthTestContext()
ctx.users.get(1001)!.wallet = 'EQAlreadyOnboarded'
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed-payload', referId: '2002' },
})
assert.equal(response.json().referalId, undefined)
// No referral path taken at all → neither info nor error logged
assert.deepEqual(ctx.infoLogs, [])
assert.deepEqual(ctx.errorLogs, [])
})
test('POST /api/auth/login assigns referral when eligible', async (t) => {
// Name already matches the default stub `parseInitData` username so the
// name-sync path doesn't add an extra save() beyond the referral one.
const mainUser = createStubUser({ id: 1001, name: 'alice', referalId: undefined, wallet: undefined })
const receiver = createStubUser({ id: 7777 })
const users = new Map<number, StubUser>([
[1001, mainUser],
[7777, receiver],
])
const lookup = async (id: number) => {
const user = users.get(id)
return user ? toResolvedUser(user) : null
}
const ctx = await createAuthTestContext({
findUserById: lookup,
findOrCreateUser: lookup,
})
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: {
initData: 'signed-payload',
referId: '7777',
},
})
const body = response.json()
assert.equal(response.statusCode, 200)
assert.equal(body.id, 1001)
assert.equal(body.referalId, 7777)
assert.equal(mainUser.referalId, 7777)
assert.equal(mainUser.saveCalls, 1)
assert.deepEqual(ctx.infoLogs, ['Referrer added successfully'])
assert.equal(body.balance, '200')
assert.equal(typeof body.ip, 'string')
})
test('POST /api/auth/login rejects ill-typed initData with validation error', async (t) => {
const ctx = await createAuthTestContext()
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: { not: 'a string' } },
})
assert.equal(response.statusCode, 200)
assert.equal(response.json().error, 'Invalid request body')
})
test('POST /api/auth/login rejects oversized initData', async (t) => {
const ctx = await createAuthTestContext()
t.after(async () => {
await ctx.app.close()
})
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'a'.repeat(8193) },
})
assert.equal(response.statusCode, 200)
assert.equal(response.json().error, 'Invalid request body')
})
// name sync — webview users have no other code path that sets `name`
test('POST /api/auth/login syncs the Telegram username into user.name', async (t) => {
const ctx = await createAuthTestContext({
parseInitData: () =>
({ user: { id: 1001, username: 'alice', first_name: 'Alice' } } as InitData),
})
t.after(async () => {
await ctx.app.close()
})
await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed' },
})
const user = ctx.users.get(1001)!
assert.equal(user.name, 'alice')
assert.equal(user.saveCalls, 1, 'saved once for the name sync')
})
test('POST /api/auth/login falls back to first_name when there is no username', async (t) => {
const ctx = await createAuthTestContext({
parseInitData: () =>
({ user: { id: 1001, first_name: 'Alice' } } as InitData),
})
t.after(async () => {
await ctx.app.close()
})
await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed' },
})
assert.equal(ctx.users.get(1001)!.name, 'Alice')
})
test('POST /api/auth/login does not save when the name is already current', async (t) => {
const ctx = await createAuthTestContext({
parseInitData: () =>
({ user: { id: 1001, username: 'alice' } } as InitData),
})
ctx.users.get(1001)!.name = 'alice'
t.after(async () => {
await ctx.app.close()
})
await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'signed' },
})
assert.equal(ctx.users.get(1001)!.saveCalls, 0, 'no redundant save')
})
const HOUR = 60 * 60 * 1000
const FRESH_PASS = { index: 7, address: 'EQ_A', name: 'alice', image: '', verifiedAt: new Date() }
const STALE_PASS = { ...FRESH_PASS, verifiedAt: new Date(Date.now() - 2 * HOUR) }
test('login returns holder=false, pass=null and the Telegram username for a newcomer', async (t) => {
const ctx = await createAuthTestContext()
t.after(() => ctx.app.close())
const res = await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
const body = res.json()
assert.equal(body.holder, false)
assert.equal(body.pass, null)
assert.equal(body.username, 'alice')
assert.deepEqual(ctx.verifyCalls, [])
})
test('login returns username=null when Telegram has no @username', async (t) => {
const ctx = await createAuthTestContext({
parseInitData: () => ({ user: { id: 1001, first_name: 'Ann' } } as InitData),
})
t.after(() => ctx.app.close())
const res = await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
assert.equal(res.json().username, null)
})
test('login with a fresh pass is a holder and does not touch the chain', async (t) => {
const ctx = await createAuthTestContext()
t.after(() => ctx.app.close())
ctx.users.get(1001)!.wallet = 'EQ_WALLET'
ctx.users.get(1001)!.pass = FRESH_PASS
const res = await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
const body = res.json()
assert.equal(body.holder, true)
assert.equal(body.pass.index, 7)
assert.deepEqual(ctx.verifyCalls, [])
})
test('login with a stale pass still owned bumps verifiedAt', async (t) => {
const ctx = await createAuthTestContext()
t.after(() => ctx.app.close())
ctx.users.get(1001)!.wallet = 'EQ_WALLET'
ctx.users.get(1001)!.pass = STALE_PASS
const res = await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
assert.equal(res.json().holder, true)
assert.deepEqual(ctx.verifyCalls, [{ passAddress: 'EQ_A', ownerAddress: 'EQ_WALLET' }])
assert.equal(ctx.setPassCalls.length, 1)
assert.equal(ctx.setPassCalls[0].index, 7)
assert.ok(ctx.setPassCalls[0].verifiedAt.getTime() > STALE_PASS.verifiedAt.getTime())
assert.deepEqual(ctx.clearPassCalls, [])
})
test('login with a stale pass that left the wallet clears it', async (t) => {
const ctx = await createAuthTestContext({ verifyPassOwnership: async () => false })
t.after(() => ctx.app.close())
ctx.users.get(1001)!.wallet = 'EQ_WALLET'
ctx.users.get(1001)!.pass = STALE_PASS
const res = await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
const body = res.json()
assert.equal(body.holder, false)
assert.equal(body.pass, null)
assert.deepEqual(ctx.clearPassCalls, [1001])
})
test('first login stamps firstLoginAt and pays the inviter for chat-invited users', async (t) => {
const ctx = await createAuthTestContext()
t.after(() => ctx.app.close())
ctx.users.set(1001, createStubUser({ joinedViaChat: true, referalId: 2002 }))
await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
assert.deepEqual(ctx.firstLogins, [1001])
assert.deepEqual(ctx.inviterCredits, [2002])
})
test('a second login pays nothing', async (t) => {
const ctx = await createAuthTestContext()
t.after(() => ctx.app.close())
ctx.users.set(1001, createStubUser({ joinedViaChat: true, referalId: 2002, firstLoginAt: new Date() }))
await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
assert.deepEqual(ctx.firstLogins, [])
assert.deepEqual(ctx.inviterCredits, [])
})
test('app deep-link referrals stamp firstLoginAt but pay no login drop', async (t) => {
const ctx = await createAuthTestContext()
t.after(() => ctx.app.close())
ctx.users.set(1001, createStubUser({ referalId: 2002 }))
await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
assert.deepEqual(ctx.firstLogins, [1001])
assert.deepEqual(ctx.inviterCredits, [])
})
test('a tipped stranger who later opens an app deep-link does not pay the deep-link referrer a chat-invite drop', async (t) => {
// markJoinedViaChat (give-tip.ts) sets joinedViaChat without ever touching
// referalId — unlike setChatReferral (a real invite-link join), which sets
// both together. So this user has joinedViaChat=true but no referalId yet.
const taggedStranger = createStubUser({ joinedViaChat: true, referalId: undefined, wallet: undefined })
const deepLinkReferrer = createStubUser({ id: 9009 })
const users = new Map<number, StubUser>([
[1001, taggedStranger],
[9009, deepLinkReferrer],
])
const lookup = async (id: number) => {
const user = users.get(id)
return user ? toResolvedUser(user) : null
}
const ctx = await createAuthTestContext({ findUserById: lookup, findOrCreateUser: lookup })
t.after(() => ctx.app.close())
const response = await ctx.app.inject({
method: 'POST',
url: '/api/auth/login',
payload: { initData: 'x', referId: '9009' },
})
// The unrelated deep-link referral still gets recorded normally...
assert.equal(response.json().referalId, 9009)
assert.equal(taggedStranger.referalId, 9009)
// ...but the chat-invite login drop must never go to it: nobody actually
// sent this user a chat invite link.
assert.deepEqual(ctx.firstLogins, [1001])
assert.deepEqual(ctx.inviterCredits, [])
})
test('inviter credit failure is logged and does not fail the login', async (t) => {
const ctx = await createAuthTestContext({ creditInviter: async () => { throw new Error('mongo down') } })
t.after(() => ctx.app.close())
ctx.users.set(1001, createStubUser({ joinedViaChat: true, referalId: 2002 }))
const response = await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
assert.equal(response.statusCode, 200)
assert.ok(ctx.errorLogs.some(m => m.includes('Invite credit failed')))
})
test('login keeps a stale pass when the provider fails', async (t) => {
const ctx = await createAuthTestContext({
verifyPassOwnership: async () => { throw new Error('toncenter down') },
})
t.after(() => ctx.app.close())
ctx.users.get(1001)!.wallet = 'EQ_WALLET'
ctx.users.get(1001)!.pass = STALE_PASS
const res = await ctx.app.inject({ method: 'POST', url: '/api/auth/login', payload: { initData: 'x' } })
assert.equal(res.json().holder, true)
assert.deepEqual(ctx.clearPassCalls, [])
assert.ok(ctx.errorLogs.some((m) => /toncenter down/.test(m)))
})