@shware/security 9.1.0 → 9.2.1
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.
- package/README.md +41 -6
- package/dist/auth/index.cjs +101 -23
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +7 -1
- package/dist/auth/index.d.cts.map +1 -1
- package/dist/auth/index.d.mts +7 -1
- package/dist/auth/index.d.mts.map +1 -1
- package/dist/auth/index.mjs +102 -24
- package/dist/auth/index.mjs.map +1 -1
- package/dist/auth/types.d.cts +11 -0
- package/dist/auth/types.d.cts.map +1 -1
- package/dist/auth/types.d.mts +11 -0
- package/dist/auth/types.d.mts.map +1 -1
- package/dist/oauth2/provider/apple.cjs +1 -1
- package/dist/oauth2/provider/apple.cjs.map +1 -1
- package/dist/oauth2/provider/apple.d.cts.map +1 -1
- package/dist/oauth2/provider/apple.d.mts.map +1 -1
- package/dist/oauth2/provider/apple.mjs +1 -1
- package/dist/oauth2/provider/apple.mjs.map +1 -1
- package/dist/oauth2/provider/google.cjs +1 -1
- package/dist/oauth2/provider/google.cjs.map +1 -1
- package/dist/oauth2/provider/google.d.cts.map +1 -1
- package/dist/oauth2/provider/google.d.mts.map +1 -1
- package/dist/oauth2/provider/google.mjs +1 -1
- package/dist/oauth2/provider/google.mjs.map +1 -1
- package/dist/oauth2/types.cjs.map +1 -1
- package/dist/oauth2/types.d.cts +2 -0
- package/dist/oauth2/types.d.cts.map +1 -1
- package/dist/oauth2/types.d.mts +2 -0
- package/dist/oauth2/types.d.mts.map +1 -1
- package/dist/oauth2/types.mjs.map +1 -1
- package/package.json +2 -2
package/dist/auth/index.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { DesktopCodes } from "./desktop-codes.mjs";
|
|
|
12
12
|
import { EmailVerificationCodes } from "./email-codes.mjs";
|
|
13
13
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
14
14
|
import { invariant } from "@shware/utils";
|
|
15
|
-
import { extend, literal, object, regex, string } from "zod/mini";
|
|
15
|
+
import { custom, extend, literal, object, optional, regex, string } from "zod/mini";
|
|
16
16
|
// src/auth/index.ts
|
|
17
17
|
const PKCE_FORMAT = /^[A-Za-z0-9_-]{43,128}$/;
|
|
18
18
|
const CODE_VERIFIER_FORMAT = /^[A-Za-z0-9._~-]{43,128}$/;
|
|
@@ -20,7 +20,6 @@ const CODE_VERIFIER_FORMAT = /^[A-Za-z0-9._~-]{43,128}$/;
|
|
|
20
20
|
const SESSION_HEADER = "X-Auth-Token";
|
|
21
21
|
/** Seconds an OAuth2 state or nonce may be used within. */
|
|
22
22
|
const OAUTH2_PARAMETER_TTL = 600;
|
|
23
|
-
const MAX_ERROR_DESCRIPTION_LENGTH = 256;
|
|
24
23
|
/** An error code safe to put on errorUri: a registered one as is, anything else as `fallback`. */
|
|
25
24
|
function safeErrorType(error, fallback) {
|
|
26
25
|
return isKnownOAuth2ErrorType(error) ? error : fallback;
|
|
@@ -36,20 +35,67 @@ const CALLBACK_ERROR_TYPES = /* @__PURE__ */ new Set([
|
|
|
36
35
|
"access_denied",
|
|
37
36
|
"temporarily_unavailable"
|
|
38
37
|
]);
|
|
39
|
-
|
|
38
|
+
/**
|
|
39
|
+
* The host's values for the flow (`attributes`, `redirectParams`), `undefined` ones dropped; `name`
|
|
40
|
+
* is what the size invariant calls them.
|
|
41
|
+
*/
|
|
42
|
+
function authorizationAttributes(attributes, name = "attributes") {
|
|
40
43
|
if (!attributes) return void 0;
|
|
41
44
|
const defined = {};
|
|
42
45
|
for (const [key, value] of Object.entries(attributes)) if (value !== void 0) defined[key] = value;
|
|
43
46
|
if (Object.keys(defined).length === 0) return void 0;
|
|
44
47
|
const size = attributesSize(defined);
|
|
45
|
-
invariant(size <= MAX_ATTRIBUTES_BYTES, `oauth2 authorization
|
|
48
|
+
invariant(size <= MAX_ATTRIBUTES_BYTES, `oauth2 authorization ${name} are ${size} bytes, at most ${MAX_ATTRIBUTES_BYTES} allowed`);
|
|
46
49
|
return defined;
|
|
47
50
|
}
|
|
51
|
+
/**
|
|
52
|
+
* What the callback's redirects say themselves. A host's `redirectParams` never carry these, even
|
|
53
|
+
* on a redirect that leaves one out (a cancel has no `reason`): the page would read it as the SDK's.
|
|
54
|
+
*/
|
|
55
|
+
const REDIRECT_PARAMS = /* @__PURE__ */ new Set([
|
|
56
|
+
"status",
|
|
57
|
+
"provider",
|
|
58
|
+
"error",
|
|
59
|
+
"reason"
|
|
60
|
+
]);
|
|
61
|
+
/** The host's `redirectParams` without the names the redirects keep for themselves. */
|
|
62
|
+
function redirectParams(params) {
|
|
63
|
+
if (!params) return void 0;
|
|
64
|
+
const own = Object.entries(params).filter(([key]) => !REDIRECT_PARAMS.has(key));
|
|
65
|
+
return authorizationAttributes(Object.fromEntries(own), "redirectParams");
|
|
66
|
+
}
|
|
67
|
+
/** `base` with `params` added, none replacing one it carries itself. */
|
|
68
|
+
function withParams(base, params = {}) {
|
|
69
|
+
const uri = new URL(base);
|
|
70
|
+
for (const [key, value] of Object.entries(params)) if (!uri.searchParams.has(key)) uri.searchParams.set(key, value);
|
|
71
|
+
return uri;
|
|
72
|
+
}
|
|
48
73
|
/** Sign in with Apple answers with `response_mode=form_post`; a charset parameter may follow. */
|
|
49
74
|
function isFormPost(request) {
|
|
50
75
|
const contentType = request.headers.get("content-type")?.toLowerCase();
|
|
51
76
|
return request.method === "POST" && !!contentType?.startsWith("application/x-www-form-urlencoded");
|
|
52
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* The platform's name object as the app posts it (iOS `PersonNameComponents`): any object, since
|
|
80
|
+
* the provider cleans each part itself and ignores what is not a string.
|
|
81
|
+
*/
|
|
82
|
+
const personNameSchema = custom((value) => typeof value === "object" && value !== null && !Array.isArray(value));
|
|
83
|
+
/**
|
|
84
|
+
* A native login body (`NativeCredential`): each protocol parameter a string when present. Which
|
|
85
|
+
* ones a provider needs is its own check (a missing `code` is an `OAuth2Error` `invalid_request`);
|
|
86
|
+
* `code_verifier`'s format has its own reason (`INVALID_CODE_VERIFIER`) and `attributes` their own
|
|
87
|
+
* schema, so neither is checked here.
|
|
88
|
+
*/
|
|
89
|
+
const nativeCredentialSchema = object({
|
|
90
|
+
state: optional(string()),
|
|
91
|
+
code: optional(string()),
|
|
92
|
+
client_id: optional(string()),
|
|
93
|
+
redirect_uri: optional(string()),
|
|
94
|
+
code_verifier: optional(string()),
|
|
95
|
+
id_token: optional(string()),
|
|
96
|
+
access_token: optional(string()),
|
|
97
|
+
fullName: optional(personNameSchema)
|
|
98
|
+
});
|
|
53
99
|
/** Google's own form post carries no attributes; an app posting JSON may add them. */
|
|
54
100
|
const oneTapBodySchema = extend(googleOneTapSchema, { attributes: attributesSchema });
|
|
55
101
|
const desktopAuthorizeSchema = object({
|
|
@@ -185,13 +231,21 @@ var Auth = class {
|
|
|
185
231
|
throw error;
|
|
186
232
|
}
|
|
187
233
|
}
|
|
188
|
-
/**
|
|
189
|
-
|
|
234
|
+
/**
|
|
235
|
+
* The error redirect of the callback flow: `refusal`'s reason and metadata ride along, and the
|
|
236
|
+
* flow's `redirectParams` once its authorization request is known. `detail` (a failed validation,
|
|
237
|
+
* the provider's `error_description`) is logged, not forwarded: the page shows a message per
|
|
238
|
+
* `error` code and never the text, so a URL the browser keeps in its history has no use for it,
|
|
239
|
+
* and a forged callback could set it to anything.
|
|
240
|
+
*/
|
|
241
|
+
redirect(error, { detail, refusal, params } = {}) {
|
|
190
242
|
invariant(this.oauth2Client, "oauth2Client is not initialized");
|
|
191
|
-
|
|
192
|
-
|
|
243
|
+
if (detail) console.warn(`OAuth2 callback failed: ${error}`, detail);
|
|
244
|
+
const uri = withParams(this.oauth2Client.errorUri, {
|
|
245
|
+
...params,
|
|
246
|
+
...refusal?.metadata
|
|
247
|
+
});
|
|
193
248
|
uri.searchParams.set("error", error);
|
|
194
|
-
if (description) uri.searchParams.set("error_description", description.slice(0, MAX_ERROR_DESCRIPTION_LENGTH));
|
|
195
249
|
if (refusal) uri.searchParams.set("reason", refusal.reason);
|
|
196
250
|
return Response.redirect(uri.href, 302);
|
|
197
251
|
}
|
|
@@ -292,6 +346,7 @@ var Auth = class {
|
|
|
292
346
|
oauth2Authorization = (request, options) => this.guard(async () => {
|
|
293
347
|
invariant(this.oauth2Client, "oauth2Client is not initialized");
|
|
294
348
|
const attributes = authorizationAttributes(options?.attributes);
|
|
349
|
+
const params = redirectParams(options?.redirectParams);
|
|
295
350
|
const { mark, setTiming } = timing({ enabled: this.timing });
|
|
296
351
|
const { provider } = param(request, PATH.OAUTH2_AUTHORIZATION);
|
|
297
352
|
const state = randomUUID();
|
|
@@ -315,7 +370,8 @@ var Auth = class {
|
|
|
315
370
|
authorizationRequestUri: uri.href,
|
|
316
371
|
additionalParameters: pkce,
|
|
317
372
|
...nonce ? { nonce } : {},
|
|
318
|
-
...attributes ? { attributes } : {}
|
|
373
|
+
...attributes ? { attributes } : {},
|
|
374
|
+
...params ? { redirectParams: params } : {}
|
|
319
375
|
};
|
|
320
376
|
session.setAttribute(this.ATTR_OAUTH2_AUTHORIZATION_REQUEST, JSON.stringify(authorizationRequest));
|
|
321
377
|
await this.repository.save(session);
|
|
@@ -331,23 +387,42 @@ var Auth = class {
|
|
|
331
387
|
invariant(this.oauth2Client, "oauth2Client is not initialized");
|
|
332
388
|
const { mark, setTiming } = timing({ enabled: this.timing });
|
|
333
389
|
const session = await this.loadSession(request);
|
|
334
|
-
if (!session) return this.redirect("invalid_request", "session not found");
|
|
390
|
+
if (!session) return this.redirect("invalid_request", { detail: "session not found" });
|
|
335
391
|
mark("load_session");
|
|
336
392
|
const json = session.getAttribute(this.ATTR_OAUTH2_AUTHORIZATION_REQUEST);
|
|
337
|
-
if (!json) return this.redirect("invalid_request", "authorization request not found");
|
|
393
|
+
if (!json) return this.redirect("invalid_request", { detail: "authorization request not found" });
|
|
338
394
|
const cached = JSON.parse(json);
|
|
395
|
+
const params = cached.redirectParams;
|
|
339
396
|
const { provider } = param(request, PATH.LOGIN_OAUTH2_CODE);
|
|
340
397
|
const data = isFormPost(request) ? Object.fromEntries(new URLSearchParams(await request.text())) : query(request);
|
|
341
398
|
const parsed = oauth2RedirectQuerySchema.safeParse(data);
|
|
342
|
-
if (!parsed.success) return this.redirect("invalid_request",
|
|
399
|
+
if (!parsed.success) return this.redirect("invalid_request", {
|
|
400
|
+
detail: "invalid redirect query",
|
|
401
|
+
params
|
|
402
|
+
});
|
|
343
403
|
if (parsed.data.error) {
|
|
344
|
-
if (parsed.data.state && parsed.data.state !== cached.state) return this.redirect("invalid_request",
|
|
345
|
-
|
|
404
|
+
if (parsed.data.state && parsed.data.state !== cached.state) return this.redirect("invalid_request", {
|
|
405
|
+
detail: "redirect state mismatch",
|
|
406
|
+
params
|
|
407
|
+
});
|
|
408
|
+
return this.redirect(safeErrorType(parsed.data.error, "server_error"), {
|
|
409
|
+
detail: parsed.data.error_description,
|
|
410
|
+
params
|
|
411
|
+
});
|
|
346
412
|
}
|
|
347
413
|
const { code, state, user } = parsed.data;
|
|
348
|
-
if (!code || !state) return this.redirect("invalid_request",
|
|
349
|
-
|
|
350
|
-
|
|
414
|
+
if (!code || !state) return this.redirect("invalid_request", {
|
|
415
|
+
detail: "invalid redirect query",
|
|
416
|
+
params
|
|
417
|
+
});
|
|
418
|
+
if (state !== cached.state) return this.redirect("invalid_request", {
|
|
419
|
+
detail: "redirect state mismatch",
|
|
420
|
+
params
|
|
421
|
+
});
|
|
422
|
+
if (provider !== cached.provider) return this.redirect("invalid_request", {
|
|
423
|
+
detail: "redirect provider mismatch",
|
|
424
|
+
params
|
|
425
|
+
});
|
|
351
426
|
mark("validate_session");
|
|
352
427
|
let signedIn;
|
|
353
428
|
try {
|
|
@@ -384,16 +459,19 @@ var Auth = class {
|
|
|
384
459
|
if (error instanceof OAuth2Error) {
|
|
385
460
|
console.warn("OAuth2 callback failed", error);
|
|
386
461
|
const type = CALLBACK_ERROR_TYPES.has(error.error) ? error.error : "server_error";
|
|
387
|
-
return this.redirect(type);
|
|
462
|
+
return this.redirect(type, { params });
|
|
388
463
|
}
|
|
389
464
|
if (error instanceof AuthenticationError) {
|
|
390
465
|
console.warn("OAuth2 sign-in refused", error.reason, error.metadata);
|
|
391
|
-
return this.redirect("access_denied",
|
|
466
|
+
return this.redirect("access_denied", {
|
|
467
|
+
refusal: error,
|
|
468
|
+
params
|
|
469
|
+
});
|
|
392
470
|
}
|
|
393
471
|
console.error("OAuth2 callback failed", error);
|
|
394
|
-
return this.redirect("server_error");
|
|
472
|
+
return this.redirect("server_error", { params });
|
|
395
473
|
}
|
|
396
|
-
const uri =
|
|
474
|
+
const uri = withParams(this.oauth2Client.successUri, params);
|
|
397
475
|
uri.searchParams.set("status", "success");
|
|
398
476
|
uri.searchParams.set("provider", provider);
|
|
399
477
|
const response = new Response(null, {
|
|
@@ -417,9 +495,9 @@ var Auth = class {
|
|
|
417
495
|
const { provider } = param(request, PATH.LOGIN_OAUTH2_NATIVE);
|
|
418
496
|
const body = await readJson(request);
|
|
419
497
|
const attributes = bodyAttributes(body);
|
|
420
|
-
const
|
|
498
|
+
const credentials = parse(nativeCredentialSchema, body);
|
|
421
499
|
const { code_verifier } = credentials;
|
|
422
|
-
if (code_verifier !== void 0 &&
|
|
500
|
+
if (code_verifier !== void 0 && !CODE_VERIFIER_FORMAT.test(code_verifier)) throw invalidArgument("INVALID_CODE_VERIFIER", "code_verifier must be 43-128 characters from [A-Za-z0-9-._~]");
|
|
423
501
|
const { clientId, userInfo, token } = await this.oauth2Client.loginOAuth2Native({
|
|
424
502
|
provider,
|
|
425
503
|
credentials
|
package/dist/auth/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/auth/index.ts"],"sourcesContent":["import { createHash, randomBytes, randomUUID } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { extend, literal, object, regex, string } from 'zod/mini';\nimport type { Principal } from '../core/index';\nimport { loginEmailSchema, sendEmailVerificationCodeSchema } from '../email/schema';\nimport { OAuth2Client, googleOneTapSchema, oauth2RedirectQuerySchema } from '../oauth2/client';\nimport { OAuth2Error, type OAuth2ErrorType, isKnownOAuth2ErrorType } from '../oauth2/error';\nimport type {\n NativeCredential,\n OAuth2AuthorizationRequest,\n PkceParameters,\n StandardClaims,\n} from '../oauth2/types';\nimport { PRINCIPAL_NAME_INDEX_NAME } from '../session/common';\nimport type { KVRepository, Session, SessionRepository } from '../session/types';\nimport {\n type CookieOptions,\n deleteCookie,\n getCookie,\n param,\n query,\n setCookie,\n} from '../utils/http';\nimport { timing } from '../utils/timing';\nimport { parse, readForm, readJson, verifyTurnstileToken } from '../utils/valid';\nimport {\n MAX_ATTRIBUTES_BYTES,\n attributesSchema,\n attributesSize,\n bodyAttributes,\n} from './attributes';\nimport { DesktopCodes } from './desktop-codes';\nimport { type EmailSender, EmailVerificationCodes } from './email-codes';\nimport { AuthenticationError } from './error';\nimport { errorResponse, invalidArgument, unauthenticated } from './respond';\nimport type {\n AuthConfig,\n AuthService,\n Authorization,\n AuthorizedHandler,\n LoggedHandler,\n LogoutOptions,\n OAuth2AuthorizationOptions,\n} from './types';\n\n// PKCE per RFC 7636: code_verifier / code_challenge are 43-128 chars from\n// the unreserved set. We restrict to base64url (drops \".\" and \"~\") since\n// that's what S256 produces and what callers should be sending; rejecting\n// the rest shrinks the accepted input shape without losing legit clients.\n// A 32-byte random verifier base64url-encodes to exactly 43 chars.\nconst PKCE_FORMAT = /^[A-Za-z0-9_-]{43,128}$/;\n\n// A native app's `code_verifier` goes on to the provider, which checks it against the challenge\n// the app sent: accept the whole RFC 7636 unreserved set here, as the provider does.\nconst CODE_VERIFIER_FORMAT = /^[A-Za-z0-9._~-]{43,128}$/;\n\n/** The header a session id travels in besides the cookie, with `session.header` on. */\nconst SESSION_HEADER = 'X-Auth-Token';\n\n/** Seconds an OAuth2 state or nonce may be used within. */\nconst OAUTH2_PARAMETER_TTL = 10 * 60;\n\n// error_description forwarded to errorUri comes from the provider or an error message: cap it so\n// the redirect URL stays short and an attacker-crafted callback cannot stuff the page with text.\nconst MAX_ERROR_DESCRIPTION_LENGTH = 256;\n\n/** An error code safe to put on errorUri: a registered one as is, anything else as `fallback`. */\nfunction safeErrorType(error: string, fallback: OAuth2ErrorType): OAuth2ErrorType {\n return isKnownOAuth2ErrorType(error) ? error : fallback;\n}\n\n/**\n * The codes a failure past validation keeps on errorUri, each one the user can act on: the code\n * expired or was used (start again), they declined, or the provider is briefly down. Every other\n * failure there (a rejected client, a user info request that failed) is the app's or the\n * provider's problem, which the user sees as `server_error`.\n */\nconst CALLBACK_ERROR_TYPES: ReadonlySet<OAuth2ErrorType> = new Set([\n 'invalid_grant',\n 'access_denied',\n 'temporarily_unavailable',\n]);\n\nfunction authorizationAttributes(\n attributes: OAuth2AuthorizationOptions['attributes']\n): Record<string, string> | undefined {\n if (!attributes) return undefined;\n const defined: Record<string, string> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) defined[key] = value;\n }\n if (Object.keys(defined).length === 0) return undefined;\n // The host's own values, written with the session: oversized is a bug in the host, not a 400.\n const size = attributesSize(defined);\n invariant(\n size <= MAX_ATTRIBUTES_BYTES,\n `oauth2 authorization attributes are ${size} bytes, at most ${MAX_ATTRIBUTES_BYTES} allowed`\n );\n return defined;\n}\n\n/** Sign in with Apple answers with `response_mode=form_post`; a charset parameter may follow. */\nfunction isFormPost(request: Request) {\n const contentType = request.headers.get('content-type')?.toLowerCase();\n return (\n request.method === 'POST' && !!contentType?.startsWith('application/x-www-form-urlencoded')\n );\n}\n\n/** Google's own form post carries no attributes; an app posting JSON may add them. */\nconst oneTapBodySchema = extend(googleOneTapSchema, { attributes: attributesSchema });\n\nconst desktopAuthorizeSchema = object({\n code_challenge: string().check(regex(PKCE_FORMAT)),\n code_challenge_method: literal('S256'),\n});\n\nconst desktopExchangeSchema = object({\n code: string(),\n code_verifier: string().check(regex(PKCE_FORMAT)),\n});\n\nexport const PATH = {\n CSRF: '/csrf',\n LOGOUT: '/logout',\n LOGGED: '/logged',\n\n OAUTH2_STATE: '/oauth2/state/:provider',\n OAUTH2_NONCE: '/oauth2/nonce/:provider',\n OAUTH2_AUTHORIZATION: '/oauth2/authorization/:provider',\n LOGIN_OAUTH2_CODE: '/login/oauth2/code/:provider',\n LOGIN_OAUTH2_NATIVE: '/login/oauth2/native/:provider',\n LOGIN_OAUTH2_ONETAP: '/login/oauth2/onetap/google',\n\n LOGIN_EMAIL: '/login/email',\n SEND_EMAIL_VERIFICATION_CODE: '/auth/sendEmailVerificationCode',\n\n // Desktop / native app sign-in via web loopback (RFC 8252 + OAuth 2.1 Auth Code Flow):\n // 1. user already authenticated with cookie session → POST DESKTOP_AUTHORIZE → { code }\n // 2. web redirects to desktop's loopback callback with the code\n // 3. desktop renderer POSTs DESKTOP_EXCHANGE with the code → server returns\n // Set-Cookie carrying a fresh session, single-use code is invalidated\n // The two-step flow keeps the actual session id off the redirect URL — only a\n // 5-minute single-use code transits via the loopback.\n DESKTOP_AUTHORIZE: '/auth/desktop/authorize',\n DESKTOP_EXCHANGE: '/auth/desktop/exchange',\n\n CLEANUP_EXPIRED_SESSIONS: '/sessions/expired/cleanup',\n} as const;\n\n/**\n * The login routes and session helpers. Every route is one straight line: read and validate the\n * request, check the credential, call the host's `onAuthorized`, sign in. Failures are thrown and\n * answered in one place per kind of route: a JSON route runs under `guard`, which maps a\n * `RequestError`, an `AuthenticationError` or an `OAuth2Error` to its google.rpc body (see\n * `respond.ts`); the redirect callback maps the same errors to `errorUri` parameters (`redirect`).\n */\nexport class Auth implements AuthService {\n private readonly timing: boolean;\n private readonly cookieName;\n private readonly cookieOptions: CookieOptions;\n private readonly kv: KVRepository;\n private readonly repository: SessionRepository;\n private readonly turnstileSecretKey?: string;\n private readonly emailCodes: EmailVerificationCodes;\n private readonly desktopCodes: DesktopCodes;\n private readonly oauth2Client: OAuth2Client | null;\n /** Provider keys whose logins may come without a nonce (`oauth2.nonce.optional`). */\n private readonly nonceOptional: ReadonlySet<string>;\n private readonly touchInterval: number;\n private readonly sessionHeader: boolean;\n private readonly ATTR_OAUTH2_AUTHORIZATION_REQUEST = 'oauth2AuthorizationRequest';\n\n constructor({\n sessionRepository,\n kvRepository,\n turnstileSecretKey,\n verificationCode,\n oauth2,\n cookie,\n session,\n timing,\n }: AuthConfig) {\n this.timing = timing ?? false;\n this.kv = kvRepository;\n this.repository = sessionRepository;\n this.turnstileSecretKey = turnstileSecretKey;\n const maxAttempts = verificationCode?.maxAttempts ?? 5;\n const resendCooldown = verificationCode?.resendCooldown ?? 60;\n invariant(maxAttempts >= 1, 'verificationCode.maxAttempts must be at least 1');\n invariant(resendCooldown >= 1, 'verificationCode.resendCooldown must be at least 1 second');\n this.emailCodes = new EmailVerificationCodes(kvRepository, { maxAttempts, resendCooldown });\n this.desktopCodes = new DesktopCodes(kvRepository);\n const { name, ...cookieOptions } = cookie ?? {};\n this.cookieName = name ?? 'SESSION';\n this.cookieOptions = {\n path: '/',\n sameSite: 'none',\n secure: true,\n httpOnly: true,\n ...cookieOptions,\n };\n this.oauth2Client = oauth2?.client ? new OAuth2Client(oauth2.client) : null;\n this.nonceOptional = new Set(oauth2?.nonce?.optional);\n this.touchInterval = (session?.touchInterval ?? 3600) * 1000;\n this.sessionHeader = session?.header ?? false;\n invariant(this.touchInterval >= 0, 'session.touchInterval must not be negative');\n }\n\n // ---- sessions and responses ------------------------------------------------------------------\n\n private getSessionId(request: Request): string | undefined {\n const fromCookie = getCookie(request, this.cookieName);\n if (fromCookie) return fromCookie;\n return (this.sessionHeader && request.headers.get(SESSION_HEADER)) || undefined;\n }\n\n /** The session the request carries, if it exists. */\n private async loadSession(request: Request): Promise<Session | null> {\n const sessionId = this.getSessionId(request);\n return sessionId ? this.repository.findById(sessionId) : null;\n }\n\n /** The signed-in principal of a session, if any. */\n private principalOf(session: Session): Principal | null {\n const name = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);\n return name ? { name: String(name) } : null;\n }\n\n /**\n * A new session signed in as `principal`. With `carryOver`, what the host kept in the pre-login\n * session moves to the new one; the authorization request (state, PKCE verifier, flow\n * attributes) is single-use and was consumed, and a principal left there from an earlier\n * sign-in is replaced. The new id is never the one the browser brought, which may have been\n * planted by an attacker who started the flow (session fixation).\n */\n private async signIn(principal: Principal, carryOver?: Session): Promise<Session> {\n const session = this.repository.createSession();\n for (const attribute of carryOver?.getAttributeNames() ?? []) {\n if (attribute === this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) continue;\n if (attribute === PRINCIPAL_NAME_INDEX_NAME) continue;\n const value = carryOver?.getAttribute(attribute);\n if (value !== null && value !== undefined) session.setAttribute(attribute, value);\n }\n session.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principal.name);\n await this.repository.save(session);\n return session;\n }\n\n /**\n * `response` carrying `session`: its cookie, renewed for the whole inactive interval, and with\n * `session.header` on, the `X-Auth-Token` header a client without a cookie jar reads.\n */\n private withSession(response: Response, session: Session, cookie?: CookieOptions): Response {\n const maxAge = session.getMaxInactiveInterval();\n setCookie(response, this.cookieName, session.getId(), {\n ...this.cookieOptions,\n ...cookie,\n maxAge,\n });\n if (this.sessionHeader) response.headers.set(SESSION_HEADER, session.getId());\n return response;\n }\n\n /** Runs a JSON route: a failure it knows is its response, anything else is the host's. */\n private async guard(run: () => Promise<Response>): Promise<Response> {\n try {\n return await run();\n } catch (error) {\n const response = errorResponse(error);\n if (response) return response;\n throw error;\n }\n }\n\n /** The error redirect of the callback flow; `refusal`'s reason and metadata ride along. */\n private redirect(\n error: OAuth2ErrorType,\n description?: string,\n refusal?: AuthenticationError\n ): Response {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const uri = new URL(this.oauth2Client.errorUri);\n // Metadata never replaces a parameter: not one errorUri carries itself, nor one set below.\n for (const [key, value] of Object.entries(refusal?.metadata ?? {})) {\n if (!uri.searchParams.has(key)) uri.searchParams.set(key, value);\n }\n uri.searchParams.set('error', error);\n if (description) {\n uri.searchParams.set('error_description', description.slice(0, MAX_ERROR_DESCRIPTION_LENGTH));\n }\n if (refusal) uri.searchParams.set('reason', refusal.reason);\n return Response.redirect(uri.href, 302);\n }\n\n // ---- basic -----------------------------------------------------------------------------------\n\n csrf = async (_request: Request): Promise<Response> => {\n const token = randomUUID();\n const response = Response.json({\n token,\n parameterName: '_csrf',\n headerName: 'X-XSRF-TOKEN',\n });\n\n // Double Submit Cookie Protection\n setCookie(response, 'XSRF-TOKEN', token, {\n path: '/',\n secure: true,\n httpOnly: false,\n sameSite: 'none',\n domain: this.cookieOptions.domain,\n });\n return response;\n };\n\n logout = async (request: Request, options?: LogoutOptions): Promise<Response> => {\n const scope = options?.scope ?? 'local';\n const sessionId = this.getSessionId(request);\n // `global` and `others` reach the principal's other sessions through the one the request\n // carries; a request without a signed-in session has no principal to widen to, and ends as\n // `local` would.\n if (scope !== 'local' && sessionId) {\n const session = await this.repository.findById(sessionId);\n const principal = session && this.principalOf(session);\n if (principal) {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n for (const id of sessions.keys()) {\n if (id !== sessionId) await this.repository.deleteById(id);\n }\n }\n }\n const response = Response.json({});\n if (scope === 'others') return response;\n if (sessionId) await this.repository.deleteById(sessionId);\n // A Set-Cookie only replaces the stored cookie when Domain and Path match (RFC 6265),\n // so clear it with the same attributes it was set with.\n deleteCookie(response, this.cookieName, this.cookieOptions);\n return response;\n };\n\n logged = async (request: Request, onLogged?: LoggedHandler): Promise<Response> => {\n const session = await this.loadSession(request);\n if (!session) return Response.json({ data: false });\n\n session.setLastAccessedTime(Date.now());\n await this.repository.save(session);\n\n const principal = this.principalOf(session);\n if (principal) await onLogged?.(principal);\n return this.withSession(Response.json({ data: principal !== null }), session);\n };\n\n // ---- oauth2 ----------------------------------------------------------------------------------\n\n private createPkceParameters(): PkceParameters {\n // 32 random bytes: a 43-char base64url verifier, the RFC 7636 minimum (a UUID is 36).\n const code_verifier = randomBytes(32).toString('base64url');\n const code_challenge = createHash('sha256')\n .update(code_verifier)\n .digest()\n .toString('base64url');\n\n return { code_verifier, code_challenge, code_challenge_method: 'S256' };\n }\n\n private getOauth2StateKey(state: string) {\n return `oauth2:state:${state}`;\n }\n\n private getOauth2NonceKey(nonce: string) {\n return `oauth2:nonce:${nonce}`;\n }\n\n /**\n * Spends a nonce `oauth2Nonce` issued for `provider`: `NONCE_MISMATCH` for one that was not,\n * or was used already. An id token is replayable until it expires; the nonce it carries makes\n * it sign in once.\n */\n private async consumeNonce(nonce: string, provider: string): Promise<void> {\n const key = this.getOauth2NonceKey(nonce);\n if ((await this.kv.getItem(key)) !== provider) throw new AuthenticationError('NONCE_MISMATCH');\n await this.kv.removeItem(key);\n }\n\n /**\n * The nonce check of the JSON logins (One Tap, native), where the client obtained the id token\n * and the nonce came from `oauth2Nonce`: spends the one the token carries, and refuses a token\n * without one when the provider's flow echoes nonces (`required`) and the host has not listed the\n * provider as optional. An id token is replayable until it expires; the nonce makes it sign in\n * once.\n */\n private async checkIssuedNonce(\n userInfo: Authorization['userInfo'],\n provider: string,\n required: boolean\n ): Promise<boolean> {\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce === 'string' && nonce) {\n await this.consumeNonce(nonce, provider);\n return true;\n }\n if (required && !this.nonceOptional.has(provider)) {\n throw new AuthenticationError('NONCE_MISSING');\n }\n return false;\n }\n\n oauth2State = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_STATE);\n const state = randomUUID();\n await this.kv.setItem(this.getOauth2StateKey(state), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ state });\n };\n\n oauth2Nonce = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_NONCE);\n const nonce = randomUUID();\n await this.kv.setItem(this.getOauth2NonceKey(nonce), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ nonce });\n };\n\n oauth2Authorization = (\n request: Request,\n options?: OAuth2AuthorizationOptions\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const attributes = authorizationAttributes(options?.attributes);\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.OAUTH2_AUTHORIZATION);\n const state = randomUUID();\n const pkce = this.createPkceParameters();\n // Sent only to a provider whose id token echoes it: the callback then requires it back, so\n // a code that was swapped in for another sign-in's yields a token the session refuses.\n const nonce = (await this.oauth2Client.nonceSupport(provider)).web ? randomUUID() : undefined;\n const uri = await this.oauth2Client.createAuthorizationUri({ provider, state, pkce, nonce });\n let session = await this.loadSession(request);\n if (!session) {\n // A session made for the flow only has to outlive the state: an abandoned flow must not\n // keep a row for the default interval. Sign-in moves to a new session, with the default.\n session = this.repository.createSession();\n session.setMaxInactiveInterval(OAUTH2_PARAMETER_TTL);\n }\n mark('fetch_session');\n\n const authorizationRequest: OAuth2AuthorizationRequest = {\n state,\n provider,\n authorizationRequestUri: uri.href,\n additionalParameters: pkce,\n ...(nonce ? { nonce } : {}),\n ...(attributes ? { attributes } : {}),\n };\n session.setAttribute(\n this.ATTR_OAUTH2_AUTHORIZATION_REQUEST,\n JSON.stringify(authorizationRequest)\n );\n await this.repository.save(session);\n mark('save_session');\n\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, session);\n });\n\n loginOAuth2Code = async (request: Request, handler: AuthorizedHandler): Promise<Response> => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // 1. the session the flow started on, and the authorization request it stored\n const session = await this.loadSession(request);\n if (!session) return this.redirect('invalid_request', 'session not found');\n mark('load_session');\n const json = session.getAttribute(this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) as string | null;\n if (!json) return this.redirect('invalid_request', 'authorization request not found');\n const cached: OAuth2AuthorizationRequest = JSON.parse(json);\n\n // 2. the provider's answer: query, or a form for Apple's response_mode=form_post\n const { provider } = param(request, PATH.LOGIN_OAUTH2_CODE);\n const data = isFormPost(request)\n ? Object.fromEntries(new URLSearchParams(await request.text()))\n : query(request);\n const parsed = oauth2RedirectQuerySchema.safeParse(data);\n if (!parsed.success) return this.redirect('invalid_request', 'invalid redirect query');\n // The provider answered with an error instead of a code (the user pressed Cancel →\n // access_denied, invalid_scope, server_error, ...). Forward it rather than reporting a\n // malformed query. This runs before the state check on purpose: providers echo state on\n // error responses, but not all reliably do, and a forged error callback can only make the\n // victim's popup show an error — nothing is exchanged or signed in. A present state that does\n // not match still wins, since that is the more accurate (and more alarming) diagnosis.\n if (parsed.data.error) {\n if (parsed.data.state && parsed.data.state !== cached.state) {\n return this.redirect('invalid_request', 'redirect state mismatch');\n }\n return this.redirect(\n safeErrorType(parsed.data.error, 'server_error'),\n parsed.data.error_description\n );\n }\n const { code, state, user } = parsed.data;\n if (!code || !state) return this.redirect('invalid_request', 'invalid redirect query');\n if (state !== cached.state) return this.redirect('invalid_request', 'redirect state mismatch');\n if (provider !== cached.provider) {\n return this.redirect('invalid_request', 'redirect provider mismatch');\n }\n mark('validate_session');\n\n // 3. exchange the code, load the user, sign in. Everything here can fail (an expired or reused\n // code, a network error, the host's handler or session store). The callback runs in a popup\n // the user is looking at, so every failure must land on errorUri, never as a JSON error.\n let signedIn: Session;\n try {\n const { clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code,\n pkce: cached.additionalParameters,\n });\n // Apple posts the user's name alongside the code, once: hand it to the provider with the token.\n const userInfo = await this.oauth2Client.getUserInfo({\n provider,\n clientId,\n token,\n response: user ? { user } : undefined,\n });\n mark('exchange_code');\n // The id token must carry the nonce this flow sent (stored with the state, not in KV: it\n // is bound to this session's request). A provider that gave no id token has nothing to\n // carry it, as has a request stored before nonces were sent.\n if (cached.nonce && token.id_token) {\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce !== 'string' || !nonce) throw new AuthenticationError('NONCE_MISSING');\n if (nonce !== cached.nonce) throw new AuthenticationError('NONCE_MISMATCH');\n mark('check_nonce');\n }\n\n const principal = await handler(request, {\n provider,\n clientId,\n userInfo,\n token,\n attributes: cached.attributes ?? {},\n });\n mark('save_principal');\n\n signedIn = await this.signIn(principal, session);\n await this.repository.deleteById(session.getId());\n mark('update_session');\n } catch (error) {\n // The details stay in the logs: an OAuth2Error message can carry a client id or a\n // provider's response, which has no place in a URL the browser keeps in its history.\n if (error instanceof OAuth2Error) {\n console.warn('OAuth2 callback failed', error);\n const type = CALLBACK_ERROR_TYPES.has(error.error) ? error.error : 'server_error';\n return this.redirect(type);\n }\n // A refusal is something the user can act on, so its reason and metadata reach the page,\n // as they reach a JSON client through the ErrorInfo.\n if (error instanceof AuthenticationError) {\n console.warn('OAuth2 sign-in refused', error.reason, error.metadata);\n return this.redirect('access_denied', undefined, error);\n }\n console.error('OAuth2 callback failed', error);\n return this.redirect('server_error');\n }\n\n const uri = new URL(this.oauth2Client.successUri);\n uri.searchParams.set('status', 'success');\n uri.searchParams.set('provider', provider);\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, signedIn);\n };\n\n /** The shared tail of the JSON login routes: the host's handler, then a signed-in session. */\n private async authorize(\n request: Request,\n handler: AuthorizedHandler,\n authorization: Authorization,\n setTiming: (response: Response) => void\n ): Promise<Response> {\n const principal = await handler(request, authorization);\n const session = await this.signIn(principal);\n const response = Response.json(principal);\n setTiming(response);\n return this.withSession(response, session);\n }\n\n loginOAuth2Native = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.LOGIN_OAUTH2_NATIVE);\n const body = await readJson(request);\n // Whatever the app sends besides its credentials for `onAuthorized` (a referral code, ...).\n const attributes = bodyAttributes(body);\n // Only the credentials go on to the provider client.\n const { attributes: _, ...credentials } = body as NativeCredential & { attributes?: unknown };\n const { code_verifier } = credentials as { code_verifier?: unknown };\n if (\n code_verifier !== undefined &&\n (typeof code_verifier !== 'string' || !CODE_VERIFIER_FORMAT.test(code_verifier))\n ) {\n throw invalidArgument(\n 'INVALID_CODE_VERIFIER',\n 'code_verifier must be 43-128 characters from [A-Za-z0-9-._~]'\n );\n }\n const { clientId, userInfo, token } = await this.oauth2Client.loginOAuth2Native({\n provider,\n credentials,\n });\n mark('login_oauth2_native');\n\n // Required when the provider's native id token echoes a nonce and the login produced one\n // (Facebook's access_token login has none to carry it).\n const required = (await this.oauth2Client.nonceSupport(provider)).native && !!token.id_token;\n if (await this.checkIssuedNonce(userInfo, provider, required)) mark('check_nonce');\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n loginOAuth2Onetap = (\n request: Request,\n handler: AuthorizedHandler,\n provider = 'google'\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // Google's own form post, or an app's JSON.\n const contentType = request.headers.get('content-type') ?? '';\n const body = contentType.includes('application/json')\n ? await readJson(request)\n : await readForm(request);\n const { attributes = {}, ...parsed } = parse(oneTapBodySchema, body);\n\n // Both the credential and the code are issued to the provider's web client.\n let clientId: string;\n let token: Authorization['token'];\n let userInfo: Authorization['userInfo'];\n if (parsed.credential) {\n ({ clientId, token, userInfo } = await this.oauth2Client.getTokenInfo({\n provider,\n credential: parsed.credential,\n }));\n mark('verify_credential');\n\n // The credential must carry a single-use nonce from `oauth2Nonce`, which the front end\n // passed to `prompt`. This replaces Google's `g_csrf_token` double-submit cookie, which\n // FedCM mode no longer sets.\n const required = (await this.oauth2Client.nonceSupport(provider)).web;\n if (await this.checkIssuedNonce(userInfo, provider, required)) mark('check_nonce');\n } else if (parsed.code) {\n ({ clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code: parsed.code,\n }));\n userInfo = await this.oauth2Client.getUserInfo({ provider, clientId, token });\n } else {\n throw invalidArgument('INVALID_ARGUMENT', 'credential or code is required');\n }\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n // ---- email -----------------------------------------------------------------------------------\n\n sendEmailVerificationCode = (request: Request, sender: EmailSender): Promise<Response> =>\n this.guard(async () => {\n invariant(this.turnstileSecretKey, 'turnstileSecretKey is not configured');\n const { email, turnstileToken } = parse(\n sendEmailVerificationCodeSchema,\n await readJson(request)\n );\n await verifyTurnstileToken(this.turnstileSecretKey, turnstileToken);\n await this.emailCodes.send(email, sender);\n return Response.json({});\n });\n\n verifyEmailCode = (email: string, verificationCode: string): Promise<void> =>\n this.emailCodes.verify(email, verificationCode);\n\n loginEmail = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n const { setTiming } = timing({ enabled: this.timing });\n const {\n email,\n verificationCode,\n attributes = {},\n } = parse(loginEmailSchema, await readJson(request));\n await this.emailCodes.verify(email, verificationCode);\n const claims: StandardClaims = { sub: email, email, email_verified: true };\n return this.authorize(\n request,\n handler,\n { provider: 'EMAIL', userInfo: { claims, data: {} }, attributes },\n setTiming\n );\n });\n\n // ---- desktop ---------------------------------------------------------------------------------\n\n /**\n * Step 1 of the desktop / native app sign-in handshake. The caller already completed normal\n * sign-in on the web (so a cookie session exists); this issues a 5-minute single-use code that\n * the web page hands off to the desktop client via a loopback redirect.\n *\n * PKCE (RFC 7636, S256 only): the desktop generates a random `code_verifier` before opening the\n * browser, derives `code_challenge = base64url(sha256(verifier))`, and threads the challenge\n * through the URL → web page → here. The challenge is pinned to the code; `desktopExchange`\n * enforces that the caller knows the matching verifier. This blocks an attacker who only\n * intercepts the auth code (browser history, malicious extension, packet capture on loopback)\n * from exchanging it.\n *\n * Requires an authenticated cookie session: anonymous callers get 401. Throttling / abuse\n * protection on this endpoint is the API layer's job (rate-limit per principal); the SDK does\n * not gate it because the upstream sign-in flow already passed CAPTCHA / OAuth / verification.\n */\n desktopAuthorize = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const principal = await this.getPrincipal(request);\n if (!principal) throw unauthenticated('Sign in first');\n const { code_challenge } = parse(desktopAuthorizeSchema, await readJson(request));\n const code = await this.desktopCodes.issue(principal, code_challenge);\n return Response.json({ code });\n });\n\n /**\n * Step 2 of the desktop / native app sign-in handshake. The desktop client hands back the auth\n * code it received via the loopback callback, and we mint a fresh session for it, independent\n * of the web cookie session that originally authorized the code, so logging out on either side\n * does not cascade to the other.\n *\n * Cookie attributes: `SameSite=None; Secure` so the cookie survives cross-site fetches from the\n * desktop renderer's `file://` / `app://` origin. The configured `cookieOptions` provide\n * everything else (`domain`, `path`, `httpOnly`); the override is targeted at the\n * SameSite/Secure pair only. In a non-HTTPS dev backend this combination is rejected by\n * Chromium, see the desktop sign-in PRD for workarounds.\n *\n * No CSRF check needed: the request carries no cookie, the auth code itself is the credential,\n * and the code's single-use removal blocks replay.\n */\n desktopExchange = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const { code, code_verifier } = parse(desktopExchangeSchema, await readJson(request));\n const principal = await this.desktopCodes.redeem(code, code_verifier);\n const session = await this.signIn(principal);\n session.setAttribute('client_type', 'desktop');\n await this.repository.save(session);\n return this.withSession(Response.json({ ok: true }), session, {\n sameSite: 'none',\n secure: true,\n });\n });\n\n // ---- session management ----------------------------------------------------------------------\n\n kick = async (principal: Principal): Promise<void> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n for (const sessionId of sessions.keys()) {\n await this.repository.deleteById(sessionId);\n }\n };\n\n /**\n * Sliding expiration: an authenticated request renews the session, as `logged` does, so a user\n * who keeps using the app is never signed out after `maxInactiveInterval` of not calling one\n * particular endpoint. No extra read: the session was just loaded to authenticate, and its\n * `lastAccessedTime` is compared in memory; writes are spaced by `session.touchInterval` (see\n * `AuthConfig`), so a session accessed again within the interval is not rewritten.\n */\n private async touch(session: Session) {\n const now = Date.now();\n if (now - session.getLastAccessedTime() < this.touchInterval) return;\n session.setLastAccessedTime(now);\n await this.repository.save(session);\n }\n\n getPrincipal = async (request: Request): Promise<Principal | null> => {\n const session = await this.loadSession(request);\n const principal = session && this.principalOf(session);\n if (!principal) return null;\n await this.touch(session);\n return principal;\n };\n\n isAuthenticated = async (request: Request): Promise<boolean> => {\n return (await this.getPrincipal(request)) !== null;\n };\n\n getSession = async <T extends boolean>(\n request: Request,\n create: T\n ): Promise<T extends true ? Session : Session | null> => {\n type Result = T extends true ? Session : Session | null;\n const session = await this.loadSession(request);\n if (session || !create) return session as Result;\n const created = this.repository.createSession();\n await this.repository.save(created);\n return created;\n };\n\n deleteSession = async (sessionId: string): Promise<void> => {\n await this.repository.deleteById(sessionId);\n };\n\n listSessions = async (principal: Principal): Promise<Session[]> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n return Array.from(sessions.values());\n };\n\n cleanupExpiredSessions = async (cleanupCount?: number): Promise<Response> => {\n await this.repository.cleanupExpiredSessions(cleanupCount);\n return Response.json({});\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkDA,MAAM,cAAc;AAIpB,MAAM,uBAAuB;;AAG7B,MAAM,iBAAiB;;AAGvB,MAAM,uBAAuB;AAI7B,MAAM,+BAA+B;;AAGrC,SAAS,cAAc,OAAe,UAA4C;CAChF,OAAO,uBAAuB,KAAK,IAAI,QAAQ;AACjD;;;;;;;AAQA,MAAM,uCAAqD,IAAI,IAAI;CACjE;CACA;CACA;AACF,CAAC;AAED,SAAS,wBACP,YACoC;CACpC,IAAI,CAAC,YAAY,OAAO,KAAA;CACxB,MAAM,UAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,UAAU,KAAA,GAAW,QAAQ,OAAO;CAE1C,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG,OAAO,KAAA;CAE9C,MAAM,OAAO,eAAe,OAAO;CACnC,UACE,QAAQ,sBACR,uCAAuC,KAAK,kBAAkB,qBAAqB,SACrF;CACA,OAAO;AACT;;AAGA,SAAS,WAAW,SAAkB;CACpC,MAAM,cAAc,QAAQ,QAAQ,IAAI,cAAc,CAAC,EAAE,YAAY;C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,MAAM,KAAK,WAAW,oBAAoB,UAAU,IAAI;EACzE,OAAO,MAAM,KAAK,SAAS,OAAO,CAAC;CACrC;CAEA,yBAAyB,OAAO,iBAA6C;EAC3E,MAAM,KAAK,WAAW,uBAAuB,YAAY;EACzD,OAAO,SAAS,KAAK,CAAC,CAAC;CACzB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/auth/index.ts"],"sourcesContent":["import { createHash, randomBytes, randomUUID } from 'node:crypto';\nimport { invariant } from '@shware/utils';\nimport { custom, extend, literal, object, optional, regex, string } from 'zod/mini';\nimport type { Principal } from '../core/index';\nimport { loginEmailSchema, sendEmailVerificationCodeSchema } from '../email/schema';\nimport { OAuth2Client, googleOneTapSchema, oauth2RedirectQuerySchema } from '../oauth2/client';\nimport { OAuth2Error, type OAuth2ErrorType, isKnownOAuth2ErrorType } from '../oauth2/error';\nimport type {\n NativeCredential,\n OAuth2AuthorizationRequest,\n PersonNameComponents,\n PkceParameters,\n StandardClaims,\n} from '../oauth2/types';\nimport { PRINCIPAL_NAME_INDEX_NAME } from '../session/common';\nimport type { KVRepository, Session, SessionRepository } from '../session/types';\nimport {\n type CookieOptions,\n deleteCookie,\n getCookie,\n param,\n query,\n setCookie,\n} from '../utils/http';\nimport { timing } from '../utils/timing';\nimport { parse, readForm, readJson, verifyTurnstileToken } from '../utils/valid';\nimport {\n MAX_ATTRIBUTES_BYTES,\n attributesSchema,\n attributesSize,\n bodyAttributes,\n} from './attributes';\nimport { DesktopCodes } from './desktop-codes';\nimport { type EmailSender, EmailVerificationCodes } from './email-codes';\nimport { AuthenticationError } from './error';\nimport { errorResponse, invalidArgument, unauthenticated } from './respond';\nimport type {\n AuthConfig,\n AuthService,\n Authorization,\n AuthorizedHandler,\n LoggedHandler,\n LogoutOptions,\n OAuth2AuthorizationOptions,\n} from './types';\n\n// PKCE per RFC 7636: code_verifier / code_challenge are 43-128 chars from\n// the unreserved set. We restrict to base64url (drops \".\" and \"~\") since\n// that's what S256 produces and what callers should be sending; rejecting\n// the rest shrinks the accepted input shape without losing legit clients.\n// A 32-byte random verifier base64url-encodes to exactly 43 chars.\nconst PKCE_FORMAT = /^[A-Za-z0-9_-]{43,128}$/;\n\n// A native app's `code_verifier` goes on to the provider, which checks it against the challenge\n// the app sent: accept the whole RFC 7636 unreserved set here, as the provider does.\nconst CODE_VERIFIER_FORMAT = /^[A-Za-z0-9._~-]{43,128}$/;\n\n/** The header a session id travels in besides the cookie, with `session.header` on. */\nconst SESSION_HEADER = 'X-Auth-Token';\n\n/** Seconds an OAuth2 state or nonce may be used within. */\nconst OAUTH2_PARAMETER_TTL = 10 * 60;\n\n/** An error code safe to put on errorUri: a registered one as is, anything else as `fallback`. */\nfunction safeErrorType(error: string, fallback: OAuth2ErrorType): OAuth2ErrorType {\n return isKnownOAuth2ErrorType(error) ? error : fallback;\n}\n\n/**\n * The codes a failure past validation keeps on errorUri, each one the user can act on: the code\n * expired or was used (start again), they declined, or the provider is briefly down. Every other\n * failure there (a rejected client, a user info request that failed) is the app's or the\n * provider's problem, which the user sees as `server_error`.\n */\nconst CALLBACK_ERROR_TYPES: ReadonlySet<OAuth2ErrorType> = new Set([\n 'invalid_grant',\n 'access_denied',\n 'temporarily_unavailable',\n]);\n\n/**\n * The host's values for the flow (`attributes`, `redirectParams`), `undefined` ones dropped; `name`\n * is what the size invariant calls them.\n */\nfunction authorizationAttributes(\n attributes: OAuth2AuthorizationOptions['attributes'],\n name = 'attributes'\n): Record<string, string> | undefined {\n if (!attributes) return undefined;\n const defined: Record<string, string> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) defined[key] = value;\n }\n if (Object.keys(defined).length === 0) return undefined;\n // The host's own values, written with the session: oversized is a bug in the host, not a 400.\n const size = attributesSize(defined);\n invariant(\n size <= MAX_ATTRIBUTES_BYTES,\n `oauth2 authorization ${name} are ${size} bytes, at most ${MAX_ATTRIBUTES_BYTES} allowed`\n );\n return defined;\n}\n\ninterface RedirectDetails {\n /** What went wrong, for the logs: the page gets the `error` code only. */\n detail?: string;\n refusal?: AuthenticationError;\n /** The flow's `redirectParams`. */\n params?: Record<string, string>;\n}\n\n/**\n * What the callback's redirects say themselves. A host's `redirectParams` never carry these, even\n * on a redirect that leaves one out (a cancel has no `reason`): the page would read it as the SDK's.\n */\nconst REDIRECT_PARAMS = new Set(['status', 'provider', 'error', 'reason']);\n\n/** The host's `redirectParams` without the names the redirects keep for themselves. */\nfunction redirectParams(params: OAuth2AuthorizationOptions['redirectParams']) {\n if (!params) return undefined;\n const own = Object.entries(params).filter(([key]) => !REDIRECT_PARAMS.has(key));\n return authorizationAttributes(Object.fromEntries(own), 'redirectParams');\n}\n\n/** `base` with `params` added, none replacing one it carries itself. */\nfunction withParams(base: string, params: Record<string, string> = {}) {\n const uri = new URL(base);\n for (const [key, value] of Object.entries(params)) {\n if (!uri.searchParams.has(key)) uri.searchParams.set(key, value);\n }\n return uri;\n}\n\n/** Sign in with Apple answers with `response_mode=form_post`; a charset parameter may follow. */\nfunction isFormPost(request: Request) {\n const contentType = request.headers.get('content-type')?.toLowerCase();\n return (\n request.method === 'POST' && !!contentType?.startsWith('application/x-www-form-urlencoded')\n );\n}\n\n/**\n * The platform's name object as the app posts it (iOS `PersonNameComponents`): any object, since\n * the provider cleans each part itself and ignores what is not a string.\n */\nconst personNameSchema = custom<PersonNameComponents>(\n (value: unknown) => typeof value === 'object' && value !== null && !Array.isArray(value)\n);\n\n/**\n * A native login body (`NativeCredential`): each protocol parameter a string when present. Which\n * ones a provider needs is its own check (a missing `code` is an `OAuth2Error` `invalid_request`);\n * `code_verifier`'s format has its own reason (`INVALID_CODE_VERIFIER`) and `attributes` their own\n * schema, so neither is checked here.\n */\nconst nativeCredentialSchema = object({\n state: optional(string()),\n code: optional(string()),\n client_id: optional(string()),\n redirect_uri: optional(string()),\n code_verifier: optional(string()),\n id_token: optional(string()),\n access_token: optional(string()),\n fullName: optional(personNameSchema),\n});\n\n/** Google's own form post carries no attributes; an app posting JSON may add them. */\nconst oneTapBodySchema = extend(googleOneTapSchema, { attributes: attributesSchema });\n\nconst desktopAuthorizeSchema = object({\n code_challenge: string().check(regex(PKCE_FORMAT)),\n code_challenge_method: literal('S256'),\n});\n\nconst desktopExchangeSchema = object({\n code: string(),\n code_verifier: string().check(regex(PKCE_FORMAT)),\n});\n\nexport const PATH = {\n CSRF: '/csrf',\n LOGOUT: '/logout',\n LOGGED: '/logged',\n\n OAUTH2_STATE: '/oauth2/state/:provider',\n OAUTH2_NONCE: '/oauth2/nonce/:provider',\n OAUTH2_AUTHORIZATION: '/oauth2/authorization/:provider',\n LOGIN_OAUTH2_CODE: '/login/oauth2/code/:provider',\n LOGIN_OAUTH2_NATIVE: '/login/oauth2/native/:provider',\n LOGIN_OAUTH2_ONETAP: '/login/oauth2/onetap/google',\n\n LOGIN_EMAIL: '/login/email',\n SEND_EMAIL_VERIFICATION_CODE: '/auth/sendEmailVerificationCode',\n\n // Desktop / native app sign-in via web loopback (RFC 8252 + OAuth 2.1 Auth Code Flow):\n // 1. user already authenticated with cookie session → POST DESKTOP_AUTHORIZE → { code }\n // 2. web redirects to desktop's loopback callback with the code\n // 3. desktop renderer POSTs DESKTOP_EXCHANGE with the code → server returns\n // Set-Cookie carrying a fresh session, single-use code is invalidated\n // The two-step flow keeps the actual session id off the redirect URL — only a\n // 5-minute single-use code transits via the loopback.\n DESKTOP_AUTHORIZE: '/auth/desktop/authorize',\n DESKTOP_EXCHANGE: '/auth/desktop/exchange',\n\n CLEANUP_EXPIRED_SESSIONS: '/sessions/expired/cleanup',\n} as const;\n\n/**\n * The login routes and session helpers. Every route is one straight line: read and validate the\n * request, check the credential, call the host's `onAuthorized`, sign in. Failures are thrown and\n * answered in one place per kind of route: a JSON route runs under `guard`, which maps a\n * `RequestError`, an `AuthenticationError` or an `OAuth2Error` to its google.rpc body (see\n * `respond.ts`); the redirect callback maps the same errors to `errorUri` parameters (`redirect`).\n */\nexport class Auth implements AuthService {\n private readonly timing: boolean;\n private readonly cookieName;\n private readonly cookieOptions: CookieOptions;\n private readonly kv: KVRepository;\n private readonly repository: SessionRepository;\n private readonly turnstileSecretKey?: string;\n private readonly emailCodes: EmailVerificationCodes;\n private readonly desktopCodes: DesktopCodes;\n private readonly oauth2Client: OAuth2Client | null;\n /** Provider keys whose logins may come without a nonce (`oauth2.nonce.optional`). */\n private readonly nonceOptional: ReadonlySet<string>;\n private readonly touchInterval: number;\n private readonly sessionHeader: boolean;\n private readonly ATTR_OAUTH2_AUTHORIZATION_REQUEST = 'oauth2AuthorizationRequest';\n\n constructor({\n sessionRepository,\n kvRepository,\n turnstileSecretKey,\n verificationCode,\n oauth2,\n cookie,\n session,\n timing,\n }: AuthConfig) {\n this.timing = timing ?? false;\n this.kv = kvRepository;\n this.repository = sessionRepository;\n this.turnstileSecretKey = turnstileSecretKey;\n const maxAttempts = verificationCode?.maxAttempts ?? 5;\n const resendCooldown = verificationCode?.resendCooldown ?? 60;\n invariant(maxAttempts >= 1, 'verificationCode.maxAttempts must be at least 1');\n invariant(resendCooldown >= 1, 'verificationCode.resendCooldown must be at least 1 second');\n this.emailCodes = new EmailVerificationCodes(kvRepository, { maxAttempts, resendCooldown });\n this.desktopCodes = new DesktopCodes(kvRepository);\n const { name, ...cookieOptions } = cookie ?? {};\n this.cookieName = name ?? 'SESSION';\n this.cookieOptions = {\n path: '/',\n sameSite: 'none',\n secure: true,\n httpOnly: true,\n ...cookieOptions,\n };\n this.oauth2Client = oauth2?.client ? new OAuth2Client(oauth2.client) : null;\n this.nonceOptional = new Set(oauth2?.nonce?.optional);\n this.touchInterval = (session?.touchInterval ?? 3600) * 1000;\n this.sessionHeader = session?.header ?? false;\n invariant(this.touchInterval >= 0, 'session.touchInterval must not be negative');\n }\n\n // ---- sessions and responses ------------------------------------------------------------------\n\n private getSessionId(request: Request): string | undefined {\n const fromCookie = getCookie(request, this.cookieName);\n if (fromCookie) return fromCookie;\n return (this.sessionHeader && request.headers.get(SESSION_HEADER)) || undefined;\n }\n\n /** The session the request carries, if it exists. */\n private async loadSession(request: Request): Promise<Session | null> {\n const sessionId = this.getSessionId(request);\n return sessionId ? this.repository.findById(sessionId) : null;\n }\n\n /** The signed-in principal of a session, if any. */\n private principalOf(session: Session): Principal | null {\n const name = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);\n return name ? { name: String(name) } : null;\n }\n\n /**\n * A new session signed in as `principal`. With `carryOver`, what the host kept in the pre-login\n * session moves to the new one; the authorization request (state, PKCE verifier, flow\n * attributes) is single-use and was consumed, and a principal left there from an earlier\n * sign-in is replaced. The new id is never the one the browser brought, which may have been\n * planted by an attacker who started the flow (session fixation).\n */\n private async signIn(principal: Principal, carryOver?: Session): Promise<Session> {\n const session = this.repository.createSession();\n for (const attribute of carryOver?.getAttributeNames() ?? []) {\n if (attribute === this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) continue;\n if (attribute === PRINCIPAL_NAME_INDEX_NAME) continue;\n const value = carryOver?.getAttribute(attribute);\n if (value !== null && value !== undefined) session.setAttribute(attribute, value);\n }\n session.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principal.name);\n await this.repository.save(session);\n return session;\n }\n\n /**\n * `response` carrying `session`: its cookie, renewed for the whole inactive interval, and with\n * `session.header` on, the `X-Auth-Token` header a client without a cookie jar reads.\n */\n private withSession(response: Response, session: Session, cookie?: CookieOptions): Response {\n const maxAge = session.getMaxInactiveInterval();\n setCookie(response, this.cookieName, session.getId(), {\n ...this.cookieOptions,\n ...cookie,\n maxAge,\n });\n if (this.sessionHeader) response.headers.set(SESSION_HEADER, session.getId());\n return response;\n }\n\n /** Runs a JSON route: a failure it knows is its response, anything else is the host's. */\n private async guard(run: () => Promise<Response>): Promise<Response> {\n try {\n return await run();\n } catch (error) {\n const response = errorResponse(error);\n if (response) return response;\n throw error;\n }\n }\n\n /**\n * The error redirect of the callback flow: `refusal`'s reason and metadata ride along, and the\n * flow's `redirectParams` once its authorization request is known. `detail` (a failed validation,\n * the provider's `error_description`) is logged, not forwarded: the page shows a message per\n * `error` code and never the text, so a URL the browser keeps in its history has no use for it,\n * and a forged callback could set it to anything.\n */\n private redirect(\n error: OAuth2ErrorType,\n { detail, refusal, params }: RedirectDetails = {}\n ): Response {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n if (detail) console.warn(`OAuth2 callback failed: ${error}`, detail);\n // A refusal's metadata wins over the host's parameters of the same name: it is about this answer.\n const uri = withParams(this.oauth2Client.errorUri, { ...params, ...refusal?.metadata });\n uri.searchParams.set('error', error);\n if (refusal) uri.searchParams.set('reason', refusal.reason);\n return Response.redirect(uri.href, 302);\n }\n\n // ---- basic -----------------------------------------------------------------------------------\n\n csrf = async (_request: Request): Promise<Response> => {\n const token = randomUUID();\n const response = Response.json({\n token,\n parameterName: '_csrf',\n headerName: 'X-XSRF-TOKEN',\n });\n\n // Double Submit Cookie Protection\n setCookie(response, 'XSRF-TOKEN', token, {\n path: '/',\n secure: true,\n httpOnly: false,\n sameSite: 'none',\n domain: this.cookieOptions.domain,\n });\n return response;\n };\n\n logout = async (request: Request, options?: LogoutOptions): Promise<Response> => {\n const scope = options?.scope ?? 'local';\n const sessionId = this.getSessionId(request);\n // `global` and `others` reach the principal's other sessions through the one the request\n // carries; a request without a signed-in session has no principal to widen to, and ends as\n // `local` would.\n if (scope !== 'local' && sessionId) {\n const session = await this.repository.findById(sessionId);\n const principal = session && this.principalOf(session);\n if (principal) {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n for (const id of sessions.keys()) {\n if (id !== sessionId) await this.repository.deleteById(id);\n }\n }\n }\n const response = Response.json({});\n if (scope === 'others') return response;\n if (sessionId) await this.repository.deleteById(sessionId);\n // A Set-Cookie only replaces the stored cookie when Domain and Path match (RFC 6265),\n // so clear it with the same attributes it was set with.\n deleteCookie(response, this.cookieName, this.cookieOptions);\n return response;\n };\n\n logged = async (request: Request, onLogged?: LoggedHandler): Promise<Response> => {\n const session = await this.loadSession(request);\n if (!session) return Response.json({ data: false });\n\n session.setLastAccessedTime(Date.now());\n await this.repository.save(session);\n\n const principal = this.principalOf(session);\n if (principal) await onLogged?.(principal);\n return this.withSession(Response.json({ data: principal !== null }), session);\n };\n\n // ---- oauth2 ----------------------------------------------------------------------------------\n\n private createPkceParameters(): PkceParameters {\n // 32 random bytes: a 43-char base64url verifier, the RFC 7636 minimum (a UUID is 36).\n const code_verifier = randomBytes(32).toString('base64url');\n const code_challenge = createHash('sha256')\n .update(code_verifier)\n .digest()\n .toString('base64url');\n\n return { code_verifier, code_challenge, code_challenge_method: 'S256' };\n }\n\n private getOauth2StateKey(state: string) {\n return `oauth2:state:${state}`;\n }\n\n private getOauth2NonceKey(nonce: string) {\n return `oauth2:nonce:${nonce}`;\n }\n\n /**\n * Spends a nonce `oauth2Nonce` issued for `provider`: `NONCE_MISMATCH` for one that was not,\n * or was used already. An id token is replayable until it expires; the nonce it carries makes\n * it sign in once.\n */\n private async consumeNonce(nonce: string, provider: string): Promise<void> {\n const key = this.getOauth2NonceKey(nonce);\n if ((await this.kv.getItem(key)) !== provider) throw new AuthenticationError('NONCE_MISMATCH');\n await this.kv.removeItem(key);\n }\n\n /**\n * The nonce check of the JSON logins (One Tap, native), where the client obtained the id token\n * and the nonce came from `oauth2Nonce`: spends the one the token carries, and refuses a token\n * without one when the provider's flow echoes nonces (`required`) and the host has not listed the\n * provider as optional. An id token is replayable until it expires; the nonce makes it sign in\n * once.\n */\n private async checkIssuedNonce(\n userInfo: Authorization['userInfo'],\n provider: string,\n required: boolean\n ): Promise<boolean> {\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce === 'string' && nonce) {\n await this.consumeNonce(nonce, provider);\n return true;\n }\n if (required && !this.nonceOptional.has(provider)) {\n throw new AuthenticationError('NONCE_MISSING');\n }\n return false;\n }\n\n oauth2State = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_STATE);\n const state = randomUUID();\n await this.kv.setItem(this.getOauth2StateKey(state), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ state });\n };\n\n oauth2Nonce = async (request: Request): Promise<Response> => {\n const { provider } = param(request, PATH.OAUTH2_NONCE);\n const nonce = randomUUID();\n await this.kv.setItem(this.getOauth2NonceKey(nonce), provider, OAUTH2_PARAMETER_TTL);\n return Response.json({ nonce });\n };\n\n oauth2Authorization = (\n request: Request,\n options?: OAuth2AuthorizationOptions\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const attributes = authorizationAttributes(options?.attributes);\n const params = redirectParams(options?.redirectParams);\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.OAUTH2_AUTHORIZATION);\n const state = randomUUID();\n const pkce = this.createPkceParameters();\n // Sent only to a provider whose id token echoes it: the callback then requires it back, so\n // a code that was swapped in for another sign-in's yields a token the session refuses.\n const nonce = (await this.oauth2Client.nonceSupport(provider)).web ? randomUUID() : undefined;\n const uri = await this.oauth2Client.createAuthorizationUri({ provider, state, pkce, nonce });\n let session = await this.loadSession(request);\n if (!session) {\n // A session made for the flow only has to outlive the state: an abandoned flow must not\n // keep a row for the default interval. Sign-in moves to a new session, with the default.\n session = this.repository.createSession();\n session.setMaxInactiveInterval(OAUTH2_PARAMETER_TTL);\n }\n mark('fetch_session');\n\n const authorizationRequest: OAuth2AuthorizationRequest = {\n state,\n provider,\n authorizationRequestUri: uri.href,\n additionalParameters: pkce,\n ...(nonce ? { nonce } : {}),\n ...(attributes ? { attributes } : {}),\n ...(params ? { redirectParams: params } : {}),\n };\n session.setAttribute(\n this.ATTR_OAUTH2_AUTHORIZATION_REQUEST,\n JSON.stringify(authorizationRequest)\n );\n await this.repository.save(session);\n mark('save_session');\n\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, session);\n });\n\n loginOAuth2Code = async (request: Request, handler: AuthorizedHandler): Promise<Response> => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // 1. the session the flow started on, and the authorization request it stored\n const session = await this.loadSession(request);\n if (!session) return this.redirect('invalid_request', { detail: 'session not found' });\n mark('load_session');\n const json = session.getAttribute(this.ATTR_OAUTH2_AUTHORIZATION_REQUEST) as string | null;\n if (!json) {\n return this.redirect('invalid_request', { detail: 'authorization request not found' });\n }\n const cached: OAuth2AuthorizationRequest = JSON.parse(json);\n // From here on the redirect back to the app is this flow's, with the host's parameters.\n const params = cached.redirectParams;\n\n // 2. the provider's answer: query, or a form for Apple's response_mode=form_post\n const { provider } = param(request, PATH.LOGIN_OAUTH2_CODE);\n const data = isFormPost(request)\n ? Object.fromEntries(new URLSearchParams(await request.text()))\n : query(request);\n const parsed = oauth2RedirectQuerySchema.safeParse(data);\n if (!parsed.success) {\n return this.redirect('invalid_request', { detail: 'invalid redirect query', params });\n }\n // The provider answered with an error instead of a code (the user pressed Cancel →\n // access_denied, invalid_scope, server_error, ...). Forward it rather than reporting a\n // malformed query. This runs before the state check on purpose: providers echo state on\n // error responses, but not all reliably do, and a forged error callback can only make the\n // victim's popup show an error — nothing is exchanged or signed in. A present state that does\n // not match still wins, since that is the more accurate (and more alarming) diagnosis.\n if (parsed.data.error) {\n if (parsed.data.state && parsed.data.state !== cached.state) {\n return this.redirect('invalid_request', { detail: 'redirect state mismatch', params });\n }\n return this.redirect(safeErrorType(parsed.data.error, 'server_error'), {\n detail: parsed.data.error_description,\n params,\n });\n }\n const { code, state, user } = parsed.data;\n if (!code || !state) {\n return this.redirect('invalid_request', { detail: 'invalid redirect query', params });\n }\n if (state !== cached.state) {\n return this.redirect('invalid_request', { detail: 'redirect state mismatch', params });\n }\n if (provider !== cached.provider) {\n return this.redirect('invalid_request', {\n detail: 'redirect provider mismatch',\n params,\n });\n }\n mark('validate_session');\n\n // 3. exchange the code, load the user, sign in. Everything here can fail (an expired or reused\n // code, a network error, the host's handler or session store). The callback runs in a popup\n // the user is looking at, so every failure must land on errorUri, never as a JSON error.\n let signedIn: Session;\n try {\n const { clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code,\n pkce: cached.additionalParameters,\n });\n // Apple posts the user's name alongside the code, once: hand it to the provider with the token.\n const userInfo = await this.oauth2Client.getUserInfo({\n provider,\n clientId,\n token,\n response: user ? { user } : undefined,\n });\n mark('exchange_code');\n // The id token must carry the nonce this flow sent (stored with the state, not in KV: it\n // is bound to this session's request). A provider that gave no id token has nothing to\n // carry it, as has a request stored before nonces were sent.\n if (cached.nonce && token.id_token) {\n const { nonce } = userInfo.data as { nonce?: unknown };\n if (typeof nonce !== 'string' || !nonce) throw new AuthenticationError('NONCE_MISSING');\n if (nonce !== cached.nonce) throw new AuthenticationError('NONCE_MISMATCH');\n mark('check_nonce');\n }\n\n const principal = await handler(request, {\n provider,\n clientId,\n userInfo,\n token,\n attributes: cached.attributes ?? {},\n });\n mark('save_principal');\n\n signedIn = await this.signIn(principal, session);\n await this.repository.deleteById(session.getId());\n mark('update_session');\n } catch (error) {\n // The details stay in the logs: an OAuth2Error message can carry a client id or a\n // provider's response, which has no place in a URL the browser keeps in its history.\n if (error instanceof OAuth2Error) {\n console.warn('OAuth2 callback failed', error);\n const type = CALLBACK_ERROR_TYPES.has(error.error) ? error.error : 'server_error';\n return this.redirect(type, { params });\n }\n // A refusal is something the user can act on, so its reason and metadata reach the page,\n // as they reach a JSON client through the ErrorInfo.\n if (error instanceof AuthenticationError) {\n console.warn('OAuth2 sign-in refused', error.reason, error.metadata);\n return this.redirect('access_denied', { refusal: error, params });\n }\n console.error('OAuth2 callback failed', error);\n return this.redirect('server_error', { params });\n }\n\n const uri = withParams(this.oauth2Client.successUri, params);\n uri.searchParams.set('status', 'success');\n uri.searchParams.set('provider', provider);\n const response = new Response(null, { status: 302, headers: { location: uri.href } });\n setTiming(response);\n return this.withSession(response, signedIn);\n };\n\n /** The shared tail of the JSON login routes: the host's handler, then a signed-in session. */\n private async authorize(\n request: Request,\n handler: AuthorizedHandler,\n authorization: Authorization,\n setTiming: (response: Response) => void\n ): Promise<Response> {\n const principal = await handler(request, authorization);\n const session = await this.signIn(principal);\n const response = Response.json(principal);\n setTiming(response);\n return this.withSession(response, session);\n }\n\n loginOAuth2Native = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n const { provider } = param(request, PATH.LOGIN_OAUTH2_NATIVE);\n const body = await readJson(request);\n // Whatever the app sends besides its credentials for `onAuthorized` (a referral code, ...).\n const attributes = bodyAttributes(body);\n // Only the credentials go on to the provider client; anything else in the body is dropped.\n const credentials: NativeCredential = parse(nativeCredentialSchema, body);\n const { code_verifier } = credentials;\n if (code_verifier !== undefined && !CODE_VERIFIER_FORMAT.test(code_verifier)) {\n throw invalidArgument(\n 'INVALID_CODE_VERIFIER',\n 'code_verifier must be 43-128 characters from [A-Za-z0-9-._~]'\n );\n }\n const { clientId, userInfo, token } = await this.oauth2Client.loginOAuth2Native({\n provider,\n credentials,\n });\n mark('login_oauth2_native');\n\n // Required when the provider's native id token echoes a nonce and the login produced one\n // (Facebook's access_token login has none to carry it).\n const required = (await this.oauth2Client.nonceSupport(provider)).native && !!token.id_token;\n if (await this.checkIssuedNonce(userInfo, provider, required)) mark('check_nonce');\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n loginOAuth2Onetap = (\n request: Request,\n handler: AuthorizedHandler,\n provider = 'google'\n ): Promise<Response> =>\n this.guard(async () => {\n invariant(this.oauth2Client, 'oauth2Client is not initialized');\n const { mark, setTiming } = timing({ enabled: this.timing });\n\n // Google's own form post, or an app's JSON.\n const contentType = request.headers.get('content-type') ?? '';\n const body = contentType.includes('application/json')\n ? await readJson(request)\n : await readForm(request);\n const { attributes = {}, ...parsed } = parse(oneTapBodySchema, body);\n\n // Both the credential and the code are issued to the provider's web client.\n let clientId: string;\n let token: Authorization['token'];\n let userInfo: Authorization['userInfo'];\n if (parsed.credential) {\n ({ clientId, token, userInfo } = await this.oauth2Client.getTokenInfo({\n provider,\n credential: parsed.credential,\n }));\n mark('verify_credential');\n\n // The credential must carry a single-use nonce from `oauth2Nonce`, which the front end\n // passed to `prompt`. This replaces Google's `g_csrf_token` double-submit cookie, which\n // FedCM mode no longer sets.\n const required = (await this.oauth2Client.nonceSupport(provider)).web;\n if (await this.checkIssuedNonce(userInfo, provider, required)) mark('check_nonce');\n } else if (parsed.code) {\n ({ clientId, token } = await this.oauth2Client.exchangeAuthorizationCode({\n provider,\n code: parsed.code,\n }));\n userInfo = await this.oauth2Client.getUserInfo({ provider, clientId, token });\n } else {\n throw invalidArgument('INVALID_ARGUMENT', 'credential or code is required');\n }\n\n return this.authorize(\n request,\n handler,\n { provider, clientId, userInfo, token, attributes },\n setTiming\n );\n });\n\n // ---- email -----------------------------------------------------------------------------------\n\n sendEmailVerificationCode = (request: Request, sender: EmailSender): Promise<Response> =>\n this.guard(async () => {\n invariant(this.turnstileSecretKey, 'turnstileSecretKey is not configured');\n const { email, turnstileToken } = parse(\n sendEmailVerificationCodeSchema,\n await readJson(request)\n );\n await verifyTurnstileToken(this.turnstileSecretKey, turnstileToken);\n await this.emailCodes.send(email, sender);\n return Response.json({});\n });\n\n verifyEmailCode = (email: string, verificationCode: string): Promise<void> =>\n this.emailCodes.verify(email, verificationCode);\n\n loginEmail = (request: Request, handler: AuthorizedHandler): Promise<Response> =>\n this.guard(async () => {\n const { setTiming } = timing({ enabled: this.timing });\n const {\n email,\n verificationCode,\n attributes = {},\n } = parse(loginEmailSchema, await readJson(request));\n await this.emailCodes.verify(email, verificationCode);\n const claims: StandardClaims = { sub: email, email, email_verified: true };\n return this.authorize(\n request,\n handler,\n { provider: 'EMAIL', userInfo: { claims, data: {} }, attributes },\n setTiming\n );\n });\n\n // ---- desktop ---------------------------------------------------------------------------------\n\n /**\n * Step 1 of the desktop / native app sign-in handshake. The caller already completed normal\n * sign-in on the web (so a cookie session exists); this issues a 5-minute single-use code that\n * the web page hands off to the desktop client via a loopback redirect.\n *\n * PKCE (RFC 7636, S256 only): the desktop generates a random `code_verifier` before opening the\n * browser, derives `code_challenge = base64url(sha256(verifier))`, and threads the challenge\n * through the URL → web page → here. The challenge is pinned to the code; `desktopExchange`\n * enforces that the caller knows the matching verifier. This blocks an attacker who only\n * intercepts the auth code (browser history, malicious extension, packet capture on loopback)\n * from exchanging it.\n *\n * Requires an authenticated cookie session: anonymous callers get 401. Throttling / abuse\n * protection on this endpoint is the API layer's job (rate-limit per principal); the SDK does\n * not gate it because the upstream sign-in flow already passed CAPTCHA / OAuth / verification.\n */\n desktopAuthorize = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const principal = await this.getPrincipal(request);\n if (!principal) throw unauthenticated('Sign in first');\n const { code_challenge } = parse(desktopAuthorizeSchema, await readJson(request));\n const code = await this.desktopCodes.issue(principal, code_challenge);\n return Response.json({ code });\n });\n\n /**\n * Step 2 of the desktop / native app sign-in handshake. The desktop client hands back the auth\n * code it received via the loopback callback, and we mint a fresh session for it, independent\n * of the web cookie session that originally authorized the code, so logging out on either side\n * does not cascade to the other.\n *\n * Cookie attributes: `SameSite=None; Secure` so the cookie survives cross-site fetches from the\n * desktop renderer's `file://` / `app://` origin. The configured `cookieOptions` provide\n * everything else (`domain`, `path`, `httpOnly`); the override is targeted at the\n * SameSite/Secure pair only. In a non-HTTPS dev backend this combination is rejected by\n * Chromium, see the desktop sign-in PRD for workarounds.\n *\n * No CSRF check needed: the request carries no cookie, the auth code itself is the credential,\n * and the code's single-use removal blocks replay.\n */\n desktopExchange = (request: Request): Promise<Response> =>\n this.guard(async () => {\n const { code, code_verifier } = parse(desktopExchangeSchema, await readJson(request));\n const principal = await this.desktopCodes.redeem(code, code_verifier);\n const session = await this.signIn(principal);\n session.setAttribute('client_type', 'desktop');\n await this.repository.save(session);\n return this.withSession(Response.json({ ok: true }), session, {\n sameSite: 'none',\n secure: true,\n });\n });\n\n // ---- session management ----------------------------------------------------------------------\n\n kick = async (principal: Principal): Promise<void> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n for (const sessionId of sessions.keys()) {\n await this.repository.deleteById(sessionId);\n }\n };\n\n /**\n * Sliding expiration: an authenticated request renews the session, as `logged` does, so a user\n * who keeps using the app is never signed out after `maxInactiveInterval` of not calling one\n * particular endpoint. No extra read: the session was just loaded to authenticate, and its\n * `lastAccessedTime` is compared in memory; writes are spaced by `session.touchInterval` (see\n * `AuthConfig`), so a session accessed again within the interval is not rewritten.\n */\n private async touch(session: Session) {\n const now = Date.now();\n if (now - session.getLastAccessedTime() < this.touchInterval) return;\n session.setLastAccessedTime(now);\n await this.repository.save(session);\n }\n\n getPrincipal = async (request: Request): Promise<Principal | null> => {\n const session = await this.loadSession(request);\n const principal = session && this.principalOf(session);\n if (!principal) return null;\n await this.touch(session);\n return principal;\n };\n\n isAuthenticated = async (request: Request): Promise<boolean> => {\n return (await this.getPrincipal(request)) !== null;\n };\n\n getSession = async <T extends boolean>(\n request: Request,\n create: T\n ): Promise<T extends true ? Session : Session | null> => {\n type Result = T extends true ? Session : Session | null;\n const session = await this.loadSession(request);\n if (session || !create) return session as Result;\n const created = this.repository.createSession();\n await this.repository.save(created);\n return created;\n };\n\n deleteSession = async (sessionId: string): Promise<void> => {\n await this.repository.deleteById(sessionId);\n };\n\n listSessions = async (principal: Principal): Promise<Session[]> => {\n const sessions = await this.repository.findByPrincipalName(principal.name);\n return Array.from(sessions.values());\n };\n\n cleanupExpiredSessions = async (cleanupCount?: number): Promise<Response> => {\n await this.repository.cleanupExpiredSessions(cleanupCount);\n return Response.json({});\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmDA,MAAM,cAAc;AAIpB,MAAM,uBAAuB;;AAG7B,MAAM,iBAAiB;;AAGvB,MAAM,uBAAuB;;AAG7B,SAAS,cAAc,OAAe,UAA4C;CAChF,OAAO,uBAAuB,KAAK,IAAI,QAAQ;AACjD;;;;;;;AAQA,MAAM,uCAAqD,IAAI,IAAI;CACjE;CAC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CACT;CAEA,kBAAkB,OAAO,YAAuC;EAC9D,OAAQ,MAAM,KAAK,aAAa,OAAO,MAAO;CAChD;CAEA,aAAa,OACX,SACA,WACuD;EAEvD,MAAM,UAAU,MAAM,KAAK,YAAY,OAAO;EAC9C,IAAI,WAAW,CAAC,QAAQ,OAAO;EAC/B,MAAM,UAAU,KAAK,WAAW,cAAc;EAC9C,MAAM,KAAK,WAAW,KAAK,OAAO;EAClC,OAAO;CACT;CAEA,gBAAgB,OAAO,cAAqC;EAC1D,MAAM,KAAK,WAAW,WAAW,SAAS;CAC5C;CAEA,eAAe,OAAO,cAA6C;EACjE,MAAM,WAAW,MAAM,KAAK,WAAW,oBAAoB,UAAU,IAAI;EACzE,OAAO,MAAM,KAAK,SAAS,OAAO,CAAC;CACrC;CAEA,yBAAyB,OAAO,iBAA6C;EAC3E,MAAM,KAAK,WAAW,uBAAuB,YAAY;EACzD,OAAO,SAAS,KAAK,CAAC,CAAC;CACzB;AACF"}
|
package/dist/auth/types.d.cts
CHANGED
|
@@ -43,6 +43,17 @@ export interface OAuth2AuthorizationOptions {
|
|
|
43
43
|
* attribution or where to go next, not for authorization decisions.
|
|
44
44
|
*/
|
|
45
45
|
attributes?: Record<string, string | undefined>;
|
|
46
|
+
/**
|
|
47
|
+
* Query parameters added to this flow's redirect back to the app, on `successUri` and on
|
|
48
|
+
* `errorUri` alike, e.g. an id the page that opened a sign-in popup matches the result against.
|
|
49
|
+
* Unlike `attributes` they reach the browser. Stored with the authorization request, so a
|
|
50
|
+
* callback that cannot find it (no session) goes without them. The names the redirects use
|
|
51
|
+
* themselves (`status`, `provider`, `error`, `error_description`, `reason`) are dropped, even
|
|
52
|
+
* where a redirect leaves one out, and a refusal's metadata wins over a parameter it shares a name
|
|
53
|
+
* with. `undefined` values are dropped, and the same 2 KB limit applies, as an invariant: a value
|
|
54
|
+
* from the browser (a query parameter) is the host's to check first.
|
|
55
|
+
*/
|
|
56
|
+
redirectParams?: Record<string, string | undefined>;
|
|
46
57
|
}
|
|
47
58
|
export interface AuthConfig {
|
|
48
59
|
timing?: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/auth/types.ts"],"mappings":";;;;;YAMY,iBAAiB,WAAW,cAAc;;;;;;;;;;;;;;;iBAerC;EACf;EACA;EACA,UAAU;EACV,QAAQ;EACR,YAAY;;;;;;;YAQF,qBACV,SAAS,SACT,eAAe,kBACZ,QAAQ;iBAEI;;;;;;;;;;;EAWf,aAAa;;
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/auth/types.ts"],"mappings":";;;;;YAMY,iBAAiB,WAAW,cAAc;;;;;;;;;;;;;;;iBAerC;EACf;EACA;EACA,UAAU;EACV,QAAQ;EACR,YAAY;;;;;;;YAQF,qBACV,SAAS,SACT,eAAe,kBACZ,QAAQ;iBAEI;;;;;;;;;;;EAWf,aAAa;;;;;;;;;;;EAWb,iBAAiB;;iBAGF;EACf;EACA,cAAc;EACd,mBAAmB;EACnB,SAAS;IAAkB;;EAC3B;;;;;;;;;IASE;;;;;;;;;;;IAWA;;EAEF;;EAEA;;;;;IAKE;;;;;IAKA;;EAEF;IACE,SAAS;IACT;;;;;;;;;;MAUE;;;;;;;;;;YAWM;iBAEK;EACf,QAAQ;;iBAGO;EAEf,OAAO,SAAS,YAAY,QAAQ;EACpC,SAAS,SAAS,SAAS,UAAU,kBAAkB,QAAQ;EAC/D,SAAS,SAAS,SAAS,WAAW,kBAAkB,QAAQ;EAGhE,cAAc,SAAS,YAAY,QAAQ;EAC3C,cAAc,SAAS,YAAY,QAAQ;EAC3C,sBACE,SAAS,SACT,UAAU,+BACP,QAAQ;EACb,kBAAkB,SAAS,SAAS,cAAc,sBAAsB,QAAQ;EAChF,oBAAoB,SAAS,SAAS,cAAc,sBAAsB,QAAQ;EAClF,oBACE,SAAS,SACT,cAAc,mBACd,sBACG,QAAQ;EAGb,4BAA4B,SAAS,SAAS,QAAQ,gBAAgB,QAAQ;EAC9E,aAAa,SAAS,SAAS,cAAc,sBAAsB,QAAQ;;;;;;EAM3E,kBAAkB,eAAe,6BAA6B;EAG9D,mBAAmB,SAAS,YAAY,QAAQ;EAChD,kBAAkB,SAAS,YAAY,QAAQ;EAG/C,OAAO,WAAW,cAAc;EAChC,kBAAkB,SAAS,YAAY;EACvC,aAAa,mBACX,SAAS,SACT,QAAQ,MACL,QAAQ,iBAAiB,UAAU;EACxC,gBAAgB,sBAAsB;EACtC,eAAe,SAAS,YAAY,QAAQ;EAC5C,eAAe,WAAW,cAAc,QAAQ;EAChD,yBAAyB,0BAA0B,QAAQ"}
|
package/dist/auth/types.d.mts
CHANGED
|
@@ -43,6 +43,17 @@ export interface OAuth2AuthorizationOptions {
|
|
|
43
43
|
* attribution or where to go next, not for authorization decisions.
|
|
44
44
|
*/
|
|
45
45
|
attributes?: Record<string, string | undefined>;
|
|
46
|
+
/**
|
|
47
|
+
* Query parameters added to this flow's redirect back to the app, on `successUri` and on
|
|
48
|
+
* `errorUri` alike, e.g. an id the page that opened a sign-in popup matches the result against.
|
|
49
|
+
* Unlike `attributes` they reach the browser. Stored with the authorization request, so a
|
|
50
|
+
* callback that cannot find it (no session) goes without them. The names the redirects use
|
|
51
|
+
* themselves (`status`, `provider`, `error`, `error_description`, `reason`) are dropped, even
|
|
52
|
+
* where a redirect leaves one out, and a refusal's metadata wins over a parameter it shares a name
|
|
53
|
+
* with. `undefined` values are dropped, and the same 2 KB limit applies, as an invariant: a value
|
|
54
|
+
* from the browser (a query parameter) is the host's to check first.
|
|
55
|
+
*/
|
|
56
|
+
redirectParams?: Record<string, string | undefined>;
|
|
46
57
|
}
|
|
47
58
|
export interface AuthConfig {
|
|
48
59
|
timing?: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/auth/types.ts"],"mappings":";;;;;YAMY,iBAAiB,WAAW,cAAc;;;;;;;;;;;;;;;iBAerC;EACf;EACA;E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AY;EACvC,aAAa,mBACX,SAAS,SACT,QAAQ,MACL,QAAQ,iBAAiB,UAAU;EACxC,gBAAgB,sBAAsB;EACtC,eAAe,SAAS,YAAY,QAAQ;EAC5C,eAAe,WAAW,cAAc,QAAQ;EAChD,yBAAyB,0BAA0B,QAAQ"}
|
|
@@ -65,7 +65,7 @@ function createAppleProvider() {
|
|
|
65
65
|
};
|
|
66
66
|
},
|
|
67
67
|
async loginOAuth2Native({ pkce: _, credentials, ...params }) {
|
|
68
|
-
|
|
68
|
+
if (!credentials.code) throw new require_oauth2_error.OAuth2Error(400, "invalid_request", "code is required");
|
|
69
69
|
const { tokenUri } = this;
|
|
70
70
|
const { code } = credentials;
|
|
71
71
|
const response = await require_oauth2_provider_common.exchangeAuthorizationCode({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apple.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error","verifyIdToken","parseAppleUser","nameClaims","cleanPersonName"],"sources":["../../../src/oauth2/provider/apple.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport { type AppleUser, cleanPersonName, nameClaims, parseAppleUser } from '../name';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n PersonNameComponents,\n Provider,\n UserInfo,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** `iss` of every Apple id token (https://appleid.apple.com/.well-known/openid-configuration). */\nconst APPLE_ISSUER = 'https://appleid.apple.com';\n\n// ref: https://account.apple.com/.well-known/openid-configuration\nexport function createAppleProvider(): Provider {\n return {\n // important notice: response_mode=form_post is required for apple\n authorizationUri: 'https://appleid.apple.com/auth/authorize?response_mode=form_post',\n tokenUri: 'https://appleid.apple.com/auth/token',\n jwkSetUri: 'https://appleid.apple.com/auth/keys',\n userNameAttribute: 'sub',\n defaultScope: ['openid', 'name', 'email'],\n // The web flow's id token echoes the request's nonce; the app's carries the one bound into\n // ASAuthorizationAppleIDRequest, hashed or not (`nonce_supported`).\n nonce: { web: true, native: true },\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n return (await response.json()) as AppleToken;\n },\n async getUserInfo({ id_token }, { clientId, response }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // The audience is the client the code was exchanged as: the bundle id for an app, the\n // Services ID for the web.\n const token = await verifyIdToken<AppleIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: APPLE_ISSUER,\n audience: clientId,\n });\n // Apple's id token never carries a name; on the first authorization of the web flow the\n // name comes in the form_post `user` instead, unsigned, so only its name parts are used\n // and the signed id token's email always wins over the one beside them.\n const user = parseAppleUser(response?.user);\n const data: AppleUserInfo = user ? { ...token, user } : token;\n return {\n data,\n claims: {\n sub: token.sub,\n email: token.email,\n email_verified: true,\n ...nameClaims({\n given_name: user?.name?.firstName,\n family_name: user?.name?.lastName,\n }),\n },\n };\n },\n async loginOAuth2Native({ pkce: _, credentials, ...params }: LoginOAuth2NativeParams) {\n
|
|
1
|
+
{"version":3,"file":"apple.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error","verifyIdToken","parseAppleUser","nameClaims","cleanPersonName"],"sources":["../../../src/oauth2/provider/apple.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport { type AppleUser, cleanPersonName, nameClaims, parseAppleUser } from '../name';\nimport type {\n LoginOAuth2NativeParams,\n NativeCredential,\n OAuth2Token,\n PersonNameComponents,\n Provider,\n UserInfo,\n} from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode, verifyIdToken } from './common';\n\n/** `iss` of every Apple id token (https://appleid.apple.com/.well-known/openid-configuration). */\nconst APPLE_ISSUER = 'https://appleid.apple.com';\n\n// ref: https://account.apple.com/.well-known/openid-configuration\nexport function createAppleProvider(): Provider {\n return {\n // important notice: response_mode=form_post is required for apple\n authorizationUri: 'https://appleid.apple.com/auth/authorize?response_mode=form_post',\n tokenUri: 'https://appleid.apple.com/auth/token',\n jwkSetUri: 'https://appleid.apple.com/auth/keys',\n userNameAttribute: 'sub',\n defaultScope: ['openid', 'name', 'email'],\n // The web flow's id token echoes the request's nonce; the app's carries the one bound into\n // ASAuthorizationAppleIDRequest, hashed or not (`nonce_supported`).\n nonce: { web: true, native: true },\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({ ...params, tokenUri: this.tokenUri });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n return (await response.json()) as AppleToken;\n },\n async getUserInfo({ id_token }, { clientId, response }) {\n invariant(id_token, 'id_token is required');\n invariant(this.jwkSetUri, 'jwkSetUri is required');\n // The audience is the client the code was exchanged as: the bundle id for an app, the\n // Services ID for the web.\n const token = await verifyIdToken<AppleIdToken>(id_token, {\n jwkSetUri: this.jwkSetUri,\n issuer: APPLE_ISSUER,\n audience: clientId,\n });\n // Apple's id token never carries a name; on the first authorization of the web flow the\n // name comes in the form_post `user` instead, unsigned, so only its name parts are used\n // and the signed id token's email always wins over the one beside them.\n const user = parseAppleUser(response?.user);\n const data: AppleUserInfo = user ? { ...token, user } : token;\n return {\n data,\n claims: {\n sub: token.sub,\n email: token.email,\n email_verified: true,\n ...nameClaims({\n given_name: user?.name?.firstName,\n family_name: user?.name?.lastName,\n }),\n },\n };\n },\n async loginOAuth2Native({ pkce: _, credentials, ...params }: LoginOAuth2NativeParams) {\n // The app's mistake, a 400 like any other malformed login body, not a server fault.\n if (!credentials.code) throw new OAuth2Error(400, 'invalid_request', 'code is required');\n const { tokenUri } = this;\n const { code } = credentials;\n const response = await exchangeAuthorizationCode({ code, tokenUri, ...params });\n if (!response.ok) {\n const { error } = (await response.json()) as AppleErrorResponse;\n throw new OAuth2Error(response.status, error);\n }\n const token = (await response.json()) as AppleToken;\n const { data, claims } = await this.getUserInfo(token, { clientId: params.clientId });\n // The app gets the name from Apple on the first authorization only and passes it along in\n // the login body as the platform's `fullName`.\n const fullName = cleanPersonName(credentials.fullName);\n const name = nameClaims({\n given_name: fullName?.givenName ?? undefined,\n family_name: fullName?.familyName ?? undefined,\n middle_name: fullName?.middleName ?? undefined,\n nickname: fullName?.nickname ?? undefined,\n });\n const userInfo: UserInfo<AppleUserInfo> = {\n data: fullName ? { ...(data as AppleUserInfo), fullName } : (data as AppleUserInfo),\n claims: { ...claims, ...name },\n };\n return { token, userInfo };\n },\n };\n}\n\nexport const apple = createAppleProvider();\n\n// Claims of Apple's id token. It carries no name or picture, not even on the first authorization.\n// https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple\nexport interface AppleIdToken {\n iss: string;\n aud: string;\n exp: number;\n iat: number;\n sub: string;\n email: string;\n email_verified: true | 'true';\n is_private_email: boolean;\n /** Native flow, first authorization only: 0 unsupported, 1 unknown, 2 likely real. */\n real_user_status?: number;\n nonce?: string;\n nonce_supported?: boolean;\n}\n\n/**\n * `userInfo.data` of an Apple login: the id token's claims, plus the unsigned name the client\n * passed on the first authorization, cleaned (see `nameClaims` for the standard claims made of it).\n */\nexport interface AppleUserInfo extends AppleIdToken {\n /** Web flow: Apple's form_post `user`, as Apple names it. */\n user?: AppleUser;\n /** Native flow: the login body's `fullName`, which alone keeps `namePrefix` / `nameSuffix`. */\n fullName?: PersonNameComponents;\n}\n\n// https://developer.apple.com/documentation/devicemanagement/implementing-the-oauth2-authentication-user-enrollment-flow\n// https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens\nexport interface AppleToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n expires_in: number;\n refresh_token: string;\n id_token: string;\n}\n\nexport interface AppleNativeCredential extends NativeCredential {\n state: string;\n code: string;\n id_token: string;\n}\n\n// https://developer.apple.com/documentation/sign_in_with_apple/errorresponse\nexport interface AppleErrorResponse {\n error:\n | 'invalid_request'\n | 'invalid_client'\n | 'invalid_grant'\n | 'unauthorized_client'\n | 'unsupported_grant_type'\n | 'invalid_scope';\n}\n"],"mappings":";;;;;;;AAcA,MAAM,eAAe;AAGrB,SAAgB,sBAAgC;CAC9C,OAAO;EAEL,kBAAkB;EAClB,UAAU;EACV,WAAW;EACX,mBAAmB;EACnB,cAAc;GAAC;GAAU;GAAQ;EAAO;EAGxC,OAAO;GAAE,KAAK;GAAM,QAAQ;EAAK;EACjC,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAOA,+BAAAA,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAMC,+BAAAA,0BAA0B;IAAE,GAAG;IAAQ,UAAU,KAAK;GAAS,CAAC;GACvF,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,UAAW,MAAM,SAAS,KAAK;IACvC,MAAM,IAAIC,qBAAAA,YAAY,SAAS,QAAQ,KAAK;GAC9C;GACA,OAAQ,MAAM,SAAS,KAAK;EAC9B;EACA,MAAM,YAAY,EAAE,YAAY,EAAE,UAAU,YAAY;GACtD,CAAA,GAAA,cAAA,UAAA,CAAU,UAAU,sBAAsB;GAC1C,CAAA,GAAA,cAAA,UAAA,CAAU,KAAK,WAAW,uBAAuB;GAGjD,MAAM,QAAQ,MAAMC,+BAAAA,cAA4B,UAAU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oBAAoB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apple.d.cts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;
|
|
1
|
+
{"version":3,"file":"apple.d.cts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;qBAoF1B,OAAK;iBAID;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;;;;;iBAOe,sBAAsB;;EAErC,OAAO;;EAEP,WAAW;;iBAKI,mBAAmB;EAClC;EACA;EACA;EACA;EACA;;iBAGe,8BAA8B;EAC7C;EACA;EACA;;iBAIe;EACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apple.d.mts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;
|
|
1
|
+
{"version":3,"file":"apple.d.mts","names":[],"sources":["../../../src/oauth2/provider/apple.ts"],"mappings":";;wBAiBgB,uBAAuB;qBAoF1B,OAAK;iBAID;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;;;;;iBAOe,sBAAsB;;EAErC,OAAO;;EAEP,WAAW;;iBAKI,mBAAmB;EAClC;EACA;EACA;EACA;EACA;;iBAGe,8BAA8B;EAC7C;EACA;EACA;;iBAIe;EACf"}
|
|
@@ -64,7 +64,7 @@ function createAppleProvider() {
|
|
|
64
64
|
};
|
|
65
65
|
},
|
|
66
66
|
async loginOAuth2Native({ pkce: _, credentials, ...params }) {
|
|
67
|
-
|
|
67
|
+
if (!credentials.code) throw new OAuth2Error(400, "invalid_request", "code is required");
|
|
68
68
|
const { tokenUri } = this;
|
|
69
69
|
const { code } = credentials;
|
|
70
70
|
const response = await exchangeAuthorizationCode({
|