@ultimat3/auth 31.55.0 → 31.57.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
@@ -130,7 +130,8 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
130
130
  - **`listUsersByOrg` orders by byte**: `collate "C"` in Postgres, a code-point compare in memory —
131
131
  never `localeCompare`, never UTF-16 `<` (`list-users-order.live.test.ts`, on an `en_US` db).
132
132
  - Every `AuthAdapter` member is REQUIRED — a missing one is a compile error at `defineAuth`, and
133
- no caller in this package refuses at runtime with `X_NOT_IMPLEMENTED`.
133
+ no caller in this package refuses at runtime with `X_NOT_IMPLEMENTED` — except the optional
134
+ `getSessionWithUser` and `findUsersByIds`, each with a fallback over required members.
134
135
  - **An api key is its owner's credential**: `verifyApiKey` re-reads the owner after the secret
135
136
  matched; `disableUser` revokes their keys. †
136
137
  - **`verifyApiKey` refuses an `env` segment that is not the stored prefix's, and touches
@@ -178,6 +179,7 @@ A rule marked `†` has its full text in [`docs/history/auth-rules.md`](../../do
178
179
  | `policy-bridge.ts` | the one funnel: identity → `Actor`, all four `ActorKind`s |
179
180
  | `session.ts` | two expiries, rotation, revocation, device list, the cookie |
180
181
  | `adapter.ts` | the seam; `builtin-adapter.ts` (Postgres, its row readers in `builtin-adapter-rows.ts`) + `memory-adapter.ts` |
182
+ | `users-by-ids.ts` | `findUsersByIds(adapter, ids)`: `MAX_USERS_BY_IDS`, de-duplication, first-appearance order; the optional member, else bounded `findUserById` |
181
183
  | `session-user.ts` | token → admitted session + its user: one join when the adapter has `getSessionWithUser`, else two reads |
182
184
  | `tables.ts` (`./schema`) | every auth table the boot applies — `AUTH_TABLES`, the limiter and TOTP DDL, and `authorization-server-schema.ts` re-exported. `x_auth_lockouts` renders through db's `tableDdl` from `AUTH_LOCKOUTS_STORAGE` (logged, stated). A LEAF: it imports nothing else but `@ultimat3/db` (`schema-subpath.test.ts`), so `FRAMEWORK_SCHEMA` keeps the barrel off `ROLE=migrate` (`MIGRATE_CEILING`). The per-table constants stay module-private (removed from the API in 22.0.0). Also on `.` |
183
185
  | `adapter-subpath.ts` | `@ultimat3/auth/adapter`: the `authLimiter`/`totpReplay`/`authServerStore` port types, their installers and resets, and `installKdfGate` |
package/README.md CHANGED
@@ -838,6 +838,7 @@ show it beside `name`. Full table and the rule each test holds:
838
838
  | `revokeSessionsCreatedBefore(auth, at, reason)` | everything minted under a rotated secret |
839
839
  | `disableUser(auth, userId, reason)` | stamps `disabledAt`, kills the sessions **and** revokes the user's live api keys — `{ user, sessionsRevoked, apiKeysRevoked }`. Re-enabling restores neither |
840
840
  | `listOrgUsers(auth, orgId, { role })` | the quarterly access review, as safe summaries — in byte (code-point) order of `email` on both adapters, whatever the database collation |
841
+ | `findUsersByIds(auth.adapter, ids)` | none: a read. The people a screen found elsewhere (a membership list, an audit trail), in one statement on `postgresAuthAdapter` (`where id = any($1::uuid[])`). Ordered by each id's first appearance in `ids`; an unknown id is absent, a repeated one answered once, `[]` reads nothing. More than `MAX_USERS_BY_IDS` (1000) ids, repeats counted, is `X_AUTH_USER_IDS_TOO_MANY` before any read (`As of 2026-11`) |
841
842
  | `updatePrivileges(auth, userId, patch, session?)` | the grant, plus the session rotation it requires. A `passwordHash` change ends every OTHER session of that user (`sessionsRevoked`) — all of them when no session of theirs was passed, as in a reset |
842
843
 
843
844
  Rotation (`rotateSession`, and `updatePrivileges` through it) mints a new **id**, never a new
@@ -875,12 +876,20 @@ lowercase, nothing else. Call it before `findUserByEmail`/`createUser` in any lo
875
876
  own, and key any bucket of your own with it — `accountKey` does.
876
877
 
877
878
  Every member of the seam is required — an adapter missing one is a compile error, never a runtime
878
- refusal — except `getSessionWithUser(id)` (`As of 2026-11`): the session and its user in ONE read,
879
+ refusal — except two, both `As of 2026-11`: `getSessionWithUser(id)` and `findUsersByIds(ids)`.
880
+ `getSessionWithUser(id)` is the session and its user in ONE read,
879
881
  `{ session, user | null }` or `null`. `authenticate` uses it when present and makes the two reads
880
882
  it replaces (`getSession`, then `findUserById`) when not, so an adapter written before it still
881
883
  binds. Both shipped adapters carry it; `authAdapterConformance` holds one that does to answering
882
884
  exactly what the two reads answer.
883
885
 
886
+ For `findUsersByIds(ids)`, call `findUsersByIds(adapter, ids)`: it uses the member when present
887
+ and one `findUserById` per distinct id (8 at once) when not — the same bound, order and answer.
888
+ Both shipped adapters carry it; `authAdapterConformance` holds it. Rows come back by first
889
+ appearance with misses left out, so pair a row with its id by `user.id`, never by position. On
890
+ Postgres an id the `uuid` type refuses is absent, and any spelling it reads (either case, no
891
+ hyphens, braces) matches as `findUserById` does.
892
+
884
893
  `x_users` gained two columns in 1.3.0 — `scopes text[]` and `external_id text unique` — plus an
885
894
  `org_id` index.
886
895
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/auth",
3
- "version": "31.55.0",
3
+ "version": "31.57.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.55.0",
54
- "@ultimat3/db": "31.55.0",
55
- "@ultimat3/schema": "31.55.0"
53
+ "@ultimat3/core": "31.57.0",
54
+ "@ultimat3/db": "31.57.0",
55
+ "@ultimat3/schema": "31.57.0"
56
56
  }
