@ultimat3/auth 31.48.0 → 31.49.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.
package/CLAUDE.md CHANGED
@@ -99,6 +99,10 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
99
99
  (`link: 'verified-email'`, default; `'never'` is the only other value).
100
100
  - **One sign-in route implementation** (`identity-provider-route-core.ts`) at
101
101
  `/auth/sso/:provider[/callback]` (the callback movable only by `callbackPath`); failure is coded JSON, success a 303 to `successPath`. †
102
+ - **A built-in callback hands `X_MFA_REQUIRED` on by `mfaPath` only**: 303 + the challenge in
103
+ `__Host-x_mfa` (`mfa-handoff.ts`, the ONE challenge cookie: `mfaChallengeOf`, `mfaChallengeCookie`,
104
+ `readMfaChallenge`, `clearMfaChallengeCookie`, `MFA_CHALLENGE_COOKIE` — all public). Never a URL, body or log
105
+ line. No `mfaPath` → 401 with the `mfaPath` fix; a non-local path is `X_CONFIG_INVALID`.
102
106
  - Refresh is **not implemented**, so the framework **stores no provider token**: `accountFor`
103
107
  (`oauth-login.ts`) writes `accessToken: null, refreshToken: null`. The columns and `AuthAccount`
104
108
  fields stay; an app that stores tokens implements `linkAccount` itself.
@@ -159,6 +163,10 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
159
163
  - **Every client registration is screened in `storeClient`**, the route's and `registerClient`'s
160
164
  alike: a list value that is empty or holds whitespace is `X_AUTH_CLIENT_INVALID` (the Postgres
161
165
  store space-joins each list). The route answers RFC 7591 JSON first.
166
+ - **An anonymous registration is bounded, and reaped**: ≤ 10 `redirect_uris` of ≤ 2,048 chars
167
+ (`invalid_client_metadata`), keyed by `ipKey`; `storeClient(…, true)` mints a
168
+ `DYNAMIC_CLIENT_PREFIX` (`d_`) id, and `purge` deletes a `d_` client older than the idle window
169
+ that nothing names — never an app-registered `c_` one. Both stores run `dynamicClientPurgeCase`.
162
170
  - **SAML = `samlIdentityProvider`**, no dependency: assertion signature required, one assertion,
163
171
  metadata keys only, replay via `auth.totpReplay`, `trustEmail: true` needs `emailDomains`.
164
172
 
@@ -189,6 +197,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
189
197
  | `revocation.ts` | per-user, per-org and before-an-instant sweeps; `disableUser` (sessions and api keys) |
190
198
  | `member-invite.ts` / `member-invite-marks.ts` | `defineMemberInvite`: a verification purpose keyed on (tenant, address), accept into `orgId` via `updatePrivileges`; revoke = link, plus membership + sessions only where a `joined` mark proves an invite granted it. The `joined`/`revoked` marks make a racing revoke win without a transaction |
191
199
  | `mfa-challenge.ts` | the sealed challenge `X_MFA_REQUIRED` carries, and `completeMfa` |
200
+ | `mfa-handoff.ts` | `mfaPath`: the challenge from a built-in callback to the app's page — path check, `__Host-x_mfa` cookie, reader |
192
201
  | `mfa-replay-postgres.ts` | the shared replay guard: the claim and the sweep. Its DDL is in `tables.ts` |
193
202
  | `mfa-secret.ts` | the TOTP secret at rest: seal on write, open on read, the one-shot that seals older rows |
194
203
  | `directory.ts` | `describeUser` (allow-list projection), `listOrgUsers`, external-id lookup |
package/README.md CHANGED
@@ -566,6 +566,77 @@ export const secondFactor = (challenge: string, code: string, ip: string) =>
566
566
  completeMfa(auth, challenge, code, { ip }); // what `login()` answers: actor, session, cookie
