@ultimat3/auth 31.49.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
@@ -196,6 +196,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
196
196
  | `jwt-bearer-resolver.ts` | an external bearer JWT → `{ actor, scopes } \| null` |
197
197
  | `revocation.ts` | per-user, per-org and before-an-instant sweeps; `disableUser` (sessions and api keys) |
198
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 |
199
200
  | `mfa-challenge.ts` | the sealed challenge `X_MFA_REQUIRED` carries, and `completeMfa` |
200
201
  | `mfa-handoff.ts` | `mfaPath`: the challenge from a built-in callback to the app's page — path check, `__Host-x_mfa` cookie, reader |
201
202
  | `mfa-replay-postgres.ts` | the shared replay guard: the claim and the sweep. Its DDL is in `tables.ts` |
package/README.md CHANGED
@@ -701,12 +701,18 @@ const verification = await consumeVerification(runtime, {
701
701
  | `DEFAULT_VERIFICATION_TTL_MS` | 24 h for `email-verify`, 1 h for `password-reset` — a reset link is a password |
702
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 |
703
703
  | `issueVerification(runtime, input)` | `{ token, expiresAt }`. The token comes back for a test or a CLI; production only ever mails it |
704
- | `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` |
705
705
 
706
706
  One live token per `(purpose, identifier)`. A wrong guess destroys nothing: the store's
707
707
  `takeVerification(purpose, identifier, tokenHash)` matches before it consumes, so an
708
708
  unauthenticated POST with any token cannot kill the victim's live link.
709
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
+
710
716
  ## Passkeys — WebAuthn sign-in and digest-bound step-up
711
717
 
712
718
  `As of 2026-11`. Verified by hand on Bun's WebCrypto — CBOR, COSE (ES256, RS256) and DER parsed in
@@ -744,11 +750,12 @@ const erase = passkeyStepUp<{ readonly memberId: string }>(auth, {
744
750
  | Export | What |
745
751
  |---|---|
746
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) |
747
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) |
748
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 |
749
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`) |
750
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 |
751
- | `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) |
752
759
 
753
760
  Every ceremony checks `clientDataJSON`'s type, the origin exactly, `rpIdHash`, UP **and** UV, the
754
761
  signature under the stored key's algorithm, and a counter that must move forward unless both are
@@ -765,7 +772,11 @@ OAuth 2.1 server: authorization code + PKCE (S256 only), refresh rotation with r
765
772
  `readDevice`/`approveDevice`/`denyDevice`); the consent page reads with
766
773
  `readRequest(url, { callerKey })` — every metadata-document fetch is metered, and an absent
767
774
  `callerKey` shares one bucket with every other unkeyed read. `oauthBearerResolver(server, { actor, resource? })` is
768
- 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 })`
769
780
  over `SQL_AUTH_SERVER_TABLES`, which the boot applies. A code is spent only by a request that could
770
781
  redeem it: client, PKCE verifier, `redirect_uri` and `resource` are checked on `getCode` before
771
782
  `takeCode` marks it used, so a request without the verifier neither burns a login nor trips the
@@ -894,7 +905,10 @@ one `idleSlideMs`.
894
905
  `getSessionWithUser` joins `x_sessions` to `x_users` by the session id, and the secret half and
895
906
  both clocks are checked on the row it returns exactly as `verifySession` checks them
896
907
  (`admitSession`, one copy). A request that slides the idle window adds the one write above.
897
- 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`.
898
912
 
899
913
  **Revocation is unaffected, and deliberately so.** `authenticate` re-reads the *user* row on every
900
914
  request — in that same join — so a revoked role takes effect on the very next one with no token-expiry lag — a better
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/auth",
3
- "version": "31.49.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.49.0",
54
- "@ultimat3/db": "31.49.0",
55
- "@ultimat3/schema": "31.49.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
  /**
@@ -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)
@@ -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,
@@ -42,11 +42,32 @@ export interface AuthServerStore {
42
42
  /** Restarts the idle window. */
