Repository navigation
Expand file tree
/
Copy pathtest_auth.js
More file actions
1408 lines (1317 loc) · 57.5 KB
/
Copy pathtest_auth.js
File metadata and controls
1408 lines (1317 loc) · 57.5 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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// test_auth.js
if (typeof globalThis.SubtleCrypto === "undefined") {
try {
const nodeCrypto = require("node:crypto");
globalThis.SubtleCrypto = nodeCrypto.webcrypto?.SubtleCrypto || class SubtleCrypto {};
} catch {
globalThis.SubtleCrypto = class SubtleCrypto {};
}
}
const express = require("express");
const devAuthKit = require("./server/server.js");
const sessionStore = require("./server/sessionStore.js");
const { DevAuthClient } = require("./client/index.js");
async function runTests() {
console.log("🧪 Starting DevAuthKit Phase 1 & Client SDK Automated Verification...\n");
const passkeyCredentials = new Map();
const passkeyChallenges = new Map();
const passkeyStore = {
async getUserHandle(userId) {
return `handle-${userId}`;
},
async create(credential) {
passkeyCredentials.set(credential.id, credential);
},
async getByCredentialId(id) {
return passkeyCredentials.get(id) || null;
},
async listByUserId() {
return [];
},
async updateCounter() {
return false;
},
async deleteByCredentialId() {
return false;
},
async put(challenge, record) {
passkeyChallenges.set(challenge, record);
},
async consume(challenge, purpose) {
const record = passkeyChallenges.get(challenge);
if (!record || record.purpose !== purpose || record.expiresAt <= Date.now()) return null;
passkeyChallenges.delete(challenge);
return record;
}
};
const app = express();
devAuthKit(app, {
jwtSecret: "test-jwt-secret",
sessionSecret: "test-session-secret",
devMode: true,
debug: false,
passkeys: {
rpName: "DevAuthKit Test",
rpID: "example.com",
origins: ["https://example.com"]
},
passkeyStore,
passkeyChallengeStore: passkeyStore
});
const { requireAuth } = devAuthKit;
app.get("/api/dashboard", requireAuth, (req, res) => {
res.json({ success: true, user: req.user });
});
const server = app.listen(0);
const port = server.address().port;
const baseUrl = `http://localhost:${port}`;
let passed = 0;
let total = 0;
function assert(condition, testName) {
total++;
if (condition) {
console.log(` ✅ [PASS] ${testName}`);
passed++;
} else {
console.error(` ❌ [FAIL] ${testName}`);
}
}
try {
console.log("\n📨 Testing unavailable mail delivery does not log credentials...");
const originalMailerConfig = devAuthKit.config.get();
devAuthKit.config.set({
...originalMailerConfig,
devMode: false,
emailProvider: "smtp",
resendApiKey: "",
mailer: undefined,
smtpMailer: undefined,
smtpMailerAvailable: false
});
const originalConsoleLog = console.log;
const mailerLogs = [];
let unavailableDeliveryRejected = false;
try {
console.log = (...args) => mailerLogs.push(args.join(" "));
await require("./server/utils/mailer").sendOTP({
email: "[email protected]",
otp: "918273",
magicLinkUrl: "https://example.com/auth/verify-magic?token=secret-token"
});
} catch (error) {
unavailableDeliveryRejected = /OTP delivery is unavailable/.test(error.message);
} finally {
console.log = originalConsoleLog;
devAuthKit.config.set(originalMailerConfig);
}
assert(
unavailableDeliveryRejected &&
!mailerLogs.join("\n").includes("918273") &&
!mailerLogs.join("\n").includes("secret-token"),
"Unavailable production mail delivery throws without logging OTP or magic-link credentials"
);
const testEmail = "[email protected]";
// Test 1: Request OTP (/auth/login)
const reqRes = await fetch(`${baseUrl}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: testEmail })
});
const reqData = await reqRes.json();
assert(reqRes.ok && reqData.devMode === true, "POST /auth/login generates OTP in Dev Mode");
// Inspect session store to retrieve generated OTP for testing
const stored = sessionStore.get ? sessionStore.get(testEmail) : sessionStore[testEmail];
const generatedOtp = stored?.otp;
assert(Boolean(generatedOtp && generatedOtp.length === 6), `Generated OTP is 6 digits (${generatedOtp})`);
// Test 2: Invalid OTP check
const badVerifyRes = await fetch(`${baseUrl}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: testEmail, otp: "000000" })
});
const badVerifyData = await badVerifyRes.json();
assert(badVerifyRes.status === 401 && badVerifyData.attemptsRemaining === 4, "Invalid OTP returns 401 and decrements attempts");
// Test 3: Correct OTP verification & JWT issuance
const goodVerifyRes = await fetch(`${baseUrl}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: testEmail, otp: generatedOtp })
});
const goodVerifyData = await goodVerifyRes.json();
assert(goodVerifyRes.ok && Boolean(goodVerifyData.token), "Valid OTP returns 200 and issues JWT token");
assert(goodVerifyData.user?.email === testEmail, "JWT user email matches requested email");
const token = goodVerifyData.token;
const setCookieHeader = goodVerifyRes.headers.get("set-cookie") || "";
assert(setCookieHeader.includes("devauth_token="), "verifyOTP automatically sets httpOnly auth cookie");
const passkeyOptionsResponse = await fetch(`${baseUrl}/auth/passkeys/register/options`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
Origin: "https://example.com",
"Content-Type": "application/json"
},
body: "{}"
});
const passkeyOptions = await passkeyOptionsResponse.json();
assert(
passkeyOptionsResponse.ok && passkeyOptions.rp.id === "example.com",
"Express exposes authenticated passkey registration options"
);
const crossOriginEnrollment = await fetch(`${baseUrl}/auth/passkeys/register/options`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
Origin: "https://attacker.example",
"Content-Type": "application/json"
},
body: "{}"
});
assert(crossOriginEnrollment.status === 403, "Cross-origin requests cannot enroll passkeys");
const passkeyListResponse = await fetch(`${baseUrl}/auth/passkeys`, {
headers: { Authorization: `Bearer ${token}` }
});
assert(passkeyListResponse.ok && (await passkeyListResponse.json()).passkeys.length === 0,
"Express exposes authenticated passkey management");
const passkeyLoginOptions = await fetch(`${baseUrl}/auth/passkeys/authenticate/options`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: testEmail })
});
assert(passkeyLoginOptions.ok, "Express exposes public passkey authentication options");
const unknownPasskeyLogin = await fetch(`${baseUrl}/auth/passkeys/authenticate/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ credential: { id: "unknown-passkey" } })
});
assert(unknownPasskeyLogin.status === 401, "Unknown passkey credentials cannot authenticate");
// Test 4: Replay protection (OTP must be cleared after verification)
const replayRes = await fetch(`${baseUrl}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: testEmail, otp: generatedOtp })
});
assert(replayRes.status === 401, "Replay attack prevented: OTP cannot be reused once verified");
// Test 5: Protected route with JWT Bearer header
const meRes = await fetch(`${baseUrl}/auth/me`, {
headers: { "Authorization": `Bearer ${token}` }
});
const meData = await meRes.json();
assert(meRes.ok && meData.user?.email === testEmail, "GET /auth/me returns authenticated user via Bearer token");
// Test 6: Custom route /api/dashboard with requireAuth
const dashRes = await fetch(`${baseUrl}/api/dashboard`, {
headers: { "Authorization": `Bearer ${token}` }
});
const dashData = await dashRes.json();
assert(dashRes.ok && dashData.success === true, "Custom route /api/dashboard accessible via requireAuth");
// Test 7: Protected route via httpOnly Cookie ONLY (no Authorization header)
const cookieTokenMatch = setCookieHeader.match(/devauth_token=([^;]+)/);
const cookieValue = cookieTokenMatch ? cookieTokenMatch[1] : "";
const cookieAuthRes = await fetch(`${baseUrl}/api/dashboard`, {
headers: { "Cookie": `devauth_token=${cookieValue}` }
});
const cookieAuthData = await cookieAuthRes.json();
assert(cookieAuthRes.ok && cookieAuthData.user?.email === testEmail, "requireAuth successfully authenticates via Cookie header only");
// Test 8: Unauthorized request without token
const unauthRes = await fetch(`${baseUrl}/api/dashboard`);
assert(unauthRes.status === 401, "Protected route denies request without authentication (401)");
// Test 8: Logout endpoint
const logoutRes = await fetch(`${baseUrl}/auth/logout`, { method: "POST" });
const logoutData = await logoutRes.json();
assert(logoutRes.ok && logoutData.message.includes("Logged out"), "POST /auth/logout returns 200");
// ==========================================
// DevAuthClient SDK Verification
// ==========================================
console.log("\n📦 Testing DevAuthClient SDK...");
const client = new DevAuthClient({
apiUrl: baseUrl,
customFetch: fetch
});
const sdkEmail = "[email protected]";
const sdkReq = await client.sendOTP(sdkEmail);
assert(sdkReq.devMode === true, "Client SDK: client.sendOTP() works");
const sdkStored = sessionStore.get ? sessionStore.get(sdkEmail) : sessionStore[sdkEmail];
const sdkOtp = sdkStored?.otp;
const verifyResult = await client.verifyOTP(sdkEmail, sdkOtp);
assert(client.isAuthenticated() === true, "Client SDK: client.isAuthenticated() is true after verify");
assert(Boolean(client.getToken()), "Client SDK: client.getToken() returns JWT");
assert(client.getUser()?.email === sdkEmail, "Client SDK: client.getUser() matches signed-in user");
// SDK authenticated fetch
const sdkFetchRes = await client.fetch("/api/dashboard");
const sdkFetchData = await sdkFetchRes.json();
assert(sdkFetchRes.ok && sdkFetchData.user?.email === sdkEmail, "Client SDK: client.fetch() automatically attaches Bearer token");
// SDK logout
await client.logout();
assert(client.isAuthenticated() === false, "Client SDK: client.isAuthenticated() is false after logout");
assert(client.getToken() === null, "Client SDK: client.getToken() is null after logout");
// Configurable asynchronous OTP storage
console.log("\n🗄️ Testing custom asynchronous OTP storage...");
const customEntries = new Map();
const customOtpStore = {
async get(email) {
return customEntries.get(email) || null;
},
async set(email, data) {
customEntries.set(email, { ...data });
},
async delete(email) {
customEntries.delete(email);
},
async recordAttempt(email) {
const entry = customEntries.get(email);
if (!entry) return 0;
entry.attempts++;
return entry.attempts;
}
};
const customStoreApp = express();
devAuthKit(customStoreApp, {
jwtSecret: "custom-store-test-secret",
sessionSecret: "custom-store-session-secret",
otpStore: customOtpStore,
devMode: true,
setHttpOnlyCookie: false
});
const customStoreServer = customStoreApp.listen(0);
try {
const customStoreUrl = `http://localhost:${customStoreServer.address().port}`;
const customEmail = "[email protected]";
const customRequest = await fetch(`${customStoreUrl}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: customEmail })
});
const customEntry = await customOtpStore.get(customEmail);
assert(customRequest.ok && Boolean(customEntry?.otp), "Async custom OTP store saves requested OTP");
const customInvalid = await fetch(`${customStoreUrl}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: customEmail, otp: "000000" })
});
const customInvalidData = await customInvalid.json();
assert(customInvalid.status === 401 && customInvalidData.attemptsRemaining === 4, "Async custom OTP store records failed attempts");
const customVerify = await fetch(`${customStoreUrl}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: customEmail, otp: customEntry.otp })
});
assert(customVerify.ok && !customEntries.has(customEmail), "Async custom OTP store deletes OTP after successful verification");
} finally {
customStoreServer.close();
}
const redisValues = new Map();
let redisTtl;
const mockRedisClient = {
async get(key) {
return redisValues.get(key) || null;
},
async set(key, value, options) {
redisValues.set(key, value);
redisTtl = options.EX;
},
async del(key) {
const keys = Array.isArray(key) ? key : [key];
return keys.reduce((deleted, item) => redisValues.delete(item) ? deleted + 1 : deleted, 0);
},
async incr(key) {
const next = Number(redisValues.get(key) || 0) + 1;
redisValues.set(key, String(next));
return next;
}
};
const redisOtpStore = new devAuthKit.RedisOtpStore(mockRedisClient, {
keyPrefix: "test:otp:",
ttlSeconds: 60
});
const redisOtp = { otp: "123456", attempts: 0, createdAt: Date.now() };
await redisOtpStore.set("[email protected]", redisOtp);
const firstRedisEntry = await redisOtpStore.get("[email protected]");
assert(redisTtl === 60 && firstRedisEntry.otp === redisOtp.otp, "Redis OTP adapter stores values with its configured TTL and prefix");
assert(await redisOtpStore.recordAttempt("[email protected]") === 1, "Redis OTP adapter records attempts through atomic INCR");
assert((await redisOtpStore.get("[email protected]")).attempts === 1, "Redis OTP adapter reads the separate attempt counter");
await redisOtpStore.set("[email protected]", { ...redisOtp, otp: "654321" });
assert((await redisOtpStore.get("[email protected]")).attempts === 0, "Redis OTP adapter resets attempts for each new OTP");
await redisOtpStore.delete("[email protected]");
assert(await redisOtpStore.get("[email protected]") === null, "Redis OTP adapter deletes stored OTP values");
const rateLimitValues = new Map();
const redisRateLimitCalls = [];
const mockRateLimitRedis = {
async incr(key) {
const count = (rateLimitValues.get(key)?.count || 0) + 1;
rateLimitValues.set(key, { count, ttl: rateLimitValues.get(key)?.ttl ?? -1 });
return count;
},
async pTTL(key) {
return rateLimitValues.get(key)?.ttl ?? -2;
},
async pExpire(key, milliseconds) {
redisRateLimitCalls.push({ key, milliseconds });
rateLimitValues.get(key).ttl = milliseconds;
return true;
}
};
const redisRateLimitStore = new devAuthKit.RedisRateLimitStore(mockRateLimitRedis, {
keyPrefix: "test:rate:"
});
assert(
await redisRateLimitStore.increment("login:ip:abc:1", 60_000) === 1 &&
await redisRateLimitStore.increment("login:ip:abc:1", 60_000) === 2 &&
redisRateLimitCalls.length === 1 &&
redisRateLimitCalls[0].key === "test:rate:login:ip:abc:1" &&
redisRateLimitCalls[0].milliseconds === 60_000,
"Redis rate-limit adapter increments atomically and applies expiry to new counters"
);
const dpopRedisValues = new Map();
const dpopSetOptions = [];
const mockDpopRedis = {
async get(key) {
return dpopRedisValues.get(key) ?? null;
},
async set(key, value, options) {
dpopSetOptions.push(options);
if (options.NX && dpopRedisValues.has(key)) return null;
dpopRedisValues.set(key, value);
return "OK";
}
};
const redisDpopReplayStore = new devAuthKit.RedisDpopReplayStore(mockDpopRedis, {
keyPrefix: "test:dpop:"
});
const concurrentJtiClaims = await Promise.all(
Array.from({ length: 10 }, () => redisDpopReplayStore.record("same-proof-jti", 45))
);
assert(
concurrentJtiClaims.filter(Boolean).length === 1 &&
dpopSetOptions[0]?.NX === true &&
dpopSetOptions[0]?.EX === 45 &&
await redisDpopReplayStore.isUsed("same-proof-jti"),
"Redis DPoP replay adapter atomically claims JTIs with an expiry"
);
assert(
await redisDpopReplayStore.record("another-proof-jti") &&
!await redisDpopReplayStore.record("same-proof-jti"),
"Redis DPoP replay adapter accepts a fresh JTI and rejects a replay"
);
const rateLimitApp = express();
devAuthKit(rateLimitApp, {
jwtSecret: "rate-limit-test-jwt-secret",
sessionSecret: "rate-limit-test-session-secret",
rateLimit: {
googleStart: { windowMs: 60_000, max: 2, perIp: true, perEmail: false },
verifyMagicLink: {
windowMs: 60_000,
max: 1,
perIp: false,
perEmail: true,
perEmailMax: 1
}
}
});
const rateLimitServer = rateLimitApp.listen(0);
try {
const rateLimitUrl = `http://localhost:${rateLimitServer.address().port}`;
const firstLimitedRequest = await fetch(`${rateLimitUrl}/auth/google`);
const secondLimitedRequest = await fetch(`${rateLimitUrl}/auth/google`);
const thirdLimitedRequest = await fetch(`${rateLimitUrl}/auth/google`);
const rateLimitBody = await thirdLimitedRequest.json();
assert(
firstLimitedRequest.headers.has("ratelimit-limit") &&
secondLimitedRequest.status !== 429 &&
thirdLimitedRequest.status === 429 &&
thirdLimitedRequest.headers.has("retry-after") &&
rateLimitBody.retryAfterSeconds > 0,
"Auth route rate limits return standard headers and a 429 response after the configured limit"
);
const firstEmailLimitRequest = await fetch(
`${rateLimitUrl}/auth/verify-magic?email=limit%40example.com`
);
const secondEmailLimitRequest = await fetch(
`${rateLimitUrl}/auth/verify-magic?email=limit%40example.com`
);
assert(
firstEmailLimitRequest.status !== 429 &&
secondEmailLimitRequest.status === 429 &&
secondEmailLimitRequest.headers.get("ratelimit-limit") === "1",
"Per-email rate limits identify query-string email addresses independently of IP"
);
} finally {
rateLimitServer.close();
}
const failedRateLimitApp = express();
devAuthKit(failedRateLimitApp, {
jwtSecret: "rate-limit-failure-jwt-secret",
sessionSecret: "rate-limit-failure-session-secret",
rateLimitStore: {
async increment() {
throw new Error("simulated store outage");
}
}
});
const failedRateLimitServer = failedRateLimitApp.listen(0);
try {
const failedRateLimitResponse = await fetch(
`http://localhost:${failedRateLimitServer.address().port}/auth/google`
);
assert(
failedRateLimitResponse.status === 503 &&
(await failedRateLimitResponse.json()).error === "Rate-limit service unavailable",
"Rate-limit storage failures fail explicitly with HTTP 503"
);
} finally {
failedRateLimitServer.close();
}
let invalidRateLimitRejected = false;
try {
devAuthKit(express(), {
rateLimit: { requestOtp: { windowMs: 0, max: 1 } }
});
} catch (error) {
invalidRateLimitRejected = error instanceof TypeError;
}
assert(invalidRateLimitRejected, "Invalid rate-limit windows are rejected during initialization");
let publicJwtSecretRejected = false;
try {
devAuthKit(express(), {
jwtSecret: "devAuthJwtSecretKey_change_in_production",
sessionSecret: "secure-test-session-secret"
});
} catch (error) {
publicJwtSecretRejected = error instanceof TypeError;
}
assert(publicJwtSecretRejected, "Express initialization rejects the public development JWT secret");
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "production";
let missingProductionSecretsRejected = false;
try {
devAuthKit(express(), { devMode: false });
} catch (error) {
missingProductionSecretsRejected = error instanceof TypeError &&
/Production requires explicit JWT and session secrets/.test(error.message);
} finally {
if (originalNodeEnv === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = originalNodeEnv;
}
assert(missingProductionSecretsRejected, "Production initialization requires explicit high-entropy JWT and session secrets");
const doctorReport = devAuthKit.checkConfig({
dpop: true,
corsOrigin: "*"
});
assert(
doctorReport.valid === false &&
doctorReport.issues.some((issue) => issue.code === "dpop_replay_store_missing") &&
doctorReport.issues.some((issue) => issue.code === "cors_wildcard_credentials"),
"Configuration doctor reports actionable DPoP and credentialed CORS errors"
);
const previousDoctorNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "production";
let productionDoctorReport;
try {
productionDoctorReport = devAuthKit.checkConfig({
jwtSecret: "production-jwt-secret-value-that-is-long-enough",
sessionSecret: "production-session-secret-that-is-long-enough",
otpStore: {},
sessionStore: {},
rateLimit: false
});
} finally {
if (previousDoctorNodeEnv === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = previousDoctorNodeEnv;
}
assert(
productionDoctorReport.issues.some((issue) => issue.code === "rate_limiting_disabled") &&
!productionDoctorReport.issues.some((issue) => issue.code === "production_secrets"),
"Configuration doctor reports production readiness warnings without exposing secrets"
);
const prismaCalls = [];
const prismaUserAdapter = devAuthKit.prismaAdapter({
account: {
async upsert(args) {
prismaCalls.push(args);
return { userId: "user-42", emailAddress: args.create.emailAddress, accessLevel: "admin" };
}
}
}, {
model: "account",
fields: { id: "userId", email: "emailAddress", role: "accessLevel" }
});
const mappedPrismaUser = await prismaUserAdapter.findOrCreateUser({ email: "[email protected]" });
assert(
prismaCalls[0]?.where.emailAddress === "[email protected]" &&
prismaCalls[0]?.create.emailAddress === "[email protected]" &&
mappedPrismaUser.id === "user-42" &&
mappedPrismaUser.email === "[email protected]" &&
mappedPrismaUser.role === "admin",
"Prisma adapter supports custom model and field mappings"
);
const userAdapterApp = express();
devAuthKit(userAdapterApp, {
jwtSecret: "user-adapter-test-secret",
sessionSecret: "user-adapter-session-secret",
devMode: true,
setHttpOnlyCookie: false,
userAdapter: {
async findOrCreateUser({ email }) {
return { id: "stable-user-1", email, role: "admin", internalSecret: "not-a-claim" };
}
},
mapUserPayload(user) {
return { plan: user.role === "admin" ? "pro" : "free" };
}
});
const userAdapterServer = userAdapterApp.listen(0);
try {
const userAdapterUrl = `http://localhost:${userAdapterServer.address().port}`;
const userAdapterEmail = "[email protected]";
await fetch(`${userAdapterUrl}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: userAdapterEmail })
});
const userAdapterOtp = sessionStore.get(userAdapterEmail)?.otp;
const userVerifyResponse = await fetch(`${userAdapterUrl}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: userAdapterEmail, otp: userAdapterOtp })
});
const userVerifyData = await userVerifyResponse.json();
assert(
userVerifyResponse.ok &&
userVerifyData.user.id === "stable-user-1" &&
userVerifyData.user.role === "admin" &&
userVerifyData.user.plan === "pro" &&
!("internalSecret" in userVerifyData.user),
"OTP verification returns stable identity and mapped safe claims without leaking other DB fields"
);
const meResponse = await fetch(`${userAdapterUrl}/auth/me`, {
headers: { Authorization: `Bearer ${userVerifyData.token}` }
});
const meData = await meResponse.json();
assert(
meResponse.ok && meData.user.id === "stable-user-1" && meData.user.plan === "pro",
"Protected routes expose persistent user claims from the verified JWT"
);
} finally {
userAdapterServer.close();
}
const googleCalls = [];
const googleApp = express();
devAuthKit(googleApp, {
jwtSecret: "google-oauth-test-secret",
sessionSecret: "google-oauth-session-secret",
setHttpOnlyCookie: true,
google: {
clientId: "test-google-client-id",
clientSecret: "test-google-client-secret",
callbackURL: "http://localhost:3000/auth/google/callback"
},
userAdapter: {
async findOrCreateUser({ email }) {
googleCalls.push({ email });
return { id: "google-user-7", email, role: "member" };
}
},
mapUserPayload(user, identity) {
return { displayName: identity.name, authProvider: identity.provider, userRole: user.role };
}
});
const googleServer = googleApp.listen(0);
const originalFetch = global.fetch;
let googleProfileVerified = true;
try {
const googleUrl = `http://localhost:${googleServer.address().port}`;
const startOAuth = async () => {
const response = await originalFetch(`${googleUrl}/auth/google`, { redirect: "manual" });
const location = response.headers.get("location");
const sessionCookie = (response.headers.get("set-cookie") || "").split(";")[0];
return {
response,
authorizationURL: location ? new URL(location) : null,
sessionCookie
};
};
const invalidStateStart = await startOAuth();
assert(
invalidStateStart.response.status === 302 &&
invalidStateStart.authorizationURL?.hostname === "accounts.google.com" &&
invalidStateStart.authorizationURL.searchParams.get("code_challenge_method") === "S256" &&
Boolean(invalidStateStart.authorizationURL.searchParams.get("code_challenge")),
"Google sign-in redirects with OAuth state and PKCE challenge"
);
const invalidStateResponse = await originalFetch(
`${googleUrl}/auth/google/callback?code=auth-code&state=invalid`,
{ headers: { Cookie: invalidStateStart.sessionCookie } }
);
assert(invalidStateResponse.status === 400, "Google callback rejects an invalid OAuth state");
const validStateStart = await startOAuth();
const authorizationURL = validStateStart.authorizationURL;
let tokenRequestBody;
global.fetch = async (input, init = {}) => {
const url = input.toString();
if (url === "https://oauth2.googleapis.com/token") {
tokenRequestBody = new URLSearchParams(init.body);
return new Response(JSON.stringify({ access_token: "mock-google-access-token" }), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
if (url === "https://www.googleapis.com/oauth2/v3/userinfo") {
assert(
init.headers.Authorization === "Bearer mock-google-access-token",
"Google profile request uses the exchanged access token"
);
return new Response(JSON.stringify({
sub: "google-subject-7",
email: "[email protected]",
email_verified: googleProfileVerified,
name: "Google User",
picture: "https://example.com/avatar.png"
}), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}
return originalFetch(input, init);
};
const callbackResponse = await originalFetch(
`${googleUrl}/auth/google/callback?code=mock-auth-code&state=${encodeURIComponent(authorizationURL.searchParams.get("state"))}`,
{ headers: { Cookie: validStateStart.sessionCookie }, redirect: "manual" }
);
const callbackData = await callbackResponse.json();
assert(
callbackResponse.ok &&
callbackData.user.id === "google-user-7" &&
callbackData.user.email === "[email protected]" &&
callbackData.user.displayName === "Google User" &&
callbackData.user.authProvider === "google" &&
callbackData.user.userRole === "member" &&
tokenRequestBody?.get("code_verifier"),
"Google callback exchanges PKCE code, resolves persistent user, and maps safe claims"
);
assert(
googleCalls.length === 1 && googleCalls[0].email === "[email protected]" &&
(callbackResponse.headers.get("set-cookie") || "").includes("devauth_token="),
"Google login uses normalized verified email and sets the auth cookie"
);
const sessionCookie = (callbackResponse.headers.get("set-cookie") || "").match(/connect\.sid=([^;,]+)/)?.[1];
const sessionMeResponse = await originalFetch(`${googleUrl}/auth/me`, {
headers: { Cookie: `connect.sid=${sessionCookie}` }
});
const sessionMeData = await sessionMeResponse.json();
assert(
Boolean(sessionCookie) &&
sessionMeResponse.ok &&
sessionMeData.user.id === "google-user-7",
"Google login regenerates and persists the authenticated session"
);
const replayResponse = await originalFetch(
`${googleUrl}/auth/google/callback?code=mock-auth-code&state=${encodeURIComponent(authorizationURL.searchParams.get("state"))}`,
{ headers: { Cookie: validStateStart.sessionCookie } }
);
assert(replayResponse.status === 400, "Google OAuth state cannot be replayed after successful login");
const googleMeResponse = await originalFetch(`${googleUrl}/auth/me`, {
headers: { Authorization: `Bearer ${callbackData.token}` }
});
const googleMeData = await googleMeResponse.json();
assert(
googleMeResponse.ok &&
googleMeData.user.id === "google-user-7" &&
googleMeData.user.displayName === "Google User",
"Google user claims authenticate protected endpoints"
);
googleProfileVerified = false;
const unverifiedStart = await startOAuth();
const unverifiedResponse = await originalFetch(
`${googleUrl}/auth/google/callback?code=mock-auth-code&state=${encodeURIComponent(unverifiedStart.authorizationURL.searchParams.get("state"))}`,
{ headers: { Cookie: unverifiedStart.sessionCookie } }
);
assert(
unverifiedResponse.status === 401 && googleCalls.length === 1,
"Google callback rejects unverified email before creating a local user"
);
} finally {
global.fetch = originalFetch;
googleServer.close();
}
console.log("\n🔄 Testing refresh-token rotation and revocation...");
const refreshEntries = new Map();
const refreshOtpStore = {
async get(email) {
return refreshEntries.get(email) || null;
},
async set(email, entry) {
refreshEntries.set(email, { ...entry });
},
async delete(email) {
refreshEntries.delete(email);
},
async recordAttempt(email) {
const entry = refreshEntries.get(email);
if (!entry) return 0;
return ++entry.attempts;
}
};
const refreshTokenStore = new devAuthKit.MemoryRefreshTokenStore();
const refreshApp = express();
devAuthKit(refreshApp, {
jwtSecret: "refresh-test-jwt-secret",
sessionSecret: "refresh-test-session-secret",
otpStore: refreshOtpStore,
refreshTokenStore,
refreshTokens: { accessTokenExpiresIn: "15m", refreshTokenExpiresInDays: 1 },
userAdapter: {
async findOrCreateUser({ email }) {
return { id: "shared-refresh-user", email, role: "user" };
}
},
devMode: true
});
refreshApp.get("/api/private", devAuthKit.requireAuth, (req, res) => {
res.json({ user: req.user });
});
const refreshServer = refreshApp.listen(0);
try {
const refreshUrl = `http://localhost:${refreshServer.address().port}`;
const loginRefreshUser = async (email) => {
const request = await originalFetch(`${refreshUrl}/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email })
});
if (!request.ok) throw new Error("Failed to request refresh-test OTP");
const otp = refreshEntries.get(email)?.otp;
const verify = await originalFetch(`${refreshUrl}/auth/verify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, otp })
});
const data = await verify.json();
const cookies = verify.headers.get("set-cookie") || "";
const cookieHeaders = verify.headers.getSetCookie?.() || [cookies];
const refreshCookieHeader = cookieHeaders.find((cookie) => cookie.startsWith("devauth_token_refresh=")) || "";
const refreshCookie = refreshCookieHeader.match(/devauth_token_refresh=([^;,]+)/)?.[1];
if (!verify.ok || !data.token || !refreshCookie) throw new Error("Refresh token login did not issue expected credentials");
return {
token: data.token,
refreshCookie,
user: data.user,
exposesRefreshToken: Object.hasOwn(data, "refreshToken"),
refreshCookieHttpOnly: /;\s*HttpOnly/i.test(refreshCookieHeader)
};
};
const rotatedLogin = await loginRefreshUser("[email protected]");
assert(
rotatedLogin.user.id === "shared-refresh-user" &&
!rotatedLogin.exposesRefreshToken &&
rotatedLogin.refreshCookieHttpOnly,
"Refresh-enabled login uses a stable user identity and keeps its token in an httpOnly cookie"
);
const rotateResponse = await originalFetch(`${refreshUrl}/auth/refresh`, {
method: "POST",
headers: { Cookie: `devauth_token_refresh=${rotatedLogin.refreshCookie}` }
});
const rotatedData = await rotateResponse.json();
const rotatedCookie = (rotateResponse.headers.get("set-cookie") || "")
.match(/devauth_token_refresh=([^;,]+)/)?.[1];
assert(
rotateResponse.ok &&
rotatedData.refreshEnabled === true &&
rotatedData.token !== rotatedLogin.token &&
rotatedCookie &&
rotatedCookie !== rotatedLogin.refreshCookie,
`Refresh endpoint rotates the httpOnly refresh token and issues a new access token (status ${rotateResponse.status}; enabled ${rotatedData.refreshEnabled}; token changed ${rotatedData.token !== rotatedLogin.token}; cookie ${Boolean(rotatedCookie)}; cookie changed ${rotatedCookie !== rotatedLogin.refreshCookie})`
);
const reuseResponse = await originalFetch(`${refreshUrl}/auth/refresh`, {
method: "POST",
headers: { Cookie: `devauth_token_refresh=${rotatedLogin.refreshCookie}` }
});
const afterReuse = await originalFetch(`${refreshUrl}/api/private`, {
headers: { Authorization: `Bearer ${rotatedData.token}` }
});
assert(
reuseResponse.status === 401 && afterReuse.status === 401,
"Refresh-token reuse revokes the complete family and its access tokens"
);
const currentLogin = await loginRefreshUser("[email protected]");
const currentRevoke = await originalFetch(`${refreshUrl}/auth/sessions/revoke`, {
method: "POST",
headers: { Authorization: `Bearer ${currentLogin.token}` }
});
const revokedCurrentAccess = await originalFetch(`${refreshUrl}/api/private`, {
headers: { Authorization: `Bearer ${currentLogin.token}` }
});
assert(
currentRevoke.ok && revokedCurrentAccess.status === 401,
"Current-session revocation immediately rejects that session's access token"
);
const allLoginA = await loginRefreshUser("[email protected]");
const allLoginB = await loginRefreshUser("[email protected]");
const revokeAllResponse = await originalFetch(`${refreshUrl}/auth/sessions/revoke-all`, {
method: "POST",
headers: { Authorization: `Bearer ${allLoginA.token}` }
});
const revokedAllAccess = await originalFetch(`${refreshUrl}/api/private`, {
headers: { Authorization: `Bearer ${allLoginB.token}` }
});
assert(
revokeAllResponse.ok && revokedAllAccess.status === 401,
"Revoke-all invalidates access tokens from every session for the user"
);
const logoutLogin = await loginRefreshUser("[email protected]");
const refreshLogout = await originalFetch(`${refreshUrl}/auth/logout`, {
method: "POST",
headers: { Cookie: `devauth_token_refresh=${logoutLogin.refreshCookie}` }
});
const logoutRevokedAccess = await originalFetch(`${refreshUrl}/api/private`, {
headers: { Authorization: `Bearer ${logoutLogin.token}` }
});
assert(
refreshLogout.ok && logoutRevokedAccess.status === 401,
"Logout revokes the refresh-token family and current access token"
);
} finally {
refreshServer.close();
}
let sdkRefreshCalls = 0;
let sdkProtectedCalls = 0;
const refreshSdk = new DevAuthClient({
apiUrl: "https://auth.example.test",
customFetch: async (url, options = {}) => {
if (url.endsWith("/auth/verify")) {
return new Response(JSON.stringify({
token: "old-access-token",
user: { email: "[email protected]" },
refreshEnabled: true
}), { status: 200, headers: { "Content-Type": "application/json" } });
}
if (url.endsWith("/auth/refresh")) {
sdkRefreshCalls++;
return new Response(JSON.stringify({
token: "new-access-token",
user: { email: "[email protected]" },
refreshEnabled: true,
expiresIn: "15m"
}), { status: 200, headers: { "Content-Type": "application/json" } });
}
if (url.endsWith("/api/private")) {
sdkProtectedCalls++;
if (options.headers.get("Authorization") === "Bearer old-access-token") {
return new Response(JSON.stringify({ error: "expired" }), { status: 401 });
}
return new Response(JSON.stringify({ success: true }), { status: 200 });
}
return new Response(JSON.stringify({ message: "ok" }), { status: 200 });
}
});
await refreshSdk.verifyOTP("[email protected]", "123456");
const sdkRefreshedResponses = await Promise.all([
refreshSdk.fetch("/api/private"),
refreshSdk.fetch("/api/private")
]);
assert(
sdkRefreshedResponses.every((response) => response.ok) &&
sdkRefreshCalls === 1 &&
sdkProtectedCalls === 4 &&
refreshSdk.getToken() === "new-access-token",
"Client SDK shares concurrent refresh requests and retries with the rotated access token"
);
console.log("\n🛡️ Testing Role-Based Access Control (RBAC requireRole)...");
const { requireRole, drizzleAdapter, mongooseAdapter } = devAuthKit;
const rbacApp = express();
devAuthKit(rbacApp, {
jwtSecret: "rbac-test-jwt-secret",
sessionSecret: "rbac-test-session-secret",
devMode: true
});
rbacApp.get("/api/admin-only", requireRole("admin"), (req, res) => {
res.json({ secret: "admin-data" });
});
rbacApp.get("/api/staff-only", requireRole(["admin", "moderator"]), (req, res) => {
res.json({ secret: "staff-data" });
});
const rbacServer = rbacApp.listen(0);
const rbacUrl = `http://localhost:${rbacServer.address().port}`;
try {
// 1. Unauthenticated request to requireRole route -> 401
const unauthRbac = await fetch(`${rbacUrl}/api/admin-only`);
assert(unauthRbac.status === 401, "requireRole returns 401 Unauthorized for unauthenticated requests");
// 2. User with role 'user' -> 403 Forbidden