@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.
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
 
@@ -188,7 +196,9 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
188
196
  | `jwt-bearer-resolver.ts` | an external bearer JWT → `{ actor, scopes } \| null` |
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 |
199
+ | `link-login.ts` | `signInWithLink` (internal, not on the barrel until the next minor): a consumed link → `LoginResult`, or `X_MFA_REQUIRED` and no session. Refuses the built-in purposes and an unverified account |
191
200
  | `mfa-challenge.ts` | the sealed challenge `X_MFA_REQUIRED` carries, and `completeMfa` |
201
+ | `mfa-handoff.ts` | `mfaPath`: the challenge from a built-in callback to the app's page — path check, `__Host-x_mfa` cookie, reader |
192
202
  | `mfa-replay-postgres.ts` | the shared replay guard: the claim and the sweep. Its DDL is in `tables.ts` |
193
203
  | `mfa-secret.ts` | the TOTP secret at rest: seal on write, open on read, the one-shot that seals older rows |
194
204
  | `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` |
@@ -630,12 +701,18 @@ const verification = await consumeVerification(runtime, {
630
701
  | `DEFAULT_VERIFICATION_TTL_MS` | 24 h for `email-verify`, 1 h for `password-reset` — a reset link is a password |
631
702
  | `MailSender` | the injected port: `send(template, to, data, locale)`. `@ultimat3/mail` is tier 4 and this package is tier 2, so the app wires it |
632
703
  | `issueVerification(runtime, input)` | `{ token, expiresAt }`. The token comes back for a test or a CLI; production only ever mails it |
633
- | `consumeVerification(runtime, input)` | the `AuthVerification` row, or `X_UNAUTHENTICATED`. Unknown, spent, expired and mismatched are one answer. An undeclared purpose on either door is `X_VERIFICATION_PURPOSE_UNKNOWN` |
704
+ | `consumeVerification(runtime, input)` | the `AuthVerification` row, or `X_UNAUTHENTICATED`. Unknown, spent, expired and mismatched are one answer. Reads only `{ store, clock }` of the runtime. An undeclared purpose on either door is `X_VERIFICATION_PURPOSE_UNKNOWN` |
634
705
 
635
706
  One live token per `(purpose, identifier)`. A wrong guess destroys nothing: the store's
636
707
  `takeVerification(purpose, identifier, tokenHash)` matches before it consumes, so an
637
708
  unauthenticated POST with any token cannot kill the victim's live link.
638
709
 
710
+ ### Signing in with a mailed link
711
+
712
+ Not exported in this release: `signInWithLink` stays internal to the package until its account
713
+ reclaim path settles, and ships in the next minor. Until then a mailed credential is
714
+ `defineVerificationPurpose` + `consumeVerification`, as above.
715
+
639
716
  ## Passkeys — WebAuthn sign-in and digest-bound step-up
640
717
 
641
718
  `As of 2026-11`. Verified by hand on Bun's WebCrypto — CBOR, COSE (ES256, RS256) and DER parsed in
@@ -673,11 +750,12 @@ const erase = passkeyStepUp<{ readonly memberId: string }>(auth, {
673
750
  | Export | What |
674
751
  |---|---|
675
752
  | `passkeyLogin(auth)` | `{ registerOptions({ userId }), register({ userId, response }), loginOptions(), login({ response, ip?, userAgent? }) }` — `login` answers `login()`'s `LoginResult`, MFA-satisfied |
753
+ | `renamePasskey(auth, { userId, id, label })` | the owner's passkey renamed (`label: null` clears it): the updated `PasskeyCredential`, or `null` when `userId` holds no passkey with that id. A label is 1-`PASSKEY_LABEL_MAX` (64) characters after trimming, then no control character or lone surrogate, else `X_PASSKEY_LABEL_INVALID` (422). Named right after `register`, or any time later An adapter with no `renamePasskey` member is `X_PASSKEY_RENAME_UNSUPPORTED` (501) |
676
754
  | `passkeyStepUp(auth, { digest, ttlMs? })` | `{ options({ userId, input }), verify({ userId, input, response }) }`; `verify` answers the stored `PasskeyEvidence` or throws `X_PASSKEY_STEP_UP_REQUIRED` (no proof, a proof for other bytes, no passkey registered) |
677
755
  | `verifyPasskeyEvidence(evidence, { rpId, origins })` | `true` only when the row is a user-verified signature, by its own key, over the challenge its nonce, digest and user derive — no adapter, no clock: a separate process re-checks it |
678
756
  | `@ultimat3/auth/client` | `newPasskey`, `getPasskey`, `passkeysSupported`: outcomes `ok` / `cancelled` / `unsupported` / `failed`, never a throw. Two modules, ~2.3 kB minified (`client-bundle.test.ts`) |
679
757
  | testing a ceremony | `softAuthenticator({ origin })` from `@ultimat3/auth/soft-authenticator`: real WebCrypto keys answering `create` / `get` — this package's own suites and an app's share the one implementation and the one path |
680
- | `PasskeyStore` | the nine `AuthAdapter` members over `x_passkeys`, `x_passkey_challenges` (sha256 of the challenge, TTL, taken by `DELETE … RETURNING`) and `x_passkey_evidence`; both adapters, one suite (`passkey-store.test.ts`, PGlite) |
758
+ | `PasskeyStore` | the nine `AuthAdapter` members, and the optional `renamePasskey`, over `x_passkeys` (its `label` column added at every boot), `x_passkey_challenges` (sha256 of the challenge, TTL, taken by `DELETE … RETURNING`) and `x_passkey_evidence`; both adapters, one suite (`passkey-store.test.ts`, PGlite) |
681
759
 
682
760
  Every ceremony checks `clientDataJSON`'s type, the origin exactly, `rpIdHash`, UP **and** UV, the
683
761
  signature under the stored key's algorithm, and a counter that must move forward unless both are
@@ -694,7 +772,11 @@ OAuth 2.1 server: authorization code + PKCE (S256 only), refresh rotation with r
694
772
  `readDevice`/`approveDevice`/`denyDevice`); the consent page reads with
695
773
  `readRequest(url, { callerKey })` — every metadata-document fetch is metered, and an absent
696
774
  `callerKey` shares one bucket with every other unkeyed read. `oauthBearerResolver(server, { actor, resource? })` is
697
- the `resolveToken`. Stores: `memoryAuthServerStore()`, `postgresAuthServerStore({ executor })`
775
+ the `resolveToken`. `resolve` answers the token's `grantId` (the grant it was issued under — a user's consent, or a
776
+ `client_credentials` client's own — kept across refresh rotation); `grants({ subject, clientId? })`
777
+ lists a subject's unrevoked grants holding at least one stored token neither expired nor retired,
778
+ and `revokeGrant({ subject, grantId })` ends one of them alone — counted once under racing calls
779
+ when the store implements `revokeLiveGrant` (the memory and Postgres stores do). Stores: `memoryAuthServerStore()`, `postgresAuthServerStore({ executor })`
698
780
  over `SQL_AUTH_SERVER_TABLES`, which the boot applies. A code is spent only by a request that could
699
781
  redeem it: client, PKCE verifier, `redirect_uri` and `resource` are checked on `getCode` before
700
782
  `takeCode` marks it used, so a request without the verifier neither burns a login nor trips the
@@ -704,7 +786,14 @@ and gets refresh tokens only if its `grantTypes` list `refresh_token` (else refr
704
786
  `unauthorized_client`). `registerClient` — the app's own path — refuses a redirect URI, grant,
705
787
  scope or resource that is empty or holds whitespace (`X_AUTH_CLIENT_INVALID`, naming the field):
706
788
  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:
789
+ list. `/oauth/register` (`registration: 'dynamic'`) is anonymous, so it is bounded: at most 10
790
+ `redirect_uris` of at most 2,048 characters each (else `invalid_client_metadata`, nothing stored),
791
+ `scope` deduplicated, and every bucket of this server keyed by network (`ipKey`: an IPv6 /64 is
792
+ one caller), registrations and metadata fetches alike. The client it writes has a `d_` id
793
+ (`registerClient`'s are `c_`), and `purge` deletes a `d_` client created before the refresh idle
794
+ window that no grant, code or device code names; a `c_` client is never purged. A metadata-document client carries
795
+ `host`, its `client_id`'s host — the one thing on the consent page its author does not choose:
796
+ show it beside `name`. Full table and the rule each test holds:
708
797
  [wiki Auth](https://github.com/developerz-ai/ultimate/wiki/Auth#authorization-server).
709
798
 
710
799
  | File | Job |
@@ -816,7 +905,10 @@ one `idleSlideMs`.
816
905
  `getSessionWithUser` joins `x_sessions` to `x_users` by the session id, and the secret half and
817
906
  both clocks are checked on the row it returns exactly as `verifySession` checks them
818
907
  (`admitSession`, one copy). A request that slides the idle window adds the one write above.
819
- Counted on PGlite by `authenticate-statements.test.ts`.
908
+ Counted on PGlite by `authenticate-statements.test.ts`. A hook that needs the session and the user
909
+ rather than an actor calls the same read: `verifySessionWithUser(auth.sessions, auth.adapter, token)`
910
+ answers `{ session, user }` (`user: null` when the session outlived its user — delete the session and
911
+ refuse), one join on an adapter with `getSessionWithUser`, else `verifySession` then `findUserById`.
820
912
 
821
913
  **Revocation is unaffected, and deliberately so.** `authenticate` re-reads the *user* row on every
822
914
  request — in that same join — so a revoked role takes effect on the very next one with no token-expiry lag — a better
@@ -927,6 +1019,7 @@ export const runtime: NonNullable<ServeOptions['runtime']> = {
927
1019
  |---|---|---|
928
1020
  | path | `/auth/sso/:provider` | `/auth/sso/:provider/callback` |
929
1021
  | success | `302` to the provider, `Set-Cookie: __Host-x_sso_<provider>` | `303` to `successPath`, `Set-Cookie: __Host-x_session` **and** the handshake cleared |
1022
+ | 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
1023
  | 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
1024
 
932
1025
  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.50.0",
4
4
  "description": "Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -38,6 +38,7 @@
38
38
  "src",
39
39
  "!src/**/*.test.ts",
40
40
  "!src/**/*-fixture.ts",
41
+ "!src/link-login.ts",
41
42
  "CLAUDE.md",
42
43
  "README.md",
43
44
  "LICENSE"
@@ -50,8 +51,8 @@
50
51
  "test": "bun test"
51
52
  },
52
53
  "dependencies": {
53
- "@ultimat3/core": "31.48.0",
54
- "@ultimat3/db": "31.48.0",
55
- "@ultimat3/schema": "31.48.0"
54
+ "@ultimat3/core": "31.50.0",
55
+ "@ultimat3/db": "31.50.0",
56
+ "@ultimat3/schema": "31.50.0"
56
57
  }
57
58
  }
package/src/adapter.ts CHANGED
@@ -250,6 +250,11 @@ export interface PasskeyCredential {
250
250
  readonly transports: readonly string[];
251
251
  readonly createdAt: Date;
252
252
  readonly lastUsedAt: Date | null;
253
+ /**
254
+ * The name its owner gave it ("Work laptop"), trimmed; absent when it has none. Optional so an
255
+ * adapter written before labels still binds: one that drops it stores a passkey with no name.
256
+ */
257
+ readonly label?: string | undefined;
253
258
  }
254
259
 
255
260
  /** An issued, not yet redeemed ceremony challenge. Never the challenge itself: its digest. */
@@ -300,6 +305,17 @@ export interface PasskeyStore {
300
305
  advancePasskeyCounter(id: string, expected: number, next: number, at: Date): Promise<boolean>;
301
306
  /** Scoped to the owner: one user cannot delete another's passkey by naming its id. */
302
307
  deletePasskey(userId: string, id: string): Promise<boolean>;
308
+ /**
309
+ * Sets the label (`null` clears it) and answers the updated row; `null` when `userId` holds no
310
+ * passkey with that id — owner-scoped as `deletePasskey` is. The label arrives validated
311
+ * (`passkeyLabel`). Optional, unlike the rest of the seam, so an adapter written before it still
312
+ * binds: `renamePasskey(auth, …)` then refuses with `X_PASSKEY_RENAME_UNSUPPORTED`.
313
+ */
314
+ renamePasskey?(
315
+ userId: string,
316
+ id: string,
317
+ label: string | null,
318
+ ): Promise<PasskeyCredential | null>;
303
319
  /** Also drops every challenge that expired before `record.createdAt`, so the table stays bounded. */
304
320
  putPasskeyChallenge(record: PasskeyChallengeRecord): Promise<void>;
305
321
  /**
@@ -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,
@@ -37,3 +37,12 @@ export const clientInvalid = (field: ClientListField, value: string): AuthError
37
37
  fix: `server.registerClient({ name, ${field}: ['<one value per element, no whitespace>'] }) # split a space-separated string into its values before registering`,
38
38
  meta: { field },
39
39
  });
40
+
41
+ /** 501: `grants({ subject })` on a store of the app's own that ships no `liveGrants`. */
42
+ export const grantsUnsupported = (): AuthError =>
43
+ new AuthError({
44
+ code: 'X_AUTH_GRANTS_UNSUPPORTED',
45
+ cause:
46
+ 'the store handed to authorizationServer({ store }) has no liveGrants method, so grants({ subject }) has nothing to read',
47
+ fix: 'authorizationServer({ store: postgresAuthServerStore({ executor }) }) # or memoryAuthServerStore(); a store of your own implements liveGrants(filter, at)',
48
+ });
@@ -36,7 +36,7 @@ export const SQL_OAUTH_GRANT_GET = 'select * from x_oauth_grants where id = $1';
36
36
  export const SQL_OAUTH_GRANT_TOUCH = 'update x_oauth_grants set refreshed_at = $2 where id = $1';
37
37
 
38
38
  export const SQL_OAUTH_GRANT_REVOKE = `
39
- update x_oauth_grants set revoked_at = $2 where id = $1 and revoked_at is null
39
+ update x_oauth_grants set revoked_at = $2 where id = $1 and revoked_at is null returning 1
40
40
  `;
41
41
 
42
42
  export const SQL_OAUTH_GRANTS_REVOKE = `
@@ -48,6 +48,17 @@ with revoked as (
48
48
  select count(*)::int as n from revoked
49
49
  `;
50
50
 
51
+ /** Byte order on the id breaks a tie, as the memory store does: no collation decides the list. */
52
+ export const SQL_OAUTH_GRANTS_LIVE = `
53
+ select g.* from x_oauth_grants g
54
+ where g.subject = $1 and ($2::text is null or g.client_id = $2) and g.revoked_at is null
55
+ and exists (
56
+ select 1 from x_oauth_tokens t
57
+ where t.grant_id = g.id and t.retired_at is null and t.expires_at > $3
58
+ )
59
+ order by g.created_at, g.id collate "C"
60
+ `;
61
+
51
62
  export const SQL_OAUTH_TOKEN_PUT = `
52
63
  insert into x_oauth_tokens (token_hash, kind, grant_id, created_at, expires_at)
53
64
  values ($1, $2, $3, $4, $5)
@@ -94,14 +105,27 @@ where device_code_hash = $1 and status = 'approved'
94
105
  returning 1
95
106
  `;
96
107
 
97
- /** Four deletes in one statement; the count is everything that went. */
108
+ /**
109
+ * Five deletes in one statement; the count is everything that went. Every CTE reads the same
110
+ * snapshot, so a client whose last grant goes in this run still holds it here: it goes next run.
111
+ * Only a self-registered client (`DYNAMIC_CLIENT_PREFIX`, `d_`) is reaped, and only with nothing
112
+ * pointing at it.
113
+ */
98
114
  export const SQL_OAUTH_PURGE = `
99
- with codes as (delete from x_oauth_codes where expires_at < $1 returning 1),
115
+ with clients as (
116
+ delete from x_oauth_clients c
117
+ where left(c.client_id, 2) = 'd_' and c.created_at < $2
118
+ and not exists (select 1 from x_oauth_grants g where g.client_id = c.client_id)
119
+ and not exists (select 1 from x_oauth_codes o where o.client_id = c.client_id)
120
+ and not exists (select 1 from x_oauth_devices d where d.client_id = c.client_id)
121
+ returning 1
122
+ ),
123
+ codes as (delete from x_oauth_codes where expires_at < $1 returning 1),
100
124
  tokens as (delete from x_oauth_tokens where expires_at < $1 returning 1),
101
125
  devices as (delete from x_oauth_devices where expires_at < $1 returning 1),
102
126
  grants as (
103
127
  delete from x_oauth_grants where revoked_at < $1 or refreshed_at < $2 returning 1
104
128
  )
105
- select ((select count(*) from codes) + (select count(*) from tokens)
129
+ select ((select count(*) from clients) + (select count(*) from codes) + (select count(*) from tokens)
106
130
  + (select count(*) from devices) + (select count(*) from grants))::int as n
107
131
  `;
@@ -162,8 +162,14 @@ export function postgresAuthServerStore(options: PostgresAuthServerStoreOptions)
162
162
  async revokeGrant(id, at) {
163
163
  await rows(SQL.SQL_OAUTH_GRANT_REVOKE, [id, at]);
164
164
  },
165
+ revokeLiveGrant: async (id, at) =>
166
+ (await rows(SQL.SQL_OAUTH_GRANT_REVOKE, [id, at])).length > 0,
165
167
  revokeGrants: (filter, at) =>
166
168
  count(SQL.SQL_OAUTH_GRANTS_REVOKE, [filter.subject, filter.clientId ?? null, at]),
169
+ liveGrants: async (filter, at) =>
170
+ (await rows(SQL.SQL_OAUTH_GRANTS_LIVE, [filter.subject, filter.clientId ?? null, at])).map(
171
+ toGrant,
172
+ ),
167
173
  async putToken(t) {
168
174
  await rows(SQL.SQL_OAUTH_TOKEN_PUT, [
169
175
  t.tokenHash,
@@ -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 }
@@ -41,11 +42,32 @@ export interface AuthServerStore {
41
42
  /** Restarts the idle window. */
42
43
  touchGrant(id: string, at: Date): Promise<void>;
43
44
  revokeGrant(id: string, at: Date): Promise<void>;
45
+ /**
46
+ * `revokeGrant` that answers, in one conditional write: `true` when this call ended the grant,
47
+ * `false` when it was unknown or already revoked — so two racing revokes count it once. Optional
48
+ * for a hand-rolled store only: the memory and Postgres stores implement it; without it, a
49
+ * per-grant revoke counts on its read before the write. A store wrapping another's `revokeGrant`
50
+ * (to audit, say) wraps this too: `revokeGrant({ subject, grantId })` calls this one when set.
51
+ * Required waits on `next`.
52
+ */
53
+ revokeLiveGrant?(id: string, at: Date): Promise<boolean>;
44
54
  /** Every live grant of `subject` (of one client when named). Answers how many. */
45
55
  revokeGrants(
46
56
  filter: { subject: string; clientId?: string | undefined },
47
57
  at: Date,
48
58
  ): Promise<number>;
59
+ /**
60
+ * The grants of `subject` (of one client when named) that are not revoked and hold a stored
61
+ * token neither expired nor retired at `at` — a consent never redeemed, or one whose tokens all
62
+ * passed their stored expiry, holds none. Token rows only: no lifetime is recomputed and no
63
+ * client permission is re-read. Oldest first. Optional for a hand-rolled store only: the memory and Postgres
64
+ * stores implement it, and without it `grants()` is `X_AUTH_GRANTS_UNSUPPORTED`. Required
65
+ * waits on `next`.
66
+ */
67
+ liveGrants?(
68
+ filter: { subject: string; clientId?: string | undefined },
69
+ at: Date,
70
+ ): Promise<readonly AuthGrantRecord[]>;
49
71
  putToken(token: AuthTokenRecord): Promise<void>;
50
72
  getToken(tokenHash: string): Promise<AuthTokenRecord | null>;
51
73
  /** Retire the live refresh token `tokenHash` and store `next`, atomically. */
@@ -67,8 +89,11 @@ export interface AuthServerStore {
67
89
  /** Approved → consumed. `false` when another poll took it first. */
68
90
  consumeDevice(deviceCodeHash: string, at: Date): Promise<boolean>;
69
91
  /**
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).
92
+ * Deletes codes, tokens and device codes expired before `before`, grants revoked before it,
93
+ * grants last refreshed before `idleBefore` (past the idle window, so unrefreshable), and every
94
+ * self-registered client (`DYNAMIC_CLIENT_PREFIX`) created before `idleBefore` that no grant,
95
+ * code or device code names — judged before this run deletes any of those, so such a client goes
96
+ * on the next run. A client the app registered is never deleted.
72
97
  */
73
98
  purge(before: Date, idleBefore: Date): Promise<number>;
74
99
  }
@@ -121,6 +146,12 @@ export function memoryAuthServerStore(): AuthServerStore {
121
146
  grants.set(id, { ...grant, revokedAt: at });
122
147
  }
123
148
  },
149
+ async revokeLiveGrant(id, at) {
150
+ const grant = grants.get(id);
151
+ if (grant === undefined || grant.revokedAt !== null) return false;
152
+ grants.set(id, { ...grant, revokedAt: at });
153
+ return true;
154
+ },
124
155
  async revokeGrants(filter, at) {
125
156
  let revoked = 0;
126
157
  for (const grant of grants.values()) {
@@ -131,6 +162,29 @@ export function memoryAuthServerStore(): AuthServerStore {
131
162
  }
132
163
  return revoked;
133
164
  },
165
+ async liveGrants(filter, at) {
166
+ // The subject's grants first: an unknown subject never walks the tokens.
167
+ const own = [...grants.values()].filter(
168
+ (grant) =>
169
+ grant.revokedAt === null &&
170
+ grant.subject === filter.subject &&
171
+ (filter.clientId === undefined || grant.clientId === filter.clientId),
172
+ );
173
+ if (own.length === 0) return [];
174
+ const ids = new Set(own.map((grant) => grant.id));
175
+ const holding = new Set<string>();
176
+ for (const token of tokens.values()) {
177
+ const live = token.retiredAt === null && token.expiresAt.getTime() > at.getTime();
178
+ if (live && ids.has(token.grantId)) holding.add(token.grantId);
179
+ }
180
+ return own
181
+ .filter((grant) => holding.has(grant.id))
182
+ .sort(
183
+ (a, b) =>
184
+ a.createdAt.getTime() - b.createdAt.getTime() ||
185
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
186
+ );
187
+ },
134
188
  async putToken(token) {
135
189
  tokens.set(token.tokenHash, token);
136
190
  },
@@ -184,6 +238,17 @@ export function memoryAuthServerStore(): AuthServerStore {
184
238
  purged += 1;
185
239
  }
186
240
  };
241
+ // First, against the rows as they stand: the Postgres statement's CTEs share one snapshot.
242
+ const named = new Set<string>(
243
+ [...grants.values(), ...codes.values(), ...devices.values()].map((row) => row.clientId),
244
+ );
245
+ sweep(
246
+ clients,
247
+ (row) =>
248
+ row.clientId.startsWith(DYNAMIC_CLIENT_PREFIX) &&
249
+ row.createdAt.getTime() < idleBefore.getTime() &&
250
+ !named.has(row.clientId),
251
+ );
187
252
  sweep(codes, (row) => expired(row, before));
188
253
  sweep(tokens, (row) => expired(row, before));
189
254
  sweep(devices, (row) => expired(row, before));
@@ -122,6 +122,7 @@ export async function resolveAccess(
122
122
  }
123
123
 
124
124
  export const resolvedGrant = (grant: AuthGrantRecord): ResolvedGrant => ({
125
+ grantId: grant.id,
125
126
  subject: grant.subject,
126
127
  scopes: new Set(grant.scopes),
127
128
  clientId: grant.clientId,