43
43
  touchGrant(id: string, at: Date): Promise<void>;
44
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>;
45
54
  /** Every live grant of `subject` (of one client when named). Answers how many. */
46
55
  revokeGrants(
47
56
  filter: { subject: string; clientId?: string | undefined },
48
57
  at: Date,
49
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[]>;
50
71
  putToken(token: AuthTokenRecord): Promise<void>;
51
72
  getToken(tokenHash: string): Promise<AuthTokenRecord | null>;
52
73
  /** Retire the live refresh token `tokenHash` and store `next`, atomically. */
@@ -125,6 +146,12 @@ export function memoryAuthServerStore(): AuthServerStore {
125
146
  grants.set(id, { ...grant, revokedAt: at });
126
147
  }
127
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
+ },
128
155
  async revokeGrants(filter, at) {
129
156
  let revoked = 0;
130
157
  for (const grant of grants.values()) {
@@ -135,6 +162,29 @@ export function memoryAuthServerStore(): AuthServerStore {
135
162
  }
136
163
  return revoked;
137
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
+ },
138
188
  async putToken(token) {
139
189
  tokens.set(token.tokenHash, token);
140
190
  },
@@ -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,
@@ -113,8 +113,29 @@ export interface DeviceCodeRecord {
113
113
 
114
114
  /** What `resolve(token)` answers for a live access token. */
115
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;
116
123
  readonly subject: string;
117
124
  readonly scopes: ReadonlySet<string>;
118
125
  readonly clientId: string;
119
126
  readonly resource: string | null;
120
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
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';
@@ -328,7 +329,9 @@ export type {
328
329
  PasskeyPolicyInput,
329
330
  PasskeyRelyingParty,
330
331
  } from './passkey-config';
332
+ export { PASSKEY_LABEL_MAX } from './passkey-errors';
331
333
  export { verifyPasskeyEvidence } from './passkey-evidence';
334
+ export { renamePasskey } from './passkey-label';
332
335
  export type { PasskeyLogin } from './passkey-login';
333
336
  export { passkeyLogin } from './passkey-login';
334
337
  export type { PasskeyStepUp, PasskeyStepUpOptions } from './passkey-step-up';
@@ -424,6 +427,8 @@ export {
424
427
  sessionExpiry,
425
428
  verifySession,
426
429
  } from './session';
430
+ export type { VerifiedSession } from './session-user';
431
+ export { verifySessionWithUser } from './session-user';
427
432
  /** A sign-out response's headers: the session cookie expired, and `Clear-Site-Data`. */
428
433
  export type { SignOutHeadersOptions } from './sign-out';
429
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'] =
@@ -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
@@ -12,6 +12,7 @@ import type {
12
12
  } from './adapter';
13
13
  import { usersUniqueViolation } from './builtin-adapter-violation';
14
14
  import { authWriteFailed } from './errors';
15
+ import { passkeyLabel } from './passkey-label';
15
16
 
16
17
  type Row = Readonly<Record<string, unknown>>;
17
18
 
@@ -49,6 +50,8 @@ const toCredential = (row: Row): PasskeyCredential => ({
49
50
  transports: strings(row, 'transports'),
50
51
  createdAt: when(row, 'created_at') ?? new Date(0),
51
52
  lastUsedAt: when(row, 'last_used_at'),
53
+ // Absent for none, as the memory store reads: a label is the one optional field of the row.
54
+ ...(strOrNull(row, 'label') === null ? {} : { label: str(row, 'label') }),
52
55
  });
53
56
 
54
57
  const toChallenge = (row: Row, ceremony: PasskeyCeremony): PasskeyChallengeRecord => ({
@@ -78,17 +81,17 @@ const toEvidence = (row: Row): PasskeyEvidence => ({
78
81
  });
79
82
 
80
83
  /** The members, over a client resolved per call — the adapter's ambient `db()` rule. */
81
- export function postgresPasskeyStore(client: () => DbClient): PasskeyStore {
84
+ export function postgresPasskeyStore(client: () => DbClient): Required<PasskeyStore> {
82
85
  return {
83
86
  async putPasskey(credential) {
84
87
  let row: Row | null;
85
88
  try {
86
89
  row = await client().one<Row>(sql`
87
90
  insert into x_passkeys (id, user_id, public_key, algorithm, sign_count, transports,
88
- created_at)
91
+ created_at, label)
89
92
  values (${credential.id}, ${credential.userId}, ${credential.publicKey},
90
93
  ${credential.algorithm}, ${credential.signCount}, ${[...credential.transports]},
91
- ${credential.createdAt})
94
+ ${credential.createdAt}, ${passkeyLabel(credential.label)})
92
95
  returning *`);
93
96
  } catch (error) {
94
97
  throw usersUniqueViolation('putPasskey', error) ?? error;
@@ -112,6 +115,13 @@ export function postgresPasskeyStore(client: () => DbClient): PasskeyStore {
112
115
  returning id`);
113
116
  return row !== null;
114
117
  },
118
+ async renamePasskey(userId, id, label) {
119
+ const row = await client().one<Row>(sql`
120
+ update x_passkeys set label = ${label}
121
+ where id = ${id} and user_id = ${userId}
122
+ returning *`);
123
+ return row === null ? null : toCredential(row);
124
+ },
115
125
  async deletePasskey(userId, id) {
116
126
  const removed = await client().execute(
117
127
  sql`delete from x_passkeys where id = ${id} and user_id = ${userId}`,
package/src/tables.ts CHANGED
@@ -128,10 +128,17 @@ const X_PASSKEYS_TABLE = `create table if not exists x_passkeys (
128
128
  sign_count bigint not null default 0,
129
129
  transports text[] not null default '{}',
130
130
  created_at timestamptz not null default now(),
131
- last_used_at timestamptz
131
+ last_used_at timestamptz,
132
+ label text
132
133
  );
133
134
  create index if not exists x_passkeys_user_id_idx on x_passkeys (user_id)`;
134
135
 
136
+ /**
137
+ * What `x_passkeys` gained with passkey labels, applied at every boot right after the create, on
138
+ * `X_USERS_UPGRADE`'s rule: idempotent, additive, nullable — a catalog update on a live table.
139
+ */
140
+ const X_PASSKEYS_UPGRADE = 'alter table x_passkeys add column if not exists label text';
141
+
135
142
  const X_PASSKEY_CHALLENGES_TABLE = `create table if not exists x_passkey_challenges (
136
143
  id text primary key,
137
144
  ceremony text not null,
@@ -167,6 +174,7 @@ export const AUTH_TABLES: readonly string[] = Object.freeze([
167
174
  X_VERIFICATIONS_TABLE,
168
175
  X_API_KEYS_TABLE,
169
176
  X_PASSKEYS_TABLE,
177
+ X_PASSKEYS_UPGRADE,
170
178
  X_PASSKEY_CHALLENGES_TABLE,
171
179
  X_PASSKEY_EVIDENCE_TABLE,
172
180
  ]);
package/src/verify.ts CHANGED
@@ -147,6 +147,17 @@ export interface ConsumeVerificationInput {
147
147
  export async function consumeVerification(
148
148
  runtime: VerificationRuntime,
149
149
  input: ConsumeVerificationInput,
150
+ ): Promise<AuthVerification> {
151
+ return consumeWith(runtime, input);
152
+ }
153
+
154
+ /**
155
+ * `consumeVerification` without the mailer: consuming sends nothing, so a caller with no mailer in
156
+ * hand (`signInWithLink`) needs none. Internal, so the exported signature stays as it shipped.
157
+ */
158
+ export async function consumeWith(
159
+ runtime: Pick<VerificationRuntime, 'store' | 'clock'>,
160
+ input: ConsumeVerificationInput,
150
161
  ): Promise<AuthVerification> {
151
162
  const purpose = verificationPurpose(input.purpose);
152
163
  const tokenHash = sha256Hex(input.token);