Repository navigation
Expand file tree
/
Copy pathbetter-auth.test.ts
More file actions
964 lines (940 loc) · 30 KB
/
Copy pathbetter-auth.test.ts
File metadata and controls
964 lines (940 loc) · 30 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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
import { test, expect } from 'vitest';
import { resolve } from 'node:path';
import request from 'supertest';
import { createTestContext } from '../../packages/pgstencil/src/testing.ts';
import { queryDatabase } from '../../packages/pgstencil/src/postgres.ts';
import {
captureEmail,
captureResponse,
stableJson,
} from '../../packages/pgstencil/src/snapshots.ts';
import { schemaChanges } from '../../examples/better-auth/src/schema.ts';
import { authOptions } from '../../examples/better-auth/src/auth.ts';
import { connectDatabase } from '../../packages/pgstencil/src/postgres.ts';
import { listen } from '../../examples/better-auth/src/node.ts';
import type { createDeterministicApp } from '../support/better-auth-entry.ts';
import { bundleDeterministicApp } from '../support/better-auth-bundle.ts';
import type { DiagnosticRecord } from '../../packages/pgstencil/src/diagnostics.ts';
import type { SignInEmailInput } from '../../packages/auth/src/better-auth.ts';
const origin = 'https://better-auth.example.test';
const migrations = resolve('packages/auth/better-auth-migrations');
const built = bundleDeterministicApp('better-auth-test');
async function fixture(
now = '2020-01-01T00:00:00.000Z',
sessionPolicy: 'single' | 'multiple' = 'multiple',
extra: Partial<
Pick<
Parameters<typeof createDeterministicApp>[0],
| 'ipAddressHeaders'
| 'appName'
| 'emailFrom'
| 'renderEmail'
| 'diagnostics'
>
> = {},
) {
const context = await createTestContext({
migrations,
now,
seed: 'better-auth-email',
});
const { createDeterministicApp } = await built;
const app = createDeterministicApp({
...context,
sessionPolicy,
...extra,
databaseUrl: context.database.url,
origin,
secret: 'better-auth-local-test-secret-32-characters',
});
const server = await listen(app.fetch);
const client = request(server.origin);
const csrfResponse = await client.get('/api/auth/csrf');
const csrfCookie = cookieFrom(csrfResponse);
const csrf = csrfResponse.body.csrf as string;
const post = (path: string, body: object, cookie = '') =>
client
.post('/api/auth/' + path)
.set('Origin', origin)
.set('Cookie', [csrfCookie, cookie].filter(Boolean).join('; '))
.set('X-CSRF-Token', csrf)
.send(body);
const get = (cookie = '') =>
client.get('/api/auth/get-session').set('Cookie', cookie);
return {
...context,
app,
server,
client,
csrf,
csrfCookie,
post,
get,
async close() {
await server.close();
await app.close();
await context.close();
},
};
}
type Fixture = Awaited<ReturnType<typeof fixture>>;
const cookieFrom = (response: request.Response) =>
(response.headers['set-cookie'] as unknown as string[])
.map((v) => v.split(';')[0])
.join('; ');
async function login(f: Fixture) {
expect(
(
await f.post('email-otp/send-verification-otp', {
email: 'alice@example.test',
type: 'sign-in',
})
).status,
).toBe(200);
const email = await f.email.next();
const otp = email.text.match(/\b\d{8}\b/)![0];
const response = await f.post('sign-in/email-otp', {
email: 'alice@example.test',
otp,
});
expect(response.status, response.text).toBe(200);
return { email, otp, response, cookie: cookieFrom(response) };
}
test('Better Auth email: repeatable cookies, database and email snapshots across parallel apps', async ({
onTestFinished,
}) => {
const fixtures = await Promise.all([fixture(), fixture()]);
for (const f of fixtures) onTestFinished(() => f.close());
expect(fixtures[0]!.server.origin).not.toBe(fixtures[1]!.server.origin);
const results = await Promise.all(fixtures.map(login));
expect(results[0]!.email).toEqual(results[1]!.email);
expect(results[0]!.response.body).toEqual(results[1]!.response.body);
expect(results[0]!.response.headers['set-cookie']).toEqual(
results[1]!.response.headers['set-cookie'],
);
const rows = await Promise.all(
fixtures.map((f) =>
queryDatabase(f.database.url, 'SELECT * FROM "session" ORDER BY id'),
),
);
expect(rows[0]).toEqual(rows[1]);
await expect(stableJson(rows[0])).toMatchFileSnapshot(
'./snapshots/better-auth-session.json',
);
await expect(captureEmail(results[0]!.email, origin)).toMatchFileSnapshot(
'./snapshots/better-auth-email.md',
);
await expect(
stableJson(results[0]!.response.headers['set-cookie']),
).toMatchFileSnapshot('./snapshots/better-auth-cookies.json');
const page = captureResponse(await fixtures[0]!.client.get('/'), origin);
await expect(page.html).toMatchFileSnapshot(
'./snapshots/better-auth-login.html',
);
await expect(page.markdown).toMatchFileSnapshot(
'./snapshots/better-auth-login.md',
);
expect(
(
await fixtures[0]!.post('sign-in/email-otp', {
email: 'alice@example.test',
otp: results[0]!.otp,
})
).status,
).not.toBe(200);
const plan = await schemaChanges(fixtures[0]!.database.url);
expect(plan.toBeCreated).toEqual([]);
expect(plan.toBeAdded).toEqual([]);
expect(plan.toBeAddedIndexes).toEqual([]);
});
test('Better Auth email rejects the entire reserved identity namespace before sending or signing in', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
for (const email of [
'plain@identity.pgstencil.invalid',
'PLAIN@IDENTITY.PGSTENCIL.INVALID',
'sub@a.identity.pgstencil.invalid',
'SUB@A.B.IDENTITY.PGSTENCIL.INVALID',
'dotted@identity.pgstencil.invalid.',
'dotted@a.identity.pgstencil.invalid.',
]) {
for (const path of [
'email-otp/send-verification-otp',
'sign-in/email-otp',
]) {
const response = await f.post(path, {
email,
type: 'sign-in',
otp: '12345678',
});
expect(response.status, `${path}: ${email}`).toBe(400);
expect(response.body).toEqual({ message: 'Invalid email' });
}
}
expect(f.email.all()).toEqual([]);
expect(await queryDatabase(f.database.url, 'SELECT id FROM "user"')).toEqual(
[],
);
expect(
await queryDatabase(f.database.url, 'SELECT id FROM verification'),
).toEqual([]);
// Similar domain names remain ordinary delivery addresses.
for (const email of [
'user@notidentity.pgstencil.invalid',
'user@identity.pgstencil.invalid.example.test',
]) {
const response = await f.post('email-otp/send-verification-otp', {
email,
type: 'sign-in',
});
expect(response.status, email).toBe(200);
expect((await f.email.next()).to).toEqual([email]);
}
});
test('Better Auth time: 23 hours, expiration boundary, isolated async contexts and unchanged host clock', async ({
onTestFinished,
}) => {
const nativeDate = globalThis.Date;
const nativeCrypto = globalThis.crypto;
const a = await fixture(),
b = await fixture('2030-06-01T00:00:00Z');
onTestFinished(() => a.close());
onTestFinished(() => b.close());
const [alice, other] = await Promise.all([login(a), login(b)]);
a.time.advanceHours(23);
expect((await a.get(alice.cookie)).body.user.email).toBe(
'alice@example.test',
);
const [one, two] = await Promise.all([a.app.probe(), b.app.probe()]);
expect(one.before).toBe(a.time.now().getTime());
expect(one.after).toBe(one.before);
expect(two.before).toBe(b.time.now().getTime());
expect(two.after).toBe(two.before);
a.time.advanceHours(1);
// Better Auth compares expiresAt < now: equality remains valid for one millisecond.
expect((await a.get(alice.cookie)).body.user.email).toBe(
'alice@example.test',
);
a.time.advanceMilliseconds(1);
expect((await a.get(alice.cookie)).body).toBeNull();
expect((await b.get(other.cookie)).body.user.email).toBe(
'alice@example.test',
);
expect(globalThis.Date).toBe(nativeDate);
expect(globalThis.crypto).toBe(nativeCrypto);
expect(Date.now()).toBeGreaterThan(Date.parse('2025-01-01'));
});
test('Better Auth email rejects expired codes and cross-origin sign-in', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
const send = await f.post('email-otp/send-verification-otp', {
email: 'alice@example.test',
type: 'sign-in',
});
expect(send.status).toBe(200);
const otp = (await f.email.next()).text.match(/\b\d{8}\b/)![0];
f.time.advanceMilliseconds(600_001);
expect(
(await f.post('sign-in/email-otp', { email: 'alice@example.test', otp }))
.status,
).not.toBe(200);
const response = await f.client
.post('/api/auth/email-otp/send-verification-otp')
.set('Origin', 'https://attacker.test')
.set('Cookie', 'browser=test')
.send({ email: 'alice@example.test', type: 'sign-in' });
expect(response.status).toBe(403);
expect(f.email.all()).toHaveLength(1);
});
/** The binding @hono/node-server passes: the connection a client cannot forge. */
const socket = (remoteAddress: string) => ({
incoming: { socket: { remoteAddress } },
});
async function directPost(
f: Fixture,
path: string,
body: object,
ip = '192.0.2.1',
headers: Record<string, string> = {},
) {
return f.app.fetch(
new Request(origin + '/api/auth/' + path, {
method: 'POST',
headers: {
origin,
'content-type': 'application/json',
'x-csrf-token': f.csrf,
cookie: f.csrfCookie,
...headers,
},
body: JSON.stringify(body),
}),
socket(ip),
);
}
test('email policy: secret-keyed codes, cross-browser redemption, concurrent single use and no token exposure', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
await f
.post('email-otp/send-verification-otp', {
email: 'alice@example.test',
type: 'sign-in',
})
.expect(200);
const otp = (await f.email.next()).text.match(/\b\d{8}\b/)![0];
const { createHmac, createHash } = await import('node:crypto');
const [record] = await queryDatabase<{ value: string }>(
f.database.url,
'SELECT value FROM verification',
);
const expected = createHmac(
'sha256',
'better-auth-local-test-secret-32-characters',
)
.update('email-otp\0')
.update(otp)
.digest('hex');
expect(record!.value).toBe(expected + ':0');
expect(record!.value).not.toContain(
createHash('sha256').update(otp).digest('base64url'),
);
// Another browser obtains its own CSRF token; it never receives the sending browser's cookies.
const other = await f.client.get('/api/auth/csrf');
const responses = await Promise.all(
Array.from({ length: 6 }, (_, i) =>
f.app.fetch(
new Request(origin + '/api/auth/sign-in/email-otp', {
method: 'POST',
headers: {
origin,
'content-type': 'application/json',
'x-csrf-token': other.body.csrf,
cookie: cookieFrom(other),
},
body: JSON.stringify({ email: 'alice@example.test', otp }),
}),
socket(`192.0.2.${i + 1}`),
),
),
);
expect(responses.filter((r) => r.status === 200)).toHaveLength(1);
const success = responses.find((r) => r.status === 200)!;
expect(await success.json()).not.toHaveProperty('token');
const cookie = success.headers
.getSetCookie()
.map((v) => v.split(';')[0])
.join('; ');
const session = await f.get(cookie);
expect(session.body.session).not.toHaveProperty('token');
const [row] = await queryDatabase<{ token: string }>(
f.database.url,
'SELECT token FROM session',
);
// DB tokens are not sufficient: a valid server signature is required on cookies.
expect(
(await f.get(`__Host-pgstencil.session_token=${row!.token}`)).body,
).toBeNull();
expect(success.headers.getSetCookie()[0]).toMatch(
/^__Host-pgstencil\.session_token=/,
);
expect(success.headers.getSetCookie()[0]).not.toContain('Domain=');
});
test('email policy: distributed IPs cannot bypass cooldown, send quota or attempt budget', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
const body = { email: 'limited@example.test', type: 'sign-in' };
const burst = await Promise.all(
Array.from({ length: 8 }, (_, i) =>
directPost(
f,
'email-otp/send-verification-otp',
body,
`192.0.2.${i + 1}`,
),
),
);
expect(burst.filter((r) => r.status === 200)).toHaveLength(1);
const otp = (await f.email.next()).text.match(/\b\d{8}\b/)![0];
for (let i = 0; i < 3; i++)
expect(
(
await directPost(
f,
'sign-in/email-otp',
{ email: body.email, otp: 'wrong-code' },
`198.51.100.${i + 1}`,
)
).status,
).not.toBe(200);
expect(
(
await directPost(
f,
'sign-in/email-otp',
{ email: body.email, otp },
'198.51.100.9',
)
).status,
).not.toBe(200);
for (let i = 0; i < 4; i++) {
f.time.advanceMilliseconds(60_000);
expect(
(
await directPost(
f,
'email-otp/send-verification-otp',
body,
`203.0.113.${i + 1}`,
)
).status,
).toBe(200);
}
f.time.advanceMilliseconds(60_000);
expect(
(
await directPost(
f,
'email-otp/send-verification-otp',
body,
'203.0.113.99',
)
).status,
).toBe(429);
f.time.advanceMilliseconds(15 * 60_000);
expect(
(
await directPost(
f,
'email-otp/send-verification-otp',
body,
'203.0.113.99',
)
).status,
).toBe(200);
});
const secret = 'better-auth-local-test-secret-32-characters';
const hmac = async (purpose: string, value: string) =>
(await import('node:crypto'))
.createHmac('sha256', secret)
.update(purpose + '\0')
.update(value)
.digest('hex');
const sendStatuses = async (
count: number,
send: (email: string, i: number) => Promise<{ status: number }>,
) => {
const statuses = [];
for (let i = 0; i < count; i++)
statuses.push(
(await send(`ip-${i}-${statuses.length}@example.test`, i)).status,
);
return statuses;
};
const sendOtp = { type: 'sign-in' };
test('IP rate limits: stored limiter keys never contain a raw client IP', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
await f
.post('email-otp/send-verification-otp', {
email: 'loopback@example.test',
type: 'sign-in',
})
.expect(200);
expect(
await sendStatuses(4, (email) =>
directPost(
f,
'email-otp/send-verification-otp',
{ ...sendOtp, email },
'203.0.113.50',
),
),
).toEqual([200, 200, 200, 429]);
await directPost(
f,
'sign-in/email-otp',
{ email: 'loopback@example.test', otp: '00000000' },
'2001:db8::77',
);
const upstream = await queryDatabase<{ key: string }>(
f.database.url,
'SELECT * FROM "rateLimit"',
);
const own = await queryDatabase<{ key: string }>(
f.database.url,
'SELECT * FROM pgstencil_auth_limits',
);
const stored = JSON.stringify([upstream, own]);
for (const ip of ['203.0.113.50', '2001:db8', '127.0.0.1', '::1'])
expect(stored).not.toContain(ip);
expect(upstream.length).toBeGreaterThanOrEqual(3);
for (const row of upstream) expect(row.key).toMatch(/^[0-9a-f]{64}$/);
// Both limiters count the same trusted address, each under its own secret-keyed purpose.
expect(upstream.map((row) => row.key)).toContain(
await hmac('rate-limit', '203.0.113.50|/email-otp/send-verification-otp'),
);
expect(own.map((row) => row.key)).toContain(
`send:ip:${await hmac('ip-rate', '203.0.113.50')}`,
);
});
test('IP rate limits: the default Node path counts the socket, so rotating x-pgstencil-client-ip cannot escape', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
// A real @hono/node-server socket: every request arrives from loopback.
expect(
await sendStatuses(4, (email, i) =>
f.client
.post('/api/auth/email-otp/send-verification-otp')
.set('Origin', origin)
.set('Cookie', f.csrfCookie)
.set('X-CSRF-Token', f.csrf)
.set('x-pgstencil-client-ip', `198.51.100.${i + 1}`)
.set('x-forwarded-for', `198.51.100.${i + 1}`)
.send({ ...sendOtp, email }),
),
).toEqual([200, 200, 200, 429]);
});
test('IP rate limits: concurrent requests from one address are counted atomically', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
const burst = await Promise.all(
Array.from({ length: 8 }, (_, i) =>
directPost(
f,
'email-otp/send-verification-otp',
{ ...sendOtp, email: `burst-${i}@example.test` },
'198.51.100.30',
),
),
);
expect(burst.filter((r) => r.status === 200)).toHaveLength(3);
expect(burst.filter((r) => r.status === 429)).toHaveLength(5);
});
test('IP rate limits: two IPv6 addresses in one /64 share one send:ip budget', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
const neighbours = ['2001:db8:1:2::a', '2001:db8:1:2:ffff:ffff:ffff:b'];
const send = (ip: string, i: number) =>
directPost(
f,
'email-otp/send-verification-otp',
{ ...sendOtp, email: `v6-${i}@example.test` },
ip,
);
// Better Auth's own /64 limit allows three a minute; stay under it.
for (let i = 0; i < 30; i++) {
if (i && i % 3 === 0) f.time.advanceMilliseconds(60_000);
expect((await send(neighbours[i % 2]!, i)).status).toBe(200);
}
f.time.advanceMilliseconds(60_000);
expect((await send(neighbours[1]!, 30)).status).toBe(429);
expect((await send('2001:db8:1:3::a', 31)).status).toBe(200);
const own = await queryDatabase<{ key: string; count: number }>(
f.database.url,
"SELECT key, count FROM pgstencil_auth_limits WHERE key LIKE 'send:ip:%'",
);
expect(own).toEqual(
expect.arrayContaining([
{
key: `send:ip:${await hmac('ip-rate', '2001:0db8:0001:0002:0000:0000:0000:0000')}`,
count: 30,
},
]),
);
});
test("IP rate limits: naming a victim's IP in x-pgstencil-client-ip spends only the caller's budget", async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
const victim = '203.0.113.9';
expect(
await sendStatuses(4, (email) =>
directPost(
f,
'email-otp/send-verification-otp',
{ ...sendOtp, email },
'198.51.100.7',
{ 'x-pgstencil-client-ip': victim },
),
),
).toEqual([200, 200, 200, 429]);
expect(
(
await directPost(
f,
'email-otp/send-verification-otp',
{ ...sendOtp, email: 'victim@example.test' },
victim,
)
).status,
).toBe(200);
});
test('IP rate limits: an explicit ipAddressHeaders opt-in counts the configured header', async ({
onTestFinished,
}) => {
const f = await fixture(undefined, undefined, {
ipAddressHeaders: ['x-real-ip'],
});
onTestFinished(() => f.close());
// Behind the trusted proxy every socket is the proxy's; the header decides.
expect(
await sendStatuses(4, (email, i) =>
directPost(
f,
'email-otp/send-verification-otp',
{ ...sendOtp, email },
'10.0.0.1',
{ 'x-real-ip': `198.51.100.${i + 1}` },
),
),
).toEqual([200, 200, 200, 200]);
expect(
await sendStatuses(4, (email, i) =>
directPost(
f,
'email-otp/send-verification-otp',
{ ...sendOtp, email: 'again-' + email },
'10.0.0.1',
{
'x-real-ip': '203.0.113.20',
'x-pgstencil-client-ip': `192.0.2.${i + 1}`,
},
),
),
).toEqual([200, 200, 200, 429]);
});
test('email policy: fifteen verification attempts per fifteen minutes stop even the right code from any IP', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
const email = 'guessed@example.test';
const send = (ip: string) =>
directPost(f, 'email-otp/send-verification-otp', { ...sendOtp, email }, ip);
const verify = (otp: string, ip: string) =>
directPost(f, 'sign-in/email-otp', { email, otp }, ip);
expect((await send('203.0.113.1')).status).toBe(200);
await f.email.next();
for (let i = 0; i < 15; i++)
expect((await verify('00000000', `198.51.100.${i + 1}`)).status).not.toBe(
429,
);
f.time.advanceMilliseconds(60_000);
expect((await send('203.0.113.2')).status).toBe(200);
const otp = (await f.email.next()).text.match(/\b\d{8}\b/)![0];
expect((await verify(otp, '192.0.2.200')).status).toBe(429);
f.time.advanceMilliseconds(15 * 60_000);
expect((await send('203.0.113.3')).status).toBe(200);
const fresh = (await f.email.next()).text.match(/\b\d{8}\b/)![0];
expect((await verify(fresh, '192.0.2.201')).status).toBe(200);
});
test('auth surface: explicit CSRF, exact origin, security headers and disabled unused endpoints', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
const body = { email: 'alice@example.test', type: 'sign-in' };
await f.client
.post('/api/auth/email-otp/send-verification-otp')
.set('Origin', origin)
.send(body)
.expect(403);
await f.client
.post('/api/auth/email-otp/send-verification-otp')
.set('Origin', origin)
.set('Cookie', f.csrfCookie)
.set('X-CSRF-Token', 'wrong')
.send(body)
.expect(403);
await f.client
.post('/api/auth/email-otp/send-verification-otp')
.set('Origin', 'https://sibling.example.test')
.set('Cookie', f.csrfCookie)
.set('X-CSRF-Token', f.csrf)
.send(body)
.expect(403);
for (const path of [
'email-otp/check-verification-otp',
'email-otp/reset-password',
'update-user',
'revoke-sessions',
])
await f.post(path, {}).expect(404);
const page = await f.client.get('/');
expect(page.headers['content-security-policy']).toContain(
"script-src 'self'",
);
expect(page.headers['content-security-policy']).toContain(
"frame-ancestors 'none'",
);
expect(page.headers['cache-control']).toBe('no-store');
expect(page.headers['referrer-policy']).toBe('no-referrer');
const api = await f.client.get('/api/auth/get-session');
for (const response of [page, api]) {
expect(response.headers['x-content-type-options']).toBe('nosniff');
expect(response.headers['x-frame-options']).toBe('DENY');
}
expect(f.email.all()).toHaveLength(0);
});
test('auth surface: an allowlisted write with a non-JSON body answers 415', async ({
onTestFinished,
}) => {
const f = await fixture();
onTestFinished(() => f.close());
for (const [path, type, body] of [
[
'email-otp/send-verification-otp',
'application/x-www-form-urlencoded',
'email=alice%40example.test&type=sign-in',
],
[
'sign-in/email-otp',
'text/plain',
'{"email":"alice@example.test","otp":"00000000"}',
],
['sign-in/social', 'multipart/form-data; boundary=x', '--x--'],
] as const)
await f.client
.post('/api/auth/' + path)
.set('Origin', origin)
.set('Cookie', f.csrfCookie)
.set('X-CSRF-Token', f.csrf)
.set('Content-Type', type)
.send(body)
.expect(415);
expect(f.email.all()).toHaveLength(0);
});
test('auth options reject a non-canonical origin, a short secret and off-origin redirect paths', ({
onTestFinished,
}) => {
// Validation runs before any query; the pool never connects.
const database = connectDatabase('postgres://unused.invalid/none');
onTestFinished(() => database.destroy());
const base = {
database,
origin: 'https://app.example.test',
secret: 'a'.repeat(32),
email: { send: async () => {} },
};
expect(() => authOptions(base)).not.toThrow();
for (const origin of [
'https://APP.example.test',
'https://app.example.test/',
'https://app.example.test:443',
'https://app.example.test/path',
])
expect(() => authOptions({ ...base, origin }), origin).toThrow(
'canonical origin',
);
expect(() => authOptions({ ...base, secret: 'a'.repeat(31) })).toThrow(
'at least 32 characters',
);
for (const path of [
'//attacker.test/',
'/\\attacker.test',
'/\t/attacker.test',
'https://attacker.test/',
'relative',
]) {
expect(() => authOptions({ ...base, successPath: path }), path).toThrow(
'application origin',
);
expect(() => authOptions({ ...base, errorPath: path }), path).toThrow(
'application origin',
);
}
for (const path of ['/', '/profile?tab=1', '/%2F%2Fattacker.test'])
expect(() =>
authOptions({ ...base, successPath: path, errorPath: path }),
).not.toThrow();
});
for (const policy of ['single', 'multiple'] as const)
test(`session policy: ${policy}`, async ({ onTestFinished }) => {
const f = await fixture('2020-01-01T00:00:00Z', policy);
onTestFinished(() => f.close());
const first = await login(f);
f.time.advanceMilliseconds(61_000);
const second = await login(f);
expect(first.cookie).not.toBe(second.cookie);
expect((await f.get(first.cookie)).body !== null).toBe(
policy === 'multiple',
);
expect((await f.get(second.cookie)).body.user.email).toBe(
'alice@example.test',
);
await f.post('sign-out', {}, second.cookie).expect(200);
expect((await f.get(second.cookie)).body).toBeNull();
expect((await f.get(first.cookie)).body !== null).toBe(
policy === 'multiple',
);
});
test('sign-in email: the default sender is signin@ the origin hostname, and emailFrom overrides it', async ({
onTestFinished,
}) => {
const derived = await fixture();
onTestFinished(() => derived.close());
expect((await login(derived)).email.from).toBe(
'signin@better-auth.example.test',
);
// A blanked binding counts as omitted.
const blank = await fixture(undefined, undefined, { emailFrom: ' ' });
onTestFinished(() => blank.close());
expect((await login(blank)).email.from).toBe(
'signin@better-auth.example.test',
);
const explicit = await fixture(undefined, undefined, {
emailFrom: 'Example <hello@mail.example.test>',
});
onTestFinished(() => explicit.close());
const { email } = await login(explicit);
expect(email.from).toBe('Example <hello@mail.example.test>');
expect(email.subject).toBe('Your sign-in code');
});
test('sign-in email: the default renderer keeps appName out of the HTML body', async ({
onTestFinished,
}) => {
const appName = `<b>Tom & "Jerry's"</b>`;
const f = await fixture(undefined, undefined, { appName });
onTestFinished(() => f.close());
const { email, otp } = await login(f);
expect(email.subject).toBe(`Your ${appName} sign-in code`);
expect(email.text).toBe(
`Your sign-in code is ${otp}. It expires in 10 minutes.`,
);
expect(email.html).toBe(
`<p>Your sign-in code is <strong>${otp}</strong>.</p><p>It expires in 10 minutes.</p>`,
);
});
test('sign-in email: a custom renderEmail composes the message and its code signs in', async ({
onTestFinished,
}) => {
const inputs: SignInEmailInput[] = [];
const f = await fixture(undefined, undefined, {
appName: 'Rhythm',
emailFrom: 'Rhythm <signin@rhythm.example.test>',
renderEmail: async (input) => {
inputs.push(input);
return {
from: input.from,
to: [input.email],
replyTo: 'help@rhythm.example.test',
subject: `Code ${input.otp}`,
text: `Bonjour ! Code : ${input.otp} (${input.expiresInMinutes} min)`,
html: `<p>Bonjour ! <b>${input.otp}</b></p>`,
};
},
});
onTestFinished(() => f.close());
const { email, otp } = await login(f);
expect(inputs).toEqual([
{
email: 'alice@example.test',
otp,
expiresInMinutes: 10,
appName: 'Rhythm',
from: 'Rhythm <signin@rhythm.example.test>',
},
]);
expect(email).toEqual({
capturedAt: '2020-01-01T00:00:00.000Z',
from: 'Rhythm <signin@rhythm.example.test>',
to: ['alice@example.test'],
replyTo: 'help@rhythm.example.test',
subject: `Code ${otp}`,
text: `Bonjour ! Code : ${otp} (10 min)`,
html: `<p>Bonjour ! <b>${otp}</b></p>`,
});
});
for (const [name, renderEmail] of [
[
'throws',
() => {
throw new Error('private-render alice@example.test');
},
],
[
'rejects',
async () => {
throw new Error('private-render alice@example.test');
},
],
[
'addresses someone else',
(input: SignInEmailInput) => ({
from: input.from,
to: ['attacker@example.test'],
subject: 'code',
text: input.otp,
html: input.otp,
}),
],
[
'adds a recipient',
(input: SignInEmailInput) => ({
from: input.from,
to: [input.email, 'attacker@example.test'],
subject: 'code',
text: input.otp,
html: input.otp,
}),
],
[
'adds a bcc',
(input: SignInEmailInput) => ({
from: input.from,
to: [input.email],
bcc: ['attacker@example.test'],
subject: 'code',
text: input.otp,
html: input.otp,
}),
],
['returns nothing', () => undefined as never],
] as const)
test(`sign-in email: a renderer that ${name} fails the send and delivers nothing`, async ({
onTestFinished,
}) => {
const records: DiagnosticRecord[] = [];
const f = await fixture(undefined, undefined, {
renderEmail,
diagnostics: { sink: (record) => records.push(record) },
});
onTestFinished(() => f.close());
const response = await f.post('email-otp/send-verification-otp', {
email: 'alice@example.test',
type: 'sign-in',
});
// Better Auth answers a failed send like a successful one; nothing reveals the failure.
expect(response.status).toBe(200);
expect(JSON.stringify(response.body)).not.toContain('private-render');
expect(f.email.all()).toEqual([]);
const failed = records.filter(
(record) => record.event === 'email.delivery.failed',
);
expect(failed).toHaveLength(1);
expect(failed[0]).toMatchObject({ reason: 'unexpected_error' });
expect(failed[0]).not.toHaveProperty('stage');
expect(records.map((record) => record.event)).not.toContain(
'email.delivery.succeeded',
);
const logged = JSON.stringify(records);
expect(logged).not.toContain('alice@example.test');
expect(logged).not.toContain('attacker@example.test');
});