@descix/platform-api 5.0.1 → 5.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@descix/platform-api",
3
- "version": "5.0.1",
3
+ "version": "5.1.1",
4
4
  "description": "Shared platform infrastructure: Firestore models, auth/session, permissions, entitlements, email",
5
5
  "repository": {
6
6
  "type": "git",
@@ -10,7 +10,9 @@
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",
15
+ "test:user-recovery": "node --test --experimental-test-module-mocks tests/user-recovery-confirmed-owner.test.js"
14
16
  },
15
17
  "exports": {
16
18
  ".": "./src/index.js",
@@ -40,7 +42,7 @@
40
42
  "node": ">=24.0.0"
41
43
  },
42
44
  "dependencies": {
43
- "@descix/cloud-core": "^2.0.0",
45
+ "@descix/cloud-core": "^2.0.4",
44
46
  "google-auth-library": "^10.5.0",
45
47
  "googleapis": "^169.0.0"
46
48
  }
@@ -5,9 +5,17 @@
5
5
  * Generates codes, stores hashed values in Firestore, sends via Gmail.
6
6
  *
7
7
  * Config values loaded at call time via getCloudConfig() from @descix/cloud-core.
8
+ *
9
+ * Local code sink: on a developer machine only, sendEmailVerification ALSO appends the plain code
10
+ * to the JSON-lines file named by LOCAL_VERIFICATION_CODE_SINK, so a local end-to-end spec can
11
+ * complete email verification without a mailbox. The key is a cloud-core local-only key
12
+ * (config-schema.json local_only_keys): admitted only from dev-overrides.json when
13
+ * isManagedCloudRuntime is false, and refused at boot everywhere else.
8
14
  */
9
15
 
10
16
  import crypto from 'crypto';
