@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,586 @@
1
+ import { TOKEN_TTL_SECONDS } from "@smartcrab/contracts-public";
2
+ import { PKCE_COOKIE_NAME, SESSION_COOKIE_NAME, clearAuthCookie, readCookie, serializeAuthCookie, } from "./cookies.js";
3
+ import { errorToResponse, problemResponse } from "./errors.js";
4
+ import { createOidcClient } from "./oidc-client.js";
5
+ import { Result } from "./result.js";
6
+ import { createSealer } from "./sealing.js";
7
+ import { generatePkceMaterial, hasInvalidNavigationOrigin, isAllowedConfiguredTarget, isRequestOriginValid, sanitizeRedirectTarget, timingSafeEqual, } from "./security.js";
8
+ import { isSessionPayload, toPublicSession } from "./session.js";
9
+ // ---------------------------------------------------------------------------
10
+ // Config validation (programmer errors -> TypeError at construction)
11
+ // ---------------------------------------------------------------------------
12
+ const requireAbsoluteUrl = (field, value) => {
13
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
14
+ throw new TypeError(`@smartcrab/server: ${field} must be an absolute URL (scheme://...)`);
15
+ }
16
+ // Shape-checked above; any residual parse failure surfaces as the URL
17
+ // constructor's own TypeError at startup, which is the desired fail-fast.
18
+ return new URL(value);
19
+ };
20
+ const isLocalhostHttp = (url) => url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1");
21
+ const BASE_PATH_PATTERN = /^\/[A-Za-z0-9\-._~/]*$/;
22
+ const normalizeIssuer = (issuer) => {
23
+ const url = requireAbsoluteUrl("issuer", issuer);
24
+ if (url.protocol !== "https:") {
25
+ throw new TypeError("@smartcrab/server: issuer must be an https:// URL (design.md §8)");
26
+ }
27
+ return issuer.replace(/\/+$/, "");
28
+ };
29
+ const resolveConfig = (config) => {
30
+ if (config.cookieDomain !== undefined) {
31
+ throw new TypeError("@smartcrab/server: cookieDomain is not supported — the __Host-auth-session cookie (design.md §22.2) forbids a Domain attribute");
32
+ }
33
+ const issuer = normalizeIssuer(config.issuer);
34
+ if (config.clientId.length === 0) {
35
+ throw new TypeError("@smartcrab/server: clientId must not be empty");
36
+ }
37
+ if (config.clientSecret.length === 0) {
38
+ throw new TypeError("@smartcrab/server: clientSecret must not be empty");
39
+ }
40
+ if (config.cookieSecret.length < 32) {
41
+ throw new TypeError("@smartcrab/server: cookieSecret must be at least 32 characters");
42
+ }
43
+ const redirectUri = requireAbsoluteUrl("redirectUri", config.redirectUri);
44
+ if (redirectUri.hash !== "") {
45
+ throw new TypeError("@smartcrab/server: redirectUri must not contain a fragment (design.md §15.9)");
46
+ }
47
+ if (redirectUri.protocol !== "https:" && !isLocalhostHttp(redirectUri)) {
48
+ throw new TypeError("@smartcrab/server: redirectUri must be https (http is allowed for localhost only, design.md §15.9)");
49
+ }
50
+ const basePath = config.basePath ?? "/auth";
51
+ if (!BASE_PATH_PATTERN.test(basePath) || (basePath !== "/" && basePath.endsWith("/"))) {
52
+ throw new TypeError("@smartcrab/server: basePath must be an absolute path without a trailing slash");
53
+ }
54
+ const scopes = config.scopes ?? ["openid", "profile", "email", "offline_access"];
55
+ if (!scopes.includes("openid")) {
56
+ throw new TypeError('@smartcrab/server: scopes must include "openid"');
57
+ }
58
+ const postLoginRedirect = config.postLoginRedirect ?? "/";
59
+ if (!isAllowedConfiguredTarget(postLoginRedirect)) {
60
+ throw new TypeError("@smartcrab/server: postLoginRedirect must be a relative path or an https URL");
61
+ }
62
+ const postLogoutRedirect = config.postLogoutRedirect ?? "/";
63
+ if (!isAllowedConfiguredTarget(postLogoutRedirect)) {
64
+ throw new TypeError("@smartcrab/server: postLogoutRedirect must be a relative path or an https URL");
65
+ }
66
+ const allowedRedirectTargets = config.allowedRedirectTargets ?? [];
67
+ for (const target of allowedRedirectTargets) {
68
+ if (!isAllowedConfiguredTarget(target)) {
69
+ throw new TypeError("@smartcrab/server: allowedRedirectTargets entries must be relative paths or https URLs");
70
+ }
71
+ }
72
+ const allowedOrigins = (config.allowedOrigins ?? []).map((origin) => requireAbsoluteUrl("allowedOrigins entry", origin).origin.toLowerCase());
73
+ const sessionTtlSeconds = config.sessionTtlSeconds ?? TOKEN_TTL_SECONDS.refreshIdle;
74
+ if (!Number.isInteger(sessionTtlSeconds) || sessionTtlSeconds <= 0) {
75
+ throw new TypeError("@smartcrab/server: sessionTtlSeconds must be a positive integer");
76
+ }
77
+ const pkceCookieTtlSeconds = config.pkceCookieTtlSeconds ?? 600;
78
+ if (!Number.isInteger(pkceCookieTtlSeconds) || pkceCookieTtlSeconds <= 0) {
79
+ throw new TypeError("@smartcrab/server: pkceCookieTtlSeconds must be a positive integer");
80
+ }
81
+ const refreshLeewaySeconds = config.refreshLeewaySeconds ?? 60;
82
+ if (!Number.isInteger(refreshLeewaySeconds) || refreshLeewaySeconds < 0) {
83
+ throw new TypeError("@smartcrab/server: refreshLeewaySeconds must be a non-negative integer");
84
+ }
85
+ const fetchImpl = config.fetch ?? ((input, init) => fetch(input, init));
86
+ return {
87
+ issuer,
88
+ clientId: config.clientId,
89
+ clientSecret: config.clientSecret,
90
+ redirectUri: config.redirectUri,
91
+ basePath,
92
+ scopes,
93
+ postLoginRedirect,
94
+ postLogoutRedirect,
95
+ allowedRedirectTargets,
96
+ allowedOrigins,
97
+ sessionTtlSeconds,
98
+ pkceCookieTtlSeconds,
99
+ refreshLeewaySeconds,
100
+ fetchImpl,
101
+ };
102
+ };
103
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
104
+ const isPkceCookiePayload = (value) => {
105
+ if (!isRecord(value))
106
+ return false;
107
+ return (value.v === 1 &&
108
+ typeof value.verifier === "string" &&
109
+ typeof value.state === "string" &&
110
+ typeof value.nonce === "string" &&
111
+ typeof value.returnTo === "string" &&
112
+ typeof value.expiresAt === "number");
113
+ };
114
+ // ---------------------------------------------------------------------------
115
+ // createServerAuth
116
+ // ---------------------------------------------------------------------------
117
+ const nowSeconds = () => Math.floor(Date.now() / 1000);
118
+ const claimsToUser = (claims) => {
119
+ const sub = claims.sub;
120
+ if (typeof sub !== "string" || sub.length === 0)
121
+ return null;
122
+ return {
123
+ sub,
124
+ ...(typeof claims.name === "string" ? { name: claims.name } : {}),
125
+ ...(typeof claims.email === "string" ? { email: claims.email } : {}),
126
+ ...(typeof claims.email_verified === "boolean" ? { emailVerified: claims.email_verified } : {}),
127
+ };
128
+ };
129
+ const redirectResponse = (location, setCookies) => {
130
+ const headers = new Headers();
131
+ headers.set("location", location);
132
+ headers.set("cache-control", "no-store");
133
+ for (const value of setCookies) {
134
+ headers.append("set-cookie", value);
135
+ }
136
+ return new Response(null, { status: 302, headers });
137
+ };
138
+ /** design.md §21.7: rotation-replay avoidance windows. */
139
+ const ROTATION_CACHE_TTL_MS = 60_000;
140
+ const ROTATION_CACHE_MAX_ENTRIES = 1000;
141
+ export const createServerAuth = (config) => {
142
+ const cfg = resolveConfig(config);
143
+ const sealer = createSealer(config.cookieSecret);
144
+ const oidc = createOidcClient({
145
+ issuer: cfg.issuer,
146
+ clientId: cfg.clientId,
147
+ clientSecret: cfg.clientSecret,
148
+ fetchImpl: cfg.fetchImpl,
149
+ });
150
+ const rotationCache = new Map();
151
+ const readRotationCache = (refreshToken) => {
152
+ const entry = rotationCache.get(refreshToken);
153
+ if (entry === undefined)
154
+ return null;
155
+ if (Date.now() - entry.storedAtMs > ROTATION_CACHE_TTL_MS) {
156
+ rotationCache.delete(refreshToken);
157
+ return null;
158
+ }
159
+ return entry;
160
+ };
161
+ const writeRotationCache = (refreshToken, entry) => {
162
+ if (rotationCache.size >= ROTATION_CACHE_MAX_ENTRIES) {
163
+ const oldest = rotationCache.keys().next();
164
+ if (!oldest.done)
165
+ rotationCache.delete(oldest.value);
166
+ }
167
+ rotationCache.set(refreshToken, entry);
168
+ };
169
+ /**
170
+ * Process-wide (per-isolate) refresh mutex: a promise chain serializes every
171
+ * refresh through this instance so two concurrent requests can never fire
172
+ * two refresh grants for the same session (design.md §21.7). The chain is
173
+ * kept alive regardless of individual job outcomes.
174
+ */
175
+ let refreshLockChain = Promise.resolve();
176
+ const withRefreshLock = (job) => {
177
+ const run = refreshLockChain.then(() => job());
178
+ refreshLockChain = run.then(() => undefined, () => undefined);
179
+ return run;
180
+ };
181
+ const clearSessionCookiePart = async () => {
182
+ const cleared = await clearAuthCookie(SESSION_COOKIE_NAME);
183
+ return Result.isSuccess(cleared) ? { clearCookie: cleared.value } : {};
184
+ };
185
+ /**
186
+ * Serializes a sealed session payload into a full `Set-Cookie` header whose
187
+ * Max-Age tracks the session's remaining lifetime. Serialization is
188
+ * deterministic for our own base64url payloads, so a failure degrades to
189
+ * "no updated cookie" rather than an error response.
190
+ */
191
+ const sessionCookieHeader = async (payload, sealedPayload) => {
192
+ const maxAge = Math.max(1, payload.expiresAt - nowSeconds());
193
+ const serialized = await serializeAuthCookie(SESSION_COOKIE_NAME, sealedPayload, maxAge);
194
+ return Result.isSuccess(serialized) ? serialized.value : undefined;
195
+ };
196
+ // -------------------------------------------------------------------------
197
+ // Handlers
198
+ // -------------------------------------------------------------------------
199
+ const loginHandler = async (request) => {
200
+ if (request.method !== "GET" && request.method !== "POST") {
201
+ return problemResponse(405, "method_not_allowed");
202
+ }
203
+ if (hasInvalidNavigationOrigin(request, cfg.allowedOrigins) ||
204
+ !isRequestOriginValid(request, cfg.allowedOrigins)) {
205
+ return problemResponse(403, "csrf_validation_failed");
206
+ }
207
+ const url = new URL(request.url);
208
+ const returnTo = sanitizeRedirectTarget(url.searchParams.get("return_to"), cfg.allowedRedirectTargets, cfg.postLoginRedirect);
209
+ const material = await generatePkceMaterial();
210
+ if (Result.isFailure(material))
211
+ return errorToResponse(material.error);
212
+ const handshake = {
213
+ v: 1,
214
+ verifier: material.value.verifier,
215
+ state: material.value.state,
216
+ nonce: material.value.nonce,
217
+ returnTo,
218
+ expiresAt: nowSeconds() + cfg.pkceCookieTtlSeconds,
219
+ };
220
+ const sealed = await sealer.seal(handshake);
221
+ if (Result.isFailure(sealed))
222
+ return errorToResponse(sealed.error);
223
+ const pkceCookie = await serializeAuthCookie(PKCE_COOKIE_NAME, sealed.value, cfg.pkceCookieTtlSeconds);
224
+ if (Result.isFailure(pkceCookie))
225
+ return errorToResponse(pkceCookie.error);
226
+ const authorizeUrl = await oidc.buildAuthorizeUrl({
227
+ redirectUri: cfg.redirectUri,
228
+ scope: cfg.scopes.join(" "),
229
+ state: material.value.state,
230
+ nonce: material.value.nonce,
231
+ codeChallenge: material.value.challenge,
232
+ });
233
+ if (Result.isFailure(authorizeUrl))
234
+ return errorToResponse(authorizeUrl.error);
235
+ return redirectResponse(authorizeUrl.value, [pkceCookie.value]);
236
+ };
237
+ const callbackHandler = async (request) => {
238
+ if (request.method !== "GET") {
239
+ return problemResponse(405, "method_not_allowed");
240
+ }
241
+ if (hasInvalidNavigationOrigin(request, cfg.allowedOrigins)) {
242
+ return problemResponse(403, "csrf_validation_failed");
243
+ }
244
+ // Every failure path also destroys the handshake cookie, making the PKCE
245
+ // cookie single-use and a poisoned flow unrepeatable (design.md §32.1).
246
+ const clearedPkce = await clearAuthCookie(PKCE_COOKIE_NAME);
247
+ const pkceClear = Result.isSuccess(clearedPkce) ? [clearedPkce.value] : [];
248
+ const failWith = (response) => {
249
+ for (const value of pkceClear)
250
+ response.headers.append("set-cookie", value);
251
+ return response;
252
+ };
253
+ const url = new URL(request.url);
254
+ const errorParam = url.searchParams.get("error");
255
+ if (errorParam !== null) {
256
+ return failWith(problemResponse(400, "oauth_authorization_error", errorParam.slice(0, 64)));
257
+ }
258
+ const code = url.searchParams.get("code");
259
+ const state = url.searchParams.get("state");
260
+ if (code === null || state === null) {
261
+ return failWith(problemResponse(400, "invalid_request", "missing_code_or_state"));
262
+ }
263
+ const pkceValue = readCookie(request, PKCE_COOKIE_NAME);
264
+ if (pkceValue === undefined) {
265
+ return failWith(problemResponse(400, "pkce_cookie_missing"));
266
+ }
267
+ const unsealed = await sealer.unseal(pkceValue);
268
+ if (Result.isFailure(unsealed) || !isPkceCookiePayload(unsealed.value)) {
269
+ return failWith(problemResponse(400, "pkce_cookie_invalid"));
270
+ }
271
+ const handshake = unsealed.value;
272
+ if (handshake.expiresAt <= nowSeconds()) {
273
+ return failWith(problemResponse(400, "pkce_cookie_invalid", "handshake_expired"));
274
+ }
275
+ if (!timingSafeEqual(handshake.state, state)) {
276
+ return failWith(problemResponse(400, "state_mismatch"));
277
+ }
278
+ const token = await oidc.exchangeCode({
279
+ code,
280
+ redirectUri: cfg.redirectUri,
281
+ codeVerifier: handshake.verifier,
282
+ });
283
+ if (Result.isFailure(token))
284
+ return failWith(errorToResponse(token.error));
285
+ const idToken = token.value.id_token;
286
+ if (idToken === undefined) {
287
+ return failWith(problemResponse(400, "token_response_invalid", "missing_id_token"));
288
+ }
289
+ const claims = await oidc.verifyIdToken(idToken, handshake.nonce);
290
+ if (Result.isFailure(claims))
291
+ return failWith(errorToResponse(claims.error));
292
+ const user = claimsToUser(claims.value);
293
+ if (user === null) {
294
+ return failWith(problemResponse(400, "id_token_invalid", "missing_sub"));
295
+ }
296
+ const nowSec = nowSeconds();
297
+ const sessionPayload = {
298
+ v: 1,
299
+ user,
300
+ accessToken: token.value.access_token,
301
+ accessTokenExpiresAt: nowSec + token.value.expires_in,
302
+ ...(token.value.refresh_token !== undefined
303
+ ? { refreshToken: token.value.refresh_token }
304
+ : {}),
305
+ idToken,
306
+ scope: token.value.scope,
307
+ createdAt: nowSec,
308
+ expiresAt: nowSec + cfg.sessionTtlSeconds,
309
+ };
310
+ const sealedSession = await sealer.seal(sessionPayload);
311
+ if (Result.isFailure(sealedSession))
312
+ return failWith(errorToResponse(sealedSession.error));
313
+ const sessionCookie = await serializeAuthCookie(SESSION_COOKIE_NAME, sealedSession.value, cfg.sessionTtlSeconds);
314
+ if (Result.isFailure(sessionCookie))
315
+ return failWith(errorToResponse(sessionCookie.error));
316
+ // The target was sanitized at login time; re-sanitize defensively before
317
+ // putting it into a Location header (design.md §32.2 open redirect禁止).
318
+ const target = sanitizeRedirectTarget(handshake.returnTo, cfg.allowedRedirectTargets, cfg.postLoginRedirect);
319
+ return redirectResponse(target, [sessionCookie.value, ...pkceClear]);
320
+ };
321
+ const logoutHandler = async (request) => {
322
+ if (request.method !== "GET" && request.method !== "POST") {
323
+ return problemResponse(405, "method_not_allowed");
324
+ }
325
+ if (hasInvalidNavigationOrigin(request, cfg.allowedOrigins) ||
326
+ !isRequestOriginValid(request, cfg.allowedOrigins)) {
327
+ return problemResponse(403, "csrf_validation_failed");
328
+ }
329
+ const url = new URL(request.url);
330
+ const returnTo = sanitizeRedirectTarget(url.searchParams.get("return_to"), cfg.allowedRedirectTargets, cfg.postLogoutRedirect);
331
+ const sessionValue = readCookie(request, SESSION_COOKIE_NAME);
332
+ if (sessionValue !== undefined) {
333
+ const unsealed = await sealer.unseal(sessionValue);
334
+ if (Result.isSuccess(unsealed) &&
335
+ isSessionPayload(unsealed.value) &&
336
+ unsealed.value.refreshToken !== undefined) {
337
+ // Best-effort family revocation (design.md §15.8): the Result is
338
+ // awaited here; local logout proceeds regardless of its outcome and
339
+ // token material is never logged.
340
+ await oidc.revokeRefreshToken(unsealed.value.refreshToken);
341
+ }
342
+ }
343
+ const clearedSession = await clearAuthCookie(SESSION_COOKIE_NAME);
344
+ const clearedPkce = await clearAuthCookie(PKCE_COOKIE_NAME);
345
+ const setCookies = [];
346
+ if (Result.isSuccess(clearedSession))
347
+ setCookies.push(clearedSession.value);
348
+ if (Result.isSuccess(clearedPkce))
349
+ setCookies.push(clearedPkce.value);
350
+ return redirectResponse(returnTo, setCookies);
351
+ };
352
+ // -------------------------------------------------------------------------
353
+ // Session resolution + refresh
354
+ // -------------------------------------------------------------------------
355
+ const buildRefreshedPayload = async (base, token) => {
356
+ let user = base.user;
357
+ let idToken = base.idToken;
358
+ if (token.id_token !== undefined) {
359
+ // OIDC Core §12.2: a refresh-response ID token is verified too (nonce
360
+ // is not required on the refresh grant).
361
+ const claims = await oidc.verifyIdToken(token.id_token, null);
362
+ if (Result.isFailure(claims))
363
+ return claims;
364
+ const updatedUser = claimsToUser(claims.value);
365
+ if (updatedUser === null) {
366
+ const error = { type: "id_token_invalid", reason: "missing_sub" };
367
+ return Result.fail(error);
368
+ }
369
+ user = updatedUser;
370
+ idToken = token.id_token;
371
+ }
372
+ const refreshToken = token.refresh_token ?? base.refreshToken;
373
+ return Result.succeed({
374
+ v: 1,
375
+ user,
376
+ accessToken: token.access_token,
377
+ accessTokenExpiresAt: nowSeconds() + token.expires_in,
378
+ ...(refreshToken !== undefined ? { refreshToken } : {}),
379
+ ...(idToken !== undefined ? { idToken } : {}),
380
+ scope: token.scope,
381
+ createdAt: base.createdAt,
382
+ expiresAt: base.expiresAt,
383
+ });
384
+ };
385
+ const refreshUnderLock = (presentedRefreshToken, basePayload) => withRefreshLock(async () => {
386
+ // Double-checked under the lock: a concurrent request may already have
387
+ // rotated this token; reuse its result instead of replaying the grant.
388
+ // Freshness is capped at the rotation-cache TTL so configurations with
389
+ // a leeway larger than the access-token TTL still reuse the just-rotated
390
+ // entry ("network復帰時に1回だけrefresh", design.md §21.7).
391
+ const cached = readRotationCache(presentedRefreshToken);
392
+ const base = cached !== null ? cached.payload : basePayload;
393
+ const freshnessFloor = Math.min(cfg.refreshLeewaySeconds, ROTATION_CACHE_TTL_MS / 1000);
394
+ if (cached !== null && cached.payload.accessTokenExpiresAt - nowSeconds() > freshnessFloor) {
395
+ return Result.succeed({ payload: cached.payload, sealedPayload: cached.sealedPayload });
396
+ }
397
+ const effectiveRefreshToken = base.refreshToken ?? presentedRefreshToken;
398
+ const token = await oidc.refreshTokens(effectiveRefreshToken);
399
+ if (Result.isFailure(token))
400
+ return token;
401
+ const updated = await buildRefreshedPayload(base, token.value);
402
+ if (Result.isFailure(updated))
403
+ return updated;
404
+ const sealed = await sealer.seal(updated.value);
405
+ if (Result.isFailure(sealed))
406
+ return sealed;
407
+ const entry = {
408
+ payload: updated.value,
409
+ sealedPayload: sealed.value,
410
+ storedAtMs: Date.now(),
411
+ };
412
+ // Atomically (under the mutex) publish the rotation: both the presented
413
+ // (now dead) and the new refresh token map to the latest session.
414
+ writeRotationCache(presentedRefreshToken, entry);
415
+ if (updated.value.refreshToken !== undefined) {
416
+ writeRotationCache(updated.value.refreshToken, entry);
417
+ }
418
+ return Result.succeed({ payload: updated.value, sealedPayload: sealed.value });
419
+ });
420
+ const resolveSession = async (sessionCookieValue, options) => {
421
+ if (sessionCookieValue === undefined) {
422
+ return { status: "unauthenticated", reason: "no_session" };
423
+ }
424
+ const unsealed = await sealer.unseal(sessionCookieValue);
425
+ if (Result.isFailure(unsealed) || !isSessionPayload(unsealed.value)) {
426
+ // Tampered or foreign cookie: fail closed and destroy it (sealing.ts).
427
+ return {
428
+ status: "unauthenticated",
429
+ reason: "invalid_session_cookie",
430
+ ...(await clearSessionCookiePart()),
431
+ };
432
+ }
433
+ let payload = unsealed.value;
434
+ let rotatedSealedPayload;
435
+ if (payload.refreshToken !== undefined) {
436
+ const rotated = readRotationCache(payload.refreshToken);
437
+ if (rotated !== null) {
438
+ payload = rotated.payload;
439
+ rotatedSealedPayload = rotated.sealedPayload;
440
+ }
441
+ }
442
+ const nowSec = nowSeconds();
443
+ if (payload.expiresAt <= nowSec) {
444
+ return {
445
+ status: "unauthenticated",
446
+ reason: "session_expired",
447
+ ...(await clearSessionCookiePart()),
448
+ };
449
+ }
450
+ const refreshDue = options.forceRefresh || payload.accessTokenExpiresAt - nowSec <= cfg.refreshLeewaySeconds;
451
+ if (!refreshDue) {
452
+ // Re-issue the cookie when the payload came from the rotation cache so
453
+ // the browser stops presenting the stale (rotated-out) one.
454
+ const reissued = rotatedSealedPayload !== undefined
455
+ ? await sessionCookieHeader(payload, rotatedSealedPayload)
456
+ : undefined;
457
+ return {
458
+ status: "authenticated",
459
+ session: toPublicSession(payload),
460
+ ...(reissued !== undefined ? { setCookie: reissued } : {}),
461
+ };
462
+ }
463
+ if (payload.refreshToken === undefined) {
464
+ // Without offline_access there is no server-side continuation; an
465
+ // expired access token ends the usable session (design.md §15.2).
466
+ return {
467
+ status: "unauthenticated",
468
+ reason: "session_expired",
469
+ ...(await clearSessionCookiePart()),
470
+ };
471
+ }
472
+ const refreshed = await refreshUnderLock(payload.refreshToken, payload);
473
+ if (Result.isFailure(refreshed)) {
474
+ const error = refreshed.error;
475
+ if (error.type === "token_endpoint_rejected" && error.code === "invalid_grant") {
476
+ // design.md §21.7: invalid_grant destroys the local session completely.
477
+ return {
478
+ status: "unauthenticated",
479
+ reason: "refresh_rejected",
480
+ ...(await clearSessionCookiePart()),
481
+ };
482
+ }
483
+ // Transient failure (network, timeout, 5xx, server_error): the session
484
+ // is NOT deleted; the next request retries the refresh (§21.7).
485
+ return { status: "unauthenticated", reason: "refresh_unavailable" };
486
+ }
487
+ const updatedCookie = await sessionCookieHeader(refreshed.value.payload, refreshed.value.sealedPayload);
488
+ return {
489
+ status: "authenticated",
490
+ session: toPublicSession(refreshed.value.payload),
491
+ ...(updatedCookie !== undefined ? { setCookie: updatedCookie } : {}),
492
+ };
493
+ };
494
+ const getSession = (request) => resolveSession(readCookie(request, SESSION_COOKIE_NAME), { forceRefresh: false });
495
+ const refreshSession = (request) => resolveSession(readCookie(request, SESSION_COOKIE_NAME), { forceRefresh: true });
496
+ const requireSession = async (request, options) => {
497
+ const outcome = await resolveSession(readCookie(request, SESSION_COOKIE_NAME), {
498
+ forceRefresh: false,
499
+ });
500
+ if (outcome.status === "authenticated") {
501
+ return {
502
+ ok: true,
503
+ session: outcome.session,
504
+ ...(outcome.setCookie !== undefined ? { setCookie: outcome.setCookie } : {}),
505
+ };
506
+ }
507
+ const mode = options?.onUnauthenticated ?? "redirect";
508
+ if (mode === "json" || outcome.reason === "refresh_unavailable") {
509
+ const response = problemResponse(outcome.reason === "refresh_unavailable" ? 503 : 401, outcome.reason);
510
+ if (outcome.clearCookie !== undefined) {
511
+ response.headers.append("set-cookie", outcome.clearCookie);
512
+ }
513
+ return { ok: false, reason: outcome.reason, response };
514
+ }
515
+ const url = new URL(request.url);
516
+ // pathname+search are URL-parser output (percent-encoded); sanitize anyway
517
+ // so a `//evil.example` path can never become a protocol-relative Location.
518
+ const returnTo = sanitizeRedirectTarget(`${url.pathname}${url.search}`, [], cfg.postLoginRedirect);
519
+ const headers = new Headers();
520
+ headers.set("location", `${cfg.basePath}/login?return_to=${encodeURIComponent(returnTo)}`);
521
+ headers.set("cache-control", "no-store");
522
+ if (outcome.clearCookie !== undefined) {
523
+ headers.set("set-cookie", outcome.clearCookie);
524
+ }
525
+ return {
526
+ ok: false,
527
+ reason: outcome.reason,
528
+ response: new Response(null, { status: 302, headers }),
529
+ };
530
+ };
531
+ const verifyAccessToken = async (token, audience) => {
532
+ const verified = await oidc.verifyAccessToken(token, audience);
533
+ if (Result.isFailure(verified))
534
+ return verified;
535
+ const claims = verified.value;
536
+ if (typeof claims.sub !== "string" || claims.sub.length === 0) {
537
+ const error = { type: "access_token_invalid", reason: "missing_sub" };
538
+ return Result.fail(error);
539
+ }
540
+ return Result.succeed({
541
+ sub: claims.sub,
542
+ scope: typeof claims.scope === "string" ? claims.scope : "",
543
+ ...(typeof claims.client_id === "string" ? { clientId: claims.client_id } : {}),
544
+ ...(typeof claims.exp === "number" ? { expiresAt: claims.exp } : {}),
545
+ claims,
546
+ });
547
+ };
548
+ return {
549
+ loginHandler,
550
+ callbackHandler,
551
+ logoutHandler,
552
+ getSession,
553
+ refreshSession,
554
+ requireSession,
555
+ verifyAccessToken,
556
+ basePath: cfg.basePath,
557
+ sessionCookieName: SESSION_COOKIE_NAME,
558
+ };
559
+ };
560
+ /**
561
+ * Standalone resource-server verifier (design.md §3.1: "その他のバックエンド
562
+ * は OIDC/JWKS で統合"). Same verification rules as the BFF: ES256 only,
563
+ * mandatory `kid`, iss/aud/exp/typ(`at+jwt`) checked against the issuer JWKS.
564
+ */
565
+ export const createAccessTokenVerifier = (options) => {
566
+ const issuer = normalizeIssuer(options.issuer);
567
+ const fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
568
+ const oidc = createOidcClient({ issuer, clientId: "", clientSecret: "", fetchImpl });
569
+ return async (token) => {
570
+ const verified = await oidc.verifyAccessToken(token, options.audience);
571
+ if (Result.isFailure(verified))
572
+ return verified;
573
+ const claims = verified.value;
574
+ if (typeof claims.sub !== "string" || claims.sub.length === 0) {
575
+ const error = { type: "access_token_invalid", reason: "missing_sub" };
576
+ return Result.fail(error);
577
+ }
578
+ return Result.succeed({
579
+ sub: claims.sub,
580
+ scope: typeof claims.scope === "string" ? claims.scope : "",
581
+ ...(typeof claims.client_id === "string" ? { clientId: claims.client_id } : {}),
582
+ ...(typeof claims.exp === "number" ? { expiresAt: claims.exp } : {}),
583
+ claims,
584
+ });
585
+ };
586
+ };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Session shapes.
3
+ *
4
+ * `SessionPayloadV1` is the sealed cookie content (internal — carries the
5
+ * access/refresh tokens). `Session` is the public view handed to application
6
+ * code: it deliberately omits the refresh token and the raw ID token so the
7
+ * SDK's public surface cannot leak long-lived credentials into UI code
8
+ * (design.md §32.2 "UIへsecretを埋め込まない").
9
+ *
10
+ * The payload guard is hand-rolled (no zod in this package — the dependency
11
+ * budget is fixed) and validates every field after unsealing; anything that
12
+ * does not conform is treated as an invalid cookie and fails closed.
13
+ */
14
+ export interface SessionUser {
15
+ readonly sub: string;
16
+ readonly name?: string;
17
+ readonly email?: string;
18
+ readonly emailVerified?: boolean;
19
+ }
20
+ export interface Session {
21
+ readonly user: SessionUser;
22
+ readonly accessToken: string;
23
+ /** Epoch seconds at which the access token expires. */
24
+ readonly accessTokenExpiresAt: number;
25
+ readonly scope: string;
26
+ /** Epoch seconds at which the BFF session itself expires. */
27
+ readonly sessionExpiresAt: number;
28
+ }
29
+ export interface SessionPayloadV1 {
30
+ readonly v: 1;
31
+ readonly user: SessionUser;
32
+ readonly accessToken: string;
33
+ readonly accessTokenExpiresAt: number;
34
+ readonly refreshToken?: string;
35
+ readonly idToken?: string;
36
+ readonly scope: string;
37
+ readonly createdAt: number;
38
+ readonly expiresAt: number;
39
+ }
40
+ export declare const isSessionPayload: (value: unknown) => value is SessionPayloadV1;
41
+ /** Strips long-lived credentials before the session reaches application code. */
42
+ export declare const toPublicSession: (payload: SessionPayloadV1) => Session;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Session shapes.
3
+ *
4
+ * `SessionPayloadV1` is the sealed cookie content (internal — carries the
5
+ * access/refresh tokens). `Session` is the public view handed to application
6
+ * code: it deliberately omits the refresh token and the raw ID token so the
7
+ * SDK's public surface cannot leak long-lived credentials into UI code
8
+ * (design.md §32.2 "UIへsecretを埋め込まない").
9
+ *
10
+ * The payload guard is hand-rolled (no zod in this package — the dependency
11
+ * budget is fixed) and validates every field after unsealing; anything that
12
+ * does not conform is treated as an invalid cookie and fails closed.
13
+ */
14
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
15
+ const isSessionUser = (value) => {
16
+ if (!isRecord(value))
17
+ return false;
18
+ if (typeof value.sub !== "string" || value.sub.length === 0)
19
+ return false;
20
+ if (value.name !== undefined && typeof value.name !== "string")
21
+ return false;
22
+ if (value.email !== undefined && typeof value.email !== "string")
23
+ return false;
24
+ if (value.emailVerified !== undefined && typeof value.emailVerified !== "boolean")
25
+ return false;
26
+ return true;
27
+ };
28
+ export const isSessionPayload = (value) => {
29
+ if (!isRecord(value))
30
+ return false;
31
+ if (value.v !== 1)
32
+ return false;
33
+ if (!isSessionUser(value.user))
34
+ return false;
35
+ if (typeof value.accessToken !== "string" || value.accessToken.length === 0)
36
+ return false;
37
+ if (typeof value.accessTokenExpiresAt !== "number")
38
+ return false;
39
+ if (typeof value.scope !== "string")
40
+ return false;
41
+ if (typeof value.createdAt !== "number" || typeof value.expiresAt !== "number")
42
+ return false;
43
+ if (value.refreshToken !== undefined && typeof value.refreshToken !== "string")
44
+ return false;
45
+ if (value.idToken !== undefined && typeof value.idToken !== "string")
46
+ return false;
47
+ return true;
48
+ };
49
+ /** Strips long-lived credentials before the session reaches application code. */
50
+ export const toPublicSession = (payload) => ({
51
+ user: payload.user,
52
+ accessToken: payload.accessToken,
53
+ accessTokenExpiresAt: payload.accessTokenExpiresAt,
54
+ scope: payload.scope,
55
+ sessionExpiresAt: payload.expiresAt,
56
+ });