@ultimat3/auth 31.49.0 → 31.51.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`: a consumed link → `LoginResult`, or `X_MFA_REQUIRED` and no session. Refuses a purpose not declared `signIn: true` (the built-ins never are) 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
@@ -695,18 +695,42 @@ const verification = await consumeVerification(runtime, {
695
695
  | Name | Is |
696
696
  |---|---|
697
697
  | `VERIFICATION_PURPOSES` | `['email-verify', 'password-reset']` — the two built in. `VerificationPurpose` is `string` (`As of 2026-11`): any declared name |
698
- | `defineVerificationPurpose({ name, template, ttlMs, identifier? })` | `{ name, issue, consume }` on the same code path — an invite, an email change, an account deletion. Twice or with no template: `X_VERIFICATION_PURPOSE_INVALID`. `emailVerification` and `passwordReset` are the built-in instances |
698
+ | `defineVerificationPurpose({ name, template, ttlMs, identifier?, signIn? })` | `{ name, issue, consume }` on the same code path — an invite, an email change, an account deletion. `signIn: true` declares the one purpose whose link signs its holder in (`signInWithLink`); absent, it never does. Twice or with no template: `X_VERIFICATION_PURPOSE_INVALID`. `emailVerification` and `passwordReset` are the built-in instances |
699
699
  | `defineMemberInvite({ name?, template, ttlMs })` | `{ purpose, invite, accept, revoke }`: a single-use invite keyed on (tenant, address). `accept` consumes it under the signed-in account's own address, sets `orgId`/`roles` and rotates the session; `revoke` kills the link and, only where this flow granted it, the membership and that account's sessions; a revoke racing an accept wins. Every bad link is `X_UNAUTHENTICATED`; a member of another tenant is `X_FORBIDDEN`. Functions, not actions (tier 2): the app wraps each in its own `action()` — `x g invite` writes them |
700
700
  | `VERIFICATION_TEMPLATES` | purpose → **catalog key** (`auth.email-verify`, `auth.password-reset`), never copy: the body lives in the app's i18n catalog |
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
+ `As of 2026-11`. `signInWithLink(auth, { purpose, identifier, token, ip?, userAgent?, signUp? })`
713
+ consumes a link issued under a purpose declared `signIn: true` and answers what `login()` answers.
714
+ With TOTP enrolled it answers `X_MFA_REQUIRED` and writes no session:
715
+ `completeMfa(auth, challenge, code, { ip, userAgent })` finishes it, as after a password. `ip` and
716
+ `userAgent` go on the session the call writes: the link's, or with TOTP the second leg's.
717
+
718
+ Redemption needs the address as well as the token. The mailed URL carries the token only, so the
719
+ page it opens asks for the address (prefilled where the same browser asked for the link) and posts
720
+ both: an address in the URL lands in every log and referrer the link passes through.
721
+
722
+ | Case | Answer |
723
+ |---|---|
724
+ | valid link, no second factor | `LoginResult`, the session `mfaSatisfied` |
725
+ | valid link, TOTP enrolled | `X_MFA_REQUIRED` with `meta.challenge`; no session row. A fresh link never clears the count of wrong codes |
726
+ | a link already consumed (its own address and token), whatever that attempt ended in | `X_UNAUTHENTICATED`: the link is spent before anything else is read. A try with the wrong address consumes nothing, so the link stays live for the right one |
727
+ | unknown, expired, mismatched or another purpose's token | `X_UNAUTHENTICATED`, and a wrong guess leaves the mailed link live |
728
+ | no account at the address | `X_UNAUTHENTICATED`, and the link is spent: enabling `signUp` takes a freshly mailed one. With `signUp: { id?, orgId?, roles?, scopes?, externalId? }` a passwordless account is created verified: in the creating write on an adapter that stores `CreateUserInput.emailVerifiedAt` (both built-in ones do). An app adapter that drops it gets a second `updateUser` stamp; if that write fails the call is `X_AUTH_WRITE_FAILED`, the account exists unverified, and the next link is refused as one that never verified its address. `signUp` never changes an account that exists |
729
+ | a disabled account | `X_UNAUTHENTICATED`, naming nothing |
730
+ | an account that never verified its address | `X_UNAUTHENTICATED`, named: whoever registered it chose its password. A verification stamp alone leaves their credentials intact. Recovery requires an app-owned flow: consume a `passwordReset` to prove the inbox, keep the account disabled while clearing every credential and session, and atomically verify recovery still owns the disable before stamping and reopening. Coordinate every administrative disable with that ownership check; `updateUser` and `enableUser` do not provide it. If ownership is lost or cleanup fails, leave the account disabled |
731
+ | `purpose` is `'email-verify'` or `'password-reset'`, is not declared `signIn: true`, or declares an `identifier` other than the exported `normaliseEmail` | `X_CONFIG_INVALID`, before the store is asked: the token stays live for its own job |
732
+ | `purpose` names nothing `defineVerificationPurpose` declared | `X_VERIFICATION_PURPOSE_UNKNOWN`, before the store is asked |
733
+
710
734
  ## Passkeys — WebAuthn sign-in and digest-bound step-up
711
735
 
712
736
  `As of 2026-11`. Verified by hand on Bun's WebCrypto — CBOR, COSE (ES256, RS256) and DER parsed in
@@ -744,11 +768,12 @@ const erase = passkeyStepUp<{ readonly memberId: string }>(auth, {
744
768
  | Export | What |
745
769
  |---|---|
746
770
  | `passkeyLogin(auth)` | `{ registerOptions({ userId }), register({ userId, response }), loginOptions(), login({ response, ip?, userAgent? }) }` — `login` answers `login()`'s `LoginResult`, MFA-satisfied |
771
+ | `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
772
  | `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
773
  | `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
