@rexezuge/identity 1.10.0 → 1.11.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/README.md CHANGED
@@ -34,11 +34,15 @@ const account = await resolveAccount(deps, 'user@example.com'); // ResolvedAccou
34
34
  ```ts
35
35
  import { UserDAO, UserEmailDAO } from '@rexezuge/identity';
36
36
 
37
- const users = new UserDAO(env.DB);
38
- const emails = new UserEmailDAO(env.DB);
37
+ const users = new UserDAO(env.DB, meter); // meter optional: the invocation's SubrequestMeter
38
+ const emails = new UserEmailDAO(env.DB, meter);
39
39
  await users.getById(account.id);
40
+
41
+ const identity = new UserIdentityService({ DB: env.DB }, { meter }); // default DAOs are metered too
40
42
  ```
41
43
 
44
+ Both DAOs take the invocation's `SubrequestMeter` as an optional second argument (unmetered when omitted), and `UserIdentityService` hands `deps.meter` to the DAOs it builds, so identity statements count against the same budget as every other DAO's.
45
+
42
46
  ## 3. Migrations
43
47
 
44
48
  ```ts
@@ -48,7 +52,15 @@ await applyIdentityMigrations(env.DB); // fresh install: users.sql
48
52
  await applyIdentityMigrations(env.DB, { upgrade: true }); // legacy DB: + upgrade-user-identity.sql (rerunnable)
49
53
  ```
50
54
 
51
- Executed through `@rexezuge/d1`'s splitter — one `batch()` per file, matching D1's own per-file apply, so a failure names its file. `IDENTITY_MIGRATIONS` / `IDENTITY_MIGRATION_SQL` carry the same pair as data for repos that apply migrations through their own runner. The upgrade backfills a verified registry row for every anchor, which is what lets pre-identity databases resolve addresses the old way until they migrate.
55
+ Executed through `@rexezuge/d1`'s splitter — one `batch()` per file, matching D1's own per-file apply, so a failure names its file. `IDENTITY_MIGRATIONS` — the ordered `{ name, sql }` list — is the one canonical export for repos that apply migrations through their own runner. `IDENTITY_MIGRATION_SQL` (the same two strings keyed by file name) is `@deprecated` and removed in 2.0. The upgrade backfills a verified registry row for every anchor, which is what lets pre-identity databases resolve addresses the old way until they migrate.
56
+
57
+ ## Extending
58
+
59
+ | Owned by the kit | Yours |
60
+ | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
61
+ | Resolution order, verified-only login, the frozen anchor, case normalisation, the schema | DAO factories (`UserIdentityDeps`), the meter, your own tables' backfill SQL |
62
+
63
+ See [`docs/design-charter.md`](../../docs/design-charter.md).
52
64
 
53
65
  ---
54
66
 
package/dist/UserDAO.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { BaseDAO } from '@rexezuge/d1';
2
2
  import type { D1Queryable } from '@rexezuge/d1';
3
+ import type { SubrequestMeter } from '@rexezuge/shared';
3
4
  import type { UserRow } from './ResolvedAccount.ts';
4
5
  /**
5
6
  * The stored form of a handle: lowercase.
@@ -24,7 +25,14 @@ declare function normalizeUsername(username: string): string;
24
25
  * normalisers.
25
26
  */
