@smartcrab/server 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,887 @@
1
+ import { TOKEN_TTL_SECONDS } from "@smartcrab/contracts-public";
2
+ import type { TokenResponse } from "@smartcrab/contracts-public";
3
+ import type { JWTPayload } from "jose";
4
+ import {
5
+ PKCE_COOKIE_NAME,
6
+ SESSION_COOKIE_NAME,
7
+ clearAuthCookie,
8
+ readCookie,
9
+ serializeAuthCookie,
10
+ } from "./cookies.js";
11
+ import { errorToResponse, problemResponse } from "./errors.js";
12
+ import type { ServerAuthError } from "./errors.js";
13
+ import type { FetchLike } from "./http.js";
14
+ import { createOidcClient } from "./oidc-client.js";
15
+ import { Result, type ResultAsync } from "./result.js";
16
+ import { createSealer } from "./sealing.js";
17
+ import {
18
+ generatePkceMaterial,
19
+ hasInvalidNavigationOrigin,
20
+ isAllowedConfiguredTarget,
21
+ isRequestOriginValid,
22
+ sanitizeRedirectTarget,
23
+ timingSafeEqual,
24
+ } from "./security.js";
25
+ import { isSessionPayload, toPublicSession } from "./session.js";
26
+ import type { Session, SessionPayloadV1, SessionUser } from "./session.js";
27
+
28
+ /**
29
+ * `createServerAuth` — the Web BFF surface of design.md §22.2:
30
+ *
31
+ * - `loginHandler` — builds the authorize redirect (Authorization Code +
32
+ * PKCE S256, state/nonce from WebCrypto) and stores the handshake in a
33
+ * short-lived, single-use `__Host-auth-pkce` cookie,
34
+ * - `callbackHandler` — validates state (constant-time), exchanges the code
35
+ * at the token endpoint, verifies the ID token (ES256/kid/iss/aud/exp/
36
+ * nonce), and issues the `__Host-auth-session` cookie (Secure, HttpOnly,
37
+ * SameSite=Lax, Path=/, **no Domain** — the `__Host-` prefix forbids one
38
+ * and this module enforces that by construction),
39
+ * - `logoutHandler` — revokes the refresh token family (§15.8, best-effort)
40
+ * and destroys the local session,
41
+ * - `getSession` / `requireSession` / `refreshSession` — session resolution
42
+ * with transparent access-token refresh,
43
+ * - refresh uses a per-instance, process-wide mutex: concurrent requests
44
+ * never trigger two refreshes (design.md §21.7 "同時refreshを禁止"), the
45
+ * latest rotated refresh token is stored atomically under that mutex, and
46
+ * `invalid_grant` wipes the local session while transient failures keep it
47
+ * (§21.7),
48
+ * - CSRF: SameSite=Lax cookies plus Origin/Referer validation on mutation
49
+ * handlers (the assignment's "choose and document" — see security.ts);
50
+ * login/callback/logout all validate state and/or origin,
51
+ * - open-redirect prevention: post-login/logout targets must be relative
52
+ * paths or byte-for-byte allowlisted URLs (§32.2).
53
+ *
54
+ * Configuration errors are programmer errors and throw `TypeError` at
55
+ * construction (fail fast at startup); runtime failures are always typed
56
+ * `Result`s or problem responses — never thrown.
57
+ */
58
+
59
+ export interface ServerAuthConfig {
60
+ /** Issuer base URL, e.g. `https://id.example-auth.com/e/env_xxx` (https only). */
61
+ readonly issuer: string;
62
+ readonly clientId: string;
63
+ readonly clientSecret: string;
64
+ /** Byte-for-byte registered callback URL (design.md §15.9). */
65
+ readonly redirectUri: string;
66
+ /** >=32 chars of entropy; HKDF-derives the AES-256-GCM cookie-sealing key. */
67
+ readonly cookieSecret: string;
68
+ /** Mount point used when building login redirects. Default `"/auth"`. */
69
+ readonly basePath?: string;
70
+ /** Default `["openid", "profile", "email", "offline_access"]`. */
71
+ readonly scopes?: readonly string[];
72
+ /** Default `"/"`. Relative path or https URL. */
73
+ readonly postLoginRedirect?: string;
74
+ /** Default `"/"`. Relative path or https URL. */
75
+ readonly postLogoutRedirect?: string;
76
+ /** Extra byte-for-byte allowed absolute redirect targets (open-redirect allowlist). */
77
+ readonly allowedRedirectTargets?: readonly string[];
78
+ /** Extra allowed Origins beyond the request's own origin (CSRF check). */
79
+ readonly allowedOrigins?: readonly string[];
80
+ /** Session cookie lifetime. Default: refresh-token idle TTL (30 days, §15.5). */
81
+ readonly sessionTtlSeconds?: number;
82
+ /** PKCE handshake cookie lifetime. Default: 600s. */
83
+ readonly pkceCookieTtlSeconds?: number;
84
+ /** Refresh when the access token expires within this window. Default: 60s. */
85
+ readonly refreshLeewaySeconds?: number;
86
+ /** Fetch implementation override (tests, custom transports). */
87
+ readonly fetch?: FetchLike;
88
+ /**
89
+ * Unsupported — rejected at construction. The `__Host-` cookie prefix
90
+ * (design.md §22.2) forbids a Domain attribute, so the SDK never emits one.
91
+ */
92
+ readonly cookieDomain?: string;
93
+ }
94
+
95
+ export type UnauthenticatedReason =
96
+ | "no_session"
97
+ | "invalid_session_cookie"
98
+ | "session_expired"
99
+ | "refresh_rejected"
100
+ | "refresh_unavailable";
101
+
102
+ export type GetSessionOutcome =
103
+ | {
104
+ readonly status: "authenticated";
105
+ readonly session: Session;
106
+ /** Present when the session was refreshed/rotated — append to the response as `Set-Cookie`. */
107
+ readonly setCookie?: string;
108
+ }
109
+ | {
110
+ readonly status: "unauthenticated";
111
+ readonly reason: UnauthenticatedReason;
112
+ /** Present when the local session must be destroyed — append to the response as `Set-Cookie`. */
113
+ readonly clearCookie?: string;
114
+ };
115
+
116
+ export type RequireSessionOutcome =
117
+ | {
118
+ readonly ok: true;
119
+ readonly session: Session;
120
+ readonly setCookie?: string;
121
+ }
122
+ | {
123
+ readonly ok: false;
124
+ readonly reason: UnauthenticatedReason;
125
+ /** Ready-to-return response: 302 to the login handler, 401 JSON (`onUnauthenticated: "json"`), or 503 on transient refresh failure. */
126
+ readonly response: Response;
127
+ };
128
+
129
+ export interface RequireSessionOptions {
130
+ /** `"redirect"` (default) sends browsers to login; `"json"` answers 401 problem JSON. */
131
+ readonly onUnauthenticated?: "redirect" | "json";
132
+ }
133
+
134
+ export interface VerifiedAccessToken {
135
+ readonly sub: string;
136
+ readonly scope: string;
137
+ readonly clientId?: string;
138
+ readonly expiresAt?: number;
139
+ /** Full verified claims (jose `JWTPayload`) for resource-server authorization logic. */
140
+ readonly claims: JWTPayload;
141
+ }
142
+
143
+ export interface ServerAuth {
144
+ readonly loginHandler: (request: Request) => Promise<Response>;
145
+ readonly callbackHandler: (request: Request) => Promise<Response>;
146
+ readonly logoutHandler: (request: Request) => Promise<Response>;
147
+ readonly getSession: (request: Request) => Promise<GetSessionOutcome>;
148
+ /** Forces an access-token refresh (serialized by the same process-wide mutex). */
149
+ readonly refreshSession: (request: Request) => Promise<GetSessionOutcome>;
150
+ readonly requireSession: (
151
+ request: Request,
152
+ options?: RequireSessionOptions,
153
+ ) => Promise<RequireSessionOutcome>;
154
+ /** Resource-server helper: verifies a platform access token (`at+jwt`) against the issuer JWKS. */
155
+ readonly verifyAccessToken: (
156
+ token: string,
157
+ audience?: string | readonly string[],
158
+ ) => ResultAsync<VerifiedAccessToken, ServerAuthError>;
159
+ readonly basePath: string;
160
+ readonly sessionCookieName: string;
161
+ }
162
+
163
+ export interface AccessTokenVerifierOptions {
164
+ readonly issuer: string;
165
+ readonly audience?: string | readonly string[];
166
+ readonly fetch?: FetchLike;
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Config validation (programmer errors -> TypeError at construction)
171
+ // ---------------------------------------------------------------------------
172
+
173
+ const requireAbsoluteUrl = (field: string, value: string): URL => {
174
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
175
+ throw new TypeError(`@smartcrab/server: ${field} must be an absolute URL (scheme://...)`);
176
+ }
177
+ // Shape-checked above; any residual parse failure surfaces as the URL
178
+ // constructor's own TypeError at startup, which is the desired fail-fast.
179
+ return new URL(value);
180
+ };
181
+
182
+ const isLocalhostHttp = (url: URL): boolean =>
183
+ url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1");
184
+
185
+ const BASE_PATH_PATTERN = /^\/[A-Za-z0-9\-._~/]*$/;
186
+
187
+ interface ResolvedConfig {
188
+ readonly issuer: string;
189
+ readonly clientId: string;
190
+ readonly clientSecret: string;
191
+ readonly redirectUri: string;
192
+ readonly basePath: string;
193
+ readonly scopes: readonly string[];
194
+ readonly postLoginRedirect: string;
195
+ readonly postLogoutRedirect: string;
196
+ readonly allowedRedirectTargets: readonly string[];
197
+ readonly allowedOrigins: readonly string[];
198
+ readonly sessionTtlSeconds: number;
199
+ readonly pkceCookieTtlSeconds: number;
200
+ readonly refreshLeewaySeconds: number;
201
+ readonly fetchImpl: FetchLike;
202
+ }
203
+
204
+ const normalizeIssuer = (issuer: string): string => {
205
+ const url = requireAbsoluteUrl("issuer", issuer);
206
+ if (url.protocol !== "https:") {
207
+ throw new TypeError("@smartcrab/server: issuer must be an https:// URL (design.md §8)");
208
+ }
209
+ return issuer.replace(/\/+$/, "");
210
+ };
211
+
212
+ const resolveConfig = (config: ServerAuthConfig): ResolvedConfig => {
213
+ if (config.cookieDomain !== undefined) {
214
+ throw new TypeError(
215
+ "@smartcrab/server: cookieDomain is not supported — the __Host-auth-session cookie (design.md §22.2) forbids a Domain attribute",
216
+ );
217
+ }
218
+ const issuer = normalizeIssuer(config.issuer);
219
+ if (config.clientId.length === 0) {
220
+ throw new TypeError("@smartcrab/server: clientId must not be empty");
221
+ }
222
+ if (config.clientSecret.length === 0) {
223
+ throw new TypeError("@smartcrab/server: clientSecret must not be empty");
224
+ }
225
+ if (config.cookieSecret.length < 32) {
226
+ throw new TypeError("@smartcrab/server: cookieSecret must be at least 32 characters");
227
+ }
228
+ const redirectUri = requireAbsoluteUrl("redirectUri", config.redirectUri);
229
+ if (redirectUri.hash !== "") {
230
+ throw new TypeError(
231
+ "@smartcrab/server: redirectUri must not contain a fragment (design.md §15.9)",
232
+ );
233
+ }
234
+ if (redirectUri.protocol !== "https:" && !isLocalhostHttp(redirectUri)) {
235
+ throw new TypeError(
236
+ "@smartcrab/server: redirectUri must be https (http is allowed for localhost only, design.md §15.9)",
237
+ );
238
+ }
239
+ const basePath = config.basePath ?? "/auth";
240
+ if (!BASE_PATH_PATTERN.test(basePath) || (basePath !== "/" && basePath.endsWith("/"))) {
241
+ throw new TypeError(
242
+ "@smartcrab/server: basePath must be an absolute path without a trailing slash",
243
+ );
244
+ }
245
+ const scopes = config.scopes ?? ["openid", "profile", "email", "offline_access"];
246
+ if (!scopes.includes("openid")) {
247
+ throw new TypeError('@smartcrab/server: scopes must include "openid"');
248
+ }
249
+ const postLoginRedirect = config.postLoginRedirect ?? "/";
250
+ if (!isAllowedConfiguredTarget(postLoginRedirect)) {
251
+ throw new TypeError(
252
+ "@smartcrab/server: postLoginRedirect must be a relative path or an https URL",
253
+ );
254
+ }
255
+ const postLogoutRedirect = config.postLogoutRedirect ?? "/";
256
+ if (!isAllowedConfiguredTarget(postLogoutRedirect)) {
257
+ throw new TypeError(
258
+ "@smartcrab/server: postLogoutRedirect must be a relative path or an https URL",
259
+ );
260
+ }
261
+ const allowedRedirectTargets = config.allowedRedirectTargets ?? [];
262
+ for (const target of allowedRedirectTargets) {
263
+ if (!isAllowedConfiguredTarget(target)) {
264
+ throw new TypeError(
265
+ "@smartcrab/server: allowedRedirectTargets entries must be relative paths or https URLs",
266
+ );
267
+ }
268
+ }
269
+ const allowedOrigins = (config.allowedOrigins ?? []).map((origin) =>
270
+ requireAbsoluteUrl("allowedOrigins entry", origin).origin.toLowerCase(),
271
+ );
272
+ const sessionTtlSeconds = config.sessionTtlSeconds ?? TOKEN_TTL_SECONDS.refreshIdle;
273
+ if (!Number.isInteger(sessionTtlSeconds) || sessionTtlSeconds <= 0) {
274
+ throw new TypeError("@smartcrab/server: sessionTtlSeconds must be a positive integer");
275
+ }
276
+ const pkceCookieTtlSeconds = config.pkceCookieTtlSeconds ?? 600;
277
+ if (!Number.isInteger(pkceCookieTtlSeconds) || pkceCookieTtlSeconds <= 0) {
278
+ throw new TypeError("@smartcrab/server: pkceCookieTtlSeconds must be a positive integer");
279
+ }
280
+ const refreshLeewaySeconds = config.refreshLeewaySeconds ?? 60;
281
+ if (!Number.isInteger(refreshLeewaySeconds) || refreshLeewaySeconds < 0) {
282
+ throw new TypeError("@smartcrab/server: refreshLeewaySeconds must be a non-negative integer");
283
+ }
284
+ const fetchImpl: FetchLike = config.fetch ?? ((input, init) => fetch(input, init));
285
+ return {
286
+ issuer,
287
+ clientId: config.clientId,
288
+ clientSecret: config.clientSecret,
289
+ redirectUri: config.redirectUri,
290
+ basePath,
291
+ scopes,
292
+ postLoginRedirect,
293
+ postLogoutRedirect,
294
+ allowedRedirectTargets,
295
+ allowedOrigins,
296
+ sessionTtlSeconds,
297
+ pkceCookieTtlSeconds,
298
+ refreshLeewaySeconds,
299
+ fetchImpl,
300
+ };
301
+ };
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // PKCE handshake cookie payload
305
+ // ---------------------------------------------------------------------------
306
+
307
+ interface PkceCookiePayloadV1 {
308
+ readonly v: 1;
309
+ readonly verifier: string;
310
+ readonly state: string;
311
+ readonly nonce: string;
312
+ readonly returnTo: string;
313
+ readonly expiresAt: number;
314
+ }
315
+
316
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
317
+ typeof value === "object" && value !== null && !Array.isArray(value);
318
+
319
+ const isPkceCookiePayload = (value: unknown): value is PkceCookiePayloadV1 => {
320
+ if (!isRecord(value)) return false;
321
+ return (
322
+ value.v === 1 &&
323
+ typeof value.verifier === "string" &&
324
+ typeof value.state === "string" &&
325
+ typeof value.nonce === "string" &&
326
+ typeof value.returnTo === "string" &&
327
+ typeof value.expiresAt === "number"
328
+ );
329
+ };
330
+
331
+ // ---------------------------------------------------------------------------
332
+ // createServerAuth
333
+ // ---------------------------------------------------------------------------
334
+
335
+ const nowSeconds = (): number => Math.floor(Date.now() / 1000);
336
+
337
+ const claimsToUser = (claims: JWTPayload): SessionUser | null => {
338
+ const sub = claims.sub;
339
+ if (typeof sub !== "string" || sub.length === 0) return null;
340
+ return {
341
+ sub,
342
+ ...(typeof claims.name === "string" ? { name: claims.name } : {}),
343
+ ...(typeof claims.email === "string" ? { email: claims.email } : {}),
344
+ ...(typeof claims.email_verified === "boolean" ? { emailVerified: claims.email_verified } : {}),
345
+ };
346
+ };
347
+
348
+ const redirectResponse = (location: string, setCookies: readonly string[]): Response => {
349
+ const headers = new Headers();
350
+ headers.set("location", location);
351
+ headers.set("cache-control", "no-store");
352
+ for (const value of setCookies) {
353
+ headers.append("set-cookie", value);
354
+ }
355
+ return new Response(null, { status: 302, headers });
356
+ };
357
+
358
+ /** design.md §21.7: rotation-replay avoidance windows. */
359
+ const ROTATION_CACHE_TTL_MS = 60_000;
360
+ const ROTATION_CACHE_MAX_ENTRIES = 1000;
361
+
362
+ interface RotationEntry {
363
+ readonly payload: SessionPayloadV1;
364
+ /** Sealed payload only — serialized into a full Set-Cookie header at the boundary. */
365
+ readonly sealedPayload: string;
366
+ readonly storedAtMs: number;
367
+ }
368
+
369
+ interface RefreshSuccess {
370
+ readonly payload: SessionPayloadV1;
371
+ readonly sealedPayload: string;
372
+ }
373
+
374
+ export const createServerAuth = (config: ServerAuthConfig): ServerAuth => {
375
+ const cfg = resolveConfig(config);
376
+ const sealer = createSealer(config.cookieSecret);
377
+ const oidc = createOidcClient({
378
+ issuer: cfg.issuer,
379
+ clientId: cfg.clientId,
380
+ clientSecret: cfg.clientSecret,
381
+ fetchImpl: cfg.fetchImpl,
382
+ });
383
+
384
+ const rotationCache = new Map<string, RotationEntry>();
385
+
386
+ const readRotationCache = (refreshToken: string): RotationEntry | null => {
387
+ const entry = rotationCache.get(refreshToken);
388
+ if (entry === undefined) return null;
389
+ if (Date.now() - entry.storedAtMs > ROTATION_CACHE_TTL_MS) {
390
+ rotationCache.delete(refreshToken);
391
+ return null;
392
+ }
393
+ return entry;
394
+ };
395
+
396
+ const writeRotationCache = (refreshToken: string, entry: RotationEntry): void => {
397
+ if (rotationCache.size >= ROTATION_CACHE_MAX_ENTRIES) {
398
+ const oldest = rotationCache.keys().next();
399
+ if (!oldest.done) rotationCache.delete(oldest.value);
400
+ }
401
+ rotationCache.set(refreshToken, entry);
402
+ };
403
+
404
+ /**
405
+ * Process-wide (per-isolate) refresh mutex: a promise chain serializes every
406
+ * refresh through this instance so two concurrent requests can never fire
407
+ * two refresh grants for the same session (design.md §21.7). The chain is
408
+ * kept alive regardless of individual job outcomes.
409
+ */
410
+ let refreshLockChain: Promise<unknown> = Promise.resolve();
411
+ const withRefreshLock = <T>(job: () => Promise<T>): Promise<T> => {
412
+ const run = refreshLockChain.then(() => job());
413
+ refreshLockChain = run.then(
414
+ () => undefined,
415
+ () => undefined,
416
+ );
417
+ return run;
418
+ };
419
+
420
+ const clearSessionCookiePart = async (): Promise<
421
+ { readonly clearCookie: string } | Record<string, never>
422
+ > => {
423
+ const cleared = await clearAuthCookie(SESSION_COOKIE_NAME);
424
+ return Result.isSuccess(cleared) ? { clearCookie: cleared.value } : {};
425
+ };
426
+
427
+ /**
428
+ * Serializes a sealed session payload into a full `Set-Cookie` header whose
429
+ * Max-Age tracks the session's remaining lifetime. Serialization is
430
+ * deterministic for our own base64url payloads, so a failure degrades to
431
+ * "no updated cookie" rather than an error response.
432
+ */
433
+ const sessionCookieHeader = async (
434
+ payload: SessionPayloadV1,
435
+ sealedPayload: string,
436
+ ): Promise<string | undefined> => {
437
+ const maxAge = Math.max(1, payload.expiresAt - nowSeconds());
438
+ const serialized = await serializeAuthCookie(SESSION_COOKIE_NAME, sealedPayload, maxAge);
439
+ return Result.isSuccess(serialized) ? serialized.value : undefined;
440
+ };
441
+
442
+ // -------------------------------------------------------------------------
443
+ // Handlers
444
+ // -------------------------------------------------------------------------
445
+
446
+ const loginHandler = async (request: Request): Promise<Response> => {
447
+ if (request.method !== "GET" && request.method !== "POST") {
448
+ return problemResponse(405, "method_not_allowed");
449
+ }
450
+ if (
451
+ hasInvalidNavigationOrigin(request, cfg.allowedOrigins) ||
452
+ !isRequestOriginValid(request, cfg.allowedOrigins)
453
+ ) {
454
+ return problemResponse(403, "csrf_validation_failed");
455
+ }
456
+ const url = new URL(request.url);
457
+ const returnTo = sanitizeRedirectTarget(
458
+ url.searchParams.get("return_to"),
459
+ cfg.allowedRedirectTargets,
460
+ cfg.postLoginRedirect,
461
+ );
462
+ const material = await generatePkceMaterial();
463
+ if (Result.isFailure(material)) return errorToResponse(material.error);
464
+ const handshake: PkceCookiePayloadV1 = {
465
+ v: 1,
466
+ verifier: material.value.verifier,
467
+ state: material.value.state,
468
+ nonce: material.value.nonce,
469
+ returnTo,
470
+ expiresAt: nowSeconds() + cfg.pkceCookieTtlSeconds,
471
+ };
472
+ const sealed = await sealer.seal(handshake);
473
+ if (Result.isFailure(sealed)) return errorToResponse(sealed.error);
474
+ const pkceCookie = await serializeAuthCookie(
475
+ PKCE_COOKIE_NAME,
476
+ sealed.value,
477
+ cfg.pkceCookieTtlSeconds,
478
+ );
479
+ if (Result.isFailure(pkceCookie)) return errorToResponse(pkceCookie.error);
480
+ const authorizeUrl = await oidc.buildAuthorizeUrl({
481
+ redirectUri: cfg.redirectUri,
482
+ scope: cfg.scopes.join(" "),
483
+ state: material.value.state,
484
+ nonce: material.value.nonce,
485
+ codeChallenge: material.value.challenge,
486
+ });
487
+ if (Result.isFailure(authorizeUrl)) return errorToResponse(authorizeUrl.error);
488
+ return redirectResponse(authorizeUrl.value, [pkceCookie.value]);
489
+ };
490
+
491
+ const callbackHandler = async (request: Request): Promise<Response> => {
492
+ if (request.method !== "GET") {
493
+ return problemResponse(405, "method_not_allowed");
494
+ }
495
+ if (hasInvalidNavigationOrigin(request, cfg.allowedOrigins)) {
496
+ return problemResponse(403, "csrf_validation_failed");
497
+ }
498
+ // Every failure path also destroys the handshake cookie, making the PKCE
499
+ // cookie single-use and a poisoned flow unrepeatable (design.md §32.1).
500
+ const clearedPkce = await clearAuthCookie(PKCE_COOKIE_NAME);
501
+ const pkceClear = Result.isSuccess(clearedPkce) ? [clearedPkce.value] : [];
502
+ const failWith = (response: Response): Response => {
503
+ for (const value of pkceClear) response.headers.append("set-cookie", value);
504
+ return response;
505
+ };
506
+
507
+ const url = new URL(request.url);
508
+ const errorParam = url.searchParams.get("error");
509
+ if (errorParam !== null) {
510
+ return failWith(problemResponse(400, "oauth_authorization_error", errorParam.slice(0, 64)));
511
+ }
512
+ const code = url.searchParams.get("code");
513
+ const state = url.searchParams.get("state");
514
+ if (code === null || state === null) {
515
+ return failWith(problemResponse(400, "invalid_request", "missing_code_or_state"));
516
+ }
517
+ const pkceValue = readCookie(request, PKCE_COOKIE_NAME);
518
+ if (pkceValue === undefined) {
519
+ return failWith(problemResponse(400, "pkce_cookie_missing"));
520
+ }
521
+ const unsealed = await sealer.unseal(pkceValue);
522
+ if (Result.isFailure(unsealed) || !isPkceCookiePayload(unsealed.value)) {
523
+ return failWith(problemResponse(400, "pkce_cookie_invalid"));
524
+ }
525
+ const handshake = unsealed.value;
526
+ if (handshake.expiresAt <= nowSeconds()) {
527
+ return failWith(problemResponse(400, "pkce_cookie_invalid", "handshake_expired"));
528
+ }
529
+ if (!timingSafeEqual(handshake.state, state)) {
530
+ return failWith(problemResponse(400, "state_mismatch"));
531
+ }
532
+ const token = await oidc.exchangeCode({
533
+ code,
534
+ redirectUri: cfg.redirectUri,
535
+ codeVerifier: handshake.verifier,
536
+ });
537
+ if (Result.isFailure(token)) return failWith(errorToResponse(token.error));
538
+ const idToken = token.value.id_token;
539
+ if (idToken === undefined) {
540
+ return failWith(problemResponse(400, "token_response_invalid", "missing_id_token"));
541
+ }
542
+ const claims = await oidc.verifyIdToken(idToken, handshake.nonce);
543
+ if (Result.isFailure(claims)) return failWith(errorToResponse(claims.error));
544
+ const user = claimsToUser(claims.value);
545
+ if (user === null) {
546
+ return failWith(problemResponse(400, "id_token_invalid", "missing_sub"));
547
+ }
548
+ const nowSec = nowSeconds();
549
+ const sessionPayload: SessionPayloadV1 = {
550
+ v: 1,
551
+ user,
552
+ accessToken: token.value.access_token,
553
+ accessTokenExpiresAt: nowSec + token.value.expires_in,
554
+ ...(token.value.refresh_token !== undefined
555
+ ? { refreshToken: token.value.refresh_token }
556
+ : {}),
557
+ idToken,
558
+ scope: token.value.scope,
559
+ createdAt: nowSec,
560
+ expiresAt: nowSec + cfg.sessionTtlSeconds,
561
+ };
562
+ const sealedSession = await sealer.seal(sessionPayload);
563
+ if (Result.isFailure(sealedSession)) return failWith(errorToResponse(sealedSession.error));
564
+ const sessionCookie = await serializeAuthCookie(
565
+ SESSION_COOKIE_NAME,
566
+ sealedSession.value,
567
+ cfg.sessionTtlSeconds,
568
+ );
569
+ if (Result.isFailure(sessionCookie)) return failWith(errorToResponse(sessionCookie.error));
570
+ // The target was sanitized at login time; re-sanitize defensively before
571
+ // putting it into a Location header (design.md §32.2 open redirect禁止).
572
+ const target = sanitizeRedirectTarget(
573
+ handshake.returnTo,
574
+ cfg.allowedRedirectTargets,
575
+ cfg.postLoginRedirect,
576
+ );
577
+ return redirectResponse(target, [sessionCookie.value, ...pkceClear]);
578
+ };
579
+
580
+ const logoutHandler = async (request: Request): Promise<Response> => {
581
+ if (request.method !== "GET" && request.method !== "POST") {
582
+ return problemResponse(405, "method_not_allowed");
583
+ }
584
+ if (
585
+ hasInvalidNavigationOrigin(request, cfg.allowedOrigins) ||
586
+ !isRequestOriginValid(request, cfg.allowedOrigins)
587
+ ) {
588
+ return problemResponse(403, "csrf_validation_failed");
589
+ }
590
+ const url = new URL(request.url);
591
+ const returnTo = sanitizeRedirectTarget(
592
+ url.searchParams.get("return_to"),
593
+ cfg.allowedRedirectTargets,
594
+ cfg.postLogoutRedirect,
595
+ );
596
+ const sessionValue = readCookie(request, SESSION_COOKIE_NAME);
597
+ if (sessionValue !== undefined) {
598
+ const unsealed = await sealer.unseal(sessionValue);
599
+ if (
600
+ Result.isSuccess(unsealed) &&
601
+ isSessionPayload(unsealed.value) &&
602
+ unsealed.value.refreshToken !== undefined
603
+ ) {
604
+ // Best-effort family revocation (design.md §15.8): the Result is
605
+ // awaited here; local logout proceeds regardless of its outcome and
606
+ // token material is never logged.
607
+ await oidc.revokeRefreshToken(unsealed.value.refreshToken);
608
+ }
609
+ }
610
+ const clearedSession = await clearAuthCookie(SESSION_COOKIE_NAME);
611
+ const clearedPkce = await clearAuthCookie(PKCE_COOKIE_NAME);
612
+ const setCookies: string[] = [];
613
+ if (Result.isSuccess(clearedSession)) setCookies.push(clearedSession.value);
614
+ if (Result.isSuccess(clearedPkce)) setCookies.push(clearedPkce.value);
615
+ return redirectResponse(returnTo, setCookies);
616
+ };
617
+
618
+ // -------------------------------------------------------------------------
619
+ // Session resolution + refresh
620
+ // -------------------------------------------------------------------------
621
+
622
+ const buildRefreshedPayload = async (
623
+ base: SessionPayloadV1,
624
+ token: TokenResponse,
625
+ ): ResultAsync<SessionPayloadV1, ServerAuthError> => {
626
+ let user = base.user;
627
+ let idToken = base.idToken;
628
+ if (token.id_token !== undefined) {
629
+ // OIDC Core §12.2: a refresh-response ID token is verified too (nonce
630
+ // is not required on the refresh grant).
631
+ const claims = await oidc.verifyIdToken(token.id_token, null);
632
+ if (Result.isFailure(claims)) return claims;
633
+ const updatedUser = claimsToUser(claims.value);
634
+ if (updatedUser === null) {
635
+ const error: ServerAuthError = { type: "id_token_invalid", reason: "missing_sub" };
636
+ return Result.fail(error);
637
+ }
638
+ user = updatedUser;
639
+ idToken = token.id_token;
640
+ }
641
+ const refreshToken = token.refresh_token ?? base.refreshToken;
642
+ return Result.succeed({
643
+ v: 1,
644
+ user,
645
+ accessToken: token.access_token,
646
+ accessTokenExpiresAt: nowSeconds() + token.expires_in,
647
+ ...(refreshToken !== undefined ? { refreshToken } : {}),
648
+ ...(idToken !== undefined ? { idToken } : {}),
649
+ scope: token.scope,
650
+ createdAt: base.createdAt,
651
+ expiresAt: base.expiresAt,
652
+ });
653
+ };
654
+
655
+ const refreshUnderLock = (
656
+ presentedRefreshToken: string,
657
+ basePayload: SessionPayloadV1,
658
+ ): Promise<Result<RefreshSuccess, ServerAuthError>> =>
659
+ withRefreshLock(async (): Promise<Result<RefreshSuccess, ServerAuthError>> => {
660
+ // Double-checked under the lock: a concurrent request may already have
661
+ // rotated this token; reuse its result instead of replaying the grant.
662
+ // Freshness is capped at the rotation-cache TTL so configurations with
663
+ // a leeway larger than the access-token TTL still reuse the just-rotated
664
+ // entry ("network復帰時に1回だけrefresh", design.md §21.7).
665
+ const cached = readRotationCache(presentedRefreshToken);
666
+ const base = cached !== null ? cached.payload : basePayload;
667
+ const freshnessFloor = Math.min(cfg.refreshLeewaySeconds, ROTATION_CACHE_TTL_MS / 1000);
668
+ if (cached !== null && cached.payload.accessTokenExpiresAt - nowSeconds() > freshnessFloor) {
669
+ return Result.succeed({ payload: cached.payload, sealedPayload: cached.sealedPayload });
670
+ }
671
+ const effectiveRefreshToken = base.refreshToken ?? presentedRefreshToken;
672
+ const token = await oidc.refreshTokens(effectiveRefreshToken);
673
+ if (Result.isFailure(token)) return token;
674
+ const updated = await buildRefreshedPayload(base, token.value);
675
+ if (Result.isFailure(updated)) return updated;
676
+ const sealed = await sealer.seal(updated.value);
677
+ if (Result.isFailure(sealed)) return sealed;
678
+ const entry: RotationEntry = {
679
+ payload: updated.value,
680
+ sealedPayload: sealed.value,
681
+ storedAtMs: Date.now(),
682
+ };
683
+ // Atomically (under the mutex) publish the rotation: both the presented
684
+ // (now dead) and the new refresh token map to the latest session.
685
+ writeRotationCache(presentedRefreshToken, entry);
686
+ if (updated.value.refreshToken !== undefined) {
687
+ writeRotationCache(updated.value.refreshToken, entry);
688
+ }
689
+ return Result.succeed({ payload: updated.value, sealedPayload: sealed.value });
690
+ });
691
+
692
+ const resolveSession = async (
693
+ sessionCookieValue: string | undefined,
694
+ options: { readonly forceRefresh: boolean },
695
+ ): Promise<GetSessionOutcome> => {
696
+ if (sessionCookieValue === undefined) {
697
+ return { status: "unauthenticated", reason: "no_session" };
698
+ }
699
+ const unsealed = await sealer.unseal(sessionCookieValue);
700
+ if (Result.isFailure(unsealed) || !isSessionPayload(unsealed.value)) {
701
+ // Tampered or foreign cookie: fail closed and destroy it (sealing.ts).
702
+ return {
703
+ status: "unauthenticated",
704
+ reason: "invalid_session_cookie",
705
+ ...(await clearSessionCookiePart()),
706
+ };
707
+ }
708
+ let payload = unsealed.value;
709
+ let rotatedSealedPayload: string | undefined;
710
+ if (payload.refreshToken !== undefined) {
711
+ const rotated = readRotationCache(payload.refreshToken);
712
+ if (rotated !== null) {
713
+ payload = rotated.payload;
714
+ rotatedSealedPayload = rotated.sealedPayload;
715
+ }
716
+ }
717
+ const nowSec = nowSeconds();
718
+ if (payload.expiresAt <= nowSec) {
719
+ return {
720
+ status: "unauthenticated",
721
+ reason: "session_expired",
722
+ ...(await clearSessionCookiePart()),
723
+ };
724
+ }
725
+ const refreshDue =
726
+ options.forceRefresh || payload.accessTokenExpiresAt - nowSec <= cfg.refreshLeewaySeconds;
727
+ if (!refreshDue) {
728
+ // Re-issue the cookie when the payload came from the rotation cache so
729
+ // the browser stops presenting the stale (rotated-out) one.
730
+ const reissued =
731
+ rotatedSealedPayload !== undefined
732
+ ? await sessionCookieHeader(payload, rotatedSealedPayload)
733
+ : undefined;
734
+ return {
735
+ status: "authenticated",
736
+ session: toPublicSession(payload),
737
+ ...(reissued !== undefined ? { setCookie: reissued } : {}),
738
+ };
739
+ }
740
+ if (payload.refreshToken === undefined) {
741
+ // Without offline_access there is no server-side continuation; an
742
+ // expired access token ends the usable session (design.md §15.2).
743
+ return {
744
+ status: "unauthenticated",
745
+ reason: "session_expired",
746
+ ...(await clearSessionCookiePart()),
747
+ };
748
+ }
749
+ const refreshed = await refreshUnderLock(payload.refreshToken, payload);
750
+ if (Result.isFailure(refreshed)) {
751
+ const error = refreshed.error;
752
+ if (error.type === "token_endpoint_rejected" && error.code === "invalid_grant") {
753
+ // design.md §21.7: invalid_grant destroys the local session completely.
754
+ return {
755
+ status: "unauthenticated",
756
+ reason: "refresh_rejected",
757
+ ...(await clearSessionCookiePart()),
758
+ };
759
+ }
760
+ // Transient failure (network, timeout, 5xx, server_error): the session
761
+ // is NOT deleted; the next request retries the refresh (§21.7).
762
+ return { status: "unauthenticated", reason: "refresh_unavailable" };
763
+ }
764
+ const updatedCookie = await sessionCookieHeader(
765
+ refreshed.value.payload,
766
+ refreshed.value.sealedPayload,
767
+ );
768
+ return {
769
+ status: "authenticated",
770
+ session: toPublicSession(refreshed.value.payload),
771
+ ...(updatedCookie !== undefined ? { setCookie: updatedCookie } : {}),
772
+ };
773
+ };
774
+
775
+ const getSession = (request: Request): Promise<GetSessionOutcome> =>
776
+ resolveSession(readCookie(request, SESSION_COOKIE_NAME), { forceRefresh: false });
777
+
778
+ const refreshSession = (request: Request): Promise<GetSessionOutcome> =>
779
+ resolveSession(readCookie(request, SESSION_COOKIE_NAME), { forceRefresh: true });
780
+
781
+ const requireSession = async (
782
+ request: Request,
783
+ options?: RequireSessionOptions,
784
+ ): Promise<RequireSessionOutcome> => {
785
+ const outcome = await resolveSession(readCookie(request, SESSION_COOKIE_NAME), {
786
+ forceRefresh: false,
787
+ });
788
+ if (outcome.status === "authenticated") {
789
+ return {
790
+ ok: true,
791
+ session: outcome.session,
792
+ ...(outcome.setCookie !== undefined ? { setCookie: outcome.setCookie } : {}),
793
+ };
794
+ }
795
+ const mode = options?.onUnauthenticated ?? "redirect";
796
+ if (mode === "json" || outcome.reason === "refresh_unavailable") {
797
+ const response = problemResponse(
798
+ outcome.reason === "refresh_unavailable" ? 503 : 401,
799
+ outcome.reason,
800
+ );
801
+ if (outcome.clearCookie !== undefined) {
802
+ response.headers.append("set-cookie", outcome.clearCookie);
803
+ }
804
+ return { ok: false, reason: outcome.reason, response };
805
+ }
806
+ const url = new URL(request.url);
807
+ // pathname+search are URL-parser output (percent-encoded); sanitize anyway
808
+ // so a `//evil.example` path can never become a protocol-relative Location.
809
+ const returnTo = sanitizeRedirectTarget(
810
+ `${url.pathname}${url.search}`,
811
+ [],
812
+ cfg.postLoginRedirect,
813
+ );
814
+ const headers = new Headers();
815
+ headers.set("location", `${cfg.basePath}/login?return_to=${encodeURIComponent(returnTo)}`);
816
+ headers.set("cache-control", "no-store");
817
+ if (outcome.clearCookie !== undefined) {
818
+ headers.set("set-cookie", outcome.clearCookie);
819
+ }
820
+ return {
821
+ ok: false,
822
+ reason: outcome.reason,
823
+ response: new Response(null, { status: 302, headers }),
824
+ };
825
+ };
826
+
827
+ const verifyAccessToken = async (
828
+ token: string,
829
+ audience?: string | readonly string[],
830
+ ): ResultAsync<VerifiedAccessToken, ServerAuthError> => {
831
+ const verified = await oidc.verifyAccessToken(token, audience);
832
+ if (Result.isFailure(verified)) return verified;
833
+ const claims = verified.value;
834
+ if (typeof claims.sub !== "string" || claims.sub.length === 0) {
835
+ const error: ServerAuthError = { type: "access_token_invalid", reason: "missing_sub" };
836
+ return Result.fail(error);
837
+ }
838
+ return Result.succeed({
839
+ sub: claims.sub,
840
+ scope: typeof claims.scope === "string" ? claims.scope : "",
841
+ ...(typeof claims.client_id === "string" ? { clientId: claims.client_id } : {}),
842
+ ...(typeof claims.exp === "number" ? { expiresAt: claims.exp } : {}),
843
+ claims,
844
+ });
845
+ };
846
+
847
+ return {
848
+ loginHandler,
849
+ callbackHandler,
850
+ logoutHandler,
851
+ getSession,
852
+ refreshSession,
853
+ requireSession,
854
+ verifyAccessToken,
855
+ basePath: cfg.basePath,
856
+ sessionCookieName: SESSION_COOKIE_NAME,
857
+ };
858
+ };
859
+
860
+ /**
861
+ * Standalone resource-server verifier (design.md §3.1: "その他のバックエンド
862
+ * は OIDC/JWKS で統合"). Same verification rules as the BFF: ES256 only,
863
+ * mandatory `kid`, iss/aud/exp/typ(`at+jwt`) checked against the issuer JWKS.
864
+ */
865
+ export const createAccessTokenVerifier = (
866
+ options: AccessTokenVerifierOptions,
867
+ ): ((token: string) => ResultAsync<VerifiedAccessToken, ServerAuthError>) => {
868
+ const issuer = normalizeIssuer(options.issuer);
869
+ const fetchImpl: FetchLike = options.fetch ?? ((input, init) => fetch(input, init));
870
+ const oidc = createOidcClient({ issuer, clientId: "", clientSecret: "", fetchImpl });
871
+ return async (token) => {
872
+ const verified = await oidc.verifyAccessToken(token, options.audience);
873
+ if (Result.isFailure(verified)) return verified;
874
+ const claims = verified.value;
875
+ if (typeof claims.sub !== "string" || claims.sub.length === 0) {
876
+ const error: ServerAuthError = { type: "access_token_invalid", reason: "missing_sub" };
877
+ return Result.fail(error);
878
+ }
879
+ return Result.succeed({
880
+ sub: claims.sub,
881
+ scope: typeof claims.scope === "string" ? claims.scope : "",
882
+ ...(typeof claims.client_id === "string" ? { clientId: claims.client_id } : {}),
883
+ ...(typeof claims.exp === "number" ? { expiresAt: claims.exp } : {}),
884
+ claims,
885
+ });
886
+ };
887
+ };