774
  | `@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
775
  | 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) |
776
+ | `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
777
 
753
778
  Every ceremony checks `clientDataJSON`'s type, the origin exactly, `rpIdHash`, UP **and** UV, the
754
779
  signature under the stored key's algorithm, and a counter that must move forward unless both are
@@ -765,7 +790,11 @@ OAuth 2.1 server: authorization code + PKCE (S256 only), refresh rotation with r
765
790
  `readDevice`/`approveDevice`/`denyDevice`); the consent page reads with
766
791
  `readRequest(url, { callerKey })` — every metadata-document fetch is metered, and an absent
767
792
  `callerKey` shares one bucket with every other unkeyed read. `oauthBearerResolver(server, { actor, resource? })` is
768
- the `resolveToken`. Stores: `memoryAuthServerStore()`, `postgresAuthServerStore({ executor })`
793
+ the `resolveToken`. `resolve` answers the token's `grantId` (the grant it was issued under — a user's consent, or a
794
+ `client_credentials` client's own — kept across refresh rotation); `grants({ subject, clientId? })`
795
+ lists a subject's unrevoked grants holding at least one stored token neither expired nor retired,
796
+ and `revokeGrant({ subject, grantId })` ends one of them alone — counted once under racing calls
797
+ when the store implements `revokeLiveGrant` (the memory and Postgres stores do). Stores: `memoryAuthServerStore()`, `postgresAuthServerStore({ executor })`
769
798
  over `SQL_AUTH_SERVER_TABLES`, which the boot applies. A code is spent only by a request that could
770
799
  redeem it: client, PKCE verifier, `redirect_uri` and `resource` are checked on `getCode` before
771
800
  `takeCode` marks it used, so a request without the verifier neither burns a login nor trips the
@@ -894,7 +923,10 @@ one `idleSlideMs`.
894
923
  `getSessionWithUser` joins `x_sessions` to `x_users` by the session id, and the secret half and
895
924
  both clocks are checked on the row it returns exactly as `verifySession` checks them
896
925
  (`admitSession`, one copy). A request that slides the idle window adds the one write above.
897
- Counted on PGlite by `authenticate-statements.test.ts`.
926
+ Counted on PGlite by `authenticate-statements.test.ts`. A hook that needs the session and the user
927
+ rather than an actor calls the same read: `verifySessionWithUser(auth.sessions, auth.adapter, token)`
928
+ answers `{ session, user }` (`user: null` when the session outlived its user — delete the session and
929
+ refuse), one join on an adapter with `getSessionWithUser`, else `verifySession` then `findUserById`.
898
930
 
899
931
  **Revocation is unaffected, and deliberately so.** `authenticate` re-reads the *user* row on every
900
932
  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.51.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.49.0",
54
- "@ultimat3/db": "31.49.0",
55
- "@ultimat3/schema": "31.49.0"
53
+ "@ultimat3/core": "31.51.0",
54
+ "@ultimat3/db": "31.51.0",
55
+ "@ultimat3/schema": "31.51.0"
56
56
  }