57
57
  }
package/src/adapter.ts CHANGED
@@ -78,6 +78,16 @@ export interface UserQuery {
78
78
  export interface UserStore {
79
79
  findUserByEmail(email: string): Promise<AuthUser | null>;
80
80
  findUserById(id: string): Promise<AuthUser | null>;
81
+ /**
82
+ * Many users by id in one read — one statement on Postgres — for a screen of people found
83
+ * elsewhere (a membership list, an audit trail). An id nobody holds is absent, never an error;
84
+ * a repeated id answers once. Ordered by each id's first appearance in `ids` (`inIdOrder`).
85
+ * Empty in, `[]` out with no read. More than `MAX_USERS_BY_IDS` ids, duplicates counted, is
86
+ * `X_AUTH_USER_IDS_TOO_MANY` before any read (`distinctUserIds`). Optional until the next major,
87
+ * like `getSessionWithUser`: callers go through `findUsersByIds(adapter, ids)`, which answers the
88
+ * same from `findUserById` on an adapter without it. Both shipped adapters implement it.
89
+ */
90
+ findUsersByIds?(ids: readonly string[]): Promise<readonly AuthUser[]>;
81
91
  createUser(input: CreateUserInput): Promise<AuthUser>;
82
92
  updateUser(id: string, patch: UserPatch): Promise<AuthUser | null>;
83
93
  /**
@@ -33,6 +33,24 @@ import {
33
33
  import { usersUniqueViolation } from './builtin-adapter-violation';
34
34
  import { authWriteFailed } from './errors';
35
35
  import { postgresPasskeyStore } from './passkey-postgres';
36
+ import { distinctUserIds, inIdOrder } from './users-by-ids';
37
+
38
+ /**
39
+ * What Postgres's `uuid` input reads: 32 hex digits in either case, a hyphen allowed after any
40
+ * group of four, the whole optionally in braces (`{…}`). The capture is the digits without braces.
41
+ */
42
+ const UUID_INPUT = /^\{?([0-9a-f]{4}(?:-?[0-9a-f]{4}){7})\}?$/i;
43
+
44
+ /**
45
+ * An id in the one spelling Postgres answers with — lowercase 8-4-4-4-12 — or `null` for a string
46
+ * the `uuid` type would refuse. Braces must pair, as they must for Postgres.
47
+ */
48
+ const canonicalUuid = (id: string): string | null => {
49
+ const match = UUID_INPUT.exec(id);
50
+ if (match === null || id.startsWith('{') !== id.endsWith('}')) return null;
51
+ const hex = (match[1] ?? '').replaceAll('-', '').toLowerCase();
52
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
53
+ };
36
54
 
37
55
  /**
38
56
  * A patch column is written as `case when <set> then <value> else <column> end` rather than
@@ -91,11 +109,40 @@ export class PostgresAuthAdapter implements AuthAdapter {
91
109
  return row === null ? null : toUser(row);
92
110
  }
93
111
 
112
+ /**
113
+ * A string the `uuid` type refuses is nobody's id: `null` with no statement, as memory answers,
114
+ * rather than the failed cast Postgres would raise — and so `findUsersByIds`' fallback over this
115
+ * method reads a mixed batch exactly as the one-statement batch does.
116
+ */
94
117
  async findUserById(id: string): Promise<AuthUser | null> {
118
+ if (canonicalUuid(id) === null) return null;
95
119
  const row = await this.#db.one<Row>(sql`select * from x_users where id = ${id}`);
96
120
  return row === null ? null : toUser(row);
97
121
  }
98
122
 
123
+ /**
124
+ * `= any($1)`: one statement and one parameter however many ids, served by the primary key. An
125
+ * id the `uuid` type would refuse is nobody's and is left out before the bind — one in the array
126
+ * would fail the whole `::uuid[]` cast. Every other spelling Postgres reads (uppercase, no
127
+ * hyphens, braces) is canonicalised to the one it answers with, so it finds the row
128
+ * `findUserById` finds, two spellings of one id answer once, and the answer's order is keyed.
129
+ */
130
+ async findUsersByIds(ids: readonly string[]): Promise<readonly AuthUser[]> {
131
+ const wanted = [
132
+ ...new Set(
133
+ distinctUserIds(ids).flatMap((id) => {
134
+ const canonical = canonicalUuid(id);
135
+ return canonical === null ? [] : [canonical];
136
+ }),
137
+ ),
138
+ ];
139
+ if (wanted.length === 0) return [];
140
+ const rows = await this.#db.query<Row>(
141
+ sql`select * from x_users where id = any(${wanted}::uuid[])`,
142
+ );
143
+ return inIdOrder(wanted, rows.map(toUser));
144
+ }
145
+
99
146
  async createUser(input: CreateUserInput): Promise<AuthUser> {
100
147
  const row = await this.#writeUser(
101
148
  'createUser',
package/src/errors.ts CHANGED
@@ -46,6 +46,7 @@ export const AUTH_OWNED_ERROR_CODES = [
46
46
  'X_AUTH_GRANTS_UNSUPPORTED',
47
47
  'X_PASSKEY_LABEL_INVALID',
48
48
  'X_PASSKEY_RENAME_UNSUPPORTED',
49
+ 'X_AUTH_USER_IDS_TOO_MANY',
49
50
  ] as const;
50
51
 
51
52
  /**
@@ -116,6 +117,7 @@ export const AUTH_ERROR_TITLES: Readonly<Record<AuthOwnedErrorCode, string>> = {
116
117
  X_AUTH_GRANTS_UNSUPPORTED: "the authorization server's store cannot list a subject's live grants",
117
118
  X_PASSKEY_LABEL_INVALID: 'the passkey label is not one a person can read back',
118
119
  X_PASSKEY_RENAME_UNSUPPORTED: 'the auth adapter cannot rename a passkey',
120
+ X_AUTH_USER_IDS_TOO_MANY: 'more user ids were asked for in one read than findUsersByIds accepts',
119
121
  };
120
122
 
121
123
  // Registered unconditionally, in one call: a second package claiming a code auth owns has to fail
package/src/index.ts CHANGED
@@ -455,6 +455,7 @@ export {
455
455
  randomToken,
456
456
  sha256Hex,
457
457
  } from './tokens';
458
+ export { findUsersByIds, MAX_USERS_BY_IDS } from './users-by-ids';
458
459
  export type {
459
460
  ConsumeVerificationInput,
460
461
  DefineVerificationPurposeInput,
package/src/link-login.ts CHANGED
@@ -12,7 +12,7 @@ import { mfaChallengeRequired } from './mfa-challenge';
12
12
  import { resolveActor } from './policy-bridge';
13
13
  import { createSession, sessionCookie } from './session';
14
14
  import { verificationPurpose } from './verification-purposes';
15
- import { consumeWith, VERIFICATION_PURPOSES, type VerificationPurpose } from './verify';
15
+ import { consumeBound, VERIFICATION_PURPOSES, type VerificationPurpose } from './verify';
16
16
 
17
17
  /** What a proven address with no account becomes. Business convention, so the app states it. */
18
18
  export interface LinkSignUp {
@@ -99,8 +99,9 @@ function assertSignInPurpose(name: string): void {
99
99
  });
100
100
  }
101
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) {
102
+ // the exported `normaliseEmail` itself, the default, not a function that happens to agree —
103
+ // or say which address its key holds (`addressOf`), the inbox its link was mailed to.
104
+ if (purpose.identifier !== normaliseEmail && purpose.addressOf === undefined) {
104
105
  throw new ConfigInvalidError({
105
106
  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
107
  fix: SIGN_IN_PURPOSE_FIX,
@@ -109,6 +110,20 @@ function assertSignInPurpose(name: string): void {
109
110
  }
110
111
  }
111
112
 
113
+ /**
114
+ * The account address a consumed key proves: the inbox `issueVerification` mailed it to, as the
115
+ * digest checked it (`consumeBound`), never `addressOf` asked a second time.
116
+ */
117
+ function addressProven(name: string, key: string, bound: string | undefined): string {
118
+ const email = normaliseEmail(bound ?? key);
119
+ if (email !== '') return email;
120
+ throw new ConfigInvalidError({
121
+ cause: `the verification purpose ${renderFixLiteral(name, "'<purpose>'")} answered no address for a key it issued, so its link proves no account`,
122
+ fix: "defineVerificationPurpose({ name, template, ttlMs, signIn: true, identifier, addressOf: (key) => key.slice(key.indexOf('|') + 1) }) // addressOf returns the address inside every key identifier writes",
123
+ meta: { purpose: name },
124
+ });
125
+ }
126
+
112
127
  async function signUpWith(auth: Auth, email: string, signUp: LinkSignUp): Promise<AuthUser> {
113
128
  const created = await auth.adapter.createUser({
114
129
  id: signUp.id ?? uuidV7(auth.clock),
@@ -142,11 +157,11 @@ async function signUpWith(auth: Auth, email: string, signUp: LinkSignUp): Promis
142
157
  */
143
158
  export async function signInWithLink(auth: Auth, input: LinkSignInInput): Promise<LoginResult> {
144
159
  assertSignInPurpose(input.purpose);
145
- const record = await consumeWith(
160
+ const { record, address } = await consumeBound(
146
161
  { store: auth.adapter, clock: auth.clock },
147
162
  { purpose: input.purpose, identifier: input.identifier, token: input.token },
148
163
  );
149
- const email = normaliseEmail(record.identifier);
164
+ const email = addressProven(input.purpose, record.identifier, address);
150
165
  const existing = await auth.adapter.findUserByEmail(email);
151
166
  if (existing === null && input.signUp === undefined) throw linkSignInRefused(input.purpose);
152
167
  if (existing !== null && existing.disabledAt !== null) throw linkSignInRefused(input.purpose);
@@ -20,6 +20,7 @@ import type {
20
20
  } from './adapter';
21
21
  import { authUniqueViolation } from './errors';
22
22
  import { memoryPasskeyStore } from './passkey-memory';
23
+ import { distinctUserIds } from './users-by-ids';
23
24
 
24
25
  const verificationKey = (purpose: string, identifier: string): string => `${purpose}:${identifier}`;
25
26
 
@@ -93,6 +94,11 @@ export class MemoryAuthAdapter implements AuthAdapter {
93
94
  return this.#users.get(id) ?? null;
94
95
  }
95
96
 
97
+ /** Walking the distinct ids IS `inIdOrder`'s order: first appearance, the unknown ones absent. */
98
+ async findUsersByIds(ids: readonly string[]): Promise<readonly AuthUser[]> {
99
+ return distinctUserIds(ids).flatMap((id) => this.#users.get(id) ?? []);
100
+ }
101
+
96
102
  /**
97
103
  * The two UNIQUE constraints `x_users` declares, enforced here because `PostgresAuthAdapter` LEANS on
98
104
  * them: `email text not null unique` and `external_id text unique` (`tables.ts`). Without them
@@ -0,0 +1,67 @@
1
+ // Single responsibility: what every `findUsersByIds` answer agrees on, above the storage — the
2
+ // bound on one read, the de-duplication, the order the answer comes back in, and the one call a
3
+ // caller makes (`findUsersByIds(adapter, ids)`), which reads one id at a time only on an adapter
4
+ // written before the member existed.
5
+
6
+ import { mapBounded } from '@ultimat3/core';
7
+ import type { AuthUser, UserStore } from './adapter';
8
+ import { AuthError } from './errors';
9
+
10
+ /**
11
+ * Most ids one `findUsersByIds` call accepts, duplicates counted. A screen of people is a page,
12
+ * never a table: past this the caller is reading everyone, which is `listUsersByOrg`'s job.
13
+ */
14
+ export const MAX_USERS_BY_IDS = 1000;
15
+
16
+ /** How many `findUserById` reads run at once on an adapter without `findUsersByIds`. */
17
+ const FALLBACK_READ_WIDTH = 8;
18
+
19
+ const usersByIdsTooMany = (count: number): AuthError =>
20
+ new AuthError({
21
+ code: 'X_AUTH_USER_IDS_TOO_MANY',
22
+ cause: `findUsersByIds was handed ${count} ids, past MAX_USERS_BY_IDS (${MAX_USERS_BY_IDS}), duplicates counted`,
23
+ fix: 'findUsersByIds(auth.adapter, ids.slice(at, at + MAX_USERS_BY_IDS)) // one call per slice of at most MAX_USERS_BY_IDS ids, or read only the page of ids the screen shows',
24
+ meta: { count, max: MAX_USERS_BY_IDS },
25
+ });
26
+
27
+ /**
28
+ * The distinct ids, in order of first appearance — refused past `MAX_USERS_BY_IDS` before any
29
+ * read, so an over-long list costs no statement. Empty in, empty out: the adapter skips its read.
30
+ */
31
+ export const distinctUserIds = (ids: readonly string[]): readonly string[] => {
32
+ if (ids.length > MAX_USERS_BY_IDS) throw usersByIdsTooMany(ids.length);
33
+ return [...new Set(ids)];
34
+ };
35
+
36
+ /**
37
+ * The rows found, in the order their ids first appear in `ids`; an id nobody holds is absent, with
38
+ * no placeholder. Every adapter answers in this one order. A miss shifts every later row, so a
39
+ * caller pairs a row with its id by `user.id`, never by position in the answer.
40
+ */
41
+ export const inIdOrder = (
42
+ ids: readonly string[],
43
+ users: readonly AuthUser[],
44
+ ): readonly AuthUser[] => {
45
+ const byId = new Map(users.map((user) => [user.id, user]));
46
+ return ids.flatMap((id) => byId.get(id) ?? []);
47
+ };
48
+
49
+ /**
50
+ * Many users by id: the adapter's own `findUsersByIds` (one statement on `postgresAuthAdapter`),
51
+ * else one `findUserById` per distinct id, at most `FALLBACK_READ_WIDTH` at once — the same
52
+ * answer, the same bound, the same order either way.
53
+ */
54
+ export const findUsersByIds = async (
55
+ adapter: Pick<UserStore, 'findUserById' | 'findUsersByIds'>,
56
+ ids: readonly string[],
57
+ ): Promise<readonly AuthUser[]> => {
58
+ if (adapter.findUsersByIds !== undefined) return adapter.findUsersByIds(ids);
59
+ const found = await mapBounded(distinctUserIds(ids), (id) => adapter.findUserById(id), {
60
+ width: FALLBACK_READ_WIDTH,
61
+ });
62
+ // Two distinct strings can name one row (`findUserById` on Postgres reads `ADA…` as `ada…`):
63
+ // the first match answers, as the adapters' own batch answers each row once.
64
+ const byId = new Map<string, AuthUser>();
65
+ for (const user of found) if (user !== null && !byId.has(user.id)) byId.set(user.id, user);
66
+ return [...byId.values()];
67
+ };
@@ -17,6 +17,12 @@ export interface VerificationPurposeDef {
17
17
  readonly signIn?: boolean | undefined;
18
18
  /** `'explicit'`: `issueVerification` mails `to`, not the identifier (an invite). Absent refuses `to`. */
19
19
  readonly recipient?: 'explicit' | undefined;
20
+ /**
21
+ * The address a store key names, where the key is more than one (a link id and the address):
22
+ * the inbox `issueVerification` mails and, for a sign-in purpose, the account the link proves.
23
+ * Absent, the key is the address.
24
+ */
25
+ readonly addressOf?: ((key: string) => string) | undefined;
20
26
  }
21
27
 
22
28
  // A Map, never a record keyed by an attacker-reachable string: `consumeVerification` looks a
@@ -40,6 +46,14 @@ export function registerVerificationPurpose(def: VerificationPurposeDef): void {
40
46
  `defineVerificationPurpose({ name: '${def.name}', template: 'auth.${def.name}', ttlMs }) # and add the key to your i18n catalog`,
41
47
  );
42
48
  }
49
+ // One function names the inbox the link goes to and the account it signs in: a `to` chosen per
50
+ // call beside it would let a link mailed to one inbox prove another's address.
51
+ if (def.addressOf !== undefined && def.recipient === 'explicit') {
52
+ throw purposeInvalid(
53
+ `the verification purpose '${def.name}' declares both addressOf and recipient: 'explicit', so the inbox its link reaches and the address it proves could differ`,
54
+ `defineVerificationPurpose({ name: '${def.name}', template, ttlMs, identifier, addressOf }) # drop recipient: addressOf names the inbox the mail goes to`,
55
+ );
56
+ }
43
57
  if (purposes.has(def.name)) {
44
58
  throw purposeInvalid(
45
59
  `the verification purpose '${def.name}' is declared twice, so which template and lifetime it has depends on import order`,
package/src/verify.ts CHANGED
@@ -10,7 +10,11 @@ import { normaliseEmail } from './email';
10
10
  import { AuthError } from './errors';
11
11
  import { assertFiniteAuthCount } from './policy-numbers';
12
12
  import { randomToken, sha256Hex } from './tokens';
13
- import { registerVerificationPurpose, verificationPurpose } from './verification-purposes';
13
+ import {
14
+ registerVerificationPurpose,
15
+ type VerificationPurposeDef,
16
+ verificationPurpose,
17
+ } from './verification-purposes';
14
18
 
15
19
  /**
16
20
  * `locale` is required, not optional: an inferred locale is how a user gets a security email
@@ -105,13 +109,16 @@ export async function issueVerification(
105
109
  // link must reach the inbox the account is keyed by, even when an app spreads a request body in.
106
110
  const explicit = purpose.recipient === 'explicit';
107
111
  if (!explicit && input.to !== undefined) throw recipientRefused(purpose.name, 'undeclared');
108
- const to = explicit ? (input.to ?? '') : identifier;
112
+ // `addressOf` asked ONCE: the inbox mailed and the address bound into the digest are one value,
113
+ // so a mapping that answers differently between two calls cannot split them.
114
+ const bound = explicit ? undefined : addressOfKey(purpose, identifier);
115
+ const to = explicit ? (input.to ?? '') : (bound ?? identifier);
109
116
  if (to.trim() === '') throw recipientRefused(purpose.name, 'blank');
110
117
  await runtime.store.putVerification({
111
118
  id: randomToken(12),
112
119
  purpose: purpose.name,
113
120
  identifier,
114
- tokenHash: sha256Hex(token),
121
+ tokenHash: tokenDigest(token, bound, purpose.signIn === true),
115
122
  expiresAt,
116
123
  consumedAt: null,
117
124
  createdAt: now,
@@ -178,19 +185,71 @@ export async function consumeVerification(
178
185
  * `consumeVerification` without the mailer: consuming sends nothing, so a caller with no mailer in
179
186
  * hand (`signInWithLink`) needs none. Internal, so the exported signature stays as it shipped.
180
187
  */
188
+ /** The prefix of a digest bound to an inbox (`addressOf`); a plain digest has none. */
189
+ const BOUND_DIGEST_TAG = 'addr1:';
190
+ /** The same, for a purpose whose link signs in: a link mailed for another job never redeems as a login. */
191
+ const SIGN_IN_DIGEST_TAG = 'addr1s:';
192
+
193
+ /**
194
+ * The digest a record holds. A purpose with `addressOf` binds the inbox the link was mailed to into
195
+ * it, so a record redeems only while `addressOf(key)` still names that inbox: a live link issued
196
+ * before the purpose's mapping changed (or under `recipient: 'explicit'`, to another `to`) digests
197
+ * differently and is refused, never read as proof of whatever address the new mapping names.
198
+ */
199
+ /**
200
+ * The address inside a key: the inbox mailed and the digest's binding, one string. A sign-in
201
+ * purpose takes the spelling an account is looked up by (`normaliseEmail`), so a mixed-case answer
202
+ * cannot mail one mailbox and sign in another account; any other purpose keeps `addressOf`'s answer
203
+ * exactly, the mailbox it names, since nothing looks an account up by it.
204
+ */
205
+ function addressOfKey(
206
+ purpose: Pick<VerificationPurposeDef, 'addressOf' | 'signIn'>,
207
+ key: string,
208
+ ): string | undefined {
209
+ if (purpose.addressOf === undefined) return undefined;
210
+ const address = purpose.addressOf(key);
211
+ return purpose.signIn === true ? normaliseEmail(address) : address;
212
+ }
213
+
214
+ function tokenDigest(token: string, bound: string | undefined, signIn: boolean): string {
215
+ if (bound === undefined) return sha256Hex(token);
216
+ // Tagged, so the formats never meet: a plain digest is 64 hex characters and can never equal a
217
+ // bound one, and among address-bound digests a sign-in one never equals a non-sign-in one,
218
+ // whichever way a purpose's `addressOf` or `signIn` was changed with links still live (a mailed
219
+ // address already in its normal spelling would otherwise digest the same either way). Without
220
+ // `addressOf` both modes are the plain digest: nothing is bound, and a sign-in purpose needs
221
+ // `addressOf` only when its key is more than the address.
222
+ const tag = signIn ? SIGN_IN_DIGEST_TAG : BOUND_DIGEST_TAG;
223
+ return `${tag}${sha256Hex(`${token}\n${bound}`)}`;
224
+ }
225
+
226
+ /** A consumed record and, for a purpose with `addressOf`, the address its digest proved. */
227
+ export interface ConsumedVerification {
228
+ readonly record: AuthVerification;
229
+ /** The exact address the digest was checked against; a sign-in reads this, never `addressOf` again. */
230
+ readonly address: string | undefined;
231
+ }
232
+
181
233
  export async function consumeWith(
182
234
  runtime: Pick<VerificationRuntime, 'store' | 'clock'>,
183
235
  input: ConsumeVerificationInput,
184
236
  ): Promise<AuthVerification> {
237
+ return (await consumeBound(runtime, input)).record;
238
+ }
239
+
240
+ /** `consumeWith`, answering the address it proved beside the record (`signInWithLink`). */
241
+ export async function consumeBound(
242
+ runtime: Pick<VerificationRuntime, 'store' | 'clock'>,
243
+ input: ConsumeVerificationInput,
244
+ ): Promise<ConsumedVerification> {
185
245
  const purpose = verificationPurpose(input.purpose);
186
- const tokenHash = sha256Hex(input.token);
187
246
  // Normalised on the way OUT as well as in, or a link issued for `ada@x.test` is unredeemable by
188
247
  // a form that posted `Ada@X.test` — one door, one key.
189
- const record = await runtime.store.takeVerification(
190
- purpose.name,
191
- purpose.identifier(input.identifier),
192
- tokenHash,
193
- );
248
+ const identifier = purpose.identifier(input.identifier);
249
+ // Asked once, and handed back: the account a sign-in looks up is the address this digest proved.
250
+ const address = addressOfKey(purpose, identifier);
251
+ const tokenHash = tokenDigest(input.token, address, purpose.signIn === true);
252
+ const record = await runtime.store.takeVerification(purpose.name, identifier, tokenHash);
194
253
  if (record === null) throw verificationInvalid(input.purpose);
195
254
  // Kept for the seam, not for the blessed adapters: `VerificationStore` is implementable by an
196
255
  // app, and one that ignores the third argument would otherwise redeem any token. Constant-time
@@ -201,7 +260,7 @@ export async function consumeWith(
201
260
  if (runtime.clock.now().getTime() >= record.expiresAt.getTime()) {
202
261
  throw verificationInvalid(input.purpose);
203
262
  }
204
- return record;
263
+ return { record, address };
205
264
  }
206
265
 
207
266
  export interface DefineVerificationPurposeInput {
@@ -224,6 +283,13 @@ export interface DefineVerificationPurposeInput {
224
283
  * Absent: `issue` refuses a `to`, so a reset link cannot be redirected by a caller's input.
225
284
  */
226
285
  readonly recipient?: 'explicit' | undefined;
286
+ /**
287
+ * Where `identifier` keys more than the address — `` `${linkId}|${email}` ``, so a second link
288
+ * never ends a live one — the address inside that key: the inbox the mail goes to and, with
289
+ * `signIn`, the account `signInWithLink` signs in. One function for both, so a link proves the
290
+ * inbox it reached. Not with `recipient: 'explicit'`. Absent, the key is the address.
291
+ */
292
+ readonly addressOf?: ((key: string) => string) | undefined;
227
293
  }
228
294
 
229
295
  export interface VerificationPurposeHandle {
@@ -259,6 +325,7 @@ export function defineVerificationPurpose(
259
325
  identifier: input.identifier ?? normaliseEmail,
260
326
  signIn: input.signIn === true,
261
327
  ...(input.recipient === 'explicit' ? { recipient: 'explicit' as const } : {}),
328
+ ...(input.addressOf === undefined ? {} : { addressOf: input.addressOf }),
262
329
  });
263
330
  const name = input.name;
264
331
  return {