@descix/platform-api 5.0.0 → 5.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@descix/platform-api",
3
- "version": "5.0.0",
3
+ "version": "5.1.0",
4
4
  "description": "Shared platform infrastructure: Firestore models, auth/session, permissions, entitlements, email",
5
5
  "repository": {
6
6
  "type": "git",
@@ -10,7 +10,8 @@
10
10
  "type": "module",
11
11
  "main": "src/index.js",
12
12
  "scripts": {
13
- "test:migration-receipt-email": "node --test --experimental-test-module-mocks tests/migration-receipt-email.test.js"
13
+ "test:migration-receipt-email": "node --test --experimental-test-module-mocks tests/migration-receipt-email.test.js",
14
+ "test:email-identity": "node --test --experimental-test-module-mocks tests/email-identity-owner.test.js"
14
15
  },
15
16
  "exports": {
16
17
  ".": "./src/index.js",
@@ -18,6 +18,7 @@ import {
18
18
  getCloudConfig,
19
19
  } from '@descix/cloud-core';
20
20
  import { sendVerificationEmail, normalizeEmail } from '../email/index.js';
21
+ import { EmailIdentityRefusal, EmailIdentityError } from '../models/index.js';
21
22
 
22
23
  const EMAIL_CODE_EXPIRY_MINUTES = 15;
23
24
  const EMAIL_CODE_MAX_ATTEMPTS = 5;
@@ -32,8 +33,28 @@ export const EmailVerificationRefusal = Object.freeze({
32
33
  EXPIRED: 'VERIFICATION_EXPIRED',
33
34
  ATTEMPTS_EXHAUSTED: 'VERIFICATION_ATTEMPTS_EXHAUSTED',
34
35
  INVALID: 'VERIFICATION_INVALID',
36
+ /** The record was requested by another account (or by none, when an account verifies). */
37
+ NOT_YOURS: EmailIdentityRefusal.VERIFICATION_NOT_YOURS,
38
+ /** The record pre-dates the account binding (no uid field): request a new code. */
39
+ UNBOUND: EmailIdentityRefusal.VERIFICATION_UNBOUND,
35
40
  });
36
41
 
42
+ /** A Firestore Timestamp (or Date) as a Date, or null. */
43
+ function asDate(value) {
44
+ if (!value) return null;
45
+ if (typeof value.toDate === 'function') return value.toDate();
46
+ return value instanceof Date ? value : null;
47
+ }
48
+
49
+ /** The requesting account of a verification call: a non-empty string uid, or null (no account). */
50
+ function requesterUid(uid) {
51
+ if (uid === undefined || uid === null) return null;
52
+ if (typeof uid !== 'string' || uid.length === 0) {
53
+ throw new Error('email verification: uid must be a non-empty string (the requesting account) or null');
54
+ }
55
+ return uid;
56
+ }
57
+
37
58
  /** An ERROR networkResponse that carries the refusal code (networkResponse ferries `code`). */
38
59
  function verificationRefusal(code, message) {
39
60
  return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, {
@@ -45,13 +66,20 @@ function verificationRefusal(code, message) {
45
66
  * Send an email verification code to the given address.
46
67
  * Generates a 6-digit code, hashes and stores it in Firestore, then emails it.
47
68
  *
69
+ * The record is bound to the requesting account: `uid` is stored on it (null for flows with no
70
+ * account, e.g. Discord link or a token-claim recipient), and every send rewrites it, so a new
71
+ * request always replaces an earlier binding. Only a record whose uid is the caller's account
72
+ * can attach the email to that account (assertEmailVerifiedFor).
73
+ *
48
74
  * @param {Object} params
49
75
  * @param {string} params.email - Email address to verify
76
+ * @param {string|null} [params.uid] - The requesting account's id (USERS doc id = sanitized credentialId)
50
77
  * @returns {Promise<Object>} networkResponse result
51
78
  */
52
79
  export async function sendEmailVerification(params) {
53
80
  const utils = getCloudConfig();
54
81
  const { email } = params;
82
+ const uid = requesterUid(params.uid);
55
83
  const normalized = normalizeEmail(email);
56
84
  if (!normalized || !normalized.includes('@')) {
57
85
  return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'Valid email address is required.');
@@ -71,6 +99,7 @@ export async function sendEmailVerification(params) {
71
99
  const db = new CacheFirestore();
72
100
  await db.put_doc(FirestoreCollections.EMAIL_VERIFICATIONS(), normalized, {
73
101
  email: normalized,
102
+ uid,
74
103
  code_hash: codeHash,
75
104
  expires_at: expiresAt,
76
105
  created_at: Timestamp.now(),
@@ -92,10 +121,12 @@ export async function sendEmailVerification(params) {
92
121
  * @param {Object} params
93
122
  * @param {string} params.email - Email address that was verified
94
123
  * @param {string} params.code - The 6-digit code to check
124
+ * @param {string|null} [params.uid] - The verifying account; must equal the record's uid
95
125
  * @returns {Promise<Object>} networkResponse result
96
126
  */
97
127
  export async function verifyEmailCode(params) {
98
128
  const { email, code } = params;
129
+ const uid = requesterUid(params.uid);
99
130
  const normalized = normalizeEmail(email);
100
131
  if (!normalized || !code) {
101
132
  return verificationRefusal(EmailVerificationRefusal.INPUT_REQUIRED, 'Email and code are required.');
@@ -105,8 +136,16 @@ export async function verifyEmailCode(params) {
105
136
  if (!record) {
106
137
  return verificationRefusal(EmailVerificationRefusal.NOT_FOUND, 'No verification code found. Please request a new code.');
107
138
  }
139
+ // Checked before the attempt counter: a caller that does not own the record never spends
140
+ // (or probes) its attempts.
141
+ if (uid !== null && !Object.prototype.hasOwnProperty.call(record, 'uid')) {
142
+ return verificationRefusal(EmailVerificationRefusal.UNBOUND, 'This verification code was issued before codes were tied to an account. Please request a new code.');
143
+ }
144
+ if ((record.uid ?? null) !== uid) {
145
+ return verificationRefusal(EmailVerificationRefusal.NOT_YOURS, 'This verification code was requested from a different account. Please request a new code.');
146
+ }
108
147
  const now = new Date();
109
- const expiresAt = record.expires_at?.toDate ? record.expires_at.toDate() : null;
148
+ const expiresAt = asDate(record.expires_at);
110
149
  if (expiresAt && expiresAt < now) {
111
150
  return verificationRefusal(EmailVerificationRefusal.EXPIRED, 'Verification code expired. Please request a new code.');
112
151
  }
@@ -125,3 +164,44 @@ export async function verifyEmailCode(params) {
125
164
  }
126
165
  return networkResponse(NetworkStatus.OK, LoginStatus.CONNECTED, { verified: true });
127
166
  }
167
+
168
+ /**
169
+ * The verification half of attaching an email to an account. Resolves when
170
+ * the EMAIL_VERIFICATIONS record for `email` was requested by `uid`, is verified, and is not past
171
+ * its expires_at (the code's expiry, EMAIL_CODE_EXPIRY_MINUTES after the send). Throws
172
+ * EmailIdentityError otherwise, with a reason per case; a record with no uid field pre-dates the
173
+ * binding and is refused, never grandfathered.
174
+ *
175
+ * @param {string} uid - The account attaching the email
176
+ * @param {string} email - The email being attached
177
+ * @returns {Promise<{ email: string }>} the normalized email
178
+ */
179
+ export async function assertEmailVerifiedFor(uid, email) {
180
+ if (!uid || typeof uid !== 'string') throw new Error('assertEmailVerifiedFor: uid is required');
181
+ const normalized = normalizeEmail(email);
182
+ if (!normalized) throw new Error('assertEmailVerifiedFor: email is required');
183
+ const db = new CacheFirestore();
184
+ const record = await db.get_doc(FirestoreCollections.EMAIL_VERIFICATIONS(), normalized);
185
+ if (!record) {
186
+ throw new EmailIdentityError(EmailIdentityRefusal.NOT_VERIFIED,
187
+ 'This email has not been verified. Enter the code we sent you before accepting the Terms of Service.');
188
+ }
189
+ if (!Object.prototype.hasOwnProperty.call(record, 'uid')) {
190
+ throw new EmailIdentityError(EmailIdentityRefusal.VERIFICATION_UNBOUND,
191
+ 'This email verification was made before codes were tied to an account. Request a new code and verify again.');
192
+ }
193
+ if (record.uid !== uid) {
194
+ throw new EmailIdentityError(EmailIdentityRefusal.VERIFICATION_NOT_YOURS,
195
+ 'This email was verified from a different account. Request a new code from this account and verify again.');
196
+ }
197
+ const expiresAt = asDate(record.expires_at);
198
+ if (!expiresAt || expiresAt <= new Date()) {
199
+ throw new EmailIdentityError(EmailIdentityRefusal.VERIFICATION_EXPIRED,
200
+ 'Your email verification has expired. Request a new code and verify again.');
201
+ }
202
+ if (record.verified !== true) {
203
+ throw new EmailIdentityError(EmailIdentityRefusal.NOT_VERIFIED,
204
+ 'This email has not been verified. Enter the code we sent you before accepting the Terms of Service.');
205
+ }
206
+ return { email: normalized };
207
+ }
package/src/auth/index.js CHANGED
@@ -5,5 +5,5 @@
5
5
  */
6
6
 
7
7
  export { createUserSession } from './session.js';
8
- export { sendEmailVerification, verifyEmailCode, EmailVerificationRefusal } from './emailVerification.js';
8
+ export { sendEmailVerification, verifyEmailCode, assertEmailVerifiedFor, EmailVerificationRefusal } from './emailVerification.js';
9
9
  export { migrateUserIfNeeded } from './migration.js';
package/src/index.js CHANGED
@@ -18,6 +18,8 @@ export {
18
18
  Role,
19
19
  App,
20
20
  User,
21
+ EmailIdentityRefusal,
22
+ EmailIdentityError,
21
23
  Community,
22
24
  UserCommunityStats,
23
25
  GuildSettings,
@@ -38,6 +40,7 @@ export {
38
40
  createUserSession,
39
41
  sendEmailVerification,
40
42
  verifyEmailCode,
43
+ assertEmailVerifiedFor,
41
44
  EmailVerificationRefusal,
42
45
  migrateUserIfNeeded
43
46
  } from './auth/index.js';
@@ -1241,7 +1241,7 @@
1241
1241
  "options": [
1242
1242
  {
1243
1243
  "flags": "-a, --app <id>",
1244
- "description": "App ID",
1244
+ "description": "App ID (in a gateway workspace, the listed repo holding this app supplies the corpus manifest, the git tree walked and the sync-state)",
1245
1245
  "required": true
1246
1246
  },
1247
1247
  {
@@ -1269,7 +1269,7 @@
1269
1269
  "options": [
1270
1270
  {
1271
1271
  "flags": "-a, --app <id>",
1272
- "description": "App ID",
1272
+ "description": "App ID (in a gateway workspace, the listed repo holding this app supplies the corpus manifest, the git tree walked and the sync-state)",
1273
1273
  "required": true
1274
1274
  },
1275
1275
  {
@@ -1320,6 +1320,29 @@
1320
1320
  ],
1321
1321
  "runbookAnchor": "#_6-knowledge-bases"
1322
1322
  },
1323
+ {
1324
+ "verbPath": "kb create",
1325
+ "description": "Create a knowledge base on an existing app (refuses a KB that already exists)",
1326
+ "arguments": [],
1327
+ "options": [
1328
+ {
1329
+ "flags": "-a, --app <app_id>",
1330
+ "description": "App ID",
1331
+ "required": true
1332
+ },
1333
+ {
1334
+ "flags": "-k, --kb <kb_name>",
1335
+ "description": "Name of the KB to create",
1336
+ "required": true
1337
+ },
1338
+ {
1339
+ "flags": "--system-instructions <text>",
1340
+ "description": "System instructions for the new KB",
1341
+ "required": false
1342
+ }
1343
+ ],
1344
+ "runbookAnchor": "#_6-knowledge-bases"
1345
+ },
1323
1346
  {
1324
1347
  "verbPath": "kb delete",
1325
1348
  "description": "Delete a knowledge base registry doc (refuses a non-empty KB unless --force)",
@@ -1350,7 +1373,7 @@
1350
1373
  "options": [
1351
1374
  {
1352
1375
  "flags": "-a, --app <id>",
1353
- "description": "App ID",
1376
+ "description": "App ID (in a gateway workspace, the listed repo holding this app supplies the sync-state)",
1354
1377
  "required": true
1355
1378
  },
1356
1379
  {
@@ -1632,6 +1655,20 @@
1632
1655
  ],
1633
1656
  "runbookAnchor": null
1634
1657
  },
1658
+ {
1659
+ "verbPath": "plugin check",
1660
+ "description": "Check a Claude plugin or marketplace directory against the limits claude.ai enforces on sync, before you publish it. Exit 0 clean, 1 on a violation, 2 when a file cannot be read.",
1661
+ "arguments": [
1662
+ {
1663
+ "name": "dir",
1664
+ "required": false,
1665
+ "variadic": false,
1666
+ "description": "Plugin or marketplace directory (default: the current directory)"
1667
+ }
1668
+ ],
1669
+ "options": [],
1670
+ "runbookAnchor": "#the-app-s-claude-plugin"
1671
+ },
1635
1672
  {
1636
1673
  "verbPath": "purchases",
1637
1674
  "description": "List your purchased communities and apps",
@@ -177,6 +177,10 @@ export const NATIVE_MCP_TOOLS = Object.freeze([
177
177
  // vocabulary, byte caps) rather than restated here — one owner for the
178
178
  // advertised contract and the enforced policy, so the two cannot drift.
179
179
  media: mediaParamSchema(),
180
+ // The chat pane's page context. Its fields and limits have ONE owner,
181
+ // @descix/app-sdk/chat-context, which the Cloud handler runs on every value it
182
+ // receives; they are deliberately not restated here.
183
+ page_context: { type: 'object', description: 'The page the reader has open, exactly as @descix/app-sdk/chat-context withChatContext() builds it from an app page\'s DeSciX.setChatContext(). The server checks it with that module and adds it ahead of the question, labelled as data supplied by the app page and not as instructions; a value that breaks the module\'s rules is refused, naming the field. It selects no knowledge base and no document: those travel in knowledgebase_names and doc_ids.' },
180
184
  // ws-c3-librarian: a WORKSTREAM is a conversational room (the Discord room model
181
185
  // generalised), so its thread owner is SERVER-derived from the id the caller
182
186
  // names — never from a caller-supplied owner, which apiFront still strips.
@@ -15,9 +15,9 @@
15
15
  * That is the silent-failure class. The schema IS the published contract, so anything not in
16
16
  * it is an ERROR, named out loud, with the nearest valid parameter suggested.
17
17
  *
18
- * Dependency-free leaf: imported by BOTH the Cloud MCP router (apiFront tools/call + the
19
- * execute_remote_command gateway, which feed it the per-command commandMeta inputSchema) and
20
- * the CLI stdio MCP server (which feeds it the NATIVE_MCP_TOOLS inputSchema). ONE validator,
18
+ * Dependency-free leaf: imported by BOTH Cloud's boundary (every door — the direct /apifront
19
+ * route, apiFront tools/call and the execute_remote_command gateway — which feed it the
20
+ * per-command published inputSchema) and the CLI stdio MCP server (which feeds it the NATIVE_MCP_TOOLS inputSchema). ONE validator,
21
21
  * one message format, no parallel implementations.
22
22
  */
23
23
 
@@ -66,8 +66,8 @@ export const PARAM_ALIASES = Object.freeze({
66
66
  * WHAT QUALIFIES. A key belongs here iff PLATFORM code WRITES it into a params bag after the
67
67
  * caller's bag has been taken, i.e. there is an INJECTOR. Two consumers read this list and they
68
68
  * sit on opposite sides of that write:
69
- * - the BOUNDARY validators (`validateParamsAgainstSchema`, reached from MCP tools/call and the
70
- * execute_remote_command gateway) run BEFORE injection, so the list is what keeps a
69
+ * - the BOUNDARY validators (`validateParamsAgainstSchema`, reached from the direct /apifront
70
+ * route, MCP tools/call and the execute_remote_command gateway) run BEFORE injection, so the list is what keeps a
71
71
  * RE-validation of an already-decorated bag from failing;
72
72
  * - the HANDLER-level guard (Cloud `assertKnownParams`) and every downstream mesh service run
73
73
  * AFTER injection, so the list is what stops a framework key being reported as an unknown
@@ -176,8 +176,9 @@ export function isPlatformInjectedParam(key) {
176
176
  * PLATFORM's own writes and are waved; everything else is still refused by
177
177
  * name.
178
178
  *
179
- * WHY THE PHASE IS PART OF THE CALL AND IS NEVER INFERRED (measured 2026-08-26). BOTH MCP doors
180
- * validate BEFORE injection — apiFront.js tools/call against the caller's `arguments`, and
179
+ * WHY THE PHASE IS PART OF THE CALL AND IS NEVER INFERRED (measured 2026-08-26). Every Cloud door
180
+ * validates BEFORE injection — apiFront.js cloud_function_route against the caller's
181
+ * `requestJSON.params`, apiFront.js tools/call against the caller's `arguments`, and
181
182
  * serviceCommands.js `execute_remote_command` against the caller's inner bag. Waving the owner's
182
183
  * keys THERE let a caller-authored `_descix: { user: { id: 'VICTIM' } }` ride a schema that
183
184
  * declares no such property straight through the boundary, and `_descix.user` is read AS IDENTITY
@@ -25,7 +25,7 @@ export const PLATFORM_BASICS_SUMMARY = [
25
25
  "PLATFORM BASICS — the identity model everything else derives from:",
26
26
  "1. A community IS its ERC-20 token, per environment: community_id == app_id == lowercased(token_symbol). One token symbol, one on-chain contract, one community.",
27
27
  "2. Every community is itself an app (its default app), and every app belongs to exactly one community. Sub-apps are named {community_id}-{short_name} (e.g. egpt-frqtl, daita-docs); the short name never contains '-'.",
28
- "3. 'descix' is a BRAND, never an identifier. The community branded 'DeSciX' has id 'daita' (token DAITA). No app or community id is ever 'descix' or 'descix-*'.",
28
+ "3. 'descix' is a BRAND, never an identifier. The root community is labelled DAITA with community_id 'daita' (== lowercased token symbol DAITA); DeSciX is the platform brand, never an id. No app or community id is ever 'descix' or 'descix-*'.",
29
29
  "4. Identifiers are environment-invariant; records are per-environment. A community or app existing in one environment (dev/demo/prod) says nothing about another — each env materializes its own records.",
30
30
  "5. An app is three slots: site/ (any web framework), assets/ (its agent instructions and description), microservice/ (optional backend). Each app has knowledge bases; RAG answers are metered against USD AI credits.",
31
31
  "6. Developers build with the published @descix/cli and @descix/app-sdk as external users: `app init` creates the record + default KB + scaffold, `descix serve` runs it locally, `kb corpus sync` publishes the KB, `site upload` publishes the site. Start with `descix tell-me-how`.",
@@ -65,10 +65,10 @@ Everything on DeSciX derives from one model:
65
65
  ## Brand vs identifier
66
66
 
67
67
  \`descix\` is the platform's **brand and infrastructure namespace** (the descix.net domain,
68
- the \`descix\` CLI) — it is **never an identifier**. The community branded "DeSciX" has
69
- \`community_id\` and \`app_id\` \`daita\` (its token is DAITA). There is no \`descix\`
70
- community, so no app is ever named \`descix\` or \`descix-*\`. Display names are free-form
71
- ("DeSciX" stays a display name); ids are always the lowercased token symbol.
68
+ the \`descix\` CLI) — it is **never an identifier**. The root community is labelled DAITA,
69
+ with \`community_id\` and \`app_id\` \`daita\` (== the lowercased token symbol DAITA); DeSciX
70
+ is the platform brand, never an id. There is no \`descix\` community, so no app is ever named
71
+ \`descix\` or \`descix-*\`. Display names are free-form; ids are always the lowercased token symbol.
72
72
 
73
73
  ## What an app is
74
74
 
@@ -65,7 +65,7 @@ const FIRST_CONTACT_SCRIPT = Object.freeze([
65
65
  // EGPT is one example effort. Point the assistant at the DAITA community's own RAG agent so
66
66
  // it learns what DeSciX is and how the tokenomics work from the platform's own source,
67
67
  // rather than reconstructing it from memory (retrieval-first, applied to onboarding).
68
- do: "The first step is to LEARN what DeSciX is from the platform itself: call ask_question_to_app({ app_id: 'daita', user_input: 'What is DeSciX, and how do its tokenomics work — how do researchers and creators earn from their contributions?' }). DAITA is the concept/platform home (the community branded 'DeSciX'); EGPT is one example effort inside it, not the platform itself. Summarize what DAITA returns for the user and cite it — do not answer this from your own memory.",
68
+ do: "The first step is to LEARN what DeSciX is from the platform itself: call ask_question_to_app({ app_id: 'daita', user_input: 'What is DeSciX, and how do its tokenomics work — how do researchers and creators earn from their contributions?' }). DAITA is the concept/platform home (the root community, labelled DAITA with community_id 'daita' == lowercased token symbol; DeSciX is the platform brand, never an id); EGPT is one example effort inside it, not the platform itself. Summarize what DAITA returns for the user and cite it — do not answer this from your own memory.",
69
69
  }),
70
70
  Object.freeze({
71
71
  step: 'ask_interest',
@@ -24,10 +24,36 @@ import {
24
24
  ProductTypes,
25
25
  getCloudConfig,
26
26
  } from '@descix/cloud-core';
27
+ import { normalizeEmail } from '../email/index.js';
27
28
 
28
- // Inline normalizeEmail — avoids circular dependency with email module
29
- function normalizeEmail(email) {
30
- return email ? email.trim().toLowerCase() : null;
29
+ /**
30
+ * Why an email could not be attached to an account (one email, one account). Every refusal is
31
+ * an EmailIdentityError carrying one of these as `code`; a consumer branches on the code, never
32
+ * on the message.
33
+ */
34
+ export const EmailIdentityRefusal = Object.freeze({
35
+ /** No verified EMAIL_VERIFICATIONS record for this email. */
36
+ NOT_VERIFIED: 'EMAIL_NOT_VERIFIED',
37
+ /** The verification record was requested by a different account. */
38
+ VERIFICATION_NOT_YOURS: 'EMAIL_VERIFICATION_NOT_YOURS',
39
+ /** The verification record is past its expires_at. */
40
+ VERIFICATION_EXPIRED: 'EMAIL_VERIFICATION_EXPIRED',
41
+ /** The verification record pre-dates the account binding (no uid field): request a new code. */
42
+ VERIFICATION_UNBOUND: 'EMAIL_VERIFICATION_UNBOUND',
43
+ /** Another (passkey) account already holds this email. */
44
+ ALREADY_REGISTERED: 'EMAIL_ALREADY_REGISTERED',
45
+ /** The only other holder is a legacy email-keyed account (USERS doc id = the email; no passkey). */
46
+ ALREADY_REGISTERED_LEGACY: 'EMAIL_ALREADY_REGISTERED_LEGACY',
47
+ });
48
+
49
+ /** A refused email-to-account attachment. `statusCode` is the HTTP status a handler answers with. */
50
+ export class EmailIdentityError extends Error {
51
+ constructor(code, message) {
52
+ super(message);
53
+ this.name = 'EmailIdentityError';
54
+ this.code = code;
55
+ this.statusCode = 403;
56
+ }
31
57
  }
32
58
 
33
59
  // --- Helper Functions ---
@@ -663,14 +689,58 @@ export class User {
663
689
  }
664
690
  }
665
691
 
692
+ /** The PROVIDER_INDEX doc id for an email: `email_<sanitizeProviderId(normalized)>`. */
693
+ static emailIndexKey(email) {
694
+ const normalized = normalizeEmail(email);
695
+ if (!normalized) throw new Error('User.emailIndexKey: an email is required');
696
+ return `email_${User.sanitizeProviderId(normalized)}`;
697
+ }
698
+
699
+ /**
700
+ * The one-email-one-account rule. Resolves when no
701
+ * account other than `uid` holds `email`. "Holds" = the email ProviderIndex row points at
702
+ * another account, another USERS doc carries the email as `email` or `verified_email`
703
+ * (accounts that pre-date the index row), or a USERS doc is keyed by the email itself (the
704
+ * legacy email-keyed form, which has no passkey). Throws EmailIdentityError
705
+ * ALREADY_REGISTERED_LEGACY when every other holder is that legacy form, else
706
+ * ALREADY_REGISTERED. A failed read throws: an unanswerable question is never read as "free".
707
+ */
708
+ static async assertEmailFreeFor(uid, email) {
709
+ if (!uid || typeof uid !== 'string') throw new Error('User.assertEmailFreeFor: uid is required');
710
+ const normalized = normalizeEmail(email);
711
+ if (!normalized) throw new Error('User.assertEmailFreeFor: email is required');
712
+ const db = new CacheFirestore();
713
+ const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), User.emailIndexKey(normalized));
714
+ const holders = new Set();
715
+ if (index?.descix_user_id) holders.add(index.descix_user_id);
716
+ if (await db.get_doc(FirestoreCollections.USERS(), normalized)) holders.add(normalized);
717
+ for (const field of ['email', 'verified_email']) {
718
+ const docs = await db.get_docs_with_ids(FirestoreCollections.USERS(), null, [[field, '==', normalized]]);
719
+ if (!Array.isArray(docs)) {
720
+ throw new Error(`User.assertEmailFreeFor: the USERS query on ${field} failed; cannot tell whether the email is free`);
721
+ }
722
+ for (const d of docs) holders.add(d._id);
723
+ }
724
+ holders.delete(uid);
725
+ if (holders.size === 0) return;
726
+ if ([...holders].every((id) => id === normalized)) {
727
+ throw new EmailIdentityError(
728
+ EmailIdentityRefusal.ALREADY_REGISTERED_LEGACY,
729
+ 'This email belongs to a DeSciX account created before passkeys. Use a different email; linking that account to a passkey is not available yet.'
730
+ );
731
+ }
732
+ throw new EmailIdentityError(
733
+ EmailIdentityRefusal.ALREADY_REGISTERED,
734
+ 'This email belongs to another account. Sign in with that account\'s passkey instead.'
735
+ );
736
+ }
737
+
666
738
  static async findByEmail(email) {
667
739
  if (!email) return null;
668
740
  const normalized = normalizeEmail(email);
669
741
  if (!normalized) return null;
670
742
  const db = new CacheFirestore();
671
- const sanitizedId = User.sanitizeProviderId(normalized);
672
- const emailIndexKey = `email_${sanitizedId}`;
673
- const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), emailIndexKey);
743
+ const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), User.emailIndexKey(normalized));
674
744
  if (index && index.descix_user_id) {
675
745
  return await User.from_firestore(index.descix_user_id);
676
746
  }
@@ -987,18 +1057,42 @@ export class User {
987
1057
  gate_passed_at: Timestamp.now(),
988
1058
  gate_source: gate_source
989
1059
  };
1060
+ const normalized = verified_email ? normalizeEmail(verified_email) : null;
1061
+ if (normalized) {
1062
+ // One email, one account: refuse before any write, then write the
1063
+ // email ProviderIndex row findByEmail reads, and release this account's previous row.
1064
+ await User.assertEmailFreeFor(this.id, normalized);
1065
+ const key = User.emailIndexKey(normalized);
1066
+ const wrote = await this.db.put_doc(FirestoreCollections.PROVIDER_INDEX(), key, {
1067
+ descix_user_id: this.id,
1068
+ provider_type: 'email',
1069
+ provider_id: normalized,
1070
+ linked_at: Timestamp.now()
1071
+ });
1072
+ if (wrote !== true) {
1073
+ throw new Error(`commitTosAndConnect: the email ProviderIndex write (${key}) failed; the email was not committed`);
1074
+ }
1075
+ const previous = normalizeEmail(this.email);
1076
+ if (previous && previous !== normalized) {
1077
+ const prevKey = User.emailIndexKey(previous);
1078
+ const prevRow = await this.db.get_doc(FirestoreCollections.PROVIDER_INDEX(), prevKey);
1079
+ if (prevRow?.descix_user_id === this.id) {
1080
+ await this.db.delete_doc(FirestoreCollections.PROVIDER_INDEX(), prevKey);
1081
+ }
1082
+ }
1083
+ updates.verified_email = normalized;
1084
+ updates.email = normalized;
1085
+ }
1086
+ const result = await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
990
1087
  this.tos_accepted_at = updates.tos_accepted_at;
991
1088
  this.tos_version = updates.tos_version;
992
1089
  this.gate_passed_at = updates.gate_passed_at;
993
1090
  this.gate_source = updates.gate_source;
994
- if (verified_email) {
995
- const normalized = normalizeEmail(verified_email);
996
- updates.verified_email = normalized;
997
- updates.email = normalized;
1091
+ if (normalized) {
998
1092
  this.verified_email = normalized;
999
1093
  this.email = normalized;
1000
1094
  }
1001
- return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1095
+ return result;
1002
1096
  }
1003
1097
 
1004
1098
  isConnected() {