57
57
  }
package/src/adapter.ts CHANGED
@@ -46,6 +46,13 @@ export interface CreateUserInput {
46
46
  readonly roles: readonly string[];
47
47
  readonly scopes?: readonly string[] | undefined;
48
48
  readonly externalId?: string | null | undefined;
49
+ /**
50
+ * The address proven at creation (a sign-in link's sign-up). An adapter that stores it in the
51
+ * same write as the row leaves no failure between the account and its stamp. Absent is
52
+ * unverified. An adapter that drops it gets a second `updateUser` stamp, and if that write fails
53
+ * the account exists unverified (`X_AUTH_WRITE_FAILED`), refused by every later link.
54
+ */
55
+ readonly emailVerifiedAt?: Date | null | undefined;
49
56
  readonly createdAt: Date;
50
57
  }
51
58
 
@@ -250,6 +257,11 @@ export interface PasskeyCredential {
250
257
  readonly transports: readonly string[];
251
258
  readonly createdAt: Date;
252
259
  readonly lastUsedAt: Date | null;
260
+ /**
261
+ * The name its owner gave it ("Work laptop"), trimmed; absent when it has none. Optional so an
262
+ * adapter written before labels still binds: one that drops it stores a passkey with no name.
263
+ */
264
+ readonly label?: string | undefined;
253
265
  }
254
266
 
255
267
  /** An issued, not yet redeemed ceremony challenge. Never the challenge itself: its digest. */
