@ultimat3/auth 31.48.0 → 31.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,13 @@ export type AuthServerGrant =
11
11
 
12
12
  export const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
13
13
 
14
+ /**
15
+ * The `client_id` prefix of a client that registered itself at `/oauth/register` (RFC 7591); one
16
+ * the app registers is `c_`. Only `storeClient` mints either, and `purge` reaps only this one —
17
+ * once older than the refresh idle window with no grant, code or device code naming it.
18
+ */
19
+ export const DYNAMIC_CLIENT_PREFIX = 'd_';
20
+
14
21
  /** `none` is a public client (PKCE is its proof); the two secret methods are a confidential one. */
15
22
  export type ClientAuthMethod = 'none' | 'client_secret_basic' | 'client_secret_post';
16
23
 
@@ -29,6 +36,11 @@ export interface AuthServerClient {
29
36
  /** Resource indicators this client SERVES — what its introspection may see. */
30
37
  readonly resources: readonly string[];
31
38
  readonly createdAt: Date;
39
+ /**
40
+ * A metadata-document client's `client_id` host: the only part of what a consent page shows that
41
+ * the document's author does not choose. Absent for a registered client.
42
+ */
43
+ readonly host?: string | undefined;
32
44
  }
33
45
 
34
46
  /** What `readRequest` screened and `approve` re-screens: the consent page's whole input. */
@@ -101,8 +113,29 @@ export interface DeviceCodeRecord {
101
113
 
102
114
  /** What `resolve(token)` answers for a live access token. */
103
115
  export interface ResolvedGrant {
116
+ /**
117
+ * The grant the token was issued under — a user's consent, or a `client_credentials` client's
118
+ * own grant — kept across every refresh rotation: what
119
+ * `revokeGrant({ subject, grantId })` ends. `resolve` always sets it; optional only so a
120
+ * `ResolvedGrant` built by hand (a test's fake source) still compiles. Required waits on `next`.
121
+ */
122
+ readonly grantId?: string | undefined;
104
123
  readonly subject: string;
105
124
  readonly scopes: ReadonlySet<string>;
106
125
  readonly clientId: string;
107
126
  readonly resource: string | null;
108
127
  }
128
+
129
+ /** One live grant of a subject, as `grants({ subject })` lists it: what a "connected apps" page shows. */
130
+ export interface LiveGrant {
131
+ readonly grantId: string;
132
+ readonly clientId: string;
133
+ readonly scopes: readonly string[];
134
+ readonly resource: string | null;
135
+ readonly createdAt: Date;
136
+ /**
137
+ * The last refresh (the creation until one). Listing reads stored token expiry, not this: a
138
+ * token issued before `refreshIdleDays` was shortened keeps its stored expiry.
139
+ */
140
+ readonly refreshedAt: Date;
141
+ }
@@ -13,7 +13,7 @@ import {
13
13
  type AuthorizationServerOptions,
14
14
  resolveAuthServerConfig,
15
15
  } from './authorization-server-config';
16
- import { consentInvalid } from './authorization-server-errors';
16
+ import { consentInvalid, grantsUnsupported } from './authorization-server-errors';
17
17
  import {
18
18
  type ReadRequestResult,
19
19
  redirectWith,
@@ -21,7 +21,7 @@ import {
21
21
  } from './authorization-server-request';
22
22
  import { authServerMetadata, authServerRoutes } from './authorization-server-routes';
23
23
  import { resolveAccess, resolvedGrant } from './authorization-server-tokens';
24
- import type { AuthorizationRequest, ResolvedGrant } from './authorization-server-types';
24
+ import type { AuthorizationRequest, LiveGrant, ResolvedGrant } from './authorization-server-types';
25
25
  import type { AuthServerRoute } from './authorization-server-wire';
26
26
  import { type DeviceReading, decideDevice, readDevice } from './grant-device';
27
27
  import { randomToken, sha256Hex } from './tokens';
@@ -74,6 +74,31 @@ export interface AuthorizationServer {
74
74
  readonly subject: string;
75
75
  readonly clientId?: string | undefined;
76
76
  }): Promise<number>;
77
+ /**
78
+ * One grant of `subject` by its `grantId`, refresh tokens included: 1, or 0 when it is unknown,
79
+ * already revoked, or another subject's (or another client's than the one named) — alike. Two
80
+ * racing calls on one grant count it once on a store implementing `revokeLiveGrant`; on one
81
+ * without it, both may answer 1.
82
+ * `authorizationServer()` always sets it; optional only so an `AuthorizationServer` of an app's
83
+ * own (a test's fake) still compiles. Required waits on `next`.
84
+ */
85
+ revokeGrant?(input: {
86
+ readonly subject: string;
87
+ readonly grantId: string;
88
+ readonly clientId?: string | undefined;
89
+ }): Promise<number>;
90
+ /**
91
+ * The live grants of `subject` (of one client when named), oldest first: not revoked and
92
+ * holding a stored token neither expired nor retired. Not a promise the next refresh succeeds:
93
+ * a client since denied refresh can stay listed while its grant row and an unexpired, unretired
94
+ * token remain (`purge` may remove the row sooner). Copies, never the rows. Each `grantId` is
95
+ * what `resolve` answers and `revokeGrant` takes.
96
+ * Always set by `authorizationServer()`; optional only as `revokeGrant` is.
97
+ */
98
+ grants?(input: {
99
+ readonly subject: string;
100
+ readonly clientId?: string | undefined;
101
+ }): Promise<readonly LiveGrant[]>;
77
102
  /** Run from the app's own `task`: nothing here runs on a timer. */
78
103
  purge(input: { readonly before: Date }): Promise<number>;
79
104
  }