17
+ import fs from 'fs';
18
+ import path from 'path';
11
19
  import {
12
20
  CacheFirestore,
13
21
  FirestoreCollections,
@@ -18,6 +26,7 @@ import {
18
26
  getCloudConfig,
19
27
  } from '@descix/cloud-core';
20
28
  import { sendVerificationEmail, normalizeEmail } from '../email/index.js';
29
+ import { EmailIdentityRefusal, EmailIdentityError } from '../models/index.js';
21
30
 
22
31
  const EMAIL_CODE_EXPIRY_MINUTES = 15;
23
32
  const EMAIL_CODE_MAX_ATTEMPTS = 5;
@@ -32,8 +41,28 @@ export const EmailVerificationRefusal = Object.freeze({
32
41
  EXPIRED: 'VERIFICATION_EXPIRED',
33
42
  ATTEMPTS_EXHAUSTED: 'VERIFICATION_ATTEMPTS_EXHAUSTED',
34
43
  INVALID: 'VERIFICATION_INVALID',
44
+ /** The record was requested by another account (or by none, when an account verifies). */
45
+ NOT_YOURS: EmailIdentityRefusal.VERIFICATION_NOT_YOURS,
46
+ /** The record pre-dates the account binding (no uid field): request a new code. */
47
+ UNBOUND: EmailIdentityRefusal.VERIFICATION_UNBOUND,
35
48
  });
36
49
 
50
+ /** A Firestore Timestamp (or Date) as a Date, or null. */
51
+ function asDate(value) {
52
+ if (!value) return null;
53
+ if (typeof value.toDate === 'function') return value.toDate();
54
+ return value instanceof Date ? value : null;
55
+ }
56
+
57
+ /** The requesting account of a verification call: a non-empty string uid, or null (no account). */
58
+ function requesterUid(uid) {
59
+ if (uid === undefined || uid === null) return null;
60
+ if (typeof uid !== 'string' || uid.length === 0) {
61
+ throw new Error('email verification: uid must be a non-empty string (the requesting account) or null');
62
+ }
63
+ return uid;
64
+ }
65
+
37
66
  /** An ERROR networkResponse that carries the refusal code (networkResponse ferries `code`). */
38
67
  function verificationRefusal(code, message) {
39
68
  return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, {
@@ -41,17 +70,82 @@ function verificationRefusal(code, message) {
41
70
  });
42
71
  }
43
72
 
73
+ /** The config key naming the local code sink file (a cloud-core local-only key). */
74
+ export const LOCAL_VERIFICATION_CODE_SINK_KEY = 'LOCAL_VERIFICATION_CODE_SINK';
75
+
76
+ /**
77
+ * The local code sink path of this process, or null when it has none. Throws when the key is set
78
+ * on a managed cloud runtime (cloud-core refuses that config at boot; reaching here means the
79
+ * refusal was bypassed) or is not an absolute path. Resolved BEFORE any side effect of a send.
80
+ */
81
+ function localVerificationCodeSink(utils) {
82
+ const sinkPath = utils[LOCAL_VERIFICATION_CODE_SINK_KEY];
83
+ if (sinkPath === undefined || sinkPath === null) return null;
84
+ if (utils.isManagedCloudRuntime !== false) {
85
+ throw new Error(`${LOCAL_VERIFICATION_CODE_SINK_KEY} is set but this process is not on a developer machine ` +
86
+ `(isManagedCloudRuntime=${utils.isManagedCloudRuntime}); refusing to send a verification code.`);
87
+ }
88
+ if (typeof sinkPath !== 'string' || !path.isAbsolute(sinkPath)) {
89
+ throw new Error(`${LOCAL_VERIFICATION_CODE_SINK_KEY} must be an absolute file path (dev-overrides.json); ` +
90
+ `got ${JSON.stringify(sinkPath)}.`);
91
+ }
92
+ return sinkPath;
93
+ }
94
+
95
+ /**
96
+ * Append one sent code to the local code sink at `sinkPath` (from localVerificationCodeSink).
97
+ * The file is created by this function with mode 600 (parent directories 700); an existing file
98
+ * readable by group or other is refused, never silently used. The code is never logged.
99
+ *
100
+ * Line contract (JSON, one object per line):
101
+ * { email, code, requested_by, expires_at, timestamp }
102
+ * email normalized address (the EMAIL_VERIFICATIONS doc id)
103
+ * code the plain 6-digit code verifyEmailCode accepts
104
+ * requested_by the requesting account's uid, or null for an account-less send
105
+ * expires_at ISO-8601 expiry of the code
106
+ * timestamp ISO-8601 time the line was written
107
+ * The newest line for an email is the live code: every send replaces the stored hash.
108
+ */
109
+ function writeLocalVerificationCode(sinkPath, { email, code, uid, expiresAt }) {
110
+ fs.mkdirSync(path.dirname(sinkPath), { recursive: true, mode: 0o700 });
111
+ const fd = fs.openSync(sinkPath, 'a', 0o600);
112
+ try {
113
+ const mode = fs.fstatSync(fd).mode & 0o777;
114
+ if (mode & 0o077) {
115
+ throw new Error(`${LOCAL_VERIFICATION_CODE_SINK_KEY} file ${sinkPath} has mode ${mode.toString(8)}; ` +
116
+ 'it must be 600. Delete it and let the sink create it.');
117
+ }
118
+ fs.writeSync(fd, JSON.stringify({
119
+ email,
120
+ code,
121
+ requested_by: uid,
122
+ expires_at: expiresAt.toISOString(),
123
+ timestamp: new Date().toISOString(),
124
+ }) + '\n');
125
+ } finally {
126
+ fs.closeSync(fd);
127
+ }
128
+ }
129
+
44
130
  /**
45
131
  * Send an email verification code to the given address.
46
- * Generates a 6-digit code, hashes and stores it in Firestore, then emails it.
132
+ * Generates a 6-digit code, hashes and stores it in Firestore, then emails it; on a developer
133
+ * machine with LOCAL_VERIFICATION_CODE_SINK set, also appends it to the local code sink.
134
+ *
135
+ * The record is bound to the requesting account: `uid` is stored on it (null for flows with no
136
+ * account, e.g. Discord link or a token-claim recipient), and every send rewrites it, so a new
137
+ * request always replaces an earlier binding. Only a record whose uid is the caller's account
138
+ * can attach the email to that account (assertEmailVerifiedFor).
47
139
  *
48
140
  * @param {Object} params
49
141
  * @param {string} params.email - Email address to verify
142
+ * @param {string|null} [params.uid] - The requesting account's id (USERS doc id = sanitized credentialId)
50
143
  * @returns {Promise<Object>} networkResponse result
51
144
  */
52
145
  export async function sendEmailVerification(params) {
53
146
  const utils = getCloudConfig();
54
147
  const { email } = params;
148
+ const uid = requesterUid(params.uid);
55
149
  const normalized = normalizeEmail(email);
56
150
  if (!normalized || !normalized.includes('@')) {
57
151
  return networkResponse(NetworkStatus.ERROR, LoginStatus.AUTH_FAILED, 'Valid email address is required.');
@@ -64,6 +158,8 @@ export async function sendEmailVerification(params) {
64
158
  );
65
159
  }
66
160
 
161
+ const sinkPath = localVerificationCodeSink(utils);
162
+
67
163
  const code = crypto.randomInt(100000, 999999).toString();
68
164
  const codeHash = crypto.createHash('sha256').update(code).digest('hex');
69
165
  const expiresAt = Timestamp.fromDate(new Date(Date.now() + EMAIL_CODE_EXPIRY_MINUTES * 60 * 1000));
@@ -71,6 +167,7 @@ export async function sendEmailVerification(params) {
71
167
  const db = new CacheFirestore();
72
168
  await db.put_doc(FirestoreCollections.EMAIL_VERIFICATIONS(), normalized, {
73
169
  email: normalized,
170
+ uid,
74
171
  code_hash: codeHash,
75
172
  expires_at: expiresAt,
76
173
  created_at: Timestamp.now(),
@@ -80,6 +177,8 @@ export async function sendEmailVerification(params) {
80
177
 
81
178
  await sendVerificationEmail(normalized, code, EMAIL_CODE_EXPIRY_MINUTES);
82
179
 
180
+ if (sinkPath) writeLocalVerificationCode(sinkPath, { email: normalized, code, uid, expiresAt: expiresAt.toDate() });
181
+
83
182
  return networkResponse(NetworkStatus.OK, LoginStatus.CONNECTED, {
84
183
  sent: true,
85
184
  expires_in_minutes: EMAIL_CODE_EXPIRY_MINUTES
@@ -92,10 +191,12 @@ export async function sendEmailVerification(params) {
92
191
  * @param {Object} params
93
192
  * @param {string} params.email - Email address that was verified
94
193
  * @param {string} params.code - The 6-digit code to check
194
+ * @param {string|null} [params.uid] - The verifying account; must equal the record's uid
95
195
  * @returns {Promise<Object>} networkResponse result
96
196
  */
97
197
  export async function verifyEmailCode(params) {
98
198
  const { email, code } = params;
199
+ const uid = requesterUid(params.uid);
99
200
  const normalized = normalizeEmail(email);
100
201
  if (!normalized || !code) {
101
202
  return verificationRefusal(EmailVerificationRefusal.INPUT_REQUIRED, 'Email and code are required.');
@@ -105,8 +206,16 @@ export async function verifyEmailCode(params) {
105
206
  if (!record) {
106
207
  return verificationRefusal(EmailVerificationRefusal.NOT_FOUND, 'No verification code found. Please request a new code.');
107
208
  }
209
+ // Checked before the attempt counter: a caller that does not own the record never spends
210
+ // (or probes) its attempts.
211
+ if (uid !== null && !Object.prototype.hasOwnProperty.call(record, 'uid')) {
212
+ return verificationRefusal(EmailVerificationRefusal.UNBOUND, 'This verification code was issued before codes were tied to an account. Please request a new code.');
213
+ }
214
+ if ((record.uid ?? null) !== uid) {
215
+ return verificationRefusal(EmailVerificationRefusal.NOT_YOURS, 'This verification code was requested from a different account. Please request a new code.');
216
+ }
108
217
  const now = new Date();
109
- const expiresAt = record.expires_at?.toDate ? record.expires_at.toDate() : null;
218
+ const expiresAt = asDate(record.expires_at);
110
219
  if (expiresAt && expiresAt < now) {
111
220
  return verificationRefusal(EmailVerificationRefusal.EXPIRED, 'Verification code expired. Please request a new code.');
112
221
  }
@@ -125,3 +234,44 @@ export async function verifyEmailCode(params) {
125
234
  }
126
235
  return networkResponse(NetworkStatus.OK, LoginStatus.CONNECTED, { verified: true });
127
236
  }
237
+
238
+ /**
239
+ * The verification half of attaching an email to an account. Resolves when
240
+ * the EMAIL_VERIFICATIONS record for `email` was requested by `uid`, is verified, and is not past
241
+ * its expires_at (the code's expiry, EMAIL_CODE_EXPIRY_MINUTES after the send). Throws
242
+ * EmailIdentityError otherwise, with a reason per case; a record with no uid field pre-dates the
243
+ * binding and is refused, never grandfathered.
244
+ *
245
+ * @param {string} uid - The account attaching the email
246
+ * @param {string} email - The email being attached
247
+ * @returns {Promise<{ email: string }>} the normalized email
248
+ */
249
+ export async function assertEmailVerifiedFor(uid, email) {
250
+ if (!uid || typeof uid !== 'string') throw new Error('assertEmailVerifiedFor: uid is required');
251
+ const normalized = normalizeEmail(email);
252
+ if (!normalized) throw new Error('assertEmailVerifiedFor: email is required');
253
+ const db = new CacheFirestore();
254
+ const record = await db.get_doc(FirestoreCollections.EMAIL_VERIFICATIONS(), normalized);
255
+ if (!record) {
256
+ throw new EmailIdentityError(EmailIdentityRefusal.NOT_VERIFIED,
257
+ 'This email has not been verified. Enter the code we sent you before accepting the Terms of Service.');
258
+ }
259
+ if (!Object.prototype.hasOwnProperty.call(record, 'uid')) {
260
+ throw new EmailIdentityError(EmailIdentityRefusal.VERIFICATION_UNBOUND,
261
+ 'This email verification was made before codes were tied to an account. Request a new code and verify again.');
262
+ }
263
+ if (record.uid !== uid) {
264
+ throw new EmailIdentityError(EmailIdentityRefusal.VERIFICATION_NOT_YOURS,
265
+ 'This email was verified from a different account. Request a new code from this account and verify again.');
266
+ }
267
+ const expiresAt = asDate(record.expires_at);
268
+ if (!expiresAt || expiresAt <= new Date()) {
269
+ throw new EmailIdentityError(EmailIdentityRefusal.VERIFICATION_EXPIRED,
270
+ 'Your email verification has expired. Request a new code and verify again.');
271
+ }
272
+ if (record.verified !== true) {
273
+ throw new EmailIdentityError(EmailIdentityRefusal.NOT_VERIFIED,
274
+ 'This email has not been verified. Enter the code we sent you before accepting the Terms of Service.');
275
+ }
276
+ return { email: normalized };
277
+ }
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';
@@ -1655,6 +1655,20 @@
1655
1655
  ],
1656
1656
  "runbookAnchor": null
1657
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
+ },
1658
1672
  {
1659
1673
  "verbPath": "purchases",
1660
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 ---
@@ -585,6 +611,7 @@ export class User {
585
611
  user.migrated_to = user_doc.migrated_to || null;
586
612
  user.migrated_at = user_doc.migrated_at || null;
587
613
  user.pending_referral_guild_id = user_doc.pending_referral_guild_id || null;
614
+ user.recovery_confirmed_at = user_doc.recovery_confirmed_at || null;
588
615
 
589
616
  return user;
590
617
  }
@@ -663,14 +690,58 @@ export class User {
663
690
  }
664
691
  }
665
692
 
693
+ /** The PROVIDER_INDEX doc id for an email: `email_<sanitizeProviderId(normalized)>`. */
694
+ static emailIndexKey(email) {
695
+ const normalized = normalizeEmail(email);
696
+ if (!normalized) throw new Error('User.emailIndexKey: an email is required');
697
+ return `email_${User.sanitizeProviderId(normalized)}`;
698
+ }
699
+
700
+ /**
701
+ * The one-email-one-account rule. Resolves when no
702
+ * account other than `uid` holds `email`. "Holds" = the email ProviderIndex row points at
703
+ * another account, another USERS doc carries the email as `email` or `verified_email`
704
+ * (accounts that pre-date the index row), or a USERS doc is keyed by the email itself (the
705
+ * legacy email-keyed form, which has no passkey). Throws EmailIdentityError
706
+ * ALREADY_REGISTERED_LEGACY when every other holder is that legacy form, else
707
+ * ALREADY_REGISTERED. A failed read throws: an unanswerable question is never read as "free".
708
+ */
709
+ static async assertEmailFreeFor(uid, email) {
710
+ if (!uid || typeof uid !== 'string') throw new Error('User.assertEmailFreeFor: uid is required');
711
+ const normalized = normalizeEmail(email);
712
+ if (!normalized) throw new Error('User.assertEmailFreeFor: email is required');
713
+ const db = new CacheFirestore();
714
+ const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), User.emailIndexKey(normalized));
715
+ const holders = new Set();
716
+ if (index?.descix_user_id) holders.add(index.descix_user_id);
717
+ if (await db.get_doc(FirestoreCollections.USERS(), normalized)) holders.add(normalized);
718
+ for (const field of ['email', 'verified_email']) {
719
+ const docs = await db.get_docs_with_ids(FirestoreCollections.USERS(), null, [[field, '==', normalized]]);
720
+ if (!Array.isArray(docs)) {
721
+ throw new Error(`User.assertEmailFreeFor: the USERS query on ${field} failed; cannot tell whether the email is free`);
722
+ }
723
+ for (const d of docs) holders.add(d._id);
724
+ }
725
+ holders.delete(uid);
726
+ if (holders.size === 0) return;
727
+ if ([...holders].every((id) => id === normalized)) {
728
+ throw new EmailIdentityError(
729
+ EmailIdentityRefusal.ALREADY_REGISTERED_LEGACY,
730
+ 'This email belongs to a DeSciX account created before passkeys. Use a different email; linking that account to a passkey is not available yet.'
731
+ );
732
+ }
733
+ throw new EmailIdentityError(
734
+ EmailIdentityRefusal.ALREADY_REGISTERED,
735
+ 'This email belongs to another account. Sign in with that account\'s passkey instead.'
736
+ );
737
+ }
738
+
666
739
  static async findByEmail(email) {
667
740
  if (!email) return null;
668
741
  const normalized = normalizeEmail(email);
669
742
  if (!normalized) return null;
670
743
  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);
744
+ const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), User.emailIndexKey(normalized));
674
745
  if (index && index.descix_user_id) {
675
746
  return await User.from_firestore(index.descix_user_id);
676
747
  }
@@ -987,24 +1058,66 @@ export class User {
987
1058
  gate_passed_at: Timestamp.now(),
988
1059
  gate_source: gate_source
989
1060
  };
1061
+ const normalized = verified_email ? normalizeEmail(verified_email) : null;
1062
+ if (normalized) {
1063
+ // One email, one account: refuse before any write, then write the
1064
+ // email ProviderIndex row findByEmail reads, and release this account's previous row.
1065
+ await User.assertEmailFreeFor(this.id, normalized);
1066
+ const key = User.emailIndexKey(normalized);
1067
+ const wrote = await this.db.put_doc(FirestoreCollections.PROVIDER_INDEX(), key, {
1068
+ descix_user_id: this.id,
1069
+ provider_type: 'email',
1070
+ provider_id: normalized,
1071
+ linked_at: Timestamp.now()
1072
+ });
1073
+ if (wrote !== true) {
1074
+ throw new Error(`commitTosAndConnect: the email ProviderIndex write (${key}) failed; the email was not committed`);
1075
+ }
1076
+ const previous = normalizeEmail(this.email);
1077
+ if (previous && previous !== normalized) {
1078
+ const prevKey = User.emailIndexKey(previous);
1079
+ const prevRow = await this.db.get_doc(FirestoreCollections.PROVIDER_INDEX(), prevKey);
1080
+ if (prevRow?.descix_user_id === this.id) {
1081
+ await this.db.delete_doc(FirestoreCollections.PROVIDER_INDEX(), prevKey);
1082
+ }
1083
+ }
1084
+ updates.verified_email = normalized;
1085
+ updates.email = normalized;
1086
+ }
1087
+ const result = await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
990
1088
  this.tos_accepted_at = updates.tos_accepted_at;
991
1089
  this.tos_version = updates.tos_version;
992
1090
  this.gate_passed_at = updates.gate_passed_at;
993
1091
  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;
1092
+ if (normalized) {
998
1093
  this.verified_email = normalized;
999
1094
  this.email = normalized;
1000
1095
  }
1001
- return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1096
+ return result;
1002
1097
  }
1003
1098
 
1004
1099
  isConnected() {
1005
1100
  return !!this.tos_accepted_at;
1006
1101
  }
1007
1102
 
1103
+ /**
1104
+ * Wallet cold-storage backup (design 2026-10-23): the user confirmed "I have printed or written it
1105
+ * down" for the recovery sheet. Stores only when (ISO string); the sheet never reaches the server.
1106
+ */
1107
+ async confirmRecovery() {
1108
+ const recovery_confirmed_at = new Date().toISOString();
1109
+ const result = await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, { recovery_confirmed_at });
1110
+ if (result !== true) {
1111
+ throw new Error(`User.confirmRecovery: the USERS write for ${this.id} failed; recovery_confirmed_at was not stored`);
1112
+ }
1113
+ this.recovery_confirmed_at = recovery_confirmed_at;
1114
+ return recovery_confirmed_at;
1115
+ }
1116
+
1117
+ hasConfirmedRecovery() {
1118
+ return typeof this.recovery_confirmed_at === 'string' && this.recovery_confirmed_at.length > 0;
1119
+ }
1120
+
1008
1121
  async stampBaseEntitlements(stamp) {
1009
1122
  const updates = { base_entitlements_stamp: stamp };
1010
1123
  this.base_entitlements_stamp = stamp;