@@ -300,6 +312,17 @@ export interface PasskeyStore {
300
312
  advancePasskeyCounter(id: string, expected: number, next: number, at: Date): Promise<boolean>;
301
313
  /** Scoped to the owner: one user cannot delete another's passkey by naming its id. */
302
314
  deletePasskey(userId: string, id: string): Promise<boolean>;
315
+ /**
316
+ * Sets the label (`null` clears it) and answers the updated row; `null` when `userId` holds no
317
+ * passkey with that id — owner-scoped as `deletePasskey` is. The label arrives validated
318
+ * (`passkeyLabel`). Optional, unlike the rest of the seam, so an adapter written before it still
319
+ * binds: `renamePasskey(auth, …)` then refuses with `X_PASSKEY_RENAME_UNSUPPORTED`.
320
+ */
321
+ renamePasskey?(
322
+ userId: string,
323
+ id: string,
324
+ label: string | null,
325
+ ): Promise<PasskeyCredential | null>;
303
326
  /** Also drops every challenge that expired before `record.createdAt`, so the table stays bounded. */
304
327
  putPasskeyChallenge(record: PasskeyChallengeRecord): Promise<void>;
305
328
  /**
@@ -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'] =
@@ -100,10 +101,10 @@ export class PostgresAuthAdapter implements AuthAdapter {
100
101
  'createUser',
101
102
  sql`
102
103
  insert into x_users (id, email, password_hash, org_id, roles, scopes, external_id,
103
- created_at)
104
+ email_verified_at, created_at)
104
105
  values (${input.id}, ${input.email}, ${input.passwordHash}, ${input.orgId},
105
106
  ${[...input.roles]}, ${[...(input.scopes ?? [])]}, ${input.externalId ?? null},
106
- ${input.createdAt})
107
+ ${input.emailVerifiedAt ?? null}, ${input.createdAt})
107
108
  returning *`,
108
109
  );
109
110
  // An empty `returning` means no row landed. A user fabricated from `{}` would travel back
@@ -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';
@@ -171,6 +172,8 @@ export { boundedKdfGate, kdfGate } from './kdf-gate';
171
172
  // The installers and their factory types are `@ultimat3/auth/adapter`'s, and only its: the boot
172
173
  // calls them with what `apps/<app>/runtime.ts` named.
173
174
  export { purgeAuthLimits } from './limiter-install';
175
+ export type { LinkSignInInput, LinkSignUp } from './link-login';
176
+ export { signInWithLink } from './link-login';
174
177
  export type { HandleDirectory } from './login-identity';
175
178
  export { normaliseHandle } from './login-identity';
176
179
  export type {
@@ -328,7 +331,9 @@ export type {
328
331
  PasskeyPolicyInput,
329
332
  PasskeyRelyingParty,
330
333
  } from './passkey-config';
334
+ export { PASSKEY_LABEL_MAX } from './passkey-errors';
331
335
  export { verifyPasskeyEvidence } from './passkey-evidence';
336
+ export { renamePasskey } from './passkey-label';
332
337
  export type { PasskeyLogin } from './passkey-login';
333
338
  export { passkeyLogin } from './passkey-login';
334
339
  export type { PasskeyStepUp, PasskeyStepUpOptions } from './passkey-step-up';
@@ -424,6 +429,8 @@ export {
424
429
  sessionExpiry,
425
430
  verifySession,
426
431
  } from './session';
432
+ export type { VerifiedSession } from './session-user';
433
+ export { verifySessionWithUser } from './session-user';
427
434
  /** A sign-out response's headers: the session cookie expired, and `Clear-Site-Data`. */
428
435
  export type { SignOutHeadersOptions } from './sign-out';
429
436
  export { SIGN_OUT_CLEAR_SITE_DATA, signOutHeaders } from './sign-out';
@@ -0,0 +1,171 @@
1
+ // Single responsibility: `signInWithLink` — a mailed link as a sign-in door. The link is consumed
2
+ // (single-use, expiring, hashed at rest: `consumeVerification`), its address resolved to a user,
3
+ // and the answer is the `LoginResult` every other door gives — or `X_MFA_REQUIRED` and no session
4
+ // when a second factor is enrolled. One call, so the second factor is not the caller's to forget.
5
+
6
+ import { ConfigInvalidError, renderFixLiteral, uuidV7 } from '@ultimat3/core';
7
+ import type { AuthUser } from './adapter';
8
+ import type { Auth, LoginResult } from './auth';
9
+ import { normaliseEmail } from './email';
10
+ import { AuthError, authWriteFailed } from './errors';
11
+ import { mfaChallengeRequired } from './mfa-challenge';
12
+ import { resolveActor } from './policy-bridge';
13
+ import { createSession, sessionCookie } from './session';
14
+ import { verificationPurpose } from './verification-purposes';
15
+ import { consumeWith, VERIFICATION_PURPOSES, type VerificationPurpose } from './verify';
16
+
17
+ /** What a proven address with no account becomes. Business convention, so the app states it. */
18
+ export interface LinkSignUp {
19
+ /** The user's id, when the app already chose one — as `register(auth, { id })` takes it. */
20
+ readonly id?: string | undefined;
21
+ readonly orgId?: string | null | undefined;
22
+ readonly roles?: readonly string[] | undefined;
23
+ readonly scopes?: readonly string[] | undefined;
24
+ readonly externalId?: string | null | undefined;
25
+ }
26
+
27
+ export interface LinkSignInInput {
28
+ /**
29
+ * The purpose the link was issued under: one the app declared for signing in
30
+ * (`defineVerificationPurpose({ …, signIn: true })`). Never `'email-verify'`,
31
+ * `'password-reset'` or any purpose not declared `signIn` — a token mailed to do one job is not
32
+ * a session.
33
+ */
34
+ readonly purpose: VerificationPurpose;
35
+ /** The address the link was mailed to. */
36
+ readonly identifier: string;
37
+ readonly token: string;
38
+ /**
39
+ * Stamped on the session this call writes. With TOTP enrolled it writes none: hand them to
40
+ * `completeMfa(auth, challenge, code, { ip, userAgent })`, the leg that does.
41
+ */
42
+ readonly ip?: string | null | undefined;
43
+ readonly userAgent?: string | null | undefined;
44
+ /**
45
+ * Declared: an address no account holds becomes a verified, passwordless one. Absent: it is
46
+ * refused. Never applied to an account that exists.
47
+ */
48
+ readonly signUp?: LinkSignUp | undefined;
49
+ }
50
+
51
+ /**
52
+ * One answer for "no account" and "disabled account", carrying nothing: the caller proved an
53
+ * inbox, which is not a reason to describe the account behind it.
54
+ */
55
+ const linkSignInRefused = (purpose: string): AuthError =>
56
+ new AuthError({
57
+ code: 'X_UNAUTHENTICATED',
58
+ cause: 'the sign-in link was valid, and its address has no account that may sign in',
59
+ fix: `signInWithLink(auth, { purpose: ${renderFixLiteral(purpose, "'<purpose>'")}, identifier, token, signUp: {} }) // only where a proven address with no account should become one, and with a freshly mailed link: this one is spent. A disabled account stays refused`,
60
+ });
61
+
62
+ /**
63
+ * An account holds the address and never proved it, so whoever registered it chose its password.
64
+ * Signing the inbox's owner into that account hands them a session somebody else can also open —
65
+ * and so does merely verifying it: the registrant's password, second factor, passkeys, API keys and
66
+ * sessions survive a stamp. Recovery needs app-owned coordination with every administrative
67
+ * disable, including an atomic ownership check when reopening. Named,
68
+ * because this caller owns the address — the rule `oauthAccountNotLinked` follows.
69
+ */
70
+ const linkAccountUnverified = (): AuthError =>
71
+ new AuthError({
72
+ code: 'X_UNAUTHENTICATED',
73
+ cause:
74
+ 'an account holds this address but never verified it, so whoever registered it may hold its password, and a sign-in link may not claim it',
75
+ fix: 'await passwordReset.issue(runtime, { identifier: email, locale }) // consuming the reset proves only the inbox; use an app-owned recovery flow that coordinates disableUser and every administrative disable, clears all credentials, and atomically verifies ownership before reopening',
76
+ });
77
+
78
+ /** The one purpose a refusal's fix names: its own, so no outstanding link of another job is promoted. */
79
+ const SIGN_IN_PURPOSE_FIX =
80
+ "defineVerificationPurpose({ name: 'sign-in', template: 'auth.sign-in', ttlMs: 15 * 60 * 1000, signIn: true }) // a purpose of its own, never one that already mails another job's links; then issue a fresh link under it and signInWithLink(auth, { purpose: 'sign-in', identifier, token })";
81
+
82
+ /** Before the store is asked, so a refused purpose leaves its token live for its own job. */
83
+ function assertSignInPurpose(name: string): void {
84
+ if ((VERIFICATION_PURPOSES as readonly string[]).includes(name)) {
85
+ throw new ConfigInvalidError({
86
+ cause: `signInWithLink() was given the built-in purpose '${name}', whose token is mailed to do that one job and is not a sign-in credential`,
87
+ fix: SIGN_IN_PURPOSE_FIX,
88
+ meta: { purpose: name },
89
+ });
90
+ }
91
+ const purpose = verificationPurpose(name);
92
+ // Opt-in, never inferred from the identifier: an email-change or account-deletion link keys on
93
+ // the address too, and was mailed to do that one job.
94
+ if (purpose.signIn !== true) {
95
+ throw new ConfigInvalidError({
96
+ cause: `the verification purpose ${renderFixLiteral(name, "'<purpose>'")} is not declared a sign-in credential, so its link was mailed to do another job`,
97
+ fix: SIGN_IN_PURPOSE_FIX,
98
+ meta: { purpose: name },
99
+ });
100
+ }
101
+ // The stored identifier is looked up as `x_users.email`, so it must be keyed the way that is:
102
+ // the exported `normaliseEmail` itself, the default, not a function that happens to agree.
103
+ if (purpose.identifier !== normaliseEmail) {
104
+ throw new ConfigInvalidError({
105
+ cause: `the verification purpose ${renderFixLiteral(name, "'<purpose>'")} declares its own identifier, so what its link proves is not known to be an account's address`,
106
+ fix: SIGN_IN_PURPOSE_FIX,
107
+ meta: { purpose: name },
108
+ });
109
+ }
110
+ }
111
+
112
+ async function signUpWith(auth: Auth, email: string, signUp: LinkSignUp): Promise<AuthUser> {
113
+ const created = await auth.adapter.createUser({
114
+ id: signUp.id ?? uuidV7(auth.clock),
115
+ email,
116
+ // No password, and never a random one: a hash nobody knows the input to is still a
117
+ // credential a reset flow could hand over.
118
+ passwordHash: null,
119
+ orgId: signUp.orgId ?? null,
120
+ roles: signUp.roles ?? [],
121
+ scopes: signUp.scopes ?? [],
122
+ externalId: signUp.externalId ?? null,
123
+ // In the creating write: a stamp written second could fail after the row landed, leaving an
124
+ // account this same door refuses on every later link.
125
+ emailVerifiedAt: auth.clock.now(),
126
+ createdAt: auth.clock.now(),
127
+ });
128
+ if (created.emailVerifiedAt !== null) return created;
129
+ // An app's own adapter that predates the field: the second write, failing closed.
130
+ const stamped = await auth.adapter.updateUser(created.id, { emailVerifiedAt: auth.clock.now() });
131
+ if (stamped === null) throw authWriteFailed('updateUser', 'x_users');
132
+ return stamped;
133
+ }
134
+
135
+ /**
136
+ * A consumed link → a session, or the second factor's challenge.
137
+ *
138
+ * The link is spent FIRST, in the store's one atomic step: every refusal below this line has
139
+ * already used it, so a link is good for one attempt whatever the attempt ends in. With a second
140
+ * factor enrolled the answer is `X_MFA_REQUIRED` carrying the sealed challenge `completeMfa`
141
+ * takes; no session row is written, and a fresh link never clears the count of wrong codes.
142
+ */
143
+ export async function signInWithLink(auth: Auth, input: LinkSignInInput): Promise<LoginResult> {
144
+ assertSignInPurpose(input.purpose);
145
+ const record = await consumeWith(
146
+ { store: auth.adapter, clock: auth.clock },
147
+ { purpose: input.purpose, identifier: input.identifier, token: input.token },
148
+ );
149
+ const email = normaliseEmail(record.identifier);
150
+ const existing = await auth.adapter.findUserByEmail(email);
151
+ if (existing === null && input.signUp === undefined) throw linkSignInRefused(input.purpose);
152
+ if (existing !== null && existing.disabledAt !== null) throw linkSignInRefused(input.purpose);
153
+ if (existing !== null && existing.emailVerifiedAt === null) throw linkAccountUnverified();
154
+ const user = existing ?? (await signUpWith(auth, email, input.signUp ?? {}));
155
+
156
+ // The inbox is proven, the second factor is not: the user's rule, whichever door they used.
157
+ if (user.mfaSecret !== null) throw await mfaChallengeRequired(auth, user.id);
158
+
159
+ const issued = await createSession(auth.sessions, {
160
+ userId: user.id,
161
+ ip: input.ip ?? null,
162
+ userAgent: input.userAgent,
163
+ mfaSatisfied: true,
164
+ });
165
+ return {
166
+ actor: resolveActor({ kind: 'user', user, session: issued.session }),
167
+ session: issued.session,
168
+ token: issued.token,
169
+ cookie: sessionCookie(issued.token, auth.sessions.policy),
170
+ };
171
+ }
@@ -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'] =
@@ -127,7 +128,7 @@ export class MemoryAuthAdapter implements AuthAdapter {
127
128
  id: input.id,
128
129
  // Stored as handed over, exactly as the `insert into x_users` binds it.
129
130
  email: input.email,
130
- emailVerifiedAt: null,
131
+ emailVerifiedAt: input.emailVerifiedAt ?? null,
131
132
  passwordHash: input.passwordHash,
132
133
  orgId: input.orgId,
133
134
  roles: [...input.roles],
@@ -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
  ]);