@@ -193,6 +218,35 @@ export function authorizationServer(options: AuthorizationServerOptions): Author
193
218
  { subject: input.subject, clientId: input.clientId },
194
219
  config.clock.now(),
195
220
  ),
221
+ async revokeGrant(input) {
222
+ const grant = await config.store.getGrant(input.grantId);
223
+ // Another subject's grant answers as an unknown one: an id is no proof of ownership.
224
+ if (grant === null || grant.revokedAt !== null || grant.subject !== input.subject) return 0;
225
+ if (input.clientId !== undefined && grant.clientId !== input.clientId) return 0;
226
+ // The store's conditional write decides a race: only the call that ended it counts it.
227
+ const at = config.clock.now();
228
+ if (config.store.revokeLiveGrant !== undefined) {
229
+ return (await config.store.revokeLiveGrant(grant.id, at)) ? 1 : 0;
230
+ }
231
+ await config.store.revokeGrant(grant.id, at);
232
+ return 1;
233
+ },
234
+ async grants(input) {
235
+ if (config.store.liveGrants === undefined) throw grantsUnsupported();
236
+ const live = await config.store.liveGrants(
237
+ { subject: input.subject, clientId: input.clientId },
238
+ config.clock.now(),
239
+ );
240
+ return live.map((grant) => ({
241
+ grantId: grant.id,
242
+ clientId: grant.clientId,
243
+ // Copies: a caller editing its listing must not edit a memory store's rows.
244
+ scopes: [...grant.scopes],
245
+ resource: grant.resource,
246
+ createdAt: new Date(grant.createdAt.getTime()),
247
+ refreshedAt: new Date(grant.refreshedAt.getTime()),
248
+ }));
249
+ },
196
250
  purge: ({ before }) =>
197
251
  config.store.purge(before, new Date(before.getTime() - config.refreshIdleMs)),
198
252
  };