26
27
  export declare class UserDAO extends BaseDAO {
27
- constructor(database: D1Queryable);
28
+ /**
29
+ * @param database The binding.
30
+ * @param meter The invocation's subrequest counter. Optional since 1.10 and
31
+ * defaulted to unmetered, exactly like `UserEmailDAO`'s: a consumer that
32
+ * meters its own DAOs must be able to meter this one, or its statements are
33
+ * subrequests the ceiling never saw.
34
+ */
35
+ constructor(database: D1Queryable, meter?: SubrequestMeter);
28
36
  /**
29
37
  * Create an account, stamped with the identity columns.
30
38
  *
@@ -1 +1 @@
1
- {"version":3,"file":"UserDAO.d.ts","sourceRoot":"","sources":["../src/UserDAO.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAEpD;;;;;;;;;;GAUG;AACH,iBAAS,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;;;;;;;GASG;AACH,qBAAa,OAAQ,SAAQ,OAAO;gBACf,QAAQ,EAAE,WAAW;IAIxC;;;;;;;;;;;;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E;IACW,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;CAG1E;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC;AAE7B,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,sBAAsB,CAAC"}
package/dist/UserDAO.js CHANGED
@@ -1 +1 @@
1
- var E=Object.defineProperty;var n=(t,e)=>E(t,"name",{value:e,configurable:!0});import{BaseDAO as o}from"@rexezuge/d1";import{newAccountId as u}from"./ResolvedAccount.js";function i(t){return t.trim().toLowerCase()}n(i,"normalizeUsername");class L extends o{static{n(this,"UserDAO")}constructor(e){super(e)}async createUser(e){const r=e.anchor.toLowerCase(),s=e.loginEmail.toLowerCase(),a=u();return await this.run("INSERT INTO users (email, created_at, id, current_email, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING",[r,e.now,a,s,e.now]),(await this.getByEmail(r))?.id===a?a:null}async ensureUsername(e,r,s){await this.run("UPDATE users SET username = COALESCE(username, ?), updated_at = COALESCE(updated_at, ?) WHERE id = ? OR email = ?",[i(r),s,e,e])}async setUsername(e,r,s){await this.run("UPDATE users SET username = ?, updated_at = ? WHERE id = ? OR email = ?",[i(r),s,e,e])}async getByEmail(e){return this.first("SELECT * FROM users WHERE email = ? LIMIT 1",[e.toLowerCase()])}async getById(e){return this.first("SELECT * FROM users WHERE id = ? LIMIT 1",[e])}async getByCurrentEmail(e){return this.first("SELECT * FROM users WHERE current_email = ? LIMIT 1",[e.toLowerCase()])}async setCurrentEmail(e,r,s){await this.run("UPDATE users SET current_email = ?, updated_at = ? WHERE id = ?",[r.toLowerCase(),s,e])}async getByUsernameCi(e){return this.first("SELECT * FROM users WHERE username = ? LIMIT 1",[e.toLowerCase()])}}export{L as UserDAO,i as normalizeUsername};
1
+ var E=Object.defineProperty;var n=(t,e)=>E(t,"name",{value:e,configurable:!0});import{BaseDAO as o}from"@rexezuge/d1";import{newAccountId as u}from"./ResolvedAccount.js";function i(t){return t.trim().toLowerCase()}n(i,"normalizeUsername");class L extends o{static{n(this,"UserDAO")}constructor(e,r){super(e,r)}async createUser(e){const r=e.anchor.toLowerCase(),s=e.loginEmail.toLowerCase(),a=u();return await this.run("INSERT INTO users (email, created_at, id, current_email, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING",[r,e.now,a,s,e.now]),(await this.getByEmail(r))?.id===a?a:null}async ensureUsername(e,r,s){await this.run("UPDATE users SET username = COALESCE(username, ?), updated_at = COALESCE(updated_at, ?) WHERE id = ? OR email = ?",[i(r),s,e,e])}async setUsername(e,r,s){await this.run("UPDATE users SET username = ?, updated_at = ? WHERE id = ? OR email = ?",[i(r),s,e,e])}async getByEmail(e){return this.first("SELECT * FROM users WHERE email = ? LIMIT 1",[e.toLowerCase()])}async getById(e){return this.first("SELECT * FROM users WHERE id = ? LIMIT 1",[e])}async getByCurrentEmail(e){return this.first("SELECT * FROM users WHERE current_email = ? LIMIT 1",[e.toLowerCase()])}async setCurrentEmail(e,r,s){await this.run("UPDATE users SET current_email = ?, updated_at = ? WHERE id = ?",[r.toLowerCase(),s,e])}async getByUsernameCi(e){return this.first("SELECT * FROM users WHERE username = ? LIMIT 1",[e.toLowerCase()])}}export{L as UserDAO,i as normalizeUsername};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/UserDAO.ts"],
4
- "sourcesContent": ["import { BaseDAO } from '@rexezuge/d1';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport { newAccountId } from './ResolvedAccount.ts';\nimport type { UserRow } from './ResolvedAccount.ts';\n\n/**\n * The stored form of a handle: lowercase.\n *\n * Every username read and every username write goes through this, so the two\n * can never disagree about case. That agreement is not cosmetic: `username` has\n * no `COLLATE NOCASE` (SQLite defaults to BINARY), so a stored `Alice2` is a\n * *different value* from `alice2` and a lookup that lowercased its parameter\n * would never find it. Normalising at the write points rather than relying on\n * each caller means a future caller cannot reintroduce an unfindable handle by\n * forgetting.\n */\nfunction normalizeUsername(username: string): string {\n return username.trim().toLowerCase();\n}\n\n/**\n * `users` rows. Converged from `backend-data/src/dao/UserDAO.ts` (identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Otter, Mail-Meow; AWS keeps\n * the id/email core without the username methods).\n *\n * Case rule everywhere in this DAO: lowercase the *parameter*, never the\n * column — `lower(col)` makes the index or primary key unusable. It is only\n * sound because every writer stores lowercase through this DAO's own\n * normalisers.\n */\nexport class UserDAO extends BaseDAO {\n public constructor(database: D1Queryable) {\n super(database);\n }\n\n /**\n * Create an account, stamped with the identity columns.\n *\n * `INSERT ... ON CONFLICT DO NOTHING` with **no conflict target**, deliberately.\n * `users` carries two unique constraints — the anchor primary key and the\n * unique index on `current_email` — and SQLite applies `DO NOTHING` only to\n * the constraints a named target covers. Naming the anchor therefore left a\n * `current_email` collision as a raised error, which callers cannot tell from\n * a transient D1 failure: it propagated instead of returning `null`, so the\n * opaque-anchor retry never ran and every login request answered 500.\n *\n * Returns the new account's id, or `null` when the insert was a silent no-op —\n * which this DAO establishes by reading the anchor row back and requiring its\n * own generated id to be the one there. The read-back lives here rather than\n * in the caller because a caller that trusted the generated id on a taken\n * anchor would point the address registry at a *phantom* account: the address\n * then resolves to nothing, and the opaque-anchor retry fails the same way.\n * Making the no-op detectable here is what keeps registration from stranding\n * an address forever.\n *\n * The row is stamped `updated_at = now` as well as `created_at`. The canonical\n * schema types `updated_at` nullable, so this is additive there — but a\n * consumer whose `updated_at` is `NOT NULL` cannot relax that through `ALTER`,\n * and D1 forbids the table rebuild that could, so omitting the column left\n * `createUser` — and with it the whole identity package — unusable on such a\n * schema. A created account is a touched account: there is no window in which\n * the row exists with no update timestamp.\n */\n public async createUser(input: { anchor: string; loginEmail: string; now: number }): Promise<string | null> {\n const anchor = input.anchor.toLowerCase();\n const loginEmail = input.loginEmail.toLowerCase();\n const id = newAccountId();\n await this.run('INSERT INTO users (email, created_at, id, current_email, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING', [\n anchor,\n input.now,\n id,\n loginEmail,\n input.now,\n ]);\n const row = await this.getByEmail(anchor);\n return row?.id === id ? id : null;\n }\n\n /**\n * @param idOrEmail The stable account key, or an anchor address as the\n * pre-identity fallback. `WHERE id = ? OR email = ?` cannot use either index\n * as a seek, so this stays off the hot path; login resolves through\n * `UserIdentityService` instead.\n */\n public async ensureUsername(idOrEmail: string, username: string, now: number): Promise<void> {\n await this.run('UPDATE users SET username = COALESCE(username, ?), updated_at = COALESCE(updated_at, ?) WHERE id = ? OR email = ?', [\n normalizeUsername(username),\n now,\n idOrEmail,\n idOrEmail,\n ]);\n }\n\n /**\n @param idOrEmail The stable account key, or an anchor address.\n */\n public async setUsername(idOrEmail: string, username: string, now: number): Promise<void> {\n await this.run('UPDATE users SET username = ?, updated_at = ? WHERE id = ? OR email = ?', [\n normalizeUsername(username),\n now,\n idOrEmail,\n idOrEmail,\n ]);\n }\n\n /**\n * Anchor lookup — used for legacy `*_email` values and cascade resolution.\n *\n * This is *not* a login lookup: an account that has changed its address is not\n * findable here by its new one. It is the pre-identity floor and the\n * attribution read.\n */\n public async getByEmail(email: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE email = ? LIMIT 1', [email.toLowerCase()]);\n }\n\n /**\n The account behind a stable key. Null on a pre-identity database.\n */\n public async getById(id: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE id = ? LIMIT 1', [id]);\n }\n\n /**\n The account currently signing in with this address. Identity-era only.\n */\n public async getByCurrentEmail(email: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE current_email = ? LIMIT 1', [email.toLowerCase()]);\n }\n\n /**\n * Move an account's sign-in address.\n *\n * The anchor `email` is deliberately untouched: it is what every legacy\n * `*_email` column and foreign key resolves against. Ordering matters — the\n * caller claims the new address first and revokes the old one third, so a\n * failure between steps never leaves the account without a way to sign in.\n */\n public async setCurrentEmail(id: string, email: string, now: number): Promise<void> {\n await this.run('UPDATE users SET current_email = ?, updated_at = ? WHERE id = ?', [email.toLowerCase(), now, id]);\n }\n\n /**\n Lookup by handle.\n */\n public async getByUsernameCi(usernameCi: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE username = ? LIMIT 1', [usernameCi.toLowerCase()]);\n }\n}\n\nexport { normalizeUsername };\n\nexport { type UserRow } from './ResolvedAccount.ts';\n"],
5
- "mappings": "+EAAA,OAAS,WAAAA,MAAe,eAExB,OAAS,gBAAAC,MAAoB,uBAc7B,SAASC,EAAkBC,EAAgB,CACzC,OAAOA,EAAS,KAAI,EAAG,YAAW,CACpC,CAFSC,EAAAF,EAAA,qBAcH,MAAOG,UAAgBL,CAAO,CA9BpC,MA8BoC,CAAAI,EAAA,gBAClC,YAAmBE,EAAqB,CACtC,MAAMA,CAAQ,CAChB,CA8BO,MAAM,WAAWC,EAA0D,CAChF,MAAMC,EAASD,EAAM,OAAO,YAAW,EACjCE,EAAaF,EAAM,WAAW,YAAW,EACzCG,EAAKT,EAAY,EACvB,aAAM,KAAK,IAAI,qHAAsH,CACnIO,EACAD,EAAM,IACNG,EACAD,EACAF,EAAM,IACP,GACW,MAAM,KAAK,WAAWC,CAAM,IAC5B,KAAOE,EAAKA,EAAK,IAC/B,CAQO,MAAM,eAAeC,EAAmBR,EAAkBS,EAAW,CAC1E,MAAM,KAAK,IAAI,oHAAqH,CAClIV,EAAkBC,CAAQ,EAC1BS,EACAD,EACAA,EACD,CACH,CAKO,MAAM,YAAYA,EAAmBR,EAAkBS,EAAW,CACvE,MAAM,KAAK,IAAI,0EAA2E,CACxFV,EAAkBC,CAAQ,EAC1BS,EACAD,EACAA,EACD,CACH,CASO,MAAM,WAAWE,EAAa,CACnC,OAAO,KAAK,MAAe,8CAA+C,CAACA,EAAM,YAAW,CAAE,CAAC,CACjG,CAKO,MAAM,QAAQH,EAAU,CAC7B,OAAO,KAAK,MAAe,2CAA4C,CAACA,CAAE,CAAC,CAC7E,CAKO,MAAM,kBAAkBG,EAAa,CAC1C,OAAO,KAAK,MAAe,sDAAuD,CAACA,EAAM,YAAW,CAAE,CAAC,CACzG,CAUO,MAAM,gBAAgBH,EAAYG,EAAeD,EAAW,CACjE,MAAM,KAAK,IAAI,kEAAmE,CAACC,EAAM,YAAW,EAAID,EAAKF,CAAE,CAAC,CAClH,CAKO,MAAM,gBAAgBI,EAAkB,CAC7C,OAAO,KAAK,MAAe,iDAAkD,CAACA,EAAW,YAAW,CAAE,CAAC,CACzG",
6
- "names": ["BaseDAO", "newAccountId", "normalizeUsername", "username", "__name", "UserDAO", "database", "input", "anchor", "loginEmail", "id", "idOrEmail", "now", "email", "usernameCi"]
4
+ "sourcesContent": ["import { BaseDAO } from '@rexezuge/d1';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { newAccountId } from './ResolvedAccount.ts';\nimport type { UserRow } from './ResolvedAccount.ts';\n\n/**\n * The stored form of a handle: lowercase.\n *\n * Every username read and every username write goes through this, so the two\n * can never disagree about case. That agreement is not cosmetic: `username` has\n * no `COLLATE NOCASE` (SQLite defaults to BINARY), so a stored `Alice2` is a\n * *different value* from `alice2` and a lookup that lowercased its parameter\n * would never find it. Normalising at the write points rather than relying on\n * each caller means a future caller cannot reintroduce an unfindable handle by\n * forgetting.\n */\nfunction normalizeUsername(username: string): string {\n return username.trim().toLowerCase();\n}\n\n/**\n * `users` rows. Converged from `backend-data/src/dao/UserDAO.ts` (identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Otter, Mail-Meow; AWS keeps\n * the id/email core without the username methods).\n *\n * Case rule everywhere in this DAO: lowercase the *parameter*, never the\n * column — `lower(col)` makes the index or primary key unusable. It is only\n * sound because every writer stores lowercase through this DAO's own\n * normalisers.\n */\nexport class UserDAO extends BaseDAO {\n /**\n * @param database The binding.\n * @param meter The invocation's subrequest counter. Optional since 1.10 and\n * defaulted to unmetered, exactly like `UserEmailDAO`'s: a consumer that\n * meters its own DAOs must be able to meter this one, or its statements are\n * subrequests the ceiling never saw.\n */\n public constructor(database: D1Queryable, meter?: SubrequestMeter) {\n super(database, meter);\n }\n\n /**\n * Create an account, stamped with the identity columns.\n *\n * `INSERT ... ON CONFLICT DO NOTHING` with **no conflict target**, deliberately.\n * `users` carries two unique constraints — the anchor primary key and the\n * unique index on `current_email` — and SQLite applies `DO NOTHING` only to\n * the constraints a named target covers. Naming the anchor therefore left a\n * `current_email` collision as a raised error, which callers cannot tell from\n * a transient D1 failure: it propagated instead of returning `null`, so the\n * opaque-anchor retry never ran and every login request answered 500.\n *\n * Returns the new account's id, or `null` when the insert was a silent no-op —\n * which this DAO establishes by reading the anchor row back and requiring its\n * own generated id to be the one there. The read-back lives here rather than\n * in the caller because a caller that trusted the generated id on a taken\n * anchor would point the address registry at a *phantom* account: the address\n * then resolves to nothing, and the opaque-anchor retry fails the same way.\n * Making the no-op detectable here is what keeps registration from stranding\n * an address forever.\n *\n * The row is stamped `updated_at = now` as well as `created_at`. The canonical\n * schema types `updated_at` nullable, so this is additive there — but a\n * consumer whose `updated_at` is `NOT NULL` cannot relax that through `ALTER`,\n * and D1 forbids the table rebuild that could, so omitting the column left\n * `createUser` — and with it the whole identity package — unusable on such a\n * schema. A created account is a touched account: there is no window in which\n * the row exists with no update timestamp.\n */\n public async createUser(input: { anchor: string; loginEmail: string; now: number }): Promise<string | null> {\n const anchor = input.anchor.toLowerCase();\n const loginEmail = input.loginEmail.toLowerCase();\n const id = newAccountId();\n await this.run('INSERT INTO users (email, created_at, id, current_email, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING', [\n anchor,\n input.now,\n id,\n loginEmail,\n input.now,\n ]);\n const row = await this.getByEmail(anchor);\n return row?.id === id ? id : null;\n }\n\n /**\n * @param idOrEmail The stable account key, or an anchor address as the\n * pre-identity fallback. `WHERE id = ? OR email = ?` cannot use either index\n * as a seek, so this stays off the hot path; login resolves through\n * `UserIdentityService` instead.\n */\n public async ensureUsername(idOrEmail: string, username: string, now: number): Promise<void> {\n await this.run('UPDATE users SET username = COALESCE(username, ?), updated_at = COALESCE(updated_at, ?) WHERE id = ? OR email = ?', [\n normalizeUsername(username),\n now,\n idOrEmail,\n idOrEmail,\n ]);\n }\n\n /**\n @param idOrEmail The stable account key, or an anchor address.\n */\n public async setUsername(idOrEmail: string, username: string, now: number): Promise<void> {\n await this.run('UPDATE users SET username = ?, updated_at = ? WHERE id = ? OR email = ?', [\n normalizeUsername(username),\n now,\n idOrEmail,\n idOrEmail,\n ]);\n }\n\n /**\n * Anchor lookup — used for legacy `*_email` values and cascade resolution.\n *\n * This is *not* a login lookup: an account that has changed its address is not\n * findable here by its new one. It is the pre-identity floor and the\n * attribution read.\n */\n public async getByEmail(email: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE email = ? LIMIT 1', [email.toLowerCase()]);\n }\n\n /**\n The account behind a stable key. Null on a pre-identity database.\n */\n public async getById(id: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE id = ? LIMIT 1', [id]);\n }\n\n /**\n The account currently signing in with this address. Identity-era only.\n */\n public async getByCurrentEmail(email: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE current_email = ? LIMIT 1', [email.toLowerCase()]);\n }\n\n /**\n * Move an account's sign-in address.\n *\n * The anchor `email` is deliberately untouched: it is what every legacy\n * `*_email` column and foreign key resolves against. Ordering matters — the\n * caller claims the new address first and revokes the old one third, so a\n * failure between steps never leaves the account without a way to sign in.\n */\n public async setCurrentEmail(id: string, email: string, now: number): Promise<void> {\n await this.run('UPDATE users SET current_email = ?, updated_at = ? WHERE id = ?', [email.toLowerCase(), now, id]);\n }\n\n /**\n Lookup by handle.\n */\n public async getByUsernameCi(usernameCi: string): Promise<UserRow | null> {\n return this.first<UserRow>('SELECT * FROM users WHERE username = ? LIMIT 1', [usernameCi.toLowerCase()]);\n }\n}\n\nexport { normalizeUsername };\n\nex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CAClH,CAKO,MAAM,gBAAgBI,EAAkB,CAC7C,OAAO,KAAK,MAAe,iDAAkD,CAACA,EAAW,YAAW,CAAE,CAAC,CACzG",
6
+ "names": ["BaseDAO", "newAccountId", "normalizeUsername", "username", "__name", "UserDAO", "database", "meter", "input", "anchor", "loginEmail", "id", "idOrEmail", "now", "email", "usernameCi"]
7
7
  }
@@ -1,4 +1,5 @@
1
1
  import type { D1Queryable } from '@rexezuge/d1';
2
+ import type { SubrequestMeter } from '@rexezuge/shared';
2
3
  import type { AccountLookupDeps } from './accountLookup.ts';
3
4
  import type { ResolvedAccount } from './ResolvedAccount.ts';
4
5
  interface UserIdentityEnv {
@@ -7,9 +8,13 @@ interface UserIdentityEnv {
7
8
  export type { UserIdentityEnv };
8
9
  /**
9
10
  * Injected DAO factories. All optional: each defaults to a real DAO over the
10
- * same D1 binding, so tests override only what they need.
11
+ * same D1 binding, so tests override only what they need. `meter` (since 1.10)
12
+ * is handed to those default DAOs, so identity statements are charged to the
13
+ * invocation's subrequest budget like every other DAO's.
11
14
  */
12
- export type UserIdentityDeps = Partial<AccountLookupDeps>;
15
+ export type UserIdentityDeps = Partial<AccountLookupDeps> & {
16
+ meter?: SubrequestMeter;
17
+ };
13
18
  /**
14
19
  * The account behind an address, plus the address-change operations.
15
20
  *
@@ -1 +1 @@
1
- {"version":3,"file":"UserIdentityService.d.ts","sourceRoot":"","sources":["../src/UserIdentityService.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAIhD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAE5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAI5D,UAAU,eAAe;IACvB,EAAE,EAAE,WAAW,CAAC;CACjB;AAED,YAAY,EAAE,eAAe,EAAE,CAAC;AAEhC;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,C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e,CAAC;IAsB3B;;;OAGG;IACU,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,SAAmD,GAAG,OAAO,CAAC,IAAI,CAAC;CAOrI"}
@@ -1 +1 @@
1
- var A=Object.defineProperty;var m=(d,i)=>A(d,"name",{value:i,configurable:!0});import{BadRequestError as n}from"@rexezuge/errors";import{isValidEmailFormat as l}from"@rexezuge/shared";import{TimestampUtil as c}from"@rexezuge/shared";import{registerAccount as h,resolveAccount as y}from"./accountLookup.js";import{newAnchor as f,summarize as p}from"./ResolvedAccount.js";import{UserDAO as E}from"./UserDAO.js";import{UserEmailDAO as D}from"./UserEmailDAO.js";class V{static{m(this,"UserIdentityService")}deps;byEmail=new Map;constructor(i,r={}){this.deps={userDAO:m(()=>Promise.resolve(new E(i.DB)),"userDAO"),userEmailDAO:m(()=>Promise.resolve(new D(i.DB)),"userEmailDAO"),...r}}async resolveAccount(i){const r=i.trim().toLowerCase();if(!l(r))return null;if(this.byEmail.has(r))return this.byEmail.get(r)??null;const t=await y(this.deps,r);return this.byEmail.set(r,t),t}async resolveAccountId(i){return(await this.resolveAccount(i))?.id??null}async resolveAccountById(i){const t=await(await this.deps.userDAO()).getById(i);return p(t)}async resolveOrRegister(i,r=c.getCurrentUnixTimestampInSeconds()){const t=await this.resolveAccount(i);if(t)return t;const e=i.trim().toLowerCase(),a=await h(this.deps,e,e,r)??await h(this.deps,e,f(),r);return this.byEmail.set(e,a),a}async listAddresses(i){return(await(await this.deps.userEmailDAO()).listByUserId(i)).map(e=>({email:e.email,isVerified:e.is_verified===1}))}async setPrimaryEmail(i,r,t=c.getCurrentUnixTimestampInSeconds()){const e=r.trim().toLowerCase();if(!l(e))throw new n("Invalid email address");const a=await this.deps.userDAO(),o=await this.deps.userEmailDAO(),s=await a.getById(i);if(!s?.id)throw new n("User not found");const u=(s.current_email??s.email).toLowerCase();if(u===e)return{id:s.id,email:e,anchorEmail:s.email,username:s.username??null};const w=await o.resolveVerified(e);if(w&&w.user_id!==s.id)throw new n("Email is already in use");return await o.register({email:e,userId:s.id,isVerified:!0,now:t}),await a.setCurrentEmail(s.id,e,t),await o.revokeAllVerified(s.id,e),this.byEmail.delete(u),this.byEmail.set(e,{id:s.id,email:e,anchorEmail:s.email,username:s.username??null}),{id:s.id,email:e,anchorEmail:s.email,username:s.username??null}}async linkVerifiedEmail(i,r,t=c.getCurrentUnixTimestampInSeconds()){const e=r.trim().toLowerCase();if(!l(e))throw new n("Invalid email address");if(await(await this.deps.userEmailDAO()).register({email:e,userId:i,isVerified:!0,now:t})==="already-claimed")throw new n("Email is already in use")}}export{V as UserIdentityService};
1
+ var A=Object.defineProperty;var m=(d,i)=>A(d,"name",{value:i,configurable:!0});import{BadRequestError as n}from"@rexezuge/errors";import{isValidEmailFormat as l}from"@rexezuge/shared";import{TimestampUtil as c}from"@rexezuge/shared";import{registerAccount as h,resolveAccount as f}from"./accountLookup.js";import{newAnchor as y,summarize as p}from"./ResolvedAccount.js";import{UserDAO as E}from"./UserDAO.js";import{UserEmailDAO as D}from"./UserEmailDAO.js";class V{static{m(this,"UserIdentityService")}deps;byEmail=new Map;constructor(i,r={}){const{meter:s,...e}=r;this.deps={userDAO:m(()=>Promise.resolve(new E(i.DB,s)),"userDAO"),userEmailDAO:m(()=>Promise.resolve(new D(i.DB,s)),"userEmailDAO"),...e}}async resolveAccount(i){const r=i.trim().toLowerCase();if(!l(r))return null;if(this.byEmail.has(r))return this.byEmail.get(r)??null;const s=await f(this.deps,r);return this.byEmail.set(r,s),s}async resolveAccountId(i){return(await this.resolveAccount(i))?.id??null}async resolveAccountById(i){const s=await(await this.deps.userDAO()).getById(i);return p(s)}async resolveOrRegister(i,r=c.getCurrentUnixTimestampInSeconds()){const s=await this.resolveAccount(i);if(s)return s;const e=i.trim().toLowerCase(),a=await h(this.deps,e,e,r)??await h(this.deps,e,y(),r);return this.byEmail.set(e,a),a}async listAddresses(i){return(await(await this.deps.userEmailDAO()).listByUserId(i)).map(e=>({email:e.email,isVerified:e.is_verified===1}))}async setPrimaryEmail(i,r,s=c.getCurrentUnixTimestampInSeconds()){const e=r.trim().toLowerCase();if(!l(e))throw new n("Invalid email address");const a=await this.deps.userDAO(),o=await this.deps.userEmailDAO(),t=await a.getById(i);if(!t?.id)throw new n("User not found");const u=(t.current_email??t.email).toLowerCase();if(u===e)return{id:t.id,email:e,anchorEmail:t.email,username:t.username??null};const w=await o.resolveVerified(e);if(w&&w.user_id!==t.id)throw new n("Email is already in use");return await o.register({email:e,userId:t.id,isVerified:!0,now:s}),await a.setCurrentEmail(t.id,e,s),await o.revokeAllVerified(t.id,e),this.byEmail.delete(u),this.byEmail.set(e,{id:t.id,email:e,anchorEmail:t.email,username:t.username??null}),{id:t.id,email:e,anchorEmail:t.email,username:t.username??null}}async linkVerifiedEmail(i,r,s=c.getCurrentUnixTimestampInSeconds()){const e=r.trim().toLowerCase();if(!l(e))throw new n("Invalid email address");if(await(await this.deps.userEmailDAO()).register({email:e,userId:i,isVerified:!0,now:s})==="already-claimed")throw new n("Email is already in use")}}export{V as UserIdentityService};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/UserIdentityService.ts"],
4
- "sourcesContent": ["import { BadRequestError } from '@rexezuge/errors';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport { isValidEmailFormat } from '@rexezuge/shared';\nimport { TimestampUtil } from '@rexezuge/shared';\nimport { registerAccount, resolveAccount } from './accountLookup.ts';\nimport type { AccountLookupDeps } from './accountLookup.ts';\nimport { newAnchor, summarize } from './ResolvedAccount.ts';\nimport type { ResolvedAccount } from './ResolvedAccount.ts';\nimport { UserDAO } from './UserDAO.ts';\nimport { UserEmailDAO } from './UserEmailDAO.ts';\n\ninterface UserIdentityEnv {\n DB: D1Queryable;\n}\n\nexport type { UserIdentityEnv };\n\n/**\n * Injected DAO factories. All optional: each defaults to a real DAO over the\n * same D1 binding, so tests override only what they need.\n */\nexport type UserIdentityDeps = Partial<AccountLookupDeps>;\n\n/**\n * The account behind an address, plus the address-change operations.\n *\n * Converged from `backend-services/src/identity/UserIdentityService.ts`\n * (identical in Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Otter; AWS and\n * Mail-Meow keep the resolve core). Canonical names merge the two spellings the\n * repos used — `resolveUserById` (Durable-DAV family) and\n * `resolveAccountById` (AWS) are one method, `resolveAccountById`.\n *\n * The instance is one per request scope: the ownership and permission paths\n * resolve the same caller several times each, and a per-instance address memo\n * costs one query per request rather than one per comparison. Bind it once in\n * the composition root and share it — constructing per consumer is the bug the\n * memo exists to prevent.\n *\n * Resolution itself lives in `accountLookup` (free functions, shared with any\n * account bootstrap); this class adds memoization and the change operations.\n */\nexport class UserIdentityService {\n private readonly deps: Required<AccountLookupDeps>;\n\n private readonly byEmail = new Map<string, ResolvedAccount | null>();\n\n public constructor(env: UserIdentityEnv, deps: UserIdentityDeps = {}) {\n this.deps = {\n userDAO: () => Promise.resolve(new UserDAO(env.DB)),\n userEmailDAO: () => Promise.resolve(new UserEmailDAO(env.DB)),\n ...deps,\n };\n }\n\n /**\n * Resolve a sign-in address to its account, or null when unknown.\n *\n * Only a verified address resolves. A revoked address (changed away from) is\n * retained so pre-change rows stay attributable, but it must never\n * authenticate, otherwise a reassigned address would inherit the previous\n * holder's account.\n */\n public async resolveAccount(email: string): Promise<ResolvedAccount | null> {\n const key = email.trim().toLowerCase();\n if (!isValidEmailFormat(key)) return null;\n if (this.byEmail.has(key)) return this.byEmail.get(key) ?? null;\n const resolved = await resolveAccount(this.deps, key);\n this.byEmail.set(key, resolved);\n return resolved;\n }\n\n /**\n Account id for a sign-in address, or null when unknown.\n */\n public async resolveAccountId(email: string): Promise<string | null> {\n const account = await this.resolveAccount(email);\n return account?.id ?? null;\n }\n\n /**\n * Account behind a stable key. The inverse direction, for a caller that\n * already holds one (a resource owner) and needs the current address.\n */\n public async resolveAccountById(userId: string): Promise<ResolvedAccount | null> {\n const userDAO = await this.deps.userDAO();\n const row = await userDAO.getById(userId);\n return summarize(row);\n }\n\n /**\n * Resolve-or-create, for a login path that may see a first-time user.\n *\n * Returns null when the address exists but cannot be resolved (a revoked\n * address) — a caller that needs \"guaranteed account\" must distinguish that\n * from \"created now\" through its own route, because silently registering on a\n * revoked address would hand the previous holder's history to the new one.\n */\n public async resolveOrRegister(email: string, now = TimestampUtil.getCurrentUnixTimestampInSeconds()): Promise<ResolvedAccount | null> {\n const existing = await this.resolveAccount(email);\n if (existing) return existing;\n const key = email.trim().toLowerCase();\n // The anchor is the address itself whenever it is free. When it is already\n // held as another account's anchor — its previous holder moved off it — the\n // opaque-anchor retry is what lets a released address be used again.\n const account = (await registerAccount(this.deps, key, key, now)) ?? (await registerAccount(this.deps, key, newAnchor(), now));\n this.byEmail.set(key, account);\n return account;\n }\n\n /**\n * Every address known for an account, verified ones first.\n */\n public async listAddresses(userId: string): Promise<Array<{ email: string; isVerified: boolean }>> {\n const emailDAO = await this.deps.userEmailDAO();\n const rows = await emailDAO.listByUserId(userId);\n return rows.map((row) => ({ email: row.email, isVerified: row.is_verified === 1 }));\n }\n\n /**\n * Point an account at a new sign-in address.\n *\n * The account id, the frozen anchor, and every id-keyed row are untouched:\n * only which address authenticates the account moves. The previous address is\n * revoked rather than deleted, so rows written before the change still resolve\n * to this account, and it is released for a later legitimate holder.\n *\n * Rejects an address already verified for another account. That check is the\n * whole reason this is not simply an `UPDATE`: an unverified change would let\n * anyone claim an address and inherit its history.\n *\n * Order is load-bearing, and it is the one the ops CLI (`change-email.ts`)\n * already gets right: claim first, move `current_email` second, revoke third.\n * Inverting it opens a window in which nothing authenticates if a later step\n * fails.\n */\n public async setPrimaryEmail(\n userId: string,\n newEmail: string,\n now = TimestampUtil.getCurrentUnixTimestampInSeconds(),\n ): Promise<ResolvedAccount> {\n const email = newEmail.trim().toLowerCase();\n if (!isValidEmailFormat(email)) throw new BadRequestError('Invalid email address');\n const userDAO = await this.deps.userDAO();\n const emailDAO = await this.deps.userEmailDAO();\n const row = await userDAO.getById(userId);\n if (!row?.id) throw new BadRequestError('User not found');\n const current = (row.current_email ?? row.email).toLowerCase();\n if (current === email) {\n return { id: row.id, email, anchorEmail: row.email, username: row.username ?? null };\n }\n const holder = await emailDAO.resolveVerified(email);\n if (holder && holder.user_id !== row.id) throw new BadRequestError('Email is already in use');\n await emailDAO.register({ email, userId: row.id, isVerified: true, now });\n await userDAO.setCurrentEmail(row.id, email, now);\n // Revoke every other verified address, so only the new one authenticates.\n await emailDAO.revokeAllVerified(row.id, email);\n this.byEmail.delete(current);\n this.byEmail.set(email, { id: row.id, email, anchorEmail: row.email, username: row.username ?? null });\n return { id: row.id, email, anchorEmail: row.email, username: row.username ?? null };\n }\n\n /**\n * Ops/migration path: attach an address that has already been proven, without\n * making it the sign-in address.\n */\n public async linkVerifiedEmail(userId: string, email: string, now = TimestampUtil.getCurrentUnixTimestampInSeconds()): Promise<void> {\n const address = email.trim().toLowerCase();\n if (!isValidEmailFormat(address)) throw new BadRequestError('Invalid email address');\n const emailDAO = await this.deps.userEmailDAO();\n const outcome = await emailDAO.register({ email: address, userId, isVerified: true, now });\n if (outcome === 'already-claimed') throw new BadRequestError('Email is already in use');\n }\n}\n"],
5
- "mappings": "+EAAA,OAAS,mBAAAA,MAAuB,mBAEhC,OAAS,sBAAAC,MAA0B,mBACnC,OAAS,iBAAAC,MAAqB,mBAC9B,OAAS,mBAAAC,EAAiB,kBAAAC,MAAsB,qBAEhD,OAAS,aAAAC,EAAW,aAAAC,MAAiB,uBAErC,OAAS,WAAAC,MAAe,eACxB,OAAS,gBAAAC,MAAoB,oBAgCvB,MAAOC,CAAmB,CAzChC,MAyCgC,CAAAC,EAAA,4BACb,KAEA,QAAU,IAAI,IAE/B,YAAmBC,EAAsBC,EAAyB,CAAA,EAAE,CAClE,KAAK,KAAO,CACV,QAASF,EAAA,IAAM,QAAQ,QAAQ,IAAIH,EAAQI,EAAI,EAAE,CAAC,EAAzC,WACT,aAAcD,EAAA,IAAM,QAAQ,QAA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B,EAAS,OAAAV,EAAQ,WAAY,GAAM,IAAAE,CAAG,CAAE,IACzE,kBAAmB,MAAM,IAAIlB,EAAgB,yBAAyB,CACxF",
6
- "names": ["BadRequestError", "isValidEmailFormat", "TimestampUtil", "registerAccount", "resolveAccount", "newAnchor", "summarize", "UserDAO", "UserEmailDAO", "UserIdentityService", "__name", "env", "deps", "email", "key", "resolved", "userId", "row", "now", "existing", "account", "newEmail", "userDAO", "emailDAO", "current", "holder", "address"]
4
+ "sourcesContent": ["import { BadRequestError } from '@rexezuge/errors';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport { isValidEmailFormat } from '@rexezuge/shared';\nimport type { SubrequestMeter } from '@rexezuge/shared';\nimport { TimestampUtil } from '@rexezuge/shared';\nimport { registerAccount, resolveAccount } from './accountLookup.ts';\nimport type { AccountLookupDeps } from './accountLookup.ts';\nimport { newAnchor, summarize } from './ResolvedAccount.ts';\nimport type { ResolvedAccount } from './ResolvedAccount.ts';\nimport { UserDAO } from './UserDAO.ts';\nimport { UserEmailDAO } from './UserEmailDAO.ts';\n\ninterface UserIdentityEnv {\n DB: D1Queryable;\n}\n\nexport type { UserIdentityEnv };\n\n/**\n * Injected DAO factories. All optional: each defaults to a real DAO over the\n * same D1 binding, so tests override only what they need. `meter` (since 1.10)\n * is handed to those default DAOs, so identity statements are charged to the\n * invocation's subrequest budget like every other DAO's.\n */\nexport type UserIdentityDeps = Partial<AccountLookupDeps> & { meter?: SubrequestMeter };\n\n/**\n * The account behind an address, plus the address-change operations.\n *\n * Converged from `backend-services/src/identity/UserIdentityService.ts`\n * (identical in Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Otter; AWS and\n * Mail-Meow keep the resolve core). Canonical names merge the two spellings the\n * repos used — `resolveUserById` (Durable-DAV family) and\n * `resolveAccountById` (AWS) are one method, `resolveAccountById`.\n *\n * The instance is one per request scope: the ownership and permission paths\n * resolve the same caller several times each, and a per-instance address memo\n * costs one query per request rather than one per comparison. Bind it once in\n * the composition root and share it — constructing per consumer is the bug the\n * memo exists to prevent.\n *\n * Resolution itself lives in `accountLookup` (free functions, shared with any\n * account bootstrap); this class adds memoization and the change operations.\n */\nexport class UserIdentityService {\n private readonly deps: Required<AccountLookupDeps>;\n\n private readonly byEmail = new Map<string, ResolvedAccount | null>();\n\n public constructor(env: UserIdentityEnv, deps: UserIdentityDeps = {}) {\n const { meter, ...factories } = deps;\n this.deps = {\n userDAO: () => Promise.resolve(new UserDAO(env.DB, meter)),\n userEmailDAO: () => Promise.resolve(new UserEmailDAO(env.DB, meter)),\n ...factories,\n };\n }\n\n /**\n * Resolve a sign-in address to its account, or null when unknown.\n *\n * Only a verified address resolves. A revoked address (changed away from) is\n * retained so pre-change rows stay attributable, but it must never\n * authenticate, otherwise a reassigned address would inherit the previous\n * holder's account.\n */\n public async resolveAccount(email: string): Promise<ResolvedAccount | null> {\n const key = email.trim().toLowerCase();\n if (!isValidEmailFormat(key)) return null;\n if (this.byEmail.has(key)) return this.byEmail.get(key) ?? null;\n const resolved = await resolveAccount(this.deps, key);\n this.byEmail.set(key, resolved);\n return resolved;\n }\n\n /**\n Account id for a sign-in address, or null when unknown.\n */\n public async resolveAccountId(email: string): Promise<string | null> {\n const account = await this.resolveAccount(email);\n return account?.id ?? null;\n }\n\n /**\n * Account behind a stable key. The inverse direction, for a caller that\n * already holds one (a resource owner) and needs the current address.\n */\n public async resolveAccountById(userId: string): Promise<ResolvedAccount | null> {\n const userDAO = await this.deps.userDAO();\n const row = await userDAO.getById(userId);\n return summarize(row);\n }\n\n /**\n * Resolve-or-create, for a login path that may see a first-time user.\n *\n * Returns null when the address exists but cannot be resolved (a revoked\n * address) — a caller that needs \"guaranteed account\" must distinguish that\n * from \"created now\" through its own route, because silently registering on a\n * revoked address would hand the previous holder's history to the new one.\n */\n public async resolveOrRegister(email: string, now = TimestampUtil.getCurrentUnixTimestampInSeconds()): Promise<ResolvedAccount | null> {\n const existing = await this.resolveAccount(email);\n if (existing) return existing;\n const key = email.trim().toLowerCase();\n // The anchor is the address itself whenever it is free. When it is already\n // held as another account's anchor — its previous holder moved off it — the\n // opaque-anchor retry is what lets a released address be used again.\n const account = (await registerAccount(this.deps, key, key, now)) ?? (await registerAccount(this.deps, key, newAnchor(), now));\n this.byEmail.set(key, account);\n return account;\n }\n\n /**\n * Every address known for an account, verified ones first.\n */\n public async listAddresses(userId: string): Promise<Array<{ email: string; isVerified: boolean }>> {\n const emailDAO = await this.deps.userEmailDAO();\n const rows = await emailDAO.listByUserId(userId);\n return rows.map((row) => ({ email: row.email, isVerified: row.is_verified === 1 }));\n }\n\n /**\n * Point an account at a new sign-in address.\n *\n * The account id, the frozen anchor, and every id-keyed row are untouched:\n * only which address authenticates the account moves. The previous address is\n * revoked rather than deleted, so rows written before the change still resolve\n * to this account, and it is released for a later legitimate holder.\n *\n * Rejects an address already verified for another account. That check is the\n * whole reason this is not simply an `UPDATE`: an unverified change would let\n * anyone claim an address and inherit its history.\n *\n * Order is load-bearing, and it is the one the ops CLI (`change-email.ts`)\n * already gets right: claim first, move `current_email` second, revoke third.\n * Inverting it opens a window in which nothing authenticates if a later step\n * fails.\n */\n public async setPrimaryEmail(\n userId: string,\n newEmail: string,\n now = TimestampUtil.getCurrentUnixTimestampInSeconds(),\n ): Promise<ResolvedAccount> {\n const email = newEmail.trim().toLowerCase();\n if (!isValidEmailFormat(email)) throw new BadRequestError('Invalid email address');\n const userDAO = await this.deps.userDAO();\n const emailDAO = await this.deps.userEmailDAO();\n const row = await userDAO.getById(userId);\n if (!row?.id) throw new BadRequestError('User not found');\n const current = (row.current_email ?? row.email).toLowerCase();\n if (current === email) {\n return { id: row.id, email, anchorEmail: row.email, username: row.username ?? null };\n }\n const holder = await emailDAO.resolveVerified(email);\n if (holder && holder.user_id !== row.id) throw new BadRequestError('Email is already in use');\n await emailDAO.register({ email, userId: row.id, isVerified: true, now });\n await userDAO.setCurrentEmail(row.id, email, now);\n // Revoke every other verified address, so only the new one authenticates.\n await emailDAO.revokeAllVerified(row.id, email);\n this.byEmail.delete(current);\n this.byEmail.set(email, { id: row.id, email, anchorEmail: row.email, username: row.username ?? null });\n return { id: row.id, email, anchorEmail: row.email, username: row.username ?? null };\n }\n\n /**\n * Ops/migration path: attach an address that has already been proven, without\n * making it the sign-in address.\n */\n public async linkVerifiedEmail(userId: string, email: string, now = TimestampUtil.getCurrentUnixTimestampInSeconds()): Promise<void> {\n const address = email.trim().toLowerCase();\n if (!isValidEmailFormat(address)) throw new BadRequestError('Invalid email address');\n const emailDAO = await this.deps.userEmailDAO();\n const outcome = await emailDAO.register({ email: address, userId, isVerified: true, now });\n if (outcome === 'already-claimed') throw new BadRequestError('Email is already in use');\n }\n}\n"],
5
+ "mappings": "+EAAA,OAAS,mBAAAA,MAAuB,mBAEhC,OAAS,sBAAAC,MAA0B,mBAEnC,OAAS,iBAAAC,MAAqB,mBAC9B,OAAS,mBAAAC,EAAiB,kBAAAC,MAAsB,qBAEhD,OAAS,aAAAC,EAAW,aAAAC,MAAiB,uBAErC,OAAS,WAAAC,MAAe,eACxB,OAAS,gBAAAC,MAAoB,oBAkCvB,MAAOC,CAAmB,CA5ChC,MA4CgC,CAAAC,EAAA,4BACb,KAEA,QAAU,IAAI,IAE/B,YAAmBC,EAAsBC,EAAyB,CAAA,EAAE,CAClE,KAAM,CAAE,MAAAC,EAAO,GAAGC,CAAS,EAAKF,EAChC,KAAK,KAAO,CACV,QAASF,EAAA,IAAM,QAAQ,QAAQ,IAAIH,EAAQI,EAAI,GAAIE,CAAK,CAAC,EAAhD,WACT,aAAcH,EAAA,IAAM,QAAQ,QAAQ,IAAIF,EAAaG,EAAI,GAAIE,CAAK,CAAC,EAArD,gBACd,GAAGC,EAEP,CAUO,MAAM,eAAeC,EAAa,CACvC,MAAMC,EAAMD,EAAM,KAAI,EAAG,YAAW,EACpC,GAAI,CAACd,EAAmBe,CAAG,EAAG,OAAO,KACrC,GAAI,KAAK,QAAQ,IAAIA,CAAG,EAAG,OAAO,KAAK,QAAQ,IAAIA,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WP,EAAI,eAAiBA,EAAI,OAAO,YAAW,EAC5D,GAAIO,IAAYX,EACd,MAAO,CAAE,GAAII,EAAI,GAAI,MAAAJ,EAAO,YAAaI,EAAI,MAAO,SAAUA,EAAI,UAAY,IAAI,EAEpF,MAAMQ,EAAS,MAAMF,EAAS,gBAAgBV,CAAK,EACnD,GAAIY,GAAUA,EAAO,UAAYR,EAAI,GAAI,MAAM,IAAInB,EAAgB,yBAAyB,EAC5F,aAAMyB,EAAS,SAAS,CAAE,MAAAV,EAAO,OAAQI,EAAI,GAAI,WAAY,GAAM,IAAAC,CAAG,CAAE,EACxE,MAAMI,EAAQ,gBAAgBL,EAAI,GAAIJ,EAAOK,CAAG,EAEhD,MAAMK,EAAS,kBAAkBN,EAAI,GAAIJ,CAAK,EAC9C,KAAK,QAAQ,OAAOW,CAAO,EAC3B,KAAK,QAAQ,IAAIX,EAAO,CAAE,GAAII,EAAI,GAAI,MAAAJ,EAAO,YAAaI,EAAI,MAAO,SAAUA,EAAI,UAAY,IAAI,CAAE,EAC9F,CAAE,GAAIA,EAAI,GAAI,MAAAJ,EAAO,YAAaI,EAAI,MAAO,SAAUA,EAAI,UAAY,IAAI,CACpF,CAMO,MAAM,kBAAkBD,EAAgBH,EAAeK,EAAMlB,EAAc,iCAAgC,EAAE,CAClH,MAAM0B,EAAUb,EAAM,KAAI,EAAG,YAAW,EACxC,GAAI,CAACd,EAAmB2B,CAAO,EAAG,MAAM,IAAI5B,EAAgB,uBAAuB,EAGnF,GADgB,MADC,MAAM,KAAK,KAAK,aAAY,GACd,SAAS,CAAE,MAAO4B,EAAS,OAAAV,EAAQ,WAAY,GAAM,IAAAE,CAAG,CAAE,IACzE,kBAAmB,MAAM,IAAIpB,EAAgB,yBAAyB,CACxF",
6
+ "names": ["BadRequestError", "isValidEmailFormat", "TimestampUtil", "registerAccount", "resolveAccount", "newAnchor", "summarize", "UserDAO", "UserEmailDAO", "UserIdentityService", "__name", "env", "deps", "meter", "factories", "email", "key", "resolved", "userId", "row", "now", "existing", "account", "newEmail", "userDAO", "emailDAO", "current", "holder", "address"]
7
7
  }
@@ -1,14 +1,20 @@
1
1
  import type { D1Queryable } from '@rexezuge/d1';
2
2
  /**
3
- * The identity migrations this package ships, by filename. `IDENTITY_MIGRATIONS`
4
- * in `migrations.ts` carries the same pair with the reasoning; this map is the
5
- * executable form.
3
+ * The executable form, keyed by the names `FRESH_MIGRATIONS` /
4
+ * `UPGRADE_MIGRATIONS` use. Private: `IDENTITY_MIGRATIONS` is the one public
5
+ * migrations export.
6
6
  */
7
- declare const IDENTITY_MIGRATION_SQL: {
7
+ declare const MIGRATION_SQL_BY_NAME: {
8
8
  readonly 'users.sql': "\n-- The account. The anchor (email) is immutable; current_email is the login.\nCREATE TABLE IF NOT EXISTS users (\n id TEXT NOT NULL PRIMARY KEY,\n email TEXT NOT NULL UNIQUE,\n current_email TEXT NOT NULL UNIQUE,\n username TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_id ON users(id);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_current_email ON users(current_email);\n\n-- The address registry: which account an address authenticates.\nCREATE TABLE IF NOT EXISTS user_emails (\n email TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n is_verified INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_user_emails_user ON user_emails(user_id);\n";
9
9
  readonly 'upgrade-user-identity.sql': "\n-- Phase 1: stable account key.\n-- SQLite cannot add a PRIMARY KEY column, so the id is a plain column with a\n-- unique index. A unique index is a valid foreign key parent, which is all the\n-- user_id references need.\nALTER TABLE users ADD COLUMN id TEXT;\n\nUPDATE users SET id = 'usr_' || lower(hex(randomblob(16))) WHERE id IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_id ON users(id);\n\n-- Phase 2: mutable sign-in address.\n-- 'email' stays as the frozen anchor; 'current_email' is what the account signs\n-- in with and what the API reports. Uniqueness is enforced here, so an address\n-- can never be claimed by two accounts.\nALTER TABLE users ADD COLUMN current_email TEXT;\n\nUPDATE users SET current_email = lower(email) WHERE current_email IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_current_email ON users(current_email);\n\n-- Phase 3: address registry.\n-- Login resolution consults is_verified = 1 only. Backfilled from the frozen\n-- anchor address of every existing account, lowercased so a legacy mixed-case\n-- row still yields exactly one login identity.\nCREATE TABLE IF NOT EXISTS user_emails (\n email TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n is_verified INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_user_emails_user ON user_emails(user_id);\n\nINSERT OR IGNORE INTO user_emails (email, user_id, is_verified, created_at)\nSELECT lower(email), id, 1, created_at FROM users;\n";
10
10
  };
11
- type IdentityMigrationName = keyof typeof IDENTITY_MIGRATION_SQL;
11
+ type IdentityMigrationName = keyof typeof MIGRATION_SQL_BY_NAME;
12
+ /**
13
+ * @deprecated Use `IDENTITY_MIGRATIONS` — the one canonical migrations export,
14
+ * an ordered `{ name, sql }` list. This map carries the same two SQL strings
15
+ * under different names. Removed in 2.0.
16
+ */
17
+ declare const IDENTITY_MIGRATION_SQL: Readonly<Record<IdentityMigrationName, string>>;
12
18
  /**
13
19
  The full fresh-install order.
14
20
  */
@@ -1 +1 @@
1
- {"version":3,"file":"applyMigrations.d.ts","sourceRoot":"","sources":["../src/applyMigrations.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD;;;;GAIG;AACH,QAAA,MAAM,sBAAsB;;;CAGlB,CAAC;AAEX,KAAK,qBAAqB,GAAG,MAAM,OAAO,sBAAsB,CAAC;AAEjE;;EAEE;AACF,QAAA,MAAM,gBAAgB,EAAE,SAAS,qBAAqB,EAAkB,CAAC;AAEzE;;EAEE;AACF,QAAA,MAAM,kBAAkB,EAAE,SAAS,qBAAqB,EAA+C,CAAC;AAExG;;;;;;;;;;;GAWG;AACH,iBAAe,uBAAuB,CAAC,EAAE,EAAE,WAAW,EAAE,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAa1G;AAED,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,CAAC;AACjG,YAAY,EAAE,qBAAqB,EAAE,CAAC"}
1
+ {"version":3,"file":"applyMigrations.d.ts","sourceRoot":"","sources":["../src/applyMigrations.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD;;;;GAIG;AACH,QAAA,MAAM,qBAAqB;;;CAGjB,CAAC;AAEX,KAAK,qBAAqB,GAAG,MAAM,OAAO,qBAAqB,CAAC;AAEhE;;;;GAIG;AACH,QAAA,MAAM,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAyB,CAAC;AAEtG;;EAEE;AACF,QAAA,MAAM,gBAAgB,EAAE,SAAS,qBAAqB,EAAkB,CAAC;AAEzE;;EAEE;AACF,QAAA,MAAM,kBAAkB,EAAE,SAAS,qBAAqB,EAA+C,CAAC;AAExG;;;;;;;;;;;GAWG;AACH,iBAAe,uBAAuB,CAAC,EAAE,EAAE,WAAW,EAAE,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAa1G;AAED,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,CAAC;AACjG,YAAY,EAAE,qBAAqB,EAAE,CAAC"}
@@ -1 +1 @@
1
- var p=Object.defineProperty;var r=(t,e)=>p(t,"name",{value:e,configurable:!0});import{executableStatements as I}from"@rexezuge/d1";import{UPGRADE_USER_IDENTITY as f,USERS_SCHEMA as l}from"./migrations.js";const a={"users.sql":l,"upgrade-user-identity.sql":f},o=["users.sql"],i=["users.sql","upgrade-user-identity.sql"];async function m(t,e={}){const c=e.upgrade===!0?i:o;for(const u of c){const s=I(a[u]);if(s.length!==0){if(t.batch){await t.batch(s.map(n=>t.prepare(n)));continue}for(const n of s)await t.prepare(n).run()}}}r(m,"applyIdentityMigrations");export{o as FRESH_MIGRATIONS,a as IDENTITY_MIGRATION_SQL,i as UPGRADE_MIGRATIONS,m as applyIdentityMigrations};
1
+ var p=Object.defineProperty;var r=(t,e)=>p(t,"name",{value:e,configurable:!0});import{executableStatements as I}from"@rexezuge/d1";import{UPGRADE_USER_IDENTITY as S,USERS_SCHEMA as _}from"./migrations.js";const o={"users.sql":_,"upgrade-user-identity.sql":S},f=o,a=["users.sql"],i=["users.sql","upgrade-user-identity.sql"];async function l(t,e={}){const c=e.upgrade===!0?i:a;for(const u of c){const s=I(o[u]);if(s.length!==0){if(t.batch){await t.batch(s.map(n=>t.prepare(n)));continue}for(const n of s)await t.prepare(n).run()}}}r(l,"applyIdentityMigrations");export{a as FRESH_MIGRATIONS,f as IDENTITY_MIGRATION_SQL,i as UPGRADE_MIGRATIONS,l as applyIdentityMigrations};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/applyMigrations.ts"],
4
- "sourcesContent": ["import { executableStatements } from '@rexezuge/d1';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport { UPGRADE_USER_IDENTITY, USERS_SCHEMA } from './migrations.ts';\n\n/**\n * The identity migrations this package ships, by filename. `IDENTITY_MIGRATIONS`\n * in `migrations.ts` carries the same pair with the reasoning; this map is the\n * executable form.\n */\nconst IDENTITY_MIGRATION_SQL = {\n 'users.sql': USERS_SCHEMA,\n 'upgrade-user-identity.sql': UPGRADE_USER_IDENTITY,\n} as const;\n\ntype IdentityMigrationName = keyof typeof IDENTITY_MIGRATION_SQL;\n\n/**\nThe full fresh-install order.\n*/\nconst FRESH_MIGRATIONS: readonly IdentityMigrationName[] = ['users.sql'];\n\n/**\nA legacy database applies the upgrade after the fresh schema is in place.\n*/\nconst UPGRADE_MIGRATIONS: readonly IdentityMigrationName[] = ['users.sql', 'upgrade-user-identity.sql'];\n\n/**\n * Apply the identity migrations to a D1 binding.\n *\n * Split and executed through `@rexezuge/d1` — the same statement splitter the\n * test helpers use — so a kit migration and an integration suite can never\n * disagree about where one statement ends. One `batch()` per file, matching\n * D1's own per-file apply, so a failure names its file.\n *\n * `upgrade: false` (the default) applies only the fresh-install schema. Pass\n * `upgrade: true` for a database whose `users` table predates the identity\n * columns; the upgrade file is rerunnable, so applying both is safe.\n */\nasync function applyIdentityMigrations(db: D1Queryable, options: { upgrade?: boolean } = {}): Promise<void> {\n const names = options.upgrade === true ? UPGRADE_MIGRATIONS : FRESH_MIGRATIONS;\n for (const name of names) {\n const statements = executableStatements(IDENTITY_MIGRATION_SQL[name]);\n if (statements.length === 0) continue;\n if (db.batch) {\n await db.batch(statements.map((sql) => db.prepare(sql)));\n continue;\n }\n for (const sql of statements) {\n await db.prepare(sql).run();\n }\n }\n}\n\nexport { applyIdentityMigrations, IDENTITY_MIGRATION_SQL, FRESH_MIGRATIONS, UPGRADE_MIGRATIONS };\nexport type { IdentityMigrationName };\n"],
5
- "mappings": "+EAAA,OAAS,wBAAAA,MAA4B,eAErC,OAAS,yBAAAC,EAAuB,gBAAAC,MAAoB,kBAOpD,MAAMC,EAAyB,CAC7B,YAAaD,EACb,4BAA6BD,GAQzBG,EAAqD,CAAC,WAAW,EAKjEC,EAAuD,CAAC,YAAa,2BAA2B,EActG,eAAeC,EAAwBC,EAAiBC,EAAiC,CAAA,EAAE,CACzF,MAAMC,EAAQD,EAAQ,UAAY,GAAOH,EAAqBD,EAC9D,UAAWM,KAAQD,EAAO,CACxB,MAAME,EAAaX,EAAqBG,EAAuBO,CAAI,CAAC,EACpE,GAAIC,EAAW,SAAW,EAC1B,IAAIJ,EAAG,MAAO,CACZ,MAAMA,EAAG,MAAMI,EAAW,IAAKC,GAAQL,EAAG,QAAQK,CAAG,CAAC,CAAC,EACvD,QACF,CACA,UAAWA,KAAOD,EAChB,MAAMJ,EAAG,QAAQK,CAAG,EAAE,IAAG,EAE7B,CACF,CAbeC,EAAAP,EAAA",
6
- "names": ["executableStatements", "UPGRADE_USER_IDENTITY", "USERS_SCHEMA", "IDENTITY_MIGRATION_SQL", "FRESH_MIGRATIONS", "UPGRADE_MIGRATIONS", "applyIdentityMigrations", "db", "options", "names", "name", "statements", "sql", "__name"]
4
+ "sourcesContent": ["import { executableStatements } from '@rexezuge/d1';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport { UPGRADE_USER_IDENTITY, USERS_SCHEMA } from './migrations.ts';\n\n/**\n * The executable form, keyed by the names `FRESH_MIGRATIONS` /\n * `UPGRADE_MIGRATIONS` use. Private: `IDENTITY_MIGRATIONS` is the one public\n * migrations export.\n */\nconst MIGRATION_SQL_BY_NAME = {\n 'users.sql': USERS_SCHEMA,\n 'upgrade-user-identity.sql': UPGRADE_USER_IDENTITY,\n} as const;\n\ntype IdentityMigrationName = keyof typeof MIGRATION_SQL_BY_NAME;\n\n/**\n * @deprecated Use `IDENTITY_MIGRATIONS` — the one canonical migrations export,\n * an ordered `{ name, sql }` list. This map carries the same two SQL strings\n * under different names. Removed in 2.0.\n */\nconst IDENTITY_MIGRATION_SQL: Readonly<Record<IdentityMigrationName, string>> = MIGRATION_SQL_BY_NAME;\n\n/**\nThe full fresh-install order.\n*/\nconst FRESH_MIGRATIONS: readonly IdentityMigrationName[] = ['users.sql'];\n\n/**\nA legacy database applies the upgrade after the fresh schema is in place.\n*/\nconst UPGRADE_MIGRATIONS: readonly IdentityMigrationName[] = ['users.sql', 'upgrade-user-identity.sql'];\n\n/**\n * Apply the identity migrations to a D1 binding.\n *\n * Split and executed through `@rexezuge/d1` — the same statement splitter the\n * test helpers use — so a kit migration and an integration suite can never\n * disagree about where one statement ends. One `batch()` per file, matching\n * D1's own per-file apply, so a failure names its file.\n *\n * `upgrade: false` (the default) applies only the fresh-install schema. Pass\n * `upgrade: true` for a database whose `users` table predates the identity\n * columns; the upgrade file is rerunnable, so applying both is safe.\n */\nasync function applyIdentityMigrations(db: D1Queryable, options: { upgrade?: boolean } = {}): Promise<void> {\n const names = options.upgrade === true ? UPGRADE_MIGRATIONS : FRESH_MIGRATIONS;\n for (const name of names) {\n const statements = executableStatements(MIGRATION_SQL_BY_NAME[name]);\n if (statements.length === 0) continue;\n if (db.batch) {\n await db.batch(statements.map((sql) => db.prepare(sql)));\n continue;\n }\n for (const sql of statements) {\n await db.prepare(sql).run();\n }\n }\n}\n\nexport { applyIdentityMigrations, IDENTITY_MIGRATION_SQL, FRESH_MIGRATIONS, UPGRADE_MIGRATIONS };\nexport type { IdentityMigrationName };\n"],
5
+ "mappings": "+EAAA,OAAS,wBAAAA,MAA4B,eAErC,OAAS,yBAAAC,EAAuB,gBAAAC,MAAoB,kBAOpD,MAAMC,EAAwB,CAC5B,YAAaD,EACb,4BAA6BD,GAUzBG,EAA0ED,EAK1EE,EAAqD,CAAC,WAAW,EAKjEC,EAAuD,CAAC,YAAa,2BAA2B,EActG,eAAeC,EAAwBC,EAAiBC,EAAiC,CAAA,EAAE,CACzF,MAAMC,EAAQD,EAAQ,UAAY,GAAOH,EAAqBD,EAC9D,UAAWM,KAAQD,EAAO,CACxB,MAAME,EAAaZ,EAAqBG,EAAsBQ,CAAI,CAAC,EACnE,GAAIC,EAAW,SAAW,EAC1B,IAAIJ,EAAG,MAAO,CACZ,MAAMA,EAAG,MAAMI,EAAW,IAAKC,GAAQL,EAAG,QAAQK,CAAG,CAAC,CAAC,EACvD,QACF,CACA,UAAWA,KAAOD,EAChB,MAAMJ,EAAG,QAAQK,CAAG,EAAE,IAAG,EAE7B,CACF,CAbeC,EAAAP,EAAA",
6
+ "names": ["executableStatements", "UPGRADE_USER_IDENTITY", "USERS_SCHEMA", "MIGRATION_SQL_BY_NAME", "IDENTITY_MIGRATION_SQL", "FRESH_MIGRATIONS", "UPGRADE_MIGRATIONS", "applyIdentityMigrations", "db", "options", "names", "name", "statements", "sql", "__name"]
7
7
  }
@@ -56,7 +56,8 @@ declare const USERS_SCHEMA = "\n-- The account. The anchor (email) is immutable;
56
56
  */
57
57
  declare const UPGRADE_USER_IDENTITY = "\n-- Phase 1: stable account key.\n-- SQLite cannot add a PRIMARY KEY column, so the id is a plain column with a\n-- unique index. A unique index is a valid foreign key parent, which is all the\n-- user_id references need.\nALTER TABLE users ADD COLUMN id TEXT;\n\nUPDATE users SET id = 'usr_' || lower(hex(randomblob(16))) WHERE id IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_id ON users(id);\n\n-- Phase 2: mutable sign-in address.\n-- 'email' stays as the frozen anchor; 'current_email' is what the account signs\n-- in with and what the API reports. Uniqueness is enforced here, so an address\n-- can never be claimed by two accounts.\nALTER TABLE users ADD COLUMN current_email TEXT;\n\nUPDATE users SET current_email = lower(email) WHERE current_email IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_current_email ON users(current_email);\n\n-- Phase 3: address registry.\n-- Login resolution consults is_verified = 1 only. Backfilled from the frozen\n-- anchor address of every existing account, lowercased so a legacy mixed-case\n-- row still yields exactly one login identity.\nCREATE TABLE IF NOT EXISTS user_emails (\n email TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n is_verified INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_user_emails_user ON user_emails(user_id);\n\nINSERT OR IGNORE INTO user_emails (email, user_id, is_verified, created_at)\nSELECT lower(email), id, 1, created_at FROM users;\n";
58
58
  /**
59
- * Every migration this package ships, in apply order.
59
+ * Every migration this package ships, in apply order — **the canonical
60
+ * migrations export** (`IDENTITY_MIGRATION_SQL` is its deprecated alias).
60
61
  *
61
62
  * `upgrade-user-identity.sql` is *not* applied on a fresh database — the
62
63
  * fresh-install path is `users.sql` alone, and the upgrade exists only for a
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,QAAA,MAAM,YAAY,oyBAuBjB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,QAAA,MAAM,qBAAqB,2/CAoC1B,CAAC;AAEF;;;;;;GAMG;AACH,QAAA,MAAM,mBAAmB,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAGrE,CAAC;AAEF,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,YAAY,EAAE,CAAC"}
1
+ {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,QAAA,MAAM,YAAY,oyBAuBjB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,QAAA,MAAM,qBAAqB,2/CAoC1B,CAAC;AAEF;;;;;;;GAOG;AACH,QAAA,MAAM,mBAAmB,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAGrE,CAAC;AAEF,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,YAAY,EAAE,CAAC"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/migrations.ts"],
4
- "sourcesContent": ["/**\n * The canonical `users` / `user_emails` schema.\n *\n * Converged from migration `0001_init.sql` + `0004_user_identity.sql` across the\n * identity-carrying repos, expressed as the *final* shape so a fresh database\n * never has to be upgraded: `users.id` is the account key from the start, and\n * `user_emails` exists from the start.\n *\n * The invariants that make an address change safe (Durable-DAV's design, which\n * is the strictest in the family and the one every other repo's upgrade is\n * migrating toward):\n *\n * - `users.id` is an opaque, unique account key — never an address.\n * - `users.email` is the **frozen anchor**: immutable, the foreign-key target\n * every legacy `*_email` value resolves against, so history survives a change.\n * - `users.current_email` is the mutable sign-in address; unique, so an address\n * can never be claimed by two accounts.\n * - `users.username` is a separately-mutable public handle, not the identity.\n * - `user_emails` is the address registry: `is_verified = 1` may authenticate;\n * a changed-from address stays at `0` (attributable, non-authenticating) and\n * is re-pointable by a later claimant.\n *\n * The anchor design is forced on D1: it honours neither\n * `PRAGMA foreign_keys = off` nor `legacy_alter_table`, and `defer_foreign_keys`\n * does not suppress `ON DELETE CASCADE`, so a live reference cannot be repointed\n * without losing rows. A fresh install just starts with the anchor in place.\n *\n * A repo with legacy tables that reference `users(email)` applies this file's\n * statements and then adds its own additive backfill (the converged pattern is\n * in `upgrade-user-identity.sql`), repointing each legacy column through\n * `user_emails` rather than through the anchor.\n */\nconst USERS_SCHEMA = `\n-- The account. The anchor (email) is immutable; current_email is the login.\nCREATE TABLE IF NOT EXISTS users (\n id TEXT NOT NULL PRIMARY KEY,\n email TEXT NOT NULL UNIQUE,\n current_email TEXT NOT NULL UNIQUE,\n username TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_id ON users(id);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_current_email ON users(current_email);\n\n-- The address registry: which account an address authenticates.\nCREATE TABLE IF NOT EXISTS user_emails (\n email TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n is_verified INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_user_emails_user ON user_emails(user_id);\n`;\n\n/**\n * The additive upgrade for a database whose `users` predates the identity\n * columns — converged from `0004_user_identity.sql` (Durable-DAV) with the\n * table-specific phases (dav_volumes, namespaces) generalized into a\n * documented extension point, because every repo's legacy tables differ.\n *\n * Run order per phase matches Durable-DAV's, and each backfill is guarded so\n * the file is rerunnable: `users.id` is only filled where still missing, and\n * every registry insert is `INSERT OR IGNORE`.\n *\n * Why the address stays in `users` at all (the anchor question, answered once):\n * SQLite rewrites a child's foreign key clause when the parent is renamed and\n * drops the parent by cascading, so the reference from a legacy\n * `owner_email`-style column cannot be repointed at `users.id` without losing\n * rows. Keeping `email` as a frozen anchor sidesteps the rebuild entirely:\n * this migration is purely additive.\n *\n * A consumer with its own legacy tables appends one additive phase per table:\n * add the `*_user_id` column with `REFERENCES users(id) ON DELETE CASCADE`\n * (`NO ACTION` would *restrict* where the existing `owner_email` cascade\n * removed rows — the two references must cascade together), backfill it by\n * resolving the stored address through `user_emails`, and index it.\n */\nconst UPGRADE_USER_IDENTITY = `\n-- Phase 1: stable account key.\n-- SQLite cannot add a PRIMARY KEY column, so the id is a plain column with a\n-- unique index. A unique index is a valid foreign key parent, which is all the\n-- user_id references need.\nALTER TABLE users ADD COLUMN id TEXT;\n\nUPDATE users SET id = 'usr_' || lower(hex(randomblob(16))) WHERE id IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_id ON users(id);\n\n-- Phase 2: mutable sign-in address.\n-- 'email' stays as the frozen anchor; 'current_email' is what the account signs\n-- in with and what the API reports. Uniqueness is enforced here, so an address\n-- can never be claimed by two accounts.\nALTER TABLE users ADD COLUMN current_email TEXT;\n\nUPDATE users SET current_email = lower(email) WHERE current_email IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_current_email ON users(current_email);\n\n-- Phase 3: address registry.\n-- Login resolution consults is_verified = 1 only. Backfilled from the frozen\n-- anchor address of every existing account, lowercased so a legacy mixed-case\n-- row still yields exactly one login identity.\nCREATE TABLE IF NOT EXISTS user_emails (\n email TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n is_verified INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_user_emails_user ON user_emails(user_id);\n\nINSERT OR IGNORE INTO user_emails (email, user_id, is_verified, created_at)\nSELECT lower(email), id, 1, created_at FROM users;\n`;\n\n/**\n * Every migration this package ships, in apply order.\n *\n * `upgrade-user-identity.sql` is *not* applied on a fresh database — the\n * fresh-install path is `users.sql` alone, and the upgrade exists only for a\n * legacy one.\n */\nconst IDENTITY_MIGRATIONS: ReadonlyArray<{ name: string; sql: string }> = [\n { name: '0001_users.sql', sql: USERS_SCHEMA },\n { name: '0002_upgrade_user_identity.sql', sql: UPGRADE_USER_IDENTITY },\n];\n\nexport { IDENTITY_MIGRATIONS, UPGRADE_USER_IDENTITY, USERS_SCHEMA };\n"],
5
- "mappings": "AAgCA,MAAMA,EAAe;;;;;;;;;;;;;;;;;;;;;;;EAgDfC,EAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6CxBC,EAAoE,CACxE,CAAE,KAAM,iBAAkB,IAAKF,CAAY,EAC3C,CAAE,KAAM,iCAAkC,IAAKC,CAAqB",
4
+ "sourcesContent": ["/**\n * The canonical `users` / `user_emails` schema.\n *\n * Converged from migration `0001_init.sql` + `0004_user_identity.sql` across the\n * identity-carrying repos, expressed as the *final* shape so a fresh database\n * never has to be upgraded: `users.id` is the account key from the start, and\n * `user_emails` exists from the start.\n *\n * The invariants that make an address change safe (Durable-DAV's design, which\n * is the strictest in the family and the one every other repo's upgrade is\n * migrating toward):\n *\n * - `users.id` is an opaque, unique account key — never an address.\n * - `users.email` is the **frozen anchor**: immutable, the foreign-key target\n * every legacy `*_email` value resolves against, so history survives a change.\n * - `users.current_email` is the mutable sign-in address; unique, so an address\n * can never be claimed by two accounts.\n * - `users.username` is a separately-mutable public handle, not the identity.\n * - `user_emails` is the address registry: `is_verified = 1` may authenticate;\n * a changed-from address stays at `0` (attributable, non-authenticating) and\n * is re-pointable by a later claimant.\n *\n * The anchor design is forced on D1: it honours neither\n * `PRAGMA foreign_keys = off` nor `legacy_alter_table`, and `defer_foreign_keys`\n * does not suppress `ON DELETE CASCADE`, so a live reference cannot be repointed\n * without losing rows. A fresh install just starts with the anchor in place.\n *\n * A repo with legacy tables that reference `users(email)` applies this file's\n * statements and then adds its own additive backfill (the converged pattern is\n * in `upgrade-user-identity.sql`), repointing each legacy column through\n * `user_emails` rather than through the anchor.\n */\nconst USERS_SCHEMA = `\n-- The account. The anchor (email) is immutable; current_email is the login.\nCREATE TABLE IF NOT EXISTS users (\n id TEXT NOT NULL PRIMARY KEY,\n email TEXT NOT NULL UNIQUE,\n current_email TEXT NOT NULL UNIQUE,\n username TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_id ON users(id);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_current_email ON users(current_email);\n\n-- The address registry: which account an address authenticates.\nCREATE TABLE IF NOT EXISTS user_emails (\n email TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n is_verified INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_user_emails_user ON user_emails(user_id);\n`;\n\n/**\n * The additive upgrade for a database whose `users` predates the identity\n * columns — converged from `0004_user_identity.sql` (Durable-DAV) with the\n * table-specific phases (dav_volumes, namespaces) generalized into a\n * documented extension point, because every repo's legacy tables differ.\n *\n * Run order per phase matches Durable-DAV's, and each backfill is guarded so\n * the file is rerunnable: `users.id` is only filled where still missing, and\n * every registry insert is `INSERT OR IGNORE`.\n *\n * Why the address stays in `users` at all (the anchor question, answered once):\n * SQLite rewrites a child's foreign key clause when the parent is renamed and\n * drops the parent by cascading, so the reference from a legacy\n * `owner_email`-style column cannot be repointed at `users.id` without losing\n * rows. Keeping `email` as a frozen anchor sidesteps the rebuild entirely:\n * this migration is purely additive.\n *\n * A consumer with its own legacy tables appends one additive phase per table:\n * add the `*_user_id` column with `REFERENCES users(id) ON DELETE CASCADE`\n * (`NO ACTION` would *restrict* where the existing `owner_email` cascade\n * removed rows — the two references must cascade together), backfill it by\n * resolving the stored address through `user_emails`, and index it.\n */\nconst UPGRADE_USER_IDENTITY = `\n-- Phase 1: stable account key.\n-- SQLite cannot add a PRIMARY KEY column, so the id is a plain column with a\n-- unique index. A unique index is a valid foreign key parent, which is all the\n-- user_id references need.\nALTER TABLE users ADD COLUMN id TEXT;\n\nUPDATE users SET id = 'usr_' || lower(hex(randomblob(16))) WHERE id IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_id ON users(id);\n\n-- Phase 2: mutable sign-in address.\n-- 'email' stays as the frozen anchor; 'current_email' is what the account signs\n-- in with and what the API reports. Uniqueness is enforced here, so an address\n-- can never be claimed by two accounts.\nALTER TABLE users ADD COLUMN current_email TEXT;\n\nUPDATE users SET current_email = lower(email) WHERE current_email IS NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_users_current_email ON users(current_email);\n\n-- Phase 3: address registry.\n-- Login resolution consults is_verified = 1 only. Backfilled from the frozen\n-- anchor address of every existing account, lowercased so a legacy mixed-case\n-- row still yields exactly one login identity.\nCREATE TABLE IF NOT EXISTS user_emails (\n email TEXT PRIMARY KEY,\n user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n is_verified INTEGER NOT NULL DEFAULT 0,\n created_at INTEGER NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_user_emails_user ON user_emails(user_id);\n\nINSERT OR IGNORE INTO user_emails (email, user_id, is_verified, created_at)\nSELECT lower(email), id, 1, created_at FROM users;\n`;\n\n/**\n * Every migration this package ships, in apply order — **the canonical\n * migrations export** (`IDENTITY_MIGRATION_SQL` is its deprecated alias).\n *\n * `upgrade-user-identity.sql` is *not* applied on a fresh database — the\n * fresh-install path is `users.sql` alone, and the upgrade exists only for a\n * legacy one.\n */\nconst IDENTITY_MIGRATIONS: ReadonlyArray<{ name: string; sql: string }> = [\n { name: '0001_users.sql', sql: USERS_SCHEMA },\n { name: '0002_upgrade_user_identity.sql', sql: UPGRADE_USER_IDENTITY },\n];\n\nexport { IDENTITY_MIGRATIONS, UPGRADE_USER_IDENTITY, USERS_SCHEMA };\n"],
5
+ "mappings": "AAgCA,MAAMA,EAAe;;;;;;;;;;;;;;;;;;;;;;;EAgDfC,EAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8CxBC,EAAoE,CACxE,CAAE,KAAM,iBAAkB,IAAKF,CAAY,EAC3C,CAAE,KAAM,iCAAkC,IAAKC,CAAqB",
6
6
  "names": ["USERS_SCHEMA", "UPGRADE_USER_IDENTITY", "IDENTITY_MIGRATIONS"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/identity",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -25,9 +25,9 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@rexezuge/errors": "1.10.0",
29
- "@rexezuge/shared": "1.10.0",
30
- "@rexezuge/d1": "1.10.0"
28
+ "@rexezuge/errors": "1.11.0",
29
+ "@rexezuge/shared": "1.11.0",
30
+ "@rexezuge/d1": "1.11.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "26.6.4",