567
567
  ```
568
568
 
569
+ **The built-in sign-in routes carry it for you: `mfaPath`, `As of 2026-11`.** `oauthLogin(auth)`
570
+ and `identityProviderRoutes(auth, …)` own the callback, so there is no handler of yours to catch
571
+ `X_MFA_REQUIRED` in. Give them the path of your second-factor page:
572
+
573
+ ```ts
574
+ import {
575
+ type Auth,
576
+ clearMfaChallengeCookie,
577
+ completeMfa,
578
+ oauthLogin,
579
+ readMfaChallenge,
580
+ } from '@ultimat3/auth';
581
+
582
+ declare const auth: Auth;
583
+
584
+ export const sso = oauthLogin(auth, { successPath: '/app', mfaPath: '/sign-in/mfa' });
585
+
586
+ /** The POST behind `/sign-in/mfa`: the challenge arrives in the cookie the callback set. */
587
+ export async function finishSso(request: Request, code: string): Promise<Response> {
588
+ const result = await completeMfa(auth, readMfaChallenge(request) ?? '', code);
589
+ const headers = new Headers({ location: '/app' });
590
+ headers.append('set-cookie', result.cookie);
591
+ headers.append('set-cookie', clearMfaChallengeCookie());
592
+ return new Response(null, { status: 303, headers });
593
+ }
594
+ ```
595
+
596
+ | `mfaPath` | An enrolled user's callback (OIDC redirect or SAML ACS) answers |
597
+ |---|---|
598
+ | set | `303` to `mfaPath`, `Set-Cookie: __Host-x_mfa=<sealed challenge>` — `HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=300` — and the state cookie cleared. No session yet |
599
+ | omitted | `401 X_MFA_REQUIRED`, no challenge anywhere; the `auth.<oauth\|sso>.refused` log line's `fix` is the `mfaPath` call above. That user cannot finish through these routes |
600
+ | not one normalised absolute path on this origin (`//host`, a scheme, `?`, `#`, `\`, `..`) | `X_CONFIG_INVALID`, at the call |
601
+
602
+ The challenge travels in that cookie and nowhere else: never the redirect URL, a response body or a
603
+ log line. Only an absent cookie is `readMfaChallenge(request) === null`: the reader opens nothing,
604
+ so an expired or tampered challenge comes back as the string it is, and `completeMfa` refuses it
605
+ (and `null ?? ''`) like any other bad challenge.
606
+
607
+ **One challenge cookie, both halves public, `As of 2026-11-19`.** A sign-in handler of your own
608
+ (a password form over `login()`) carries its challenge in the same cookie the built-in callbacks
609
+ write, so one second-factor page serves every first leg:
610
+
611
+ | Export | What it is |
612
+ |---|---|
613
+ | `mfaChallengeOf(error)` | the sealed challenge of an `X_MFA_REQUIRED`, `null` for every other throw |
614
+ | `mfaChallengeCookie(challenge)` | the `Set-Cookie` line that holds it: `__Host-x_mfa`, `HttpOnly; Secure; Path=/; SameSite=Lax`, `Max-Age` the challenge's own five minutes |
615
+ | `readMfaChallenge(request)` | the held challenge as sent, unverified (expiry is `completeMfa`'s), or `null` when no cookie came |
616
+ | `clearMfaChallengeCookie()` | the `Set-Cookie` line that drops it, sent with the response that finishes the second leg |
617
+ | `MFA_CHALLENGE_COOKIE` | the cookie's name, for a test that builds a `cookie:` header or asserts a `Set-Cookie` |
618
+
619
+ ```ts
620
+ import { type Auth, login, mfaChallengeCookie, mfaChallengeOf } from '@ultimat3/auth';
621
+
622
+ declare const auth: Auth;
623
+
624
+ /** The first leg: a session, or the challenge held for `/sign-in/mfa`. */
625
+ export async function signIn(email: string, password: string, ip: string): Promise<Response> {
626
+ const headers = new Headers();
627
+ try {
628
+ headers.append('set-cookie', (await login(auth, { email, password, ip })).cookie);
629
+ headers.set('location', '/app');
630
+ } catch (error) {
631
+ const challenge = mfaChallengeOf(error);
632
+ if (challenge === null) throw error;
633
+ headers.append('set-cookie', mfaChallengeCookie(challenge));
634
+ headers.set('location', '/sign-in/mfa');
635
+ }
636
+ return new Response(null, { status: 303, headers });
637
+ }
638
+ ```
639
+
569
640
  | `completeMfa` is given | Answer |
570
641
  |---|---|
571
642
  | a live challenge and the current code, or an unused recovery code | `{ actor, session, token, cookie }`, `mfaSatisfied: true` |
@@ -704,7 +775,14 @@ and gets refresh tokens only if its `grantTypes` list `refresh_token` (else refr
704
775
  `unauthorized_client`). `registerClient` — the app's own path — refuses a redirect URI, grant,
705
776
  scope or resource that is empty or holds whitespace (`X_AUTH_CLIENT_INVALID`, naming the field):
706
777
  the Postgres store keeps each list space-joined, so such a value would read back as a different
707
- list. Full table and the rule each test holds:
778
+ list. `/oauth/register` (`registration: 'dynamic'`) is anonymous, so it is bounded: at most 10
779
+ `redirect_uris` of at most 2,048 characters each (else `invalid_client_metadata`, nothing stored),
780
+ `scope` deduplicated, and every bucket of this server keyed by network (`ipKey`: an IPv6 /64 is
781
+ one caller), registrations and metadata fetches alike. The client it writes has a `d_` id
782
+ (`registerClient`'s are `c_`), and `purge` deletes a `d_` client created before the refresh idle
783
+ window that no grant, code or device code names; a `c_` client is never purged. A metadata-document client carries
784
+ `host`, its `client_id`'s host — the one thing on the consent page its author does not choose:
785
+ show it beside `name`. Full table and the rule each test holds:
708
786
  [wiki Auth](https://github.com/developerz-ai/ultimate/wiki/Auth#authorization-server).
709
787
 
710
788
  | File | Job |
@@ -927,6 +1005,7 @@ export const runtime: NonNullable<ServeOptions['runtime']> = {
927
1005
  |---|---|---|
928
1006
  | path | `/auth/sso/:provider` | `/auth/sso/:provider/callback` |
929
1007
  | success | `302` to the provider, `Set-Cookie: __Host-x_sso_<provider>` | `303` to `successPath`, `Set-Cookie: __Host-x_session` **and** the handshake cleared |
1008
+ | second factor owed | — | `303` to `mfaPath`, `Set-Cookie: __Host-x_mfa`, handshake cleared; with no `mfaPath`, `401 X_MFA_REQUIRED` ([MFA](#mfa--totp-and-recovery-codes)) |
930
1009
  | failure | coded JSON, status per code: `code` + `title` + `docs`, one fixed `cause`, `fix: x errors explain <CODE> --json` | the same, handshake cleared either way |
931
1010
 
932
1011
  A **descriptor**, never a mounted handler — the same category as `mcpHttpRoute()`. `@ultimat3/http`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/auth",
3
- "version": "31.48.0",
3
+ "version": "31.49.0",
4
4
  "description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -50,8 +50,8 @@
50
50
  "test": "bun test"
51
51
  },
52
52
  "dependencies": {
53
- "@ultimat3/core": "31.48.0",
54
- "@ultimat3/db": "31.48.0",
55
- "@ultimat3/schema": "31.48.0"
53
+ "@ultimat3/core": "31.49.0",
54
+ "@ultimat3/db": "31.49.0",
55
+ "@ultimat3/schema": "31.49.0"
56
56
  }
57
57
  }
@@ -7,11 +7,13 @@ import { isJsonObject, logger, stringField, timingSafeEqual } from '@ultimat3/co
7
7
  import { outbound } from '@ultimat3/core/outbound';
8
8
  import type { ResolvedAuthServerConfig } from './authorization-server-config';
9
9
  import { type ClientListField, clientInvalid } from './authorization-server-errors';
10
- import type {
11
- AuthServerClient,
12
- AuthServerGrant,
13
- ClientAuthMethod,
10
+ import {
11
+ type AuthServerClient,
12
+ type AuthServerGrant,
13
+ type ClientAuthMethod,
14
+ DYNAMIC_CLIENT_PREFIX,
14
15
  } from './authorization-server-types';
16
+ import { ipKey } from './rate-limit';
15
17
  import { randomToken, sha256Hex } from './tokens';
16
18
 
17
19
  /** A metadata document is a few hundred bytes; 5 KiB is RFC 7591 metadata with room to spare. */
@@ -58,9 +60,10 @@ function clientFromDocument(clientId: string, body: unknown, at: Date): AuthServ
58
60
  const method = body['token_endpoint_auth_method'];
59
61
  if (method !== undefined && method !== 'none') return null;
60
62
  const name = body['client_name'];
63
+ const host = new URL(clientId).host;
61
64
  return {
62
65
  clientId,
63
- name: typeof name === 'string' && name !== '' ? name : new URL(clientId).host,
66
+ name: typeof name === 'string' && name !== '' ? name : host,
64
67
  secretHash: null,
65
68
  authMethod: 'none',
66
69
  redirectUris: redirects,
@@ -68,6 +71,7 @@ function clientFromDocument(clientId: string, body: unknown, at: Date): AuthServ
68
71
  scopes: [],
69
72
  resources: [],
70
73
  createdAt: at,
74
+ host,
71
75
  };
72
76
  }
73
77
 
@@ -75,8 +79,8 @@ export interface ClientDirectory {
75
79
  /**
76
80
  * Every metadata fetch is metered through `config.limiter`: an unauthenticated request naming
77
81
  * `https://<anyone>/<path>` would otherwise be one outbound GET per path. `callerKey` (the
78
- * caller's address) is the bucket; absent, every unkeyed fetch shares ONE bucket. Rejects with
79
- * `X_ACCOUNT_LOCKED` once the bucket is over the limit.
82
+ * caller's address) names the bucket, keyed by its network (`ipKey`); absent, every unkeyed
83
+ * fetch shares ONE bucket. Rejects with `X_ACCOUNT_LOCKED` once the bucket is over the limit.
80
84
  */
81
85
  find(clientId: string, callerKey?: string): Promise<AuthServerClient | null>;
82
86
  }
@@ -102,7 +106,9 @@ export function clientDirectory(config: ResolvedAuthServerConfig): ClientDirecto
102
106
  const nowMs = config.clock.now().getTime();
103
107
  const hit = cache.get(clientId);
104
108
  if (hit !== undefined && hit.untilMs > nowMs) return hit.client;
105
- await config.limiter.reserve(`oauth-client-metadata:${callerKey ?? UNKEYED_CALLER}`);
109
+ // The caller's network, never its address: a /64 is one subscriber's (as `login` keys).
110
+ const bucket = callerKey === undefined ? UNKEYED_CALLER : ipKey(callerKey);
111
+ await config.limiter.reserve(`oauth-client-metadata:${bucket}`);
106
112
  let client: AuthServerClient | null = null;
107
113
  try {
108
114
  const answer = await outbound(
@@ -177,16 +183,20 @@ function screenLists(input: RegisterClientInput): void {
177
183
  }
178
184
  }
179
185
 
180
- /** Screened here, before the secret is minted or the row written, for every caller alike. */
186
+ /**
187
+ * Screened here, before the secret is minted or the row written, for every caller alike. `dynamic`
188
+ * is the registration route's alone: its `DYNAMIC_CLIENT_PREFIX` id is what `purge` may reap.
189
+ */
181
190
  export async function storeClient(
182
191
  config: ResolvedAuthServerConfig,
183
192
  input: RegisterClientInput,
193
+ dynamic = false,
184
194
  ): Promise<RegisteredClient> {
185
195
  screenLists(input);
186
196
  const method = input.authMethod ?? 'none';
187
197
  const clientSecret = method === 'none' ? null : randomToken(32);
188
198
  const client: AuthServerClient = {
189
- clientId: `c_${randomToken(16)}`,
199
+ clientId: `${dynamic ? DYNAMIC_CLIENT_PREFIX : 'c_'}${randomToken(16)}`,
190
200
  name: input.name,
191
201
  secretHash: clientSecret === null ? null : sha256Hex(clientSecret),
192
202
  authMethod: method,
@@ -94,14 +94,27 @@ where device_code_hash = $1 and status = 'approved'
94
94
  returning 1
95
95
  `;
96
96
 
97
- /** Four deletes in one statement; the count is everything that went. */
97
+ /**
98
+ * Five deletes in one statement; the count is everything that went. Every CTE reads the same
99
+ * snapshot, so a client whose last grant goes in this run still holds it here: it goes next run.
100
+ * Only a self-registered client (`DYNAMIC_CLIENT_PREFIX`, `d_`) is reaped, and only with nothing
101
+ * pointing at it.
102
+ */
98
103
  export const SQL_OAUTH_PURGE = `
99
- with codes as (delete from x_oauth_codes where expires_at < $1 returning 1),
104
+ with clients as (
105
+ delete from x_oauth_clients c
106
+ where left(c.client_id, 2) = 'd_' and c.created_at < $2
107
+ and not exists (select 1 from x_oauth_grants g where g.client_id = c.client_id)
108
+ and not exists (select 1 from x_oauth_codes o where o.client_id = c.client_id)
109
+ and not exists (select 1 from x_oauth_devices d where d.client_id = c.client_id)
110
+ returning 1
111
+ ),
112
+ codes as (delete from x_oauth_codes where expires_at < $1 returning 1),
100
113
  tokens as (delete from x_oauth_tokens where expires_at < $1 returning 1),
101
114
  devices as (delete from x_oauth_devices where expires_at < $1 returning 1),
102
115
  grants as (
103
116
  delete from x_oauth_grants where revoked_at < $1 or refreshed_at < $2 returning 1
104
117
  )
105
- select ((select count(*) from codes) + (select count(*) from tokens)
118
+ select ((select count(*) from clients) + (select count(*) from codes) + (select count(*) from tokens)
106
119
  + (select count(*) from devices) + (select count(*) from grants))::int as n
107
120
  `;
@@ -1,6 +1,7 @@
1
1
  // Single responsibility: RFC 7591 dynamic client registration, for the MCP clients that still use
2
2
  // it — on only under `registration: 'dynamic'`, counted per address. Never a machine client: an
3
- // open endpoint handing out `client_credentials` would let anyone mint itself a scope.
3
+ // open endpoint handing out `client_credentials` would let anyone mint itself a scope. Bounded:
4
+ // a capped redirect list, counted per network, and reaped by `purge` once idle and grantless.
4
5
 
5
6
  import { isJsonObject } from '@ultimat3/core';
6
7
  import { isRedirectUri, storeClient } from './authorization-server-clients';
@@ -9,6 +10,14 @@ import type { AuthServerGrant, ClientAuthMethod } from './authorization-server-t
9
10
  import { DEVICE_GRANT } from './authorization-server-types';
10
11
  import type { AuthServerHttpContext, AuthServerHttpRequest } from './authorization-server-wire';
11
12
  import { jsonAnswer, throttledAnswer } from './authorization-server-wire';
13
+ import { ipKey } from './rate-limit';
14
+
15
+ /**
16
+ * An anonymous caller writes this row, so it is bounded: an MCP client registers one to three
17
+ * loopback or https callbacks, and a URL past 2 KiB is past what browsers reliably carry.
18
+ */
19
+ const REGISTER_MAX_REDIRECT_URIS = 10;
20
+ const REGISTER_MAX_REDIRECT_URI_LENGTH = 2_048;
12
21
 
13
22
  const SELF_SERVICE_GRANTS: ReadonlySet<string> = new Set<AuthServerGrant>([
14
23
  'authorization_code',
@@ -33,7 +42,8 @@ export async function registerHandler(
33
42
  ctx: AuthServerHttpContext,
34
43
  ): Promise<Response> {
35
44
  try {
36
- await config.limiter.reserve(`oauth-register:${ctx.ip ?? 'unknown'}`);
45
+ // The network, never the address: a /64 is one subscriber's, so one bucket (as `login` keys).
46
+ await config.limiter.reserve(`oauth-register:${ipKey(ctx.ip ?? 'unknown')}`);
37
47
  } catch (error) {
38
48
  const answer = throttledAnswer(error, 'too many registrations');
39
49
  if (answer === null) throw error;
@@ -58,6 +68,16 @@ export async function registerHandler(
58
68
  );
59
69
  }
60
70
  const redirects = stringList(body['redirect_uris'] ?? []);
71
+ if (
72
+ redirects !== null &&
73
+ (redirects.length > REGISTER_MAX_REDIRECT_URIS ||
74
+ redirects.some((uri) => uri.length > REGISTER_MAX_REDIRECT_URI_LENGTH))
75
+ ) {
76
+ return metadataError(
77
+ 'invalid_client_metadata',
78
+ `redirect_uris holds at most ${REGISTER_MAX_REDIRECT_URIS} URIs of at most ${REGISTER_MAX_REDIRECT_URI_LENGTH} characters each`,
79
+ );
80
+ }
61
81
  const needsRedirect = grants.includes('authorization_code');
62
82
  if (
63
83
  redirects === null ||
@@ -74,18 +94,24 @@ export async function registerHandler(
74
94
  return metadataError('invalid_client_metadata', 'token_endpoint_auth_method is not supported');
75
95
  }
76
96
  const scope = body['scope'];
77
- const scopes = typeof scope === 'string' ? scope.split(' ').filter((s) => s !== '') : [];
97
+ // Deduplicated: every token is one the server grants, so the stored list is at most that set.
98
+ const scopes =
99
+ typeof scope === 'string' ? [...new Set(scope.split(' ').filter((s) => s !== ''))] : [];
78
100
  if (!scopes.every((s) => config.scopes.has(s))) {
79
101
  return metadataError('invalid_client_metadata', 'a scope is not one this server grants');
80
102
  }
81
103
  const name = body['client_name'];
82
- const { client, clientSecret } = await storeClient(config, {
83
- name: typeof name === 'string' && name !== '' ? name.slice(0, 200) : 'unnamed client',
84
- authMethod: method as ClientAuthMethod,
85
- redirectUris: redirects,
86
- grantTypes: grants as readonly AuthServerGrant[],
87
- scopes,
88
- });
104
+ const { client, clientSecret } = await storeClient(
105
+ config,
106
+ {
107
+ name: typeof name === 'string' && name !== '' ? name.slice(0, 200) : 'unnamed client',
108
+ authMethod: method as ClientAuthMethod,
109
+ redirectUris: redirects,
110
+ grantTypes: grants as readonly AuthServerGrant[],
111
+ scopes,
112
+ },
113
+ true,
114
+ );
89
115
  return jsonAnswer(201, {
90
116
  client_id: client.clientId,
91
117
  ...(clientSecret === null ? {} : { client_secret: clientSecret, client_secret_expires_at: 0 }),
@@ -11,6 +11,7 @@ import type {
11
11
  AuthTokenRecord,
12
12
  DeviceCodeRecord,
13
13
  } from './authorization-server-types';
14
+ import { DYNAMIC_CLIENT_PREFIX } from './authorization-server-types';
14
15
 
15
16
  export type RefreshRotation =
16
17
  | { readonly outcome: 'rotated'; readonly grantId: string }
@@ -67,8 +68,11 @@ export interface AuthServerStore {
67
68
  /** Approved → consumed. `false` when another poll took it first. */
68
69
  consumeDevice(deviceCodeHash: string, at: Date): Promise<boolean>;
69
70
  /**
70
- * Deletes codes, tokens and device codes expired before `before`, grants revoked before it, and
71
- * grants last refreshed before `idleBefore` (past the idle window, so unrefreshable).
71
+ * Deletes codes, tokens and device codes expired before `before`, grants revoked before it,
72
+ * grants last refreshed before `idleBefore` (past the idle window, so unrefreshable), and every
73
+ * self-registered client (`DYNAMIC_CLIENT_PREFIX`) created before `idleBefore` that no grant,
74
+ * code or device code names — judged before this run deletes any of those, so such a client goes
75
+ * on the next run. A client the app registered is never deleted.
72
76
  */
73
77
  purge(before: Date, idleBefore: Date): Promise<number>;
74
78
  }
@@ -184,6 +188,17 @@ export function memoryAuthServerStore(): AuthServerStore {
184
188
  purged += 1;
185
189
  }
186
190
  };
191
+ // First, against the rows as they stand: the Postgres statement's CTEs share one snapshot.
192
+ const named = new Set<string>(
193
+ [...grants.values(), ...codes.values(), ...devices.values()].map((row) => row.clientId),
194
+ );
195
+ sweep(
196
+ clients,
197
+ (row) =>
198
+ row.clientId.startsWith(DYNAMIC_CLIENT_PREFIX) &&
199
+ row.createdAt.getTime() < idleBefore.getTime() &&
200
+ !named.has(row.clientId),
201
+ );
187
202
  sweep(codes, (row) => expired(row, before));
188
203
  sweep(tokens, (row) => expired(row, before));
189
204
  sweep(devices, (row) => expired(row, before));
@@ -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. */
@@ -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
@@ -217,6 +217,13 @@ export {
217
217
  MFA_CHALLENGE_TTL_MS,
218
218
  mfaChallengeRequired,
219
219
  } from './mfa-challenge';
220
+ export {
221
+ clearMfaChallengeCookie,
222
+ MFA_CHALLENGE_COOKIE,
223
+ mfaChallengeCookie,
224
+ mfaChallengeOf,
225
+ readMfaChallenge,
226
+ } from './mfa-handoff';
220
227
  export type {
221
228
  PostgresTotpReplayGuard,
222
229
  PostgresTotpReplayGuardOptions,
@@ -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) {