@@ -43,7 +43,7 @@ export class PostgresAuthAdapter implements AuthAdapter {
43
43
  readonly name = 'builtin-postgres';
44
44
  readonly #client: DbClient | undefined;
45
45
  readonly #clock: Clock;
46
- readonly #passkeys: PasskeyStore = postgresPasskeyStore(() => this.#db);
46
+ readonly #passkeys: Required<PasskeyStore> = postgresPasskeyStore(() => this.#db);
47
47
  // The passkey members are `passkey-postgres.ts`'s, bound once: closures over the store, no `this`.
48
48
  readonly putPasskey: PasskeyStore['putPasskey'] = this.#passkeys.putPasskey;
49
49
  readonly findPasskey: PasskeyStore['findPasskey'] = this.#passkeys.findPasskey;
@@ -51,6 +51,7 @@ export class PostgresAuthAdapter implements AuthAdapter {
51
51
  readonly advancePasskeyCounter: PasskeyStore['advancePasskeyCounter'] =
52
52
  this.#passkeys.advancePasskeyCounter;
53
53
  readonly deletePasskey: PasskeyStore['deletePasskey'] = this.#passkeys.deletePasskey;
54
+ readonly renamePasskey: Required<PasskeyStore>['renamePasskey'] = this.#passkeys.renamePasskey;
54
55
  readonly putPasskeyChallenge: PasskeyStore['putPasskeyChallenge'] =
55
56
  this.#passkeys.putPasskeyChallenge;
56
57
  readonly takePasskeyChallenge: PasskeyStore['takePasskeyChallenge'] =
@@ -17,9 +17,10 @@ export interface ClientScopeOptions {
17
17
  }
18
18
 
19
19
  /**
20
- * `''` for the anonymous page — the empty scope core reads as "nobody". Otherwise the principal
21
- * AND who is really acting, so an admin impersonating a user is not the user's own scope: their
22
- * stores must never share records, on the page or on disk. The derivation is core's, because
20
+ * `''` for the anonymous page — the empty scope core reads as "nobody". Otherwise the principal,
21
+ * who is really acting and the actor's org, so an admin impersonating a user is not the user's own
22
+ * scope, nor one person in two orgs one scope: their stores must never share records, on the page
23
+ * or on disk. The derivation is core's, because
23
24
  * `@ultimat3/action` compares against it and may not reach this tier's sibling for one function.
24
25
  */
25
26
  export function clientScopeOf(actor: Actor, options: ClientScopeOptions = {}): string {
package/src/errors.ts CHANGED
@@ -43,6 +43,9 @@ export const AUTH_OWNED_ERROR_CODES = [
43
43
  'X_SAML_METADATA_INVALID',
44
44
  'X_IDENTITY_PROVIDER_UNKNOWN',
45
45
  'X_AUTH_CLIENT_INVALID',
46
+ 'X_AUTH_GRANTS_UNSUPPORTED',
47
+ 'X_PASSKEY_LABEL_INVALID',
48
+ 'X_PASSKEY_RENAME_UNSUPPORTED',
46
49
  ] as const;
47
50
 
48
51
  /**
@@ -110,6 +113,9 @@ export const AUTH_ERROR_TITLES: Readonly<Record<AuthOwnedErrorCode, string>> = {
110
113
  X_IDENTITY_PROVIDER_UNKNOWN: 'the URL named an identity provider the sso routes were not given',
111
114
  X_AUTH_CLIENT_INVALID:
112
115
  'an oauth client was registered with a list value the store cannot hold as one value',
116
+ X_AUTH_GRANTS_UNSUPPORTED: "the authorization server's store cannot list a subject's live grants",
117
+ X_PASSKEY_LABEL_INVALID: 'the passkey label is not one a person can read back',
118
+ X_PASSKEY_RENAME_UNSUPPORTED: 'the auth adapter cannot rename a passkey',
113
119
  };
114
120
 
115
121
  // Registered unconditionally, in one call: a second package claiming a code auth owns has to fail
@@ -79,11 +79,15 @@ export async function exchangeRefresh(
79
79
  const token = await config.store.getToken(hash);
80
80
  if (token === null || token.kind !== 'refresh')
81
81
  return invalidGrant('the refresh token is unknown');
82
- if (token.retiredAt !== null) return replayed(config, token.grantId, client.clientId);
83
82
  const grant = await config.store.getGrant(token.grantId);
83
+ // Asked BEFORE the replay branch: a retired token is a replay only from the client it was issued
84
+ // to. Presented by any other client it would otherwise revoke a grant that client never held.
85
+ const foreign = grant !== null && grant.clientId !== client.clientId;
86
+ if (token.retiredAt !== null && !foreign) {
87
+ return replayed(config, token.grantId, client.clientId);
88
+ }
84
89
  if (grant === null || grant.revokedAt !== null) return invalidGrant('the grant is revoked');
85
- if (grant.clientId !== client.clientId)
86
- return invalidGrant('the token was issued to another client');
90
+ if (foreign) return invalidGrant('the token was issued to another client');
87
91
  if (grant.refreshedAt.getTime() + config.refreshIdleMs <= now.getTime()) {
88
92
  return invalidGrant('the grant sat idle past its refresh window');
89
93
  }
@@ -23,6 +23,13 @@ import {
23
23
  readIdentityState,
24
24
  } from './identity-provider-cookie';
25
25
  import { oauthRouteStatus } from './identity-provider-status';
26
+ import {
27
+ mfaChallengeCookie,
28
+ mfaChallengeOf,
29
+ mfaHandoffMissing,
30
+ mfaLandingPath,
31
+ type SignInFactory,
32
+ } from './mfa-handoff';
26
33
  import { oauthStateInvalid } from './oauth-errors';
27
34
  import type { OAuthGrants } from './oauth-login';
28
35
  import { OAUTH_START_ROUTE_PATH } from './oauth-paths';
@@ -66,6 +73,14 @@ export interface SignInRouteOptions {
66
73
  readonly secret?: string | undefined;
67
74
  /** A fixed landing path, never `?next=`: `nextAfterSignIn` in `@ultimat3/http` is the one check. */
68
75
  readonly successPath?: string | undefined;
76
+ /**
77
+ * The app's own second-factor page. A user with TOTP enrolled is sent there (303) instead of to
78
+ * `successPath`, with the sealed challenge in the `__Host-x_mfa` cookie — HttpOnly, and living
79
+ * `MFA_CHALLENGE_TTL_MS`: `completeMfa(auth, readMfaChallenge(request) ?? '', code)` finishes.
80
+ * Omit it and that user's callback is refused `X_MFA_REQUIRED` (401): they cannot finish here.
81
+ * One absolute path on this origin, or `X_CONFIG_INVALID` at the call.
82
+ */
83
+ readonly mfaPath?: string | undefined;
69
84
  /** The client address recorded on the session; `@ultimat3/http` knows the proxy chain. */
70
85
  readonly clientIp?: ((request: Request) => string | null | undefined) | undefined;
71
86
  readonly env?: Readonly<Record<string, string | undefined>> | undefined;
@@ -79,6 +94,8 @@ export interface SignInRoutePolicy {
79
94
  unknown(segment: string): UltimateError;
80
95
  /** `auth.sso` / `auth.oauth`: the log event prefix (`<prefix>.refused`). */
81
96
  readonly event: string;
97
+ /** The call an operator edits: what a `fix:` line about these routes' options names. */
98
+ readonly factory: SignInFactory;
82
99
  readonly names: { readonly start: string; readonly callback: string; readonly acs: string };
83
100
  /** A throw with no code, logged and turned into the refusal served. Its text never is. */
84
101
  uncoded(error: unknown): UltimateError;
@@ -98,14 +115,20 @@ export interface SignInRoutes {
98
115
  const MAX_FORM_BYTES = 512 * 1024;
99
116
  const FRAMEWORK_CODE = /^X_[A-Z0-9_]+$/;
100
117
 
118
+ /** The one place these routes put a line on a Response: each is a `serializeSetCookie` value. */
119
+ function withCookies(init: Record<string, string>, cookies: readonly string[]): Headers {
120
+ const headers = new Headers(init);
121
+ for (const cookie of cookies) headers.append('set-cookie', cookie);
122
+ return headers;
123
+ }
124
+
101
125
  function problem(policy: SignInRoutePolicy, error: unknown, cookies: readonly string[]): Response {
102
126
  const refusal = isUltimateError(error) ? error : policy.uncoded(error);
103
127
  const status = oauthRouteStatus(refusal.code);
104
128
  const fields = { code: refusal.code, status, cause: refusal.cause, fix: refusal.fix };
105
129
  if (status >= 500) logger.error(`${policy.event}.refused`, fields);
106
130
  else logger.info(`${policy.event}.refused`, fields);
107
- const headers = new Headers({ 'content-type': 'application/json; charset=utf-8' });
108
- for (const cookie of cookies) headers.append('set-cookie', cookie);
131
+ const headers = withCookies({ 'content-type': 'application/json; charset=utf-8' }, cookies);
109
132
  // An anonymous caller reads the code, its title and docs, and one fixed sentence; the authored
110
133
  // cause and fix name env vars and what an IdP answered, so they go to the log only.
111
134
  const body = {
@@ -170,6 +193,8 @@ export function signInRoutes(
170
193
  policy: SignInRoutePolicy,
171
194
  ): SignInRoutes {
172
195
  const back = policy.callbackPath ?? callbackPath();
196
+ const mfaPath =
197
+ options.mfaPath === undefined ? undefined : mfaLandingPath(policy.factory, options.mfaPath);
173
198
  const seal = {
174
199
  clock: auth.clock,
175
200
  ...(options.secret === undefined ? {} : { secret: options.secret }),
@@ -183,8 +208,9 @@ export function signInRoutes(
183
208
  const provider = policy.resolve(startSegment(request), 'start');
184
209
  const callbackUrl = `${base}${back.pathFor(provider.id)}`;
185
210
  const redirect = await provider.begin({ callbackUrl, clock: auth.clock });
186
- const headers = new Headers({ location: redirect.location });
187
- headers.append('set-cookie', identityStateCookie(provider, redirect.state, seal));
211
+ const headers = withCookies({ location: redirect.location }, [
212
+ identityStateCookie(provider, redirect.state, seal),
213
+ ]);
188
214
  return new Response(null, { status: 302, headers });
189
215
  } catch (error) {
190
216
  return problem(policy, error, []);
@@ -224,13 +250,20 @@ export function signInRoutes(
224
250
  ip: options.clientIp?.(request) ?? null,
225
251
  userAgent: request.headers.get('user-agent'),
226
252
  });
227
- const headers = new Headers({ location: options.successPath ?? '/' });
228
- headers.append('set-cookie', result.cookie);
229
- for (const cookie of clear) headers.append('set-cookie', cookie);
253
+ const headers = withCookies({ location: options.successPath ?? '/' }, [
254
+ result.cookie,
255
+ ...clear,
256
+ ]);
230
257
  // 303: the answer may arrive as a POST, and the destination is a GET either way.
231
258
  return new Response(null, { status: 303, headers });
232
259
  } catch (error) {
233
- return problem(policy, error, clear);
260
+ // Identity proven, second factor owed. The challenge goes to the app's page in a cookie
261
+ // only this origin's server reads — never the URL, a body or the log line `problem` writes.
262
+ const challenge = mfaChallengeOf(error);
263
+ if (challenge === null) return problem(policy, error, clear);
264
+ if (mfaPath === undefined) return problem(policy, mfaHandoffMissing(policy.factory), clear);
265
+ const headers = withCookies({ location: mfaPath }, [mfaChallengeCookie(challenge), ...clear]);
266
+ return new Response(null, { status: 303, headers });
234
267
  }
235
268
  };
236
269
 
@@ -71,6 +71,7 @@ export function identityProviderRoutes(
71
71
  },
72
72
  unknown: identityProviderUnknown,
73
73
  event: 'auth.sso',
74
+ factory: 'identityProviderRoutes',
74
75
  names: { start: 'auth.sso.start', callback: 'auth.sso.callback', acs: 'auth.sso.acs' },
75
76
  uncoded,
76
77
  grants: (identity) => options.resolveGrants?.(identity),
package/src/index.ts CHANGED
@@ -87,6 +87,7 @@ export type {
87
87
  AuthTokenRecord,
88
88
  ClientAuthMethod,
89
89
  DeviceCodeRecord,
90
+ LiveGrant,
90
91
  ResolvedGrant,
91
92
  } from './authorization-server-types';
92
93
  export { DEVICE_GRANT } from './authorization-server-types';
@@ -217,6 +218,13 @@ export {
217
218
  MFA_CHALLENGE_TTL_MS,
218
219
  mfaChallengeRequired,
219
220
  } from './mfa-challenge';
221
+ export {
222
+ clearMfaChallengeCookie,
223
+ MFA_CHALLENGE_COOKIE,
224
+ mfaChallengeCookie,
225
+ mfaChallengeOf,
226
+ readMfaChallenge,
227
+ } from './mfa-handoff';
220
228
  export type {
221
229
  PostgresTotpReplayGuard,
222
230
  PostgresTotpReplayGuardOptions,
@@ -321,7 +329,9 @@ export type {
321
329
  PasskeyPolicyInput,
322
330
  PasskeyRelyingParty,
323
331
  } from './passkey-config';
332
+ export { PASSKEY_LABEL_MAX } from './passkey-errors';
324
333
  export { verifyPasskeyEvidence } from './passkey-evidence';
334
+ export { renamePasskey } from './passkey-label';
325
335
  export type { PasskeyLogin } from './passkey-login';
326
336
  export { passkeyLogin } from './passkey-login';
327
337
  export type { PasskeyStepUp, PasskeyStepUpOptions } from './passkey-step-up';
@@ -417,6 +427,8 @@ export {
417
427
  sessionExpiry,
418
428
  verifySession,
419
429
  } from './session';
430
+ export type { VerifiedSession } from './session-user';
431
+ export { verifySessionWithUser } from './session-user';
420
432
  /** A sign-out response's headers: the session cookie expired, and `Clear-Site-Data`. */
421
433
  export type { SignOutHeadersOptions } from './sign-out';
422
434
  export { SIGN_OUT_CLEAR_SITE_DATA, signOutHeaders } from './sign-out';
@@ -49,7 +49,7 @@ export class MemoryAuthAdapter implements AuthAdapter {
49
49
  readonly #accounts = new Map<string, AuthAccount>();
50
50
  readonly #verifications = new Map<string, AuthVerification>();
51
51
  readonly #apiKeys = new Map<string, AuthApiKeyRecord>();
52
- readonly #passkeys: PasskeyStore = memoryPasskeyStore();
52
+ readonly #passkeys: Required<PasskeyStore> = memoryPasskeyStore();
53
53
  // The passkey members are `passkey-memory.ts`'s, bound once: closures over the store, no `this`.
54
54
  readonly putPasskey: PasskeyStore['putPasskey'] = this.#passkeys.putPasskey;
55
55
  readonly findPasskey: PasskeyStore['findPasskey'] = this.#passkeys.findPasskey;
@@ -57,6 +57,7 @@ export class MemoryAuthAdapter implements AuthAdapter {
57
57
  readonly advancePasskeyCounter: PasskeyStore['advancePasskeyCounter'] =
58
58
  this.#passkeys.advancePasskeyCounter;
59
59
  readonly deletePasskey: PasskeyStore['deletePasskey'] = this.#passkeys.deletePasskey;
60
+ readonly renamePasskey: Required<PasskeyStore>['renamePasskey'] = this.#passkeys.renamePasskey;
60
61
  readonly putPasskeyChallenge: PasskeyStore['putPasskeyChallenge'] =
61
62
  this.#passkeys.putPasskeyChallenge;
62
63
  readonly takePasskeyChallenge: PasskeyStore['takePasskeyChallenge'] =
@@ -0,0 +1,92 @@
1
+ // Single responsibility: how the built-in sign-in routes hand an `X_MFA_REQUIRED` challenge to the
2
+ // app's own second-factor page — the `mfaPath` they redirect to, the one cookie the challenge rides
3
+ // in, and its reader. A cookie and never the URL or a body: a URL is in a log, a history and a
4
+ // `Referer`; `__Host-` + `HttpOnly` is read by this origin's server and nothing else.
5
+
6
+ import {
7
+ ConfigInvalidError,
8
+ isUltimateError,
9
+ readCookie,
10
+ renderCauseValue,
11
+ serializeSetCookie,
12
+ } from '@ultimat3/core';
13
+ import { AuthError } from './errors';
14
+ import { MFA_CHALLENGE_TTL_MS } from './mfa-challenge';
15
+ import type { RequestLike } from './session';
16
+
17
+ /** `__Host-`: Secure, `Path=/`, no `Domain` — a sibling subdomain can neither read nor plant it. */
18
+ export const MFA_CHALLENGE_COOKIE = '__Host-x_mfa';
19
+
20
+ /** The sign-in front door a `fix:` line names: the call an operator edits. */
21
+ export type SignInFactory = 'oauthLogin' | 'identityProviderRoutes';
22
+
23
+ const CALL: Readonly<Record<SignInFactory, string>> = {
24
+ oauthLogin: "oauthLogin(auth, { mfaPath: '/sign-in/mfa' })",
25
+ identityProviderRoutes: "identityProviderRoutes(auth, { providers, mfaPath: '/sign-in/mfa' })",
26
+ };
27
+
28
+ /** A stand-in origin to read `mfaPath` against: only its pathname is ever compared. */
29
+ const ORIGIN = 'https://x.invalid';
30
+
31
+ const PAGE =
32
+ "on that page: completeMfa(auth, readMfaChallenge(request) ?? '', code), then send result.cookie and clearMfaChallengeCookie()";
33
+
34
+ /**
35
+ * `mfaPath`, refused at the call when a browser could read it as anywhere but a path on this
36
+ * origin: `//host`, `/\host` and a scheme are all "another site" to a `Location` header.
37
+ */
38
+ export function mfaLandingPath(factory: SignInFactory, path: string): string {
39
+ const local =
40
+ typeof path === 'string' &&
41
+ path.startsWith('/') &&
42
+ // `//host` is another origin — and `//` or `//[` is no URL at all: `new URL` throws, uncoded.
43
+ !path.startsWith('//') &&
44
+ !/[\\?#]/.test(path) &&
45
+ URL.canParse(path, ORIGIN) &&
46
+ // A `..` or `.` segment normalises away, so the pathname is no longer the whole input.
47
+ new URL(path, ORIGIN).pathname === path;
48
+ if (!local) {
49
+ throw new ConfigInvalidError({
50
+ cause: `${factory}({ mfaPath: ${renderCauseValue(path)} }) is not a normalised absolute path on this origin, so the MFA challenge cookie would be followed by a redirect somewhere else`,
51
+ fix: `${CALL[factory]} // one absolute path: no host, query, fragment, backslash or ./.. segment`,
52
+ });
53
+ }
54
+ return path;
55
+ }
56
+
57
+ /** The sealed challenge of an `X_MFA_REQUIRED`, or `null` for every other throw. */
58
+ export function mfaChallengeOf(error: unknown): string | null {
59
+ if (!isUltimateError(error) || error.code !== 'X_MFA_REQUIRED') return null;
60
+ const challenge = error.meta?.['challenge'];
61
+ return typeof challenge === 'string' && challenge !== '' ? challenge : null;
62
+ }
63
+
64
+ /**
65
+ * What the callback is refused with when no `mfaPath` was given: the same code, with the cause and
66
+ * fix that are true for a built-in route — there is no "your sign-in handler" to catch it in — and
67
+ * WITHOUT the challenge, which has nowhere to travel and so is not kept.
68
+ */
69
+ export const mfaHandoffMissing = (factory: SignInFactory): AuthError =>
70
+ new AuthError({
71
+ code: 'X_MFA_REQUIRED',
72
+ cause: `this account has TOTP enrolled, and ${factory}() was given no mfaPath to hand the second-factor challenge to, so the sign-in cannot finish`,
73
+ fix: `${CALL[factory]} // ${PAGE}`,
74
+ });
75
+
76
+ /** The challenge as a `Set-Cookie`, living exactly as long as the challenge itself. */
77
+ export const mfaChallengeCookie = (challenge: string): string =>
78
+ serializeSetCookie(MFA_CHALLENGE_COOKIE, challenge, {
79
+ maxAge: Math.floor(MFA_CHALLENGE_TTL_MS / 1000),
80
+ });
81
+
82
+ /** Sent with the response that finishes (or abandons) the second leg. */
83
+ export const clearMfaChallengeCookie = (): string =>
84
+ serializeSetCookie(MFA_CHALLENGE_COOKIE, '', { maxAge: 0 });
85
+
86
+ /**
87
+ * The challenge a built-in callback handed to `mfaPath`, or `null`: what `completeMfa` takes as its
88
+ * second argument. Unverified here on purpose — `completeMfa` opens the seal and checks the expiry.
89
+ */
90
+ export function readMfaChallenge(request: RequestLike): string | null {
91
+ return readCookie(request.headers.get('cookie'), MFA_CHALLENGE_COOKIE);
92
+ }
@@ -70,6 +70,14 @@ export interface OAuthLoginOptions {
70
70
  readonly timeoutMs?: number | undefined;
71
71
  /** Where a signed-in browser lands. A fixed path — never read from the request. See below. */
72
72
  readonly successPath?: string | undefined;
73
+ /**
74
+ * The app's own second-factor page. A user with TOTP enrolled is sent there (303) instead of to
75
+ * `successPath`, with the sealed challenge in the `__Host-x_mfa` cookie — HttpOnly, and living
76
+ * `MFA_CHALLENGE_TTL_MS`: `completeMfa(auth, readMfaChallenge(request) ?? '', code)` finishes.
77
+ * Omit it and that user's callback is refused `X_MFA_REQUIRED` (401): they cannot finish here.
78
+ * One absolute path on this origin, or `X_CONFIG_INVALID` at the call.
79
+ */
80
+ readonly mfaPath?: string | undefined;
73
81
  /** Narrower scopes than the provider's defaults, when the app wants less. */
74
82
  readonly scopes?: readonly string[] | undefined;
75
83
  /**
@@ -197,6 +205,7 @@ export function oauthLogin(auth: Auth, options: OAuthLoginOptions = {}): OAuthLo
197
205
  },
198
206
  unknown,
199
207
  event: 'auth.oauth',
208
+ factory: 'oauthLogin',
200
209
  names: { start: 'auth.oauth.start', callback: 'auth.oauth.callback', acs: 'auth.oauth.acs' },
201
210
  uncoded,
202
211
  grants(identity) {
@@ -79,6 +79,15 @@ function checkOrigin(rpId: string, origin: unknown): string {
79
79
  if (!secure) {
80
80
  throw passkeyConfigInvalid('origins', origin, 'only https, or http://localhost, runs WebAuthn');
81
81
  }
82
+ // A browser sends ONE exact origin, so a pattern matches nothing and every ceremony would fail
83
+ // `X_PASSKEY_INVALID` in production: `*` parses as a host character, and is refused here.
84
+ if (!HOST.test(url.hostname) || IPV4.test(url.hostname)) {
85
+ throw passkeyConfigInvalid(
86
+ 'origins',
87
+ origin,
88
+ 'its host is not a DNS name — a wildcard (*) matches no origin and an IP is no rp id: list each one',
89
+ );
90
+ }
82
91
  if (url.hostname !== rpId && !url.hostname.endsWith(`.${rpId}`)) {
83
92
  throw passkeyConfigInvalid('origins', origin, `its host is not ${rpId} or a subdomain of it`);
84
93
  }
@@ -87,3 +87,25 @@ export const stepUpDigestInvalid = (length: number): AuthError =>
87
87
 
88
88
  /** A SHA-512 in hex is 128 bytes; this leaves room for a versioned, prefixed one. */
89
89
  export const MAX_STEP_UP_DIGEST_BYTES = 1024;
90
+
91
+ /** At `renamePasskey`: a label is shown back to its owner, so it must read as one. */
92
+ export const passkeyLabelInvalid = (reason: string): AuthError =>
93
+ new AuthError({
94
+ code: 'X_PASSKEY_LABEL_INVALID',
95
+ cause: `the passkey label is ${reason}: a label is 1-${PASSKEY_LABEL_MAX} characters after trimming, then no control character or lone surrogate`,
96
+ fix: "renamePasskey(auth, { userId, id, label: 'Work laptop' }) // or label: null to clear it",
97
+ callerFix: `name the passkey in 1 to ${PASSKEY_LABEL_MAX} characters`,
98
+ meta: { reason },
99
+ });
100
+
101
+ /** An adapter written before `renamePasskey`: the member is optional, so this is asked per call. */
102
+ export const passkeyRenameUnsupported = (adapter: string): AuthError =>
103
+ new AuthError({
104
+ code: 'X_PASSKEY_RENAME_UNSUPPORTED',
105
+ cause: `the auth adapter ${renderCauseValue(adapter)} has no renamePasskey method, so a passkey label cannot be written`,
106
+ fix: 'defineAuth({ adapter: postgresAuthAdapter() }) // or memoryAuthAdapter(); an adapter of your own implements renamePasskey(userId, id, label), held by authAdapterConformance',
107
+ meta: { adapter },
108
+ });
109
+
110
+ /** Longest label a person can give a passkey, in characters (UTF-16 code units are not a person's). */
111
+ export const PASSKEY_LABEL_MAX = 64;
@@ -0,0 +1,52 @@
1
+ // Single responsibility: a passkey's label — the name its owner gives it ("Work laptop") so a list of
2
+ // several can be told apart and the right one removed. One reader for every label written
3
+ // (`passkeyLabel`), and `renamePasskey`, the owner-scoped rename — right after `register`, or later.
4
+
5
+ import type { PasskeyCredential } from './adapter';
6
+ import type { Auth } from './auth';
7
+ import { PASSKEY_LABEL_MAX, passkeyLabelInvalid, passkeyRenameUnsupported } from './passkey-errors';
8
+
9
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it finds.
10
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
11
+ /** A surrogate half with no partner: memory would keep it, Postgres' UTF-8 `text` cannot. */
12
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
13
+
14
+ /** Counted by code point and stopped at the first one past the limit: no array of a huge input. */
15
+ const longerThan = (text: string, max: number): boolean => {
16
+ let length = 0;
17
+ for (const _character of text) {
18
+ length += 1;
19
+ if (length > max) return true;
20
+ }
21
+ return false;
22
+ };
23
+
24
+ /**
25
+ * The label as stored: trimmed, `null` for none. Judged AFTER the trim: blank, longer than
26
+ * `PASSKEY_LABEL_MAX` characters, holding a control character (a newline in a list row, an escape in
27
+ * a log line) or a lone surrogate (text no adapter can store as written) is refused.
28
+ */
29
+ export function passkeyLabel(label: string | null | undefined): string | null {
30
+ if (label === undefined || label === null) return null;
31
+ const trimmed = label.trim();
32
+ if (trimmed === '') throw passkeyLabelInvalid('blank');
33
+ if (longerThan(trimmed, PASSKEY_LABEL_MAX)) throw passkeyLabelInvalid('too long');
34
+ if (CONTROL.test(trimmed)) throw passkeyLabelInvalid('holding a control character');
35
+ if (LONE_SURROGATE.test(trimmed)) throw passkeyLabelInvalid('not well-formed text');
36
+ return trimmed;
37
+ }
38
+
39
+ /**
40
+ * Renames one of `userId`'s passkeys; `label: null` clears it. Answers the updated credential, or
41
+ * `null` when no passkey of that user has the id — another user's included, exactly as
42
+ * `deletePasskey` answers `false` for it. The app wraps it in its own action, as it wraps
43
+ * `passkeyLogin`'s ceremonies, with the signed-in user's id.
44
+ */
45
+ export async function renamePasskey(
46
+ auth: Auth,
47
+ input: { readonly userId: string; readonly id: string; readonly label: string | null },
48
+ ): Promise<PasskeyCredential | null> {
49
+ const rename = auth.adapter.renamePasskey;
50
+ if (rename === undefined) throw passkeyRenameUnsupported(auth.adapter.name);
51
+ return await rename.call(auth.adapter, input.userId, input.id, passkeyLabel(input.label));
52
+ }
@@ -10,19 +10,27 @@ import type {
10
10
  PasskeyStore,
11
11
  } from './adapter';
12
12
  import { authUniqueViolation } from './errors';
13
+ import { passkeyLabel } from './passkey-label';
13
14
 
14
15
  const byCreated = <T extends { readonly createdAt: Date; readonly id: string }>(a: T, b: T) =>
15
16
  a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
16
17
 
17
18
  /** The members over three maps, as closures — `MemoryAuthAdapter` binds each one as a field. */
18
- export function memoryPasskeyStore(): PasskeyStore {
19
+ export function memoryPasskeyStore(): Required<PasskeyStore> {
19
20
  const passkeys = new Map<string, PasskeyCredential>();
20
21
  const challenges = new Map<string, PasskeyChallengeRecord>();
21
22
  const evidence = new Map<string, PasskeyEvidence>();
22
23
  return {
23
24
  async putPasskey(credential) {
24
25
  if (passkeys.has(credential.id)) throw authUniqueViolation('putPasskey', 'x_passkeys', 'id');
25
- const stored = { ...credential, transports: [...credential.transports] };
26
+ // Through the one label reader, as a rename is: trimmed, refused when no label at all.
27
+ const { label: given, ...rest } = credential;
28
+ const label = passkeyLabel(given);
29
+ const stored: PasskeyCredential = {
30
+ ...rest,
31
+ transports: [...credential.transports],
32
+ ...(label === null ? {} : { label }),
33
+ };
26
34
  passkeys.set(credential.id, stored);
27
35
  return stored;
28
36
  },
@@ -42,6 +50,15 @@ export function memoryPasskeyStore(): PasskeyStore {
42
50
  if (passkeys.get(id)?.userId !== userId) return false;
43
51
  return passkeys.delete(id);
44
52
  },
53
+ async renamePasskey(userId, id, label) {
54
+ const row = passkeys.get(id);
55
+ if (row === undefined || row.userId !== userId) return null;
56
+ // Absent, never `undefined` or `null`: a stored row reads as Postgres' does, field for field.
57
+ const { label: _previous, ...rest } = row;
58
+ const renamed: PasskeyCredential = label === null ? rest : { ...rest, label };
59
+ passkeys.set(id, renamed);
60
+ return renamed;
61
+ },
45
62
  async putPasskeyChallenge(record) {
46
63
  // Swept from the oldest put, stopping at the first live one: insertion order is issue order,
47
64
  // so a put costs the expired rows it removes plus one. A full scan per put made a flood of