@rexezuge/identity 1.7.2 → 1.8.1
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/dist/UserEmailDAO.d.ts
CHANGED
|
@@ -39,6 +39,18 @@ export declare class UserEmailDAO extends BaseDAO {
|
|
|
39
39
|
* someone, and silently re-pointing it would hand one account's identity to
|
|
40
40
|
* another. Callers check `resolveVerified` first and reject on a hit.
|
|
41
41
|
* An unverified (revoked) row is re-pointed, which releases the address.
|
|
42
|
+
*
|
|
43
|
+
* The `WHERE user_emails.is_verified = 0` on the upsert is **load-bearing**,
|
|
44
|
+
* not a refinement. The read above and this write are two statements, so a
|
|
45
|
+
* caller that checked `resolveVerified` a moment earlier can still be racing
|
|
46
|
+
* another claim for the same address — and an unconditional `DO UPDATE` lets
|
|
47
|
+
* the loser re-point a row that is verified *now*, which is an account
|
|
48
|
+
* takeover rather than a failed claim. The conditional update makes the write
|
|
49
|
+
* itself refuse, and `meta.changes` turns "lost the race" into the same
|
|
50
|
+
* `'already-claimed'` answer the pre-read would have given.
|
|
51
|
+
*
|
|
52
|
+
* Without it the read is an optimisation; with it, it is still an
|
|
53
|
+
* optimisation and the invariant no longer depends on a statement ordering.
|
|
42
54
|
*/
|
|
43
55
|
register(input: {
|
|
44
56
|
email: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserEmailDAO.d.ts","sourceRoot":"","sources":["../src/UserEmailDAO.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,iBAAiB,CAAC;AAEvD,qBAAa,YAAa,SAAQ,OAAO;IACvC;;;;;;;;;OASG;gBACgB,QAAQ,EAAE,WAAW,EAAE,KAAK,CAAC,EAAE,eAAe;IAIjE
|
|
1
|
+
{"version":3,"file":"UserEmailDAO.d.ts","sourceRoot":"","sources":["../src/UserEmailDAO.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,iBAAiB,CAAC;AAEvD,qBAAa,YAAa,SAAQ,OAAO;IACvC;;;;;;;;;OASG;gBACgB,QAAQ,EAAE,WAAW,EAAE,KAAK,CAAC,EAAE,eAAe;IAIjE;;;;;;;;;;;;;;;;;;;OAmBG;IACU,QAAQ,CAAC,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,UAAU,CAAC;IAczG,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAO7D;;MAEE;IACW,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC;IAI5D,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAIlE;;MAEE;IACW,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIjD;;;OAGG;IACU,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAGnF"}
|
package/dist/UserEmailDAO.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
var t=Object.defineProperty;var a=(s,e)=>t(s,"name",{value:e,configurable:!0});import{BaseDAO as
|
|
1
|
+
var t=Object.defineProperty;var a=(s,e)=>t(s,"name",{value:e,configurable:!0});import{BaseDAO as l}from"@rexezuge/d1";class _ extends l{static{a(this,"UserEmailDAO")}constructor(e,i){super(e,i)}async register(e){const i=e.email.toLowerCase(),r=await this.get(i);return r&&r.is_verified===1||((await this.run(`INSERT INTO user_emails (email, user_id, is_verified, created_at)
|
|
2
2
|
VALUES (?, ?, ?, ?)
|
|
3
|
-
ON CONFLICT(email) DO UPDATE SET user_id = excluded.user_id, is_verified = excluded.is_verified
|
|
3
|
+
ON CONFLICT(email) DO UPDATE SET user_id = excluded.user_id, is_verified = excluded.is_verified
|
|
4
|
+
WHERE user_emails.is_verified = 0`,[i,e.userId,e.isVerified?1:0,e.now])).meta?.changes??0)===0?"already-claimed":"claimed"}async get(e){return this.first("SELECT * FROM user_emails WHERE email = ? LIMIT 1",[e.toLowerCase()])}async resolveVerified(e){return this.first("SELECT * FROM user_emails WHERE email = ? AND is_verified = 1 LIMIT 1",[e.toLowerCase()])}async listByUserId(e){return this.all("SELECT * FROM user_emails WHERE user_id = ? ORDER BY is_verified DESC, created_at ASC",[e])}async revoke(e){await this.run("UPDATE user_emails SET is_verified = 0 WHERE email = ?",[e.toLowerCase()])}async revokeAllVerified(e,i){await this.run("UPDATE user_emails SET is_verified = 0 WHERE user_id = ? AND email != ?",[e,i.toLowerCase()])}}export{_ as UserEmailDAO};
|
package/dist/UserEmailDAO.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/UserEmailDAO.ts"],
|
|
4
|
-
"sourcesContent": ["import { BaseDAO } from '@rexezuge/d1';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport type { SubrequestMeter } from '@rexezuge/shared';\n\n/**\n * One known address for an account.\n *\n * `is_verified` gates login: `1` means the address may authenticate the\n * account, `0` means it was changed away from and is retained only so rows\n * written before the change still resolve. A revoked row is re-pointed (not\n * deleted) when a later account legitimately claims the address, so an address\n * is never permanently reserved.\n *\n * Converged from `backend-data/src/dao/UserEmailDAO.ts` (identical in Durable-DAV,\n * Durable-DAV-Router, Edge-Git, Mail-Otter).\n */\nexport interface UserEmailRow {\n email: string;\n user_id: string;\n is_verified: number;\n created_at: number;\n}\n\nexport type EmailClaim = 'claimed' | 'already-claimed';\n\nexport class UserEmailDAO extends BaseDAO {\n /**\n * @param database The binding.\n * @param meter The invocation's subrequest counter. Optional, and defaulted,\n * because a consumer that meters its own DAOs must be able to meter this one\n * too: a DAO that charges nothing does not under-report loudly, it spends a\n * subrequest the ceiling never saw — and the failure surfaces as the platform\n * terminating an invocation, on no request, with no error in the application.\n * The parameter exists so adopting this class does not silently un-meter a\n * repository whose every other statement is charged.\n */\n public constructor(database: D1Queryable, meter?: SubrequestMeter) {\n super(database, meter);\n }\n\n /**\n * Claim an address for an account.\n *\n * An existing verified row is left alone: the address already belongs to\n * someone, and silently re-pointing it would hand one account's identity to\n * another. Callers check `resolveVerified` first and reject on a hit.\n * An unverified (revoked) row is re-pointed, which releases the address.\n */\n public async register(input: { email: string; userId: string; isVerified: boolean; now: number }): Promise<EmailClaim> {\n const email = input.email.toLowerCase();\n const existing = await this.get(email);\n if (existing && existing.is_verified === 1) return 'already-claimed';\n await this.run(\n `INSERT INTO user_emails (email, user_id, is_verified, created_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT(email) DO UPDATE SET user_id = excluded.user_id, is_verified = excluded.is_verified`,\n [email, input.userId, input.isVerified ? 1 : 0, input.now],\n );\n return 'claimed';\n }\n\n public async get(email: string): Promise<UserEmailRow | null> {\n // Lowercase the *parameter*: the column is stored lowercased by every\n // writer, so `lower(email) = ?` matched identically while making the\n // primary key unusable.\n return this.first<UserEmailRow>('SELECT * FROM user_emails WHERE email = ? LIMIT 1', [email.toLowerCase()]);\n }\n\n /**\n Login resolution: only a verified address identifies an account.\n */\n public async resolveVerified(email: string): Promise<UserEmailRow | null> {\n return this.first<UserEmailRow>('SELECT * FROM user_emails WHERE email = ? AND is_verified = 1 LIMIT 1', [email.toLowerCase()]);\n }\n\n public async listByUserId(userId: string): Promise<UserEmailRow[]> {\n return this.all<UserEmailRow>('SELECT * FROM user_emails WHERE user_id = ? ORDER BY is_verified DESC, created_at ASC', [userId]);\n }\n\n /**\n Revoke an address for login while keeping it resolvable for attribution.\n */\n public async revoke(email: string): Promise<void> {\n await this.run('UPDATE user_emails SET is_verified = 0 WHERE email = ?', [email.toLowerCase()]);\n }\n\n /**\n * Revoke every verified address for an account. Used when an account's login\n * address changes, so only the new address can authenticate it.\n */\n public async revokeAllVerified(userId: string, exceptEmail: string): Promise<void> {\n await this.run('UPDATE user_emails SET is_verified = 0 WHERE user_id = ? AND email != ?', [userId, exceptEmail.toLowerCase()]);\n }\n}\n"],
|
|
5
|
-
"mappings": "+EAAA,OAAS,WAAAA,MAAe,eAyBlB,MAAOC,UAAqBD,CAAO,CAzBzC,MAyByC,CAAAE,EAAA,qBAWvC,YAAmBC,EAAuBC,EAAuB,CAC/D,MAAMD,EAAUC,CAAK,CACvB,
|
|
4
|
+
"sourcesContent": ["import { BaseDAO } from '@rexezuge/d1';\nimport type { D1Queryable } from '@rexezuge/d1';\nimport type { SubrequestMeter } from '@rexezuge/shared';\n\n/**\n * One known address for an account.\n *\n * `is_verified` gates login: `1` means the address may authenticate the\n * account, `0` means it was changed away from and is retained only so rows\n * written before the change still resolve. A revoked row is re-pointed (not\n * deleted) when a later account legitimately claims the address, so an address\n * is never permanently reserved.\n *\n * Converged from `backend-data/src/dao/UserEmailDAO.ts` (identical in Durable-DAV,\n * Durable-DAV-Router, Edge-Git, Mail-Otter).\n */\nexport interface UserEmailRow {\n email: string;\n user_id: string;\n is_verified: number;\n created_at: number;\n}\n\nexport type EmailClaim = 'claimed' | 'already-claimed';\n\nexport class UserEmailDAO extends BaseDAO {\n /**\n * @param database The binding.\n * @param meter The invocation's subrequest counter. Optional, and defaulted,\n * because a consumer that meters its own DAOs must be able to meter this one\n * too: a DAO that charges nothing does not under-report loudly, it spends a\n * subrequest the ceiling never saw — and the failure surfaces as the platform\n * terminating an invocation, on no request, with no error in the application.\n * The parameter exists so adopting this class does not silently un-meter a\n * repository whose every other statement is charged.\n */\n public constructor(database: D1Queryable, meter?: SubrequestMeter) {\n super(database, meter);\n }\n\n /**\n * Claim an address for an account.\n *\n * An existing verified row is left alone: the address already belongs to\n * someone, and silently re-pointing it would hand one account's identity to\n * another. Callers check `resolveVerified` first and reject on a hit.\n * An unverified (revoked) row is re-pointed, which releases the address.\n *\n * The `WHERE user_emails.is_verified = 0` on the upsert is **load-bearing**,\n * not a refinement. The read above and this write are two statements, so a\n * caller that checked `resolveVerified` a moment earlier can still be racing\n * another claim for the same address — and an unconditional `DO UPDATE` lets\n * the loser re-point a row that is verified *now*, which is an account\n * takeover rather than a failed claim. The conditional update makes the write\n * itself refuse, and `meta.changes` turns \"lost the race\" into the same\n * `'already-claimed'` answer the pre-read would have given.\n *\n * Without it the read is an optimisation; with it, it is still an\n * optimisation and the invariant no longer depends on a statement ordering.\n */\n public async register(input: { email: string; userId: string; isVerified: boolean; now: number }): Promise<EmailClaim> {\n const email = input.email.toLowerCase();\n const existing = await this.get(email);\n if (existing && existing.is_verified === 1) return 'already-claimed';\n const result = await this.run(\n `INSERT INTO user_emails (email, user_id, is_verified, created_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT(email) DO UPDATE SET user_id = excluded.user_id, is_verified = excluded.is_verified\n WHERE user_emails.is_verified = 0`,\n [email, input.userId, input.isVerified ? 1 : 0, input.now],\n );\n return (result.meta?.changes ?? 0) === 0 ? 'already-claimed' : 'claimed';\n }\n\n public async get(email: string): Promise<UserEmailRow | null> {\n // Lowercase the *parameter*: the column is stored lowercased by every\n // writer, so `lower(email) = ?` matched identically while making the\n // primary key unusable.\n return this.first<UserEmailRow>('SELECT * FROM user_emails WHERE email = ? LIMIT 1', [email.toLowerCase()]);\n }\n\n /**\n Login resolution: only a verified address identifies an account.\n */\n public async resolveVerified(email: string): Promise<UserEmailRow | null> {\n return this.first<UserEmailRow>('SELECT * FROM user_emails WHERE email = ? AND is_verified = 1 LIMIT 1', [email.toLowerCase()]);\n }\n\n public async listByUserId(userId: string): Promise<UserEmailRow[]> {\n return this.all<UserEmailRow>('SELECT * FROM user_emails WHERE user_id = ? ORDER BY is_verified DESC, created_at ASC', [userId]);\n }\n\n /**\n Revoke an address for login while keeping it resolvable for attribution.\n */\n public async revoke(email: string): Promise<void> {\n await this.run('UPDATE user_emails SET is_verified = 0 WHERE email = ?', [email.toLowerCase()]);\n }\n\n /**\n * Revoke every verified address for an account. Used when an account's login\n * address changes, so only the new address can authenticate it.\n */\n public async revokeAllVerified(userId: string, exceptEmail: string): Promise<void> {\n await this.run('UPDATE user_emails SET is_verified = 0 WHERE user_id = ? AND email != ?', [userId, exceptEmail.toLowerCase()]);\n }\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,WAAAA,MAAe,eAyBlB,MAAOC,UAAqBD,CAAO,CAzBzC,MAyByC,CAAAE,EAAA,qBAWvC,YAAmBC,EAAuBC,EAAuB,CAC/D,MAAMD,EAAUC,CAAK,CACvB,CAsBO,MAAM,SAASC,EAA0E,CAC9F,MAAMC,EAAQD,EAAM,MAAM,YAAW,EAC/BE,EAAW,MAAM,KAAK,IAAID,CAAK,EACrC,OAAIC,GAAYA,EAAS,cAAgB,KAC1B,MAAM,KAAK,IACxB;;;0CAIA,CAACD,EAAOD,EAAM,OAAQA,EAAM,WAAa,EAAI,EAAGA,EAAM,GAAG,CAAC,GAE7C,MAAM,SAAW,KAAO,EARY,kBAQY,SACjE,CAEO,MAAM,IAAIC,EAAa,CAI5B,OAAO,KAAK,MAAoB,oDAAqD,CAACA,EAAM,YAAW,CAAE,CAAC,CAC5G,CAKO,MAAM,gBAAgBA,EAAa,CACxC,OAAO,KAAK,MAAoB,wEAAyE,CAACA,EAAM,YAAW,CAAE,CAAC,CAChI,CAEO,MAAM,aAAaE,EAAc,CACtC,OAAO,KAAK,IAAkB,wFAAyF,CAACA,CAAM,CAAC,CACjI,CAKO,MAAM,OAAOF,EAAa,CAC/B,MAAM,KAAK,IAAI,yDAA0D,CAACA,EAAM,YAAW,CAAE,CAAC,CAChG,CAMO,MAAM,kBAAkBE,EAAgBC,EAAmB,CAChE,MAAM,KAAK,IAAI,0EAA2E,CAACD,EAAQC,EAAY,YAAW,CAAE,CAAC,CAC/H",
|
|
6
6
|
"names": ["BaseDAO", "UserEmailDAO", "__name", "database", "meter", "input", "email", "existing", "userId", "exceptEmail"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accountLookup.d.ts","sourceRoot":"","sources":["../src/accountLookup.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAChC,YAAY,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,CAAC;CAC3C;AAED;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"accountLookup.d.ts","sourceRoot":"","sources":["../src/accountLookup.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAChC,YAAY,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,CAAC;CAC3C;AAED;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAAC,IAAI,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CA8D5G;AAED;;EAEE;AACF,wBAAsB,aAAa,CAAC,IAAI,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAGlG;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,iBAAiB,EACvB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAsBjC"}
|
package/dist/accountLookup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var s=(r,t)=>f(r,"name",{value:t,configurable:!0});import{isMissingSchemaError as l}from"@rexezuge/d1";import{summarize as o}from"./ResolvedAccount.js";async function m(r,t){const e=t.trim().toLowerCase();if(!e)return null;const i=await r.userDAO(),a=await r.userEmailDAO().then(c=>c.get(e)).catch(c=>{if(l(c))return null;throw c});if(a)return a.is_verified===1?o(await i.getById(a.user_id)):null;const u=await i.getByCurrentEmail(e);if(u)return o(u);const n=await i.getByEmail(e);return n?.current_email!=null&&n.current_email.trim().toLowerCase()!==e?null:o(n)}s(m,"resolveAccount");async function d(r,t){return(await m(r,t))?.id??null}s(d,"resolveUserId");async function g(r,t,e,i){const u=await(await r.userDAO()).createUser({anchor:e,loginEmail:t,now:i});return u===null?null:(await r.userEmailDAO().then(n=>n.register({email:t,userId:u,isVerified:!0,now:i})).catch(n=>{if(!l(n))throw n}),m(r,t))}s(g,"registerAccount");export{g as registerAccount,m as resolveAccount,d as resolveUserId};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/accountLookup.ts"],
|
|
4
|
-
"sourcesContent": ["import { isMissingSchemaError } from '@rexezuge/d1';\nimport { summarize } from './ResolvedAccount.ts';\nimport type { ResolvedAccount } from './ResolvedAccount.ts';\nimport { UserDAO } from './UserDAO.ts';\nimport { UserEmailDAO } from './UserEmailDAO.ts';\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 interface AccountLookupDeps {\n userDAO: () => Promise<UserDAO>;\n userEmailDAO: () => Promise<UserEmailDAO>;\n}\n\n/**\n * Address -> account resolution, as free functions so the service and any\n * higher-level account bootstrap share one implementation instead of\n * re-deriving the query.\n *\n * Converged from `backend-services/src/user/accountLookup.ts` (identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Otter).\n */\nexport async function resolveAccount(deps: AccountLookupDeps, email: string): Promise<ResolvedAccount | null> {\n const normalized = email.trim().toLowerCase();\n if (!normalized) return null;\n const userDAO = await deps.userDAO();\n // A known address is authoritative: the registry says which account it belongs\n // to, and a *revoked* row (the account moved off this address) must not\n // resolve at all. Falling through to the legacy lookups in that case would let\n // a reassigned address keep authenticating the previous holder's account.\n //\n // Only a *missing registry* falls through, and \"missing\" means one specific\n // thing: the identity migration has not run. The previous\n // `.catch(() => null)` answered that question for **every** failure, so a\n // transient D1 error on this one statement made the code proceed to the anchor\n // lookup below — `getByEmail`, which is an attribution lookup whose key is a\n // re-registrable string, not an identity. An address whose account had moved\n // off it (so its `user_emails` row is revoked, and correctly refuses to\n // resolve) would then be resolved against the *previous holder's* anchor, and\n // that account's id was installed as the caller's identity: full access to\n // someone else's rows from one failed `SELECT`.\n //\n // So the degradation is narrowed to `isMissingSchemaError`, and everything\n // else rethrows.\n // The `null` in the `catch` answers the same question the DAO's own `null`\n // answers — no row — so the two branches below share one type. When this read\n // returned `undefined` on success and `null` on a missing schema, the widened\n // union had to be narrowed by truthiness at a point that had nothing to do\n // with which branch it came from.\n const registered = await deps\n .userEmailDAO()\n .then((dao) => dao.get(normalized))\n .catch((error: unknown) => {\n if (isMissingSchemaError(error)) return null;\n throw error;\n });\n if (registered) {\n return registered.is_verified === 1 ? summarize(await userDAO.getById(registered.user_id)) : null;\n }\n // No registry row at all. Safe to fall through: the identity migration\n // backfilled a verified row for every anchor, so a row-less address is either\n // new or on a pre-identity database, where the address *is* the anchor.\n //\n // No `.catch` on either: a failed `users` read is an outage, and reporting it\n // as \"no such account\" would turn a D1 blip into a 404 and a spurious\n // re-registration attempt.\n const byCurrent = await userDAO.getByCurrentEmail(normalized);\n const legacy =
|
|
5
|
-
"mappings": "+EAAA,OAAS,wBAAAA,MAA4B,eACrC,OAAS,aAAAC,MAAiB,uBAsB1B,eAAsBC,EAAeC,EAAyBC,EAAa,CACzE,MAAMC,EAAaD,EAAM,KAAI,EAAG,YAAW,EAC3C,GAAI,CAACC,EAAY,OAAO,KACxB,MAAMC,EAAU,MAAMH,EAAK,QAAO,EAwB5BI,EAAa,MAAMJ,EACtB,aAAY,EACZ,KAAMK,GAAQA,EAAI,IAAIH,CAAU,CAAC,EACjC,MAAOI,GAAkB,CACxB,GAAIT,EAAqBS,CAAK,EAAG,OAAO,KACxC,MAAMA,CACR,CAAC,EACH,GAAIF,EACF,OAAOA,EAAW,cAAgB,EAAIN,EAAU,MAAMK,EAAQ,QAAQC,EAAW,OAAO,CAAC,EAAI,
|
|
6
|
-
"names": ["isMissingSchemaError", "summarize", "resolveAccount", "deps", "email", "normalized", "userDAO", "registered", "dao", "error", "legacy", "__name", "resolveUserId", "registerAccount", "loginEmail", "anchor", "now", "created"]
|
|
4
|
+
"sourcesContent": ["import { isMissingSchemaError } from '@rexezuge/d1';\nimport { summarize } from './ResolvedAccount.ts';\nimport type { ResolvedAccount } from './ResolvedAccount.ts';\nimport { UserDAO } from './UserDAO.ts';\nimport { UserEmailDAO } from './UserEmailDAO.ts';\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 interface AccountLookupDeps {\n userDAO: () => Promise<UserDAO>;\n userEmailDAO: () => Promise<UserEmailDAO>;\n}\n\n/**\n * Address -> account resolution, as free functions so the service and any\n * higher-level account bootstrap share one implementation instead of\n * re-deriving the query.\n *\n * Converged from `backend-services/src/user/accountLookup.ts` (identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Git, Mail-Otter).\n */\nexport async function resolveAccount(deps: AccountLookupDeps, email: string): Promise<ResolvedAccount | null> {\n const normalized = email.trim().toLowerCase();\n if (!normalized) return null;\n const userDAO = await deps.userDAO();\n // A known address is authoritative: the registry says which account it belongs\n // to, and a *revoked* row (the account moved off this address) must not\n // resolve at all. Falling through to the legacy lookups in that case would let\n // a reassigned address keep authenticating the previous holder's account.\n //\n // Only a *missing registry* falls through, and \"missing\" means one specific\n // thing: the identity migration has not run. The previous\n // `.catch(() => null)` answered that question for **every** failure, so a\n // transient D1 error on this one statement made the code proceed to the anchor\n // lookup below — `getByEmail`, which is an attribution lookup whose key is a\n // re-registrable string, not an identity. An address whose account had moved\n // off it (so its `user_emails` row is revoked, and correctly refuses to\n // resolve) would then be resolved against the *previous holder's* anchor, and\n // that account's id was installed as the caller's identity: full access to\n // someone else's rows from one failed `SELECT`.\n //\n // So the degradation is narrowed to `isMissingSchemaError`, and everything\n // else rethrows.\n // The `null` in the `catch` answers the same question the DAO's own `null`\n // answers — no row — so the two branches below share one type. When this read\n // returned `undefined` on success and `null` on a missing schema, the widened\n // union had to be narrowed by truthiness at a point that had nothing to do\n // with which branch it came from.\n const registered = await deps\n .userEmailDAO()\n .then((dao) => dao.get(normalized))\n .catch((error: unknown) => {\n if (isMissingSchemaError(error)) return null;\n throw error;\n });\n if (registered) {\n return registered.is_verified === 1 ? summarize(await userDAO.getById(registered.user_id)) : null;\n }\n // No registry row at all. Safe to fall through: the identity migration\n // backfilled a verified row for every anchor, so a row-less address is either\n // new or on a pre-identity database, where the address *is* the anchor.\n //\n // No `.catch` on either: a failed `users` read is an outage, and reporting it\n // as \"no such account\" would turn a D1 blip into a 404 and a spurious\n // re-registration attempt.\n const byCurrent = await userDAO.getByCurrentEmail(normalized);\n if (byCurrent) return summarize(byCurrent);\n const legacy = await userDAO.getByEmail(normalized);\n // The same rule the registry branch above applies, reached the other way.\n // `getByEmail` is the *anchor* lookup, and an anchor is frozen — so a row\n // found here whose mutable address has since moved away is an account that\n // left this address, and answering with its id would install the caller's\n // identity as that account. It is reachable whenever the registry is absent\n // or incomplete: a pre-identity database has no `user_emails` at all, and the\n // migration deliberately leaves `current_email` NULL for the mixed-case\n // accounts it cannot disambiguate.\n //\n // The comparison is case-insensitive on both sides because `getByEmail`\n // lowercases its parameter while `email` is stored as originally supplied:\n // a case variant of an address the account still holds must resolve, and a\n // case variant of one it left must not.\n if (legacy?.current_email != null && legacy.current_email.trim().toLowerCase() !== normalized) return null;\n return summarize(legacy);\n}\n\n/**\nAccount id for a sign-in address, or null when unknown.\n*/\nexport async function resolveUserId(deps: AccountLookupDeps, email: string): Promise<string | null> {\n const account = await resolveAccount(deps, email);\n return account?.id ?? null;\n}\n\n/**\n * Insert an account and claim its sign-in address.\n *\n * The anchor is the address itself whenever it is free, which keeps new rows\n * shaped like the pre-identity ones. It falls back to an opaque anchor only when\n * the address is already held as another account's anchor — i.e. its previous\n * holder moved off it — so a released address is never permanently unusable.\n *\n * Returns null when the insert could not produce a *new* account holding this\n * address, which is the caller's signal to retry with a different anchor.\n *\n * The read-back is load-bearing, not defensive. `createUser` is\n * `ON CONFLICT(email) DO NOTHING`, so when the anchor is already taken the\n * insert is silently a no-op and the generated `id` belongs to nobody. Trusting\n * it would (a) re-point the address registry at a phantom account that resolves\n * to nothing, permanently stranding the address, and (b) on the opaque-anchor\n * retry, hand the caller an account whose address the registry refuses to\n * re-point because the phantom row already marked it verified. Re-reading the\n * anchor row and requiring *our* id to be the one there makes the no-op\n * detectable, so the retry gets a genuinely new account.\n */\nexport async function registerAccount(\n deps: AccountLookupDeps,\n loginEmail: string,\n anchor: string,\n now: number,\n): Promise<ResolvedAccount | null> {\n const userDAO = await deps.userDAO();\n const created = await userDAO.createUser({ anchor, loginEmail, now });\n // `null` is the detected no-op: the anchor was already held. The caller's\n // signal to retry with an opaque anchor — see `newAnchor`.\n if (created === null) return null;\n // Claim the sign-in address *before* resolving, otherwise the fresh account is\n // invisible to the registry and registration looks like a failure. An address\n // already verified for another account is left alone by `register`, and the\n // resolve below then reports that account instead.\n await deps\n .userEmailDAO()\n .then((dao) => dao.register({ email: loginEmail, userId: created, isVerified: true, now }))\n .catch((error: unknown) => {\n // Pre-identity registry only, per the same rule `resolveAccount` follows: a\n // missing table is tolerated, a failed write is not. Swallowing the second\n // would return an account the address registry has never heard of, which\n // resolves to nothing on the next login.\n if (isMissingSchemaError(error)) return;\n throw error;\n });\n return resolveAccount(deps, loginEmail);\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,wBAAAA,MAA4B,eACrC,OAAS,aAAAC,MAAiB,uBAsB1B,eAAsBC,EAAeC,EAAyBC,EAAa,CACzE,MAAMC,EAAaD,EAAM,KAAI,EAAG,YAAW,EAC3C,GAAI,CAACC,EAAY,OAAO,KACxB,MAAMC,EAAU,MAAMH,EAAK,QAAO,EAwB5BI,EAAa,MAAMJ,EACtB,aAAY,EACZ,KAAMK,GAAQA,EAAI,IAAIH,CAAU,CAAC,EACjC,MAAOI,GAAkB,CACxB,GAAIT,EAAqBS,CAAK,EAAG,OAAO,KACxC,MAAMA,CACR,CAAC,EACH,GAAIF,EACF,OAAOA,EAAW,cAAgB,EAAIN,EAAU,MAAMK,EAAQ,QAAQC,EAAW,OAAO,CAAC,EAAI,KAS/F,MAAMG,EAAY,MAAMJ,EAAQ,kBAAkBD,CAAU,EAC5D,GAAIK,EAAW,OAAOT,EAAUS,CAAS,EACzC,MAAMC,EAAS,MAAML,EAAQ,WAAWD,CAAU,EAclD,OAAIM,GAAQ,eAAiB,MAAQA,EAAO,cAAc,KAAI,EAAG,YAAW,IAAON,EAAmB,KAC/FJ,EAAUU,CAAM,CACzB,CA9DsBC,EAAAV,EAAA,kBAmEtB,eAAsBW,EAAcV,EAAyBC,EAAa,CAExE,OADgB,MAAMF,EAAeC,EAAMC,CAAK,IAChC,IAAM,IACxB,CAHsBQ,EAAAC,EAAA,iBA0BtB,eAAsBC,EACpBX,EACAY,EACAC,EACAC,EAAW,CAGX,MAAMC,EAAU,MADA,MAAMf,EAAK,QAAO,GACJ,WAAW,CAAE,OAAAa,EAAQ,WAAAD,EAAY,IAAAE,CAAG,CAAE,EAGpE,OAAIC,IAAY,KAAa,MAK7B,MAAMf,EACH,aAAY,EACZ,KAAMK,GAAQA,EAAI,SAAS,CAAE,MAAOO,EAAY,OAAQG,EAAS,WAAY,GAAM,IAAAD,CAAG,CAAE,CAAC,EACzF,MAAOR,GAAkB,CAKxB,GAAI,CAAAT,EAAqBS,CAAK,EAC9B,MAAMA,CACR,CAAC,EACIP,EAAeC,EAAMY,CAAU,EACxC,CA3BsBH,EAAAE,EAAA",
|
|
6
|
+
"names": ["isMissingSchemaError", "summarize", "resolveAccount", "deps", "email", "normalized", "userDAO", "registered", "dao", "error", "byCurrent", "legacy", "__name", "resolveUserId", "registerAccount", "loginEmail", "anchor", "now", "created"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/identity",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.1",
|
|
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/d1": "1.
|
|
29
|
-
"@rexezuge/
|
|
30
|
-
"@rexezuge/
|
|
28
|
+
"@rexezuge/d1": "1.8.1",
|
|
29
|
+
"@rexezuge/errors": "1.8.1",
|
|
30
|
+
"@rexezuge/shared": "1.8.1"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "26.6.4",
|