@smartcrab/server 0.8.0 → 0.9.0-next-20261203092527

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.
@@ -1,1151 +0,0 @@
1
- import { parseSetCookie } from "cookie";
2
- import { SignJWT, exportJWK } from "jose";
3
- import type { JWTHeaderParameters } from "jose";
4
- import { describe, expect, test } from "vitest";
5
- import { isBase64Url } from "./base64.js";
6
- import { PKCE_COOKIE_NAME, SESSION_COOKIE_NAME } from "./cookies.js";
7
- import type { FetchLike } from "./http.js";
8
- import { createServerAuth } from "./server-auth.js";
9
- import type { ServerAuth } from "./server-auth.js";
10
-
11
- /**
12
- * Full login → callback → session → refresh → logout state machine against a
13
- * stubbed Authorization Server (discovery + JWKS + token + revocation served
14
- * by an injected fetch). A real EC P-256 key pair signs ID tokens so the jose
15
- * verification path runs exactly as in production.
16
- */
17
-
18
- const ISSUER = "https://id.example.com/e/env_test";
19
- const CLIENT_ID = "cli_testclient";
20
- const CLIENT_SECRET = "test_client_secret";
21
- const COOKIE_SECRET = "0123456789abcdef0123456789abcdef";
22
- const REDIRECT_URI = "https://app.example.com/auth/callback";
23
- const APP_ORIGIN = "https://app.example.com";
24
- const KID = "test-signing-key-1";
25
- const USER_SUB = "usr_testuser";
26
- const API_AUDIENCE = "https://api.example.com";
27
-
28
- const generatedKeyPair = await crypto.subtle.generateKey(
29
- { name: "ECDSA", namedCurve: "P-256" },
30
- true,
31
- ["sign", "verify"],
32
- );
33
- if (!("publicKey" in generatedKeyPair) || !("privateKey" in generatedKeyPair)) {
34
- throw new Error("expected an ECDSA key pair");
35
- }
36
- const signingKeyPair: CryptoKeyPair = generatedKeyPair;
37
- const publicJwk = await exportJWK(signingKeyPair.publicKey);
38
- publicJwk.kid = KID;
39
- publicJwk.alg = "ES256";
40
- publicJwk.use = "sig";
41
-
42
- const discoveryDocument = () => ({
43
- issuer: ISSUER,
44
- authorization_endpoint: `${ISSUER}/oauth2/authorize`,
45
- token_endpoint: `${ISSUER}/oauth2/token`,
46
- userinfo_endpoint: `${ISSUER}/oauth2/userinfo`,
47
- jwks_uri: `${ISSUER}/oauth2/jwks`,
48
- revocation_endpoint: `${ISSUER}/oauth2/revoke`,
49
- introspection_endpoint: `${ISSUER}/oauth2/introspect`,
50
- end_session_endpoint: `${ISSUER}/oauth2/logout`,
51
- response_types_supported: ["code"],
52
- grant_types_supported: ["authorization_code", "refresh_token"],
53
- code_challenge_methods_supported: ["S256"],
54
- token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post", "none"],
55
- scopes_supported: ["openid", "profile", "email", "offline_access"],
56
- subject_types_supported: ["public"],
57
- id_token_signing_alg_values_supported: ["ES256"],
58
- claims_supported: ["sub", "iss", "aud", "exp", "iat", "nonce", "name", "email", "email_verified"],
59
- });
60
-
61
- interface IdTokenOptions {
62
- readonly nonce?: string;
63
- readonly issuer?: string;
64
- readonly audience?: string;
65
- readonly kid?: string | null;
66
- readonly expirationSeconds?: number;
67
- readonly signingKey?: CryptoKey;
68
- readonly typ?: string;
69
- }
70
-
71
- const signIdToken = async (options: IdTokenOptions = {}): Promise<string> => {
72
- const header: JWTHeaderParameters = { alg: "ES256", typ: options.typ ?? "JWT" };
73
- const kid = options.kid === null ? undefined : (options.kid ?? KID);
74
- if (kid !== undefined) header.kid = kid;
75
- let jwt = new SignJWT({
76
- sub: USER_SUB,
77
- name: "Test User",
78
- email: "test@example.com",
79
- email_verified: true,
80
- ...(options.nonce !== undefined ? { nonce: options.nonce } : {}),
81
- })
82
- .setProtectedHeader(header)
83
- .setIssuer(options.issuer ?? ISSUER)
84
- .setAudience(options.audience ?? CLIENT_ID)
85
- .setIssuedAt();
86
- const expiration = options.expirationSeconds ?? Math.floor(Date.now() / 1000) + 300;
87
- jwt = jwt.setExpirationTime(expiration);
88
- return jwt.sign(options.signingKey ?? signingKeyPair.privateKey);
89
- };
90
-
91
- const signAccessToken = async (
92
- options: { audience?: string; issuer?: string; typ?: string; kid?: string | null } = {},
93
- ): Promise<string> => {
94
- const header: JWTHeaderParameters = { alg: "ES256", typ: options.typ ?? "at+jwt" };
95
- const kid = options.kid === null ? undefined : (options.kid ?? KID);
96
- if (kid !== undefined) header.kid = kid;
97
- return new SignJWT({ sub: USER_SUB, client_id: CLIENT_ID, scope: "openid profile" })
98
- .setProtectedHeader(header)
99
- .setIssuer(options.issuer ?? ISSUER)
100
- .setAudience(options.audience ?? API_AUDIENCE)
101
- .setIssuedAt()
102
- .setExpirationTime(Math.floor(Date.now() / 1000) + 300)
103
- .sign(signingKeyPair.privateKey);
104
- };
105
-
106
- interface TokenCall {
107
- readonly body: URLSearchParams;
108
- readonly authorization: string | null;
109
- }
110
-
111
- interface StubState {
112
- discoveryHits: number;
113
- jwksHits: number;
114
- readonly tokenCalls: TokenCall[];
115
- readonly revocationCalls: URLSearchParams[];
116
- currentNonce: string | null;
117
- tokenHandler: (params: URLSearchParams) => Promise<Response>;
118
- }
119
-
120
- const jsonResponse = (body: unknown, status = 200): Response =>
121
- new Response(JSON.stringify(body), {
122
- status,
123
- headers: { "content-type": "application/json" },
124
- });
125
-
126
- const defaultTokenHandler =
127
- (state: StubState) =>
128
- async (params: URLSearchParams): Promise<Response> => {
129
- const grantType = params.get("grant_type");
130
- if (grantType === "authorization_code") {
131
- const idToken = await signIdToken({ nonce: state.currentNonce ?? "" });
132
- return jsonResponse({
133
- access_token: "atk_initial",
134
- token_type: "Bearer",
135
- expires_in: 300,
136
- refresh_token: "rt_1",
137
- id_token: idToken,
138
- scope: "openid profile email offline_access",
139
- });
140
- }
141
- if (grantType === "refresh_token") {
142
- return jsonResponse({
143
- access_token: "atk_refreshed",
144
- token_type: "Bearer",
145
- expires_in: 300,
146
- refresh_token: "rt_2",
147
- scope: "openid profile email offline_access",
148
- });
149
- }
150
- return jsonResponse({ error: "unsupported_grant_type" }, 400);
151
- };
152
-
153
- const createStubState = (): StubState => {
154
- const state: StubState = {
155
- discoveryHits: 0,
156
- jwksHits: 0,
157
- tokenCalls: [],
158
- revocationCalls: [],
159
- currentNonce: null,
160
- tokenHandler: async () => jsonResponse({ error: "server_error" }, 500),
161
- };
162
- state.tokenHandler = defaultTokenHandler(state);
163
- return state;
164
- };
165
-
166
- const createStubFetch = (state: StubState): FetchLike => {
167
- return async (input, init) => {
168
- const url =
169
- typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
170
- if (url === `${ISSUER}/.well-known/openid-configuration`) {
171
- state.discoveryHits += 1;
172
- return jsonResponse(discoveryDocument());
173
- }
174
- if (url === `${ISSUER}/oauth2/jwks`) {
175
- state.jwksHits += 1;
176
- return jsonResponse({ keys: [publicJwk] });
177
- }
178
- if (url === `${ISSUER}/oauth2/token`) {
179
- const body = typeof init?.body === "string" ? init.body : "";
180
- const authorization = new Headers(init?.headers).get("authorization");
181
- const params = new URLSearchParams(body);
182
- state.tokenCalls.push({ body: params, authorization });
183
- return state.tokenHandler(params);
184
- }
185
- if (url === `${ISSUER}/oauth2/revoke`) {
186
- const body = typeof init?.body === "string" ? init.body : "";
187
- state.revocationCalls.push(new URLSearchParams(body));
188
- return new Response(null, { status: 200 });
189
- }
190
- return new Response("not found", { status: 404 });
191
- };
192
- };
193
-
194
- /** Resolves after `ms`, or rejects as soon as the caller's deadline aborts. */
195
- const delay = (ms: number, signal?: AbortSignal | null): Promise<void> =>
196
- new Promise((resolve, reject) => {
197
- setTimeout(resolve, ms);
198
- signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
199
- });
200
-
201
- const createTestAuth = (
202
- state: StubState,
203
- overrides: {
204
- readonly fetch?: FetchLike;
205
- readonly refreshLeewaySeconds?: number;
206
- readonly allowedRedirectTargets?: readonly string[];
207
- readonly postLoginRedirect?: string;
208
- readonly basePath?: string;
209
- } = {},
210
- ): ServerAuth =>
211
- createServerAuth({
212
- issuer: ISSUER,
213
- clientId: CLIENT_ID,
214
- clientSecret: CLIENT_SECRET,
215
- redirectUri: REDIRECT_URI,
216
- cookieSecret: COOKIE_SECRET,
217
- fetch: overrides.fetch ?? createStubFetch(state),
218
- ...(overrides.basePath !== undefined ? { basePath: overrides.basePath } : {}),
219
- ...(overrides.refreshLeewaySeconds !== undefined
220
- ? { refreshLeewaySeconds: overrides.refreshLeewaySeconds }
221
- : {}),
222
- ...(overrides.allowedRedirectTargets !== undefined
223
- ? { allowedRedirectTargets: overrides.allowedRedirectTargets }
224
- : {}),
225
- ...(overrides.postLoginRedirect !== undefined
226
- ? { postLoginRedirect: overrides.postLoginRedirect }
227
- : {}),
228
- });
229
-
230
- interface LoginArtifacts {
231
- readonly state: string;
232
- readonly nonce: string;
233
- readonly pkceCookieValue: string;
234
- readonly location: URL;
235
- readonly setCookieHeader: string;
236
- }
237
-
238
- const runLogin = async (auth: ServerAuth, returnTo?: string): Promise<LoginArtifacts> => {
239
- const url = `${APP_ORIGIN}/auth/login${returnTo !== undefined ? `?return_to=${encodeURIComponent(returnTo)}` : ""}`;
240
- const response = await auth.loginHandler(new Request(url));
241
- expect(response.status).toBe(302);
242
- const location = new URL(response.headers.get("location") ?? "");
243
- const setCookieHeader = response.headers.getSetCookie()[0] ?? "";
244
- const parsed = parseSetCookie(setCookieHeader);
245
- return {
246
- state: location.searchParams.get("state") ?? "",
247
- nonce: location.searchParams.get("nonce") ?? "",
248
- pkceCookieValue: parsed.value ?? "",
249
- location,
250
- setCookieHeader,
251
- };
252
- };
253
-
254
- const runCallback = async (
255
- auth: ServerAuth,
256
- input: { readonly state: string; readonly pkceCookieValue: string; readonly code?: string },
257
- ): Promise<Response> => {
258
- const code = input.code ?? `ac_${"a".repeat(32)}`;
259
- const url = `${APP_ORIGIN}/auth/callback?code=${encodeURIComponent(code)}&state=${encodeURIComponent(input.state)}`;
260
- return auth.callbackHandler(
261
- new Request(url, { headers: { cookie: `${PKCE_COOKIE_NAME}=${input.pkceCookieValue}` } }),
262
- );
263
- };
264
-
265
- /** Runs a full successful login and returns the `Cookie` header fragment for the session. */
266
- const completeLogin = async (
267
- auth: ServerAuth,
268
- state: StubState,
269
- returnTo?: string,
270
- ): Promise<string> => {
271
- const login = await runLogin(auth, returnTo);
272
- state.currentNonce = login.nonce;
273
- const callbackResponse = await runCallback(auth, login);
274
- expect(callbackResponse.status).toBe(302);
275
- const sessionSet = callbackResponse.headers
276
- .getSetCookie()
277
- .find((value) => value.startsWith(`${SESSION_COOKIE_NAME}=`));
278
- expect(sessionSet).toBeDefined();
279
- return `${SESSION_COOKIE_NAME}=${parseSetCookie(sessionSet ?? "").value ?? ""}`;
280
- };
281
-
282
- const sessionRequest = (path: string, cookieHeader: string): Request =>
283
- new Request(`${APP_ORIGIN}${path}`, { headers: { cookie: cookieHeader } });
284
-
285
- const refreshGrantCalls = (state: StubState): TokenCall[] =>
286
- state.tokenCalls.filter((call) => call.body.get("grant_type") === "refresh_token");
287
-
288
- // ---------------------------------------------------------------------------
289
- // login handler
290
- // ---------------------------------------------------------------------------
291
-
292
- describe("loginHandler", () => {
293
- test("redirects to the authorize endpoint with Authorization Code + PKCE S256", async () => {
294
- const state = createStubState();
295
- const auth = createTestAuth(state);
296
- const login = await runLogin(auth);
297
-
298
- expect(login.location.origin + login.location.pathname).toBe(`${ISSUER}/oauth2/authorize`);
299
- const params = login.location.searchParams;
300
- expect(params.get("response_type")).toBe("code");
301
- expect(params.get("client_id")).toBe(CLIENT_ID);
302
- expect(params.get("redirect_uri")).toBe(REDIRECT_URI);
303
- expect(params.get("scope")).toBe("openid profile email offline_access");
304
- expect(params.get("code_challenge_method")).toBe("S256");
305
- const challenge = params.get("code_challenge") ?? "";
306
- // base64url(SHA-256(verifier)) — 32 bytes, 43 chars, no padding.
307
- expect(challenge.length).toBe(43);
308
- expect(isBase64Url(challenge)).toBe(true);
309
- expect(login.state.length).toBe(43);
310
- expect(login.nonce.length).toBe(43);
311
- expect(isBase64Url(login.state)).toBe(true);
312
- expect(isBase64Url(login.nonce)).toBe(true);
313
- });
314
-
315
- test("sets the PKCE handshake cookie with __Host- conforming attributes", async () => {
316
- const state = createStubState();
317
- const auth = createTestAuth(state);
318
- const login = await runLogin(auth);
319
-
320
- const parsed = parseSetCookie(login.setCookieHeader);
321
- expect(parsed.name).toBe(PKCE_COOKIE_NAME);
322
- expect(parsed.httpOnly).toBe(true);
323
- expect(parsed.secure).toBe(true);
324
- expect(parsed.sameSite).toBe("lax");
325
- expect(parsed.path).toBe("/");
326
- expect(parsed.maxAge).toBe(600);
327
- // __Host- prefix rule: no Domain attribute, ever.
328
- expect(parsed.domain).toBeUndefined();
329
- expect(login.setCookieHeader.toLowerCase()).not.toContain("domain=");
330
- // Sealed payload: v1.<iv>.<ciphertext>, opaque to the client.
331
- expect(parsed.value ?? "").toMatch(/^v1\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/);
332
- });
333
-
334
- test("POST login with a foreign Origin is rejected (CSRF)", async () => {
335
- const state = createStubState();
336
- const auth = createTestAuth(state);
337
- const response = await auth.loginHandler(
338
- new Request(`${APP_ORIGIN}/auth/login`, {
339
- method: "POST",
340
- headers: { origin: "https://evil.example.com" },
341
- }),
342
- );
343
- expect(response.status).toBe(403);
344
- const body: unknown = await response.json();
345
- expect(body).toMatchObject({ code: "csrf_validation_failed" });
346
- });
347
-
348
- test("POST login with the same Origin succeeds", async () => {
349
- const state = createStubState();
350
- const auth = createTestAuth(state);
351
- const response = await auth.loginHandler(
352
- new Request(`${APP_ORIGIN}/auth/login`, {
353
- method: "POST",
354
- headers: { origin: APP_ORIGIN },
355
- }),
356
- );
357
- expect(response.status).toBe(302);
358
- });
359
-
360
- test("POST login without Origin and Referer fails closed", async () => {
361
- const state = createStubState();
362
- const auth = createTestAuth(state);
363
- const response = await auth.loginHandler(
364
- new Request(`${APP_ORIGIN}/auth/login`, { method: "POST" }),
365
- );
366
- expect(response.status).toBe(403);
367
- });
368
-
369
- test("POST login with a same-origin Referer (no Origin) succeeds", async () => {
370
- const state = createStubState();
371
- const auth = createTestAuth(state);
372
- const response = await auth.loginHandler(
373
- new Request(`${APP_ORIGIN}/auth/login`, {
374
- method: "POST",
375
- headers: { referer: `${APP_ORIGIN}/login-page` },
376
- }),
377
- );
378
- expect(response.status).toBe(302);
379
- });
380
-
381
- test("rejects unsupported methods", async () => {
382
- const state = createStubState();
383
- const auth = createTestAuth(state);
384
- const response = await auth.loginHandler(
385
- new Request(`${APP_ORIGIN}/auth/login`, { method: "DELETE" }),
386
- );
387
- expect(response.status).toBe(405);
388
- });
389
-
390
- test("oversized discovery documents are rejected before parsing", async () => {
391
- const oversized = "x".repeat(128 * 1024);
392
- const fetchImpl: FetchLike = async () =>
393
- new Response(oversized, {
394
- status: 200,
395
- headers: { "content-length": String(128 * 1024) },
396
- });
397
- const auth = createServerAuth({
398
- issuer: ISSUER,
399
- clientId: CLIENT_ID,
400
- clientSecret: CLIENT_SECRET,
401
- redirectUri: REDIRECT_URI,
402
- cookieSecret: COOKIE_SECRET,
403
- fetch: fetchImpl,
404
- });
405
- const response = await auth.loginHandler(new Request(`${APP_ORIGIN}/auth/login`));
406
- expect(response.status).toBe(502);
407
- const body: unknown = await response.json();
408
- expect(body).toMatchObject({ code: "response_too_large" });
409
- });
410
- });
411
-
412
- // ---------------------------------------------------------------------------
413
- // callback handler
414
- // ---------------------------------------------------------------------------
415
-
416
- describe("callbackHandler", () => {
417
- test("full flow issues the §22.2 session cookie and clears the handshake cookie", async () => {
418
- const state = createStubState();
419
- const auth = createTestAuth(state);
420
- const login = await runLogin(auth, "/dashboard");
421
- state.currentNonce = login.nonce;
422
-
423
- const response = await runCallback(auth, login);
424
- expect(response.status).toBe(302);
425
- expect(response.headers.get("location")).toBe("/dashboard");
426
-
427
- const setCookies = response.headers.getSetCookie();
428
- const sessionHeader = setCookies.find((value) => value.startsWith(`${SESSION_COOKIE_NAME}=`));
429
- expect(sessionHeader).toBeDefined();
430
- const session = parseSetCookie(sessionHeader ?? "");
431
- expect(session.name).toBe(SESSION_COOKIE_NAME);
432
- expect(session.httpOnly).toBe(true);
433
- expect(session.secure).toBe(true);
434
- expect(session.sameSite).toBe("lax");
435
- expect(session.path).toBe("/");
436
- expect(session.domain).toBeUndefined();
437
- expect((sessionHeader ?? "").toLowerCase()).not.toContain("domain=");
438
- expect(session.value ?? "").toMatch(/^v1\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/);
439
-
440
- const pkceClear = setCookies.find((value) => value.startsWith(`${PKCE_COOKIE_NAME}=`));
441
- expect(pkceClear).toBeDefined();
442
- const cleared = parseSetCookie(pkceClear ?? "");
443
- expect(cleared.maxAge).toBe(0);
444
-
445
- // The token endpoint was called with client_secret_basic (§15.4).
446
- expect(state.tokenCalls).toHaveLength(1);
447
- const call = state.tokenCalls[0];
448
- expect(call?.body.get("grant_type")).toBe("authorization_code");
449
- expect(call?.body.get("redirect_uri")).toBe(REDIRECT_URI);
450
- expect(call?.body.get("code_verifier") ?? "").toHaveLength(64);
451
- expect(call?.authorization?.startsWith("Basic ")).toBe(true);
452
- const decoded = atob((call?.authorization ?? "").slice("Basic ".length));
453
- expect(decoded).toBe(`${encodeURIComponent(CLIENT_ID)}:${encodeURIComponent(CLIENT_SECRET)}`);
454
- });
455
-
456
- test("completes a slow token exchange without losing the login", async () => {
457
- const state = createStubState();
458
- const upstream = createStubFetch(state);
459
- const auth = createTestAuth(state, {
460
- fetch: async (input, init) => {
461
- if (input !== `${ISSUER}/oauth2/token`) return upstream(input, init);
462
- // Rejects if the caller's deadline aborts first — which is exactly how
463
- // the single-use authorization code used to be burned.
464
- await delay(6_000, init?.signal);
465
- return upstream(input, init);
466
- },
467
- });
468
-
469
- const cookie = await completeLogin(auth, state);
470
- expect(await auth.getSession(sessionRequest("/", cookie))).toMatchObject({
471
- status: "authenticated",
472
- session: { user: { sub: USER_SUB } },
473
- });
474
- }, 20_000);
475
-
476
- test("rejects a state mismatch (constant-time compared)", async () => {
477
- const state = createStubState();
478
- const auth = createTestAuth(state);
479
- const login = await runLogin(auth);
480
- state.currentNonce = login.nonce;
481
-
482
- const response = await runCallback(auth, { ...login, state: `${"b".repeat(43)}` });
483
- expect(response.status).toBe(400);
484
- const body: unknown = await response.json();
485
- expect(body).toMatchObject({ code: "state_mismatch" });
486
- // No session cookie is issued on failure, and the handshake cookie is cleared.
487
- const setCookies = response.headers.getSetCookie();
488
- expect(setCookies.some((value) => value.startsWith(`${SESSION_COOKIE_NAME}=`))).toBe(false);
489
- expect(
490
- setCookies.some(
491
- (value) => value.startsWith(`${PKCE_COOKIE_NAME}=`) && value.includes("Max-Age=0"),
492
- ),
493
- ).toBe(true);
494
- expect(state.tokenCalls).toHaveLength(0);
495
- });
496
-
497
- test("rejects a callback without the handshake cookie", async () => {
498
- const state = createStubState();
499
- const auth = createTestAuth(state);
500
- const response = await auth.callbackHandler(
501
- new Request(`${APP_ORIGIN}/auth/callback?code=ac_${"a".repeat(32)}&state=whatever`),
502
- );
503
- expect(response.status).toBe(400);
504
- const body: unknown = await response.json();
505
- expect(body).toMatchObject({ code: "pkce_cookie_missing" });
506
- });
507
-
508
- test("rejects a tampered handshake cookie", async () => {
509
- const state = createStubState();
510
- const auth = createTestAuth(state);
511
- const response = await runCallback(auth, {
512
- state: "whatever",
513
- pkceCookieValue: `v1.${"A".repeat(16)}.${"B".repeat(43)}`,
514
- });
515
- expect(response.status).toBe(400);
516
- const body: unknown = await response.json();
517
- expect(body).toMatchObject({ code: "pkce_cookie_invalid" });
518
- });
519
-
520
- test("surfaces known authorization errors without provider-supplied descriptions", async () => {
521
- const state = createStubState();
522
- const auth = createTestAuth(state);
523
- const login = await runLogin(auth);
524
- const callbackUrl = new URL("/auth/callback", APP_ORIGIN);
525
- callbackUrl.searchParams.set("error", "access_denied");
526
- callbackUrl.searchParams.set("error_description", "private provider details");
527
- callbackUrl.searchParams.set("state", login.state);
528
- const response = await auth.callbackHandler(
529
- new Request(callbackUrl, {
530
- headers: { cookie: `${PKCE_COOKIE_NAME}=${login.pkceCookieValue}` },
531
- }),
532
- );
533
- expect(response.status).toBe(400);
534
- const body: unknown = await response.json();
535
- expect(body).toMatchObject({
536
- code: "oauth_authorization_error",
537
- detail: "access_denied",
538
- });
539
- expect(JSON.stringify(body)).not.toContain("private provider details");
540
- });
541
-
542
- test("replaces unknown authorization errors with a fixed generic detail", async () => {
543
- const state = createStubState();
544
- const auth = createTestAuth(state);
545
- const login = await runLogin(auth);
546
- const attackerText = `sensitive@example.com ${"private".repeat(16)}`;
547
- const callbackUrl = new URL("/auth/callback", APP_ORIGIN);
548
- callbackUrl.searchParams.set("error", attackerText);
549
- callbackUrl.searchParams.set("error_description", "also private");
550
- callbackUrl.searchParams.set("state", login.state);
551
- const response = await auth.callbackHandler(
552
- new Request(callbackUrl, {
553
- headers: { cookie: `${PKCE_COOKIE_NAME}=${login.pkceCookieValue}` },
554
- }),
555
- );
556
- expect(response.status).toBe(400);
557
- const body: unknown = await response.json();
558
- expect(body).toMatchObject({
559
- code: "oauth_authorization_error",
560
- detail: "server_error",
561
- });
562
- expect(JSON.stringify(body)).not.toContain(attackerText);
563
- expect(JSON.stringify(body)).not.toContain("also private");
564
- });
565
-
566
- test("rejects a nonce mismatch in the ID token", async () => {
567
- const state = createStubState();
568
- const auth = createTestAuth(state);
569
- const login = await runLogin(auth);
570
- state.currentNonce = "definitely-not-the-handshake-nonce";
571
- const response = await runCallback(auth, login);
572
- expect(response.status).toBe(400);
573
- const body: unknown = await response.json();
574
- expect(body).toMatchObject({ code: "id_token_invalid" });
575
- });
576
-
577
- test("rejects an ID token with the wrong issuer", async () => {
578
- const state = createStubState();
579
- state.tokenHandler = async () =>
580
- jsonResponse({
581
- access_token: "atk",
582
- token_type: "Bearer",
583
- expires_in: 300,
584
- refresh_token: "rt_1",
585
- id_token: await signIdToken({ issuer: "https://evil.example.com" }),
586
- scope: "openid",
587
- });
588
- const auth = createTestAuth(state);
589
- const login = await runLogin(auth);
590
- const response = await runCallback(auth, login);
591
- expect(response.status).toBe(400);
592
- const body: unknown = await response.json();
593
- expect(body).toMatchObject({ code: "id_token_invalid" });
594
- });
595
-
596
- test("rejects an ID token with the wrong audience", async () => {
597
- const state = createStubState();
598
- state.tokenHandler = async () =>
599
- jsonResponse({
600
- access_token: "atk",
601
- token_type: "Bearer",
602
- expires_in: 300,
603
- id_token: await signIdToken({ audience: "cli_someoneelse" }),
604
- scope: "openid",
605
- });
606
- const auth = createTestAuth(state);
607
- const login = await runLogin(auth);
608
- const response = await runCallback(auth, login);
609
- expect(response.status).toBe(400);
610
- const body: unknown = await response.json();
611
- expect(body).toMatchObject({ code: "id_token_invalid" });
612
- });
613
-
614
- test("rejects an expired ID token", async () => {
615
- const state = createStubState();
616
- state.tokenHandler = async () => {
617
- const idToken = await signIdToken({
618
- nonce: state.currentNonce ?? "",
619
- expirationSeconds: Math.floor(Date.now() / 1000) - 3600,
620
- });
621
- return jsonResponse({
622
- access_token: "atk",
623
- token_type: "Bearer",
624
- expires_in: 300,
625
- id_token: idToken,
626
- scope: "openid",
627
- });
628
- };
629
- const auth = createTestAuth(state);
630
- const login = await runLogin(auth);
631
- state.currentNonce = login.nonce;
632
- const response = await runCallback(auth, login);
633
- expect(response.status).toBe(400);
634
- const body: unknown = await response.json();
635
- expect(body).toMatchObject({ code: "id_token_invalid" });
636
- });
637
-
638
- test("rejects a non-ES256 ID token (unknown alg never accepted, §15.6)", async () => {
639
- const state = createStubState();
640
- state.tokenHandler = async () => {
641
- const hs256Token = await new SignJWT({ sub: USER_SUB, nonce: state.currentNonce ?? "" })
642
- .setProtectedHeader({ alg: "HS256", typ: "JWT" })
643
- .setIssuer(ISSUER)
644
- .setAudience(CLIENT_ID)
645
- .setIssuedAt()
646
- .setExpirationTime(Math.floor(Date.now() / 1000) + 300)
647
- .sign(new TextEncoder().encode("hs256-shared-secret"));
648
- return jsonResponse({
649
- access_token: "atk",
650
- token_type: "Bearer",
651
- expires_in: 300,
652
- id_token: hs256Token,
653
- scope: "openid",
654
- });
655
- };
656
- const auth = createTestAuth(state);
657
- const login = await runLogin(auth);
658
- state.currentNonce = login.nonce;
659
- const response = await runCallback(auth, login);
660
- expect(response.status).toBe(400);
661
- const body: unknown = await response.json();
662
- expect(body).toMatchObject({ code: "id_token_invalid" });
663
- });
664
-
665
- test("rejects an ID token without a kid (§15.6 kid必須)", async () => {
666
- const state = createStubState();
667
- state.tokenHandler = async () =>
668
- jsonResponse({
669
- access_token: "atk",
670
- token_type: "Bearer",
671
- expires_in: 300,
672
- id_token: await signIdToken({ kid: null }),
673
- scope: "openid",
674
- });
675
- const auth = createTestAuth(state);
676
- const login = await runLogin(auth);
677
- const response = await runCallback(auth, login);
678
- expect(response.status).toBe(400);
679
- });
680
-
681
- test("unknown kid triggers exactly one JWKS refetch, then fails closed", async () => {
682
- const state = createStubState();
683
- state.tokenHandler = async () =>
684
- jsonResponse({
685
- access_token: "atk",
686
- token_type: "Bearer",
687
- expires_in: 300,
688
- id_token: await signIdToken({ kid: "unknown-key-id" }),
689
- scope: "openid",
690
- });
691
- const auth = createTestAuth(state);
692
- const login = await runLogin(auth);
693
- const response = await runCallback(auth, login);
694
- expect(response.status).toBe(400);
695
- const body: unknown = await response.json();
696
- expect(body).toMatchObject({ code: "id_token_invalid" });
697
- expect(state.jwksHits).toBe(2); // initial fetch + one rotation refetch
698
- });
699
-
700
- test("rejects an ID token signed by a foreign key", async () => {
701
- const foreign = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
702
- "sign",
703
- "verify",
704
- ]);
705
- if (!("privateKey" in foreign)) throw new Error("expected an ECDSA key pair");
706
- const state = createStubState();
707
- state.tokenHandler = async () =>
708
- jsonResponse({
709
- access_token: "atk",
710
- token_type: "Bearer",
711
- expires_in: 300,
712
- id_token: await signIdToken({ signingKey: foreign.privateKey }),
713
- scope: "openid",
714
- });
715
- const auth = createTestAuth(state);
716
- const login = await runLogin(auth);
717
- const response = await runCallback(auth, login);
718
- expect(response.status).toBe(400);
719
- const body: unknown = await response.json();
720
- expect(body).toMatchObject({ code: "id_token_invalid" });
721
- });
722
-
723
- test("absolute return_to URLs fall back to the configured default (open redirect禁止)", async () => {
724
- const state = createStubState();
725
- const auth = createTestAuth(state);
726
- const login = await runLogin(auth, "https://evil.example.com/steal");
727
- state.currentNonce = login.nonce;
728
- const response = await runCallback(auth, login);
729
- expect(response.status).toBe(302);
730
- expect(response.headers.get("location")).toBe("/");
731
- });
732
-
733
- test("protocol-relative return_to falls back to the default", async () => {
734
- const state = createStubState();
735
- const auth = createTestAuth(state);
736
- const login = await runLogin(auth, "//evil.example.com/steal");
737
- state.currentNonce = login.nonce;
738
- const response = await runCallback(auth, login);
739
- expect(response.headers.get("location")).toBe("/");
740
- });
741
-
742
- test("byte-for-byte allowlisted absolute targets are honored", async () => {
743
- const state = createStubState();
744
- const auth = createTestAuth(state, {
745
- allowedRedirectTargets: ["https://docs.example.com/welcome"],
746
- });
747
- const login = await runLogin(auth, "https://docs.example.com/welcome");
748
- state.currentNonce = login.nonce;
749
- const response = await runCallback(auth, login);
750
- expect(response.headers.get("location")).toBe("https://docs.example.com/welcome");
751
- });
752
- });
753
-
754
- // ---------------------------------------------------------------------------
755
- // getSession / requireSession
756
- // ---------------------------------------------------------------------------
757
-
758
- describe("getSession / requireSession", () => {
759
- test("returns the public session for a valid cookie", async () => {
760
- const state = createStubState();
761
- const auth = createTestAuth(state);
762
- const cookie = await completeLogin(auth, state);
763
-
764
- const outcome = await auth.getSession(sessionRequest("/api/me", cookie));
765
- expect(outcome.status).toBe("authenticated");
766
- if (outcome.status !== "authenticated") return;
767
- expect(outcome.session.user.sub).toBe(USER_SUB);
768
- expect(outcome.session.user.email).toBe("test@example.com");
769
- expect(outcome.session.accessToken).toBe("atk_initial");
770
- expect(outcome.session.scope).toBe("openid profile email offline_access");
771
- expect(outcome.setCookie).toBeUndefined();
772
- // The public session never carries the refresh token (§32.2).
773
- expect("refreshToken" in outcome.session).toBe(false);
774
- });
775
-
776
- test("no cookie → unauthenticated/no_session", async () => {
777
- const state = createStubState();
778
- const auth = createTestAuth(state);
779
- const outcome = await auth.getSession(new Request(`${APP_ORIGIN}/api/me`));
780
- expect(outcome.status).toBe("unauthenticated");
781
- if (outcome.status !== "unauthenticated") return;
782
- expect(outcome.reason).toBe("no_session");
783
- expect(outcome.clearCookie).toBeUndefined();
784
- });
785
-
786
- test("tampered cookie fails closed and is destroyed", async () => {
787
- const state = createStubState();
788
- const auth = createTestAuth(state);
789
- const forged = `${SESSION_COOKIE_NAME}=v1.${"A".repeat(16)}.${"C".repeat(43)}`;
790
- const outcome = await auth.getSession(sessionRequest("/api/me", forged));
791
- expect(outcome.status).toBe("unauthenticated");
792
- if (outcome.status !== "unauthenticated") return;
793
- expect(outcome.reason).toBe("invalid_session_cookie");
794
- expect(outcome.clearCookie).toBeDefined();
795
- const cleared = parseSetCookie(outcome.clearCookie ?? "");
796
- expect(cleared.maxAge).toBe(0);
797
- expect(cleared.name).toBe(SESSION_COOKIE_NAME);
798
- });
799
-
800
- test("requireSession redirects browsers to login with a safe return_to", async () => {
801
- const state = createStubState();
802
- const auth = createTestAuth(state);
803
- const outcome = await auth.requireSession(new Request(`${APP_ORIGIN}/settings?tab=security`));
804
- expect(outcome.ok).toBe(false);
805
- if (outcome.ok) return;
806
- expect(outcome.reason).toBe("no_session");
807
- expect(outcome.response.status).toBe(302);
808
- expect(outcome.response.headers.get("location")).toBe(
809
- "/auth/login?return_to=%2Fsettings%3Ftab%3Dsecurity",
810
- );
811
- });
812
-
813
- test("requireSession redirects to a single-slash login path when basePath is root", async () => {
814
- const state = createStubState();
815
- const auth = createTestAuth(state, { basePath: "/" });
816
- const outcome = await auth.requireSession(new Request(`${APP_ORIGIN}/settings`));
817
- expect(outcome.ok).toBe(false);
818
- if (outcome.ok) return;
819
- expect(outcome.response.headers.get("location")).toBe("/login?return_to=%2Fsettings");
820
- });
821
-
822
- test("requireSession json mode answers a 401 problem", async () => {
823
- const state = createStubState();
824
- const auth = createTestAuth(state);
825
- const outcome = await auth.requireSession(new Request(`${APP_ORIGIN}/api/me`), {
826
- onUnauthenticated: "json",
827
- });
828
- expect(outcome.ok).toBe(false);
829
- if (outcome.ok) return;
830
- expect(outcome.response.status).toBe(401);
831
- const body: unknown = await outcome.response.json();
832
- expect(body).toMatchObject({ code: "no_session" });
833
- });
834
-
835
- test("requireSession passes an authenticated request through with its session", async () => {
836
- const state = createStubState();
837
- const auth = createTestAuth(state);
838
- const cookie = await completeLogin(auth, state);
839
- const outcome = await auth.requireSession(sessionRequest("/api/me", cookie));
840
- expect(outcome.ok).toBe(true);
841
- if (!outcome.ok) return;
842
- expect(outcome.session.user.sub).toBe(USER_SUB);
843
- });
844
- });
845
-
846
- // ---------------------------------------------------------------------------
847
- // refresh (mutex, rotation, invalid_grant — design.md §21.7)
848
- // ---------------------------------------------------------------------------
849
-
850
- describe("access token refresh", () => {
851
- test("refreshes within the leeway window and rotates the refresh token", async () => {
852
- const state = createStubState();
853
- const auth = createTestAuth(state, { refreshLeewaySeconds: 10_000 });
854
- const cookie = await completeLogin(auth, state);
855
-
856
- const outcome = await auth.getSession(sessionRequest("/api/me", cookie));
857
- expect(outcome.status).toBe("authenticated");
858
- if (outcome.status !== "authenticated") return;
859
- expect(outcome.session.accessToken).toBe("atk_refreshed");
860
- // The re-issued cookie is a full Set-Cookie header with §22.2 attributes.
861
- expect(outcome.setCookie).toBeDefined();
862
- const reissued = parseSetCookie(outcome.setCookie ?? "");
863
- expect(reissued.name).toBe(SESSION_COOKIE_NAME);
864
- expect(reissued.httpOnly).toBe(true);
865
- expect(reissued.secure).toBe(true);
866
- expect(reissued.sameSite).toBe("lax");
867
- expect(reissued.path).toBe("/");
868
- expect((outcome.setCookie ?? "").toLowerCase()).not.toContain("domain=");
869
-
870
- const refreshes = refreshGrantCalls(state);
871
- expect(refreshes).toHaveLength(1);
872
- expect(refreshes[0]?.body.get("refresh_token")).toBe("rt_1");
873
- expect(refreshes[0]?.authorization?.startsWith("Basic ")).toBe(true);
874
- });
875
-
876
- test("the process-wide mutex serializes concurrent refreshes to one token-endpoint hit", async () => {
877
- const state = createStubState();
878
- const auth = createTestAuth(state, { refreshLeewaySeconds: 10_000 });
879
- const cookie = await completeLogin(auth, state);
880
-
881
- const outcomes = await Promise.all(
882
- Array.from({ length: 5 }, () => auth.getSession(sessionRequest("/api/me", cookie))),
883
- );
884
- for (const outcome of outcomes) {
885
- expect(outcome.status).toBe("authenticated");
886
- if (outcome.status === "authenticated") {
887
- expect(outcome.session.accessToken).toBe("atk_refreshed");
888
- }
889
- }
890
- expect(refreshGrantCalls(state)).toHaveLength(1);
891
- });
892
-
893
- test("a cookie holding the rotated-out refresh token reuses the latest session (no replay)", async () => {
894
- const state = createStubState();
895
- const auth = createTestAuth(state, { refreshLeewaySeconds: 10_000 });
896
- const cookie = await completeLogin(auth, state);
897
-
898
- const first = await auth.getSession(sessionRequest("/api/me", cookie));
899
- expect(first.status).toBe("authenticated");
900
- expect(refreshGrantCalls(state)).toHaveLength(1);
901
-
902
- // Same (stale) cookie again: the in-process rotation cache answers it.
903
- const second = await auth.getSession(sessionRequest("/api/me", cookie));
904
- expect(second.status).toBe("authenticated");
905
- if (second.status === "authenticated") {
906
- expect(second.session.accessToken).toBe("atk_refreshed");
907
- expect(second.setCookie).toBeDefined();
908
- expect(parseSetCookie(second.setCookie ?? "").name).toBe(SESSION_COOKIE_NAME);
909
- }
910
- expect(refreshGrantCalls(state)).toHaveLength(1);
911
- });
912
-
913
- test("invalid_grant destroys the local session completely (§21.7)", async () => {
914
- const state = createStubState();
915
- state.tokenHandler = async (params) => {
916
- if (params.get("grant_type") === "refresh_token") {
917
- return jsonResponse({ error: "invalid_grant" }, 400);
918
- }
919
- return defaultTokenHandler(state)(params);
920
- };
921
- const auth = createTestAuth(state, { refreshLeewaySeconds: 10_000 });
922
- const cookie = await completeLogin(auth, state);
923
-
924
- const outcome = await auth.getSession(sessionRequest("/api/me", cookie));
925
- expect(outcome.status).toBe("unauthenticated");
926
- if (outcome.status !== "unauthenticated") return;
927
- expect(outcome.reason).toBe("refresh_rejected");
928
- expect(outcome.clearCookie).toBeDefined();
929
- expect(parseSetCookie(outcome.clearCookie ?? "").maxAge).toBe(0);
930
- });
931
-
932
- test("transient refresh failures keep the session (§21.7)", async () => {
933
- const state = createStubState();
934
- state.tokenHandler = async (params) => {
935
- if (params.get("grant_type") === "refresh_token") {
936
- return jsonResponse({ error: "temporarily_unavailable" }, 503);
937
- }
938
- return defaultTokenHandler(state)(params);
939
- };
940
- const auth = createTestAuth(state, { refreshLeewaySeconds: 10_000 });
941
- const cookie = await completeLogin(auth, state);
942
-
943
- const outcome = await auth.getSession(sessionRequest("/api/me", cookie));
944
- expect(outcome.status).toBe("unauthenticated");
945
- if (outcome.status !== "unauthenticated") return;
946
- expect(outcome.reason).toBe("refresh_unavailable");
947
- // The session cookie is NOT cleared — the next request retries.
948
- expect(outcome.clearCookie).toBeUndefined();
949
-
950
- const required = await auth.requireSession(sessionRequest("/api/me", cookie));
951
- expect(required.ok).toBe(false);
952
- if (!required.ok) {
953
- expect(required.response.status).toBe(503);
954
- }
955
- });
956
-
957
- test("a network failure during refresh keeps the session", async () => {
958
- const state = createStubState();
959
- state.tokenHandler = async (params) => {
960
- if (params.get("grant_type") === "refresh_token") {
961
- throw new TypeError("fetch failed");
962
- }
963
- return defaultTokenHandler(state)(params);
964
- };
965
- const auth = createTestAuth(state, { refreshLeewaySeconds: 10_000 });
966
- const cookie = await completeLogin(auth, state);
967
-
968
- const outcome = await auth.getSession(sessionRequest("/api/me", cookie));
969
- expect(outcome.status).toBe("unauthenticated");
970
- if (outcome.status !== "unauthenticated") return;
971
- expect(outcome.reason).toBe("refresh_unavailable");
972
- expect(outcome.clearCookie).toBeUndefined();
973
- });
974
-
975
- test("refreshSession forces a refresh even for a fresh access token", async () => {
976
- const state = createStubState();
977
- const auth = createTestAuth(state);
978
- const cookie = await completeLogin(auth, state);
979
-
980
- const outcome = await auth.refreshSession(sessionRequest("/api/me", cookie));
981
- expect(outcome.status).toBe("authenticated");
982
- if (outcome.status !== "authenticated") return;
983
- expect(outcome.session.accessToken).toBe("atk_refreshed");
984
- expect(refreshGrantCalls(state)).toHaveLength(1);
985
- });
986
- });
987
-
988
- // ---------------------------------------------------------------------------
989
- // logout handler
990
- // ---------------------------------------------------------------------------
991
-
992
- describe("logoutHandler", () => {
993
- test("clears the session cookie and revokes the refresh token family (§15.8)", async () => {
994
- const state = createStubState();
995
- const auth = createTestAuth(state);
996
- const cookie = await completeLogin(auth, state);
997
-
998
- const response = await auth.logoutHandler(
999
- new Request(`${APP_ORIGIN}/auth/logout`, { headers: { cookie } }),
1000
- );
1001
- expect(response.status).toBe(302);
1002
- expect(response.headers.get("location")).toBe("/");
1003
-
1004
- const setCookies = response.headers.getSetCookie();
1005
- const sessionClear = setCookies.find((value) => value.startsWith(`${SESSION_COOKIE_NAME}=`));
1006
- expect(sessionClear).toBeDefined();
1007
- expect(parseSetCookie(sessionClear ?? "").maxAge).toBe(0);
1008
-
1009
- expect(state.revocationCalls).toHaveLength(1);
1010
- expect(state.revocationCalls[0]?.get("token")).toBe("rt_1");
1011
- expect(state.revocationCalls[0]?.get("token_type_hint")).toBe("refresh_token");
1012
- });
1013
-
1014
- test("POST logout with a foreign Origin is rejected", async () => {
1015
- const state = createStubState();
1016
- const auth = createTestAuth(state);
1017
- const response = await auth.logoutHandler(
1018
- new Request(`${APP_ORIGIN}/auth/logout`, {
1019
- method: "POST",
1020
- headers: { origin: "https://evil.example.com" },
1021
- }),
1022
- );
1023
- expect(response.status).toBe(403);
1024
- });
1025
-
1026
- test("POST logout with the same Origin succeeds", async () => {
1027
- const state = createStubState();
1028
- const auth = createTestAuth(state);
1029
- const response = await auth.logoutHandler(
1030
- new Request(`${APP_ORIGIN}/auth/logout`, {
1031
- method: "POST",
1032
- headers: { origin: APP_ORIGIN },
1033
- }),
1034
- );
1035
- expect(response.status).toBe(302);
1036
- });
1037
-
1038
- test("logout without a session is idempotent and sanitizes return_to", async () => {
1039
- const state = createStubState();
1040
- const auth = createTestAuth(state);
1041
- const response = await auth.logoutHandler(
1042
- new Request(
1043
- `${APP_ORIGIN}/auth/logout?return_to=${encodeURIComponent("https://evil.example.com")}`,
1044
- ),
1045
- );
1046
- expect(response.status).toBe(302);
1047
- expect(response.headers.get("location")).toBe("/");
1048
- expect(state.revocationCalls).toHaveLength(0);
1049
- });
1050
- });
1051
-
1052
- // ---------------------------------------------------------------------------
1053
- // verifyAccessToken (resource-server helper)
1054
- // ---------------------------------------------------------------------------
1055
-
1056
- describe("verifyAccessToken", () => {
1057
- test("verifies an at+jwt access token against the issuer JWKS", async () => {
1058
- const state = createStubState();
1059
- const auth = createTestAuth(state);
1060
- const token = await signAccessToken();
1061
- const result = await auth.verifyAccessToken(token, API_AUDIENCE);
1062
- expect(result.type).toBe("Success");
1063
- if (result.type !== "Success") return;
1064
- expect(result.value.sub).toBe(USER_SUB);
1065
- expect(result.value.clientId).toBe(CLIENT_ID);
1066
- expect(result.value.scope).toBe("openid profile");
1067
- expect(result.value.expiresAt).toBeTypeOf("number");
1068
- });
1069
-
1070
- test("rejects a token with the wrong typ (must be at+jwt, §15.6)", async () => {
1071
- const state = createStubState();
1072
- const auth = createTestAuth(state);
1073
- const token = await signAccessToken({ typ: "JWT" });
1074
- const result = await auth.verifyAccessToken(token, API_AUDIENCE);
1075
- expect(result.type).toBe("Failure");
1076
- });
1077
-
1078
- test("rejects a token with the wrong audience", async () => {
1079
- const state = createStubState();
1080
- const auth = createTestAuth(state);
1081
- const token = await signAccessToken({ audience: "https://other-api.example.com" });
1082
- const result = await auth.verifyAccessToken(token, API_AUDIENCE);
1083
- expect(result.type).toBe("Failure");
1084
- if (result.type !== "Failure") return;
1085
- expect(result.error.type).toBe("access_token_invalid");
1086
- });
1087
-
1088
- test("rejects garbage input without throwing", async () => {
1089
- const state = createStubState();
1090
- const auth = createTestAuth(state);
1091
- const result = await auth.verifyAccessToken("not-a-jwt", API_AUDIENCE);
1092
- expect(result.type).toBe("Failure");
1093
- if (result.type !== "Failure") return;
1094
- expect(result.error.type).toBe("access_token_invalid");
1095
- });
1096
- });
1097
-
1098
- // ---------------------------------------------------------------------------
1099
- // config validation
1100
- // ---------------------------------------------------------------------------
1101
-
1102
- describe("createServerAuth config validation", () => {
1103
- const baseConfig = {
1104
- issuer: ISSUER,
1105
- clientId: CLIENT_ID,
1106
- clientSecret: CLIENT_SECRET,
1107
- redirectUri: REDIRECT_URI,
1108
- cookieSecret: COOKIE_SECRET,
1109
- };
1110
-
1111
- test("rejects cookieDomain — the __Host- prefix forbids a Domain attribute", () => {
1112
- expect(() => createServerAuth({ ...baseConfig, cookieDomain: ".example.com" })).toThrow(
1113
- TypeError,
1114
- );
1115
- });
1116
-
1117
- test("allows HTTP only for localhost and 127.0.0.1 redirect URIs (§15.9)", () => {
1118
- expect(() =>
1119
- createServerAuth({ ...baseConfig, redirectUri: "http://app.example.com/callback" }),
1120
- ).toThrow(TypeError);
1121
- expect(() =>
1122
- createServerAuth({ ...baseConfig, redirectUri: "http://[::1]:3000/auth/callback" }),
1123
- ).toThrow(TypeError);
1124
- expect(() =>
1125
- createServerAuth({ ...baseConfig, redirectUri: "http://localhost:3000/auth/callback" }),
1126
- ).not.toThrow();
1127
- expect(() =>
1128
- createServerAuth({ ...baseConfig, redirectUri: "http://127.0.0.1:3000/auth/callback" }),
1129
- ).not.toThrow();
1130
- });
1131
-
1132
- test("rejects a redirectUri with a fragment (§15.9)", () => {
1133
- expect(() =>
1134
- createServerAuth({ ...baseConfig, redirectUri: `${REDIRECT_URI}#fragment` }),
1135
- ).toThrow(TypeError);
1136
- });
1137
-
1138
- test("rejects a short cookieSecret", () => {
1139
- expect(() => createServerAuth({ ...baseConfig, cookieSecret: "too-short" })).toThrow(TypeError);
1140
- });
1141
-
1142
- test("rejects scopes without openid", () => {
1143
- expect(() => createServerAuth({ ...baseConfig, scopes: ["profile"] })).toThrow(TypeError);
1144
- });
1145
-
1146
- test("rejects an http issuer", () => {
1147
- expect(() => createServerAuth({ ...baseConfig, issuer: "http://id.example.com" })).toThrow(
1148
- TypeError,
1149
- );
1150
- });
1151
- });