@@ -13,6 +13,8 @@ export interface VerificationPurposeDef {
13
13
  readonly ttlMs: number;
14
14
  /** How the identifier becomes the store key and the mail address. */
15
15
  readonly identifier: (raw: string) => string;
16
+ /** Declared a sign-in credential: the one thing `signInWithLink` consumes. Absent is no. */
17
+ readonly signIn?: boolean | undefined;
16
18
  }
17
19
 
18
20
  // A Map, never a record keyed by an attacker-reachable string: `consumeVerification` looks a
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);
@@ -179,6 +190,11 @@ export interface DefineVerificationPurposeInput {
179
190
  readonly ttlMs: number;
180
191
  /** The identifier's one normalisation. Defaults to `normaliseEmail`, the address door's. */
181
192
  readonly identifier?: ((raw: string) => string) | undefined;
193
+ /**
194
+ * `true`: this purpose's link signs its holder in (`signInWithLink`). Stated, never inferred:
195
+ * an email-change or account-deletion link proves the same inbox but was mailed to do one job.
196
+ */
197
+ readonly signIn?: boolean | undefined;
182
198
  }
183
199
 
184
200
  export interface VerificationPurposeHandle {
@@ -212,6 +228,7 @@ export function defineVerificationPurpose(
212
228
  template: input.template,
213
229
  ttlMs,
214
230
  identifier: input.identifier ?? normaliseEmail,
231
+ signIn: input.signIn === true,
215
232
  });
216
233
  const name = input.name;
217
234
  return {