@descix/platform-api 5.2.0 → 5.3.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.
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * NOTE: KnowledgeBase, IPDocMetadata, and ChunkMetadata are intentionally NOT extracted here
7
7
  * because they contain dynamic imports to Cloud-specific services (pineconeService,
8
- * googleStorageService, geminiAPI). Those classes remain in DeSciX_Cloud/microservice/services/ipStorageUtils.js.
8
+ * googleStorageService, geminiAPI). Those classes remain in Cloud's ipStorageUtils.js.
9
9
  *
10
10
  * All config values are loaded lazily via getCloudConfig() from @descix/cloud-core.
11
11
  * The bootstrap must complete before any model methods are called.
@@ -23,8 +23,23 @@ import {
23
23
  Timestamp,
24
24
  ProductTypes,
25
25
  getCloudConfig,
26
+ Firestore,
26
27
  } from '@descix/cloud-core';
27
28
  import { normalizeEmail } from '../email/index.js';
29
+ import {
30
+ AccountAdminRefusal,
31
+ AccountAdminError,
32
+ ACCOUNT_READ_LIMIT,
33
+ accountAdminBlocker,
34
+ receiptData,
35
+ encodeStoreValue,
36
+ canonicalJson,
37
+ moveKey,
38
+ secretPath,
39
+ entryDataHash,
40
+ assertDeletePlanCurrent,
41
+ assertDocumentAsPlanned,
42
+ } from '../account-admin/contract.js';
28
43
 
29
44
  /**
30
45
  * Why an email could not be attached to an account (one email, one account). Every refusal is
@@ -86,6 +101,140 @@ export function sanitizeCredentialId(credentialId) {
86
101
  return credentialId.replace(/\//g, '_').replace(/\+/g, '-');
87
102
  }
88
103
 
104
+ /**
105
+ * The passkey a Powch account was registered with: the `passkey` field of the USERS doc keyed by
106
+ * sanitizeCredentialId(credential_id). Written once, by User.createForPasskey from a VERIFIED
107
+ * registration; read at every sign-in by User.passkeyOf, whose public key is the only thing an
108
+ * assertion signature is checked against. Public material only: no private key, no PRF output.
109
+ */
110
+ export const PASSKEY_FIELDS = Object.freeze({
111
+ credential_id: 'the credential id, base64url (sanitizeCredentialId of it is the account id)',
112
+ public_key: 'the credential public key (COSE), base64url, from the verified registration',
113
+ counter: 'the signature counter last verified (a passkey that does not count stays 0)',
114
+ transports: 'the transports the browser reported at registration (array of strings, may be empty)',
115
+ rp_id: 'the WebAuthn rpID the passkey was created for',
116
+ registered_at: 'when the registration was verified (ISO string)',
117
+ source: 'which owner write stored the record (a PasskeySource value); written by the owner, never by a caller',
118
+ });
119
+
120
+ /** Which owner write stored a passkey record: the `source` of every stored PASSKEY_FIELDS bag. */
121
+ export const PasskeySource = Object.freeze({
122
+ /** User.createForPasskey, from a verified registration. */
123
+ REGISTERED: 'registered',
124
+ /** User.attachRecoveredPasskey, the operator upgrade of a key-less account; the only kind removeRecoveredPasskey deletes. */
125
+ RECOVERED: 'recovered',
126
+ });
127
+
128
+ /** Where a credential id stands with respect to its account (User.passkeyOf). */
129
+ export const PasskeyState = Object.freeze({
130
+ /** No USERS doc for this credential: no account was ever registered with it. */
131
+ NOT_REGISTERED: 'NOT_REGISTERED',
132
+ /** The account exists but holds no passkey public key: registered before keys were stored. */
133
+ NO_PUBLIC_KEY: 'NO_PUBLIC_KEY',
134
+ /** The account holds the passkey's public key. */
135
+ REGISTERED: 'REGISTERED',
136
+ });
137
+
138
+ /** Why the owner refused a passkey record: the `code` of every PasskeyRecordError. */
139
+ export const PasskeyRecordRefusal = Object.freeze({
140
+ INVALID: 'PASSKEY_RECORD_INVALID',
141
+ ALREADY_REGISTERED: 'PASSKEY_ALREADY_REGISTERED',
142
+ /** attach/remove: no USERS doc exists for the credential. */
143
+ ACCOUNT_NOT_FOUND: 'PASSKEY_ACCOUNT_NOT_FOUND',
144
+ /** attach: the account already holds a passkey public key; only a key-less account is upgraded. */
145
+ KEY_ALREADY_ON_FILE: 'PASSKEY_KEY_ALREADY_ON_FILE',
146
+ /** remove: the account does not hold exactly the key the operator wrote; nothing is removed. */
147
+ ROLLBACK_MISMATCH: 'PASSKEY_ROLLBACK_MISMATCH',
148
+ /** attach: the account is not a Powch passkey account of this credential (user_info.credentialId and the powch auth provider, as User._newDocData wrote them). */
149
+ NOT_LEGACY_POWCH_ACCOUNT: 'PASSKEY_NOT_LEGACY_POWCH_ACCOUNT',
150
+ /** remove: the stored record was not written by attachRecoveredPasskey (or carries no source); nothing is removed. */
151
+ NOT_RECOVERED: 'PASSKEY_NOT_RECOVERED',
152
+ });
153
+
154
+ /** The fields that identify one written passkey record for a rollback: every PASSKEY_FIELDS key except
155
+ * `counter`, which each verified sign-in advances after the write. */
156
+ const PASSKEY_IDENTITY_FIELDS = Object.freeze(Object.keys(PASSKEY_FIELDS).filter((k) => k !== 'counter'));
157
+
158
+ /** A passkey record refused by its owner. `code` is a PasskeyRecordRefusal value. */
159
+ export class PasskeyRecordError extends Error {
160
+ constructor(code, message) {
161
+ super(message);
162
+ this.name = 'PasskeyRecordError';
163
+ this.code = code;
164
+ }
165
+ }
166
+
167
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
168
+ /** An operator range-read prefix: a lowercase local part ending in '@' or '+' (operatorEmailRulePrefixes). */
169
+ const EMAIL_PREFIX = /^[a-z0-9._%+-]+[@+]$/;
170
+
171
+ /**
172
+ * The full passkey bag (every PASSKEY_FIELDS key) from a partial one, or a PasskeyRecordError naming the
173
+ * first bad field. Nothing is defaulted except `transports` (absent = none reported); `source` must be a
174
+ * PasskeySource value (a record without one is invalid).
175
+ * @param {Object} partial
176
+ * @returns {{ credential_id: string, public_key: string, counter: number, transports: string[], rp_id: string, registered_at: string, source: string }}
177
+ */
178
+ export function normalizePasskey(partial) {
179
+ const p = partial || {};
180
+ const bad = (field, why) => new PasskeyRecordError(PasskeyRecordRefusal.INVALID, `passkey.${field} ${why}`);
181
+ if (typeof p.credential_id !== 'string' || !BASE64URL.test(p.credential_id)) throw bad('credential_id', 'must be a base64url string');
182
+ if (typeof p.public_key !== 'string' || !BASE64URL.test(p.public_key)) throw bad('public_key', 'must be a base64url string');
183
+ if (!Number.isInteger(p.counter) || p.counter < 0) throw bad('counter', 'must be a non-negative integer');
184
+ const transports = p.transports ?? [];
185
+ if (!Array.isArray(transports) || transports.some((t) => typeof t !== 'string')) throw bad('transports', 'must be an array of strings');
186
+ if (typeof p.rp_id !== 'string' || p.rp_id.length === 0) throw bad('rp_id', 'must be a non-empty string');
187
+ if (typeof p.registered_at !== 'string' || Number.isNaN(Date.parse(p.registered_at))) throw bad('registered_at', 'must be an ISO time string');
188
+ if (!Object.values(PasskeySource).includes(p.source)) throw bad('source', `must be one of ${Object.values(PasskeySource).join(', ')}`);
189
+ const out = {};
190
+ for (const key of Object.keys(PASSKEY_FIELDS)) out[key] = key === 'transports' ? [...transports] : p[key];
191
+ return out;
192
+ }
193
+
194
+ /**
195
+ * A caller's passkey bag normalized as the record the owner write `source` stores. The owner writes
196
+ * `source`: a caller bag naming another source is refused (PASSKEY_RECORD_INVALID).
197
+ * @param {Object} partial
198
+ * @param {string} source - a PasskeySource value
199
+ */
200
+ function passkeyWrittenAs(partial, source) {
201
+ const p = partial || {};
202
+ if (p.source !== undefined && p.source !== source) {
203
+ throw new PasskeyRecordError(PasskeyRecordRefusal.INVALID, `passkey.source is written by the owner (${source} here); the bag names ${JSON.stringify(p.source)}`);
204
+ }
205
+ return normalizePasskey({ ...p, source });
206
+ }
207
+
208
+ /**
209
+ * The USERS account id of a credential id, or PASSKEY_RECORD_INVALID when the id is not base64url.
210
+ * @param {string} credential_id
211
+ * @param {string} caller - the owner method, named in the refusal
212
+ */
213
+ function passkeyAccountId(credential_id, caller) {
214
+ const user_id = sanitizeCredentialId(credential_id);
215
+ if (!user_id || !BASE64URL.test(credential_id)) {
216
+ throw new PasskeyRecordError(PasskeyRecordRefusal.INVALID, `${caller}: the credential id must be a base64url string`);
217
+ }
218
+ return user_id;
219
+ }
220
+
221
+ /**
222
+ * The fields in which a stored passkey record differs from the record an operator receipt names: every
223
+ * PASSKEY_FIELDS key except `counter` (sign-ins move it). [] means the account holds exactly the record
224
+ * that attachRecoveredPasskey wrote from this receipt. The one comparison: removeRecoveredPasskey removes
225
+ * only on [], and the operator re-key owner decides "this run's key" with it. Pure; reads nothing.
226
+ * @param {Object|null} stored - the USERS doc's `passkey` field as read (null/undefined: none on file)
227
+ * @param {Object} receiptPasskey - the bag the operator re-key recovered (its receipt's `passkey`)
228
+ * @returns {string[]} the differing field names
229
+ */
230
+ export function recoveredPasskeyDifferences(stored, receiptPasskey) {
231
+ const bag = passkeyWrittenAs(receiptPasskey, PasskeySource.RECOVERED);
232
+ if (stored == null) return [...PASSKEY_IDENTITY_FIELDS];
233
+ if (stored.source !== PasskeySource.RECOVERED) return ['source'];
234
+ const held = normalizePasskey(stored);
235
+ return PASSKEY_IDENTITY_FIELDS.filter((k) => JSON.stringify(held[k]) !== JSON.stringify(bag[k]));
236
+ }
237
+
89
238
  export async function get_default_community() {
90
239
  const utils = getCloudConfig();
91
240
  const community_id = utils.DEFAULT_COMMUNITY_ID;
@@ -471,6 +620,13 @@ export class App {
471
620
  // --- User Class ---
472
621
 
473
622
  export class User {
623
+ /**
624
+ * The USERS fields only the operator stamps write, each transactionally: the merge stamp (markMigrated /
625
+ * unmarkMigrated) and the delete stamp `admin_delete` (userAccountOwner.stampDelete / clearDeleteStamp).
626
+ * to_dict never carries them, so no whole-document writer undoes or forges one.
627
+ */
628
+ static OPERATOR_STAMP_FIELDS = Object.freeze(['migrated_to', 'migrated_at', 'admin_delete']);
629
+
474
630
  constructor(
475
631
  id, email = null, user_info = null,
476
632
  wallet_address = null, signature = null,
@@ -527,6 +683,9 @@ export class User {
527
683
  to_dict() {
528
684
  const copy = { ...this };
529
685
  delete copy.db;
686
+ // The operator stamps are written ONLY by their transactional writers: a whole-document write of an
687
+ // instance hydrated before a merge, a delete's start or their undoing must never undo or forge one.
688
+ for (const k of User.OPERATOR_STAMP_FIELDS) delete copy[k];
530
689
  copy.roles = copy.roles instanceof Map ? Object.fromEntries(copy.roles) : (copy.roles || {});
531
690
  copy.provider_links = copy.provider_links instanceof Map ? Object.fromEntries(copy.provider_links) : (copy.provider_links || {});
532
691
  copy.nfts = copy.nfts instanceof Map ? Object.fromEntries(copy.nfts) : (copy.nfts || {});
@@ -596,12 +755,12 @@ export class User {
596
755
  user_doc.api_signatures || []
597
756
  );
598
757
 
599
- // ws-user-domain-owners: hydrate owner-method-backed fields that are NOT
758
+ // hydrate owner-method-backed fields that are NOT
600
759
  // constructor params. commitTosAndConnect/stampBaseEntitlements/markMigrated/
601
760
  // setPendingReferral write these via db.update_doc_fields (targeted field
602
761
  // writes onto FirestoreCollections.USERS()), so they exist on the Firestore
603
762
  // doc but were previously dropped on every from_firestore() load. Mirrors
604
- // Cloud ipStorageUtils.js User.from_firestore (commit 105a152).
763
+ // Cloud ipStorageUtils.js User.from_firestore.
605
764
  user.tos_accepted_at = user_doc.tos_accepted_at || null;
606
765
  user.tos_version = user_doc.tos_version || null;
607
766
  user.gate_passed_at = user_doc.gate_passed_at || null;
@@ -616,6 +775,274 @@ export class User {
616
775
  return user;
617
776
  }
618
777
 
778
+ /** The USERS doc a new account starts with (to_firestore and createForPasskey). */
779
+ static _newDocData(user_id, user_info, auth_provider, discord_user_id, google_user_id) {
780
+ return {
781
+ id: user_id,
782
+ email: user_info?.email || null,
783
+ discord_user_id: discord_user_id,
784
+ google_user_id: google_user_id,
785
+ auth_providers: [auth_provider],
786
+ user_info: user_info,
787
+ wallet_address: null,
788
+ signature: null,
789
+ roles: {},
790
+ nfts: {},
791
+ ad_campaigns: {},
792
+ total_rep: 0,
793
+ total_ref_generic: 0,
794
+ total_dip: 0,
795
+ claimed_promotions: [],
796
+ accumulated_ref_commission: 0,
797
+ accumulated_rep_commission: 0,
798
+ accumulated_dip_commission: 0
799
+ };
800
+ }
801
+
802
+ /**
803
+ * The one check that an account may receive a recovered passkey (attachRecoveredPasskey and
804
+ * _passkeyRecoveryStatusOf both run it): the USERS doc exists (PASSKEY_ACCOUNT_NOT_FOUND), is the Powch
805
+ * passkey account of `credential_id` as _newDocData writes one (`user_info.credentialId` equal to it and
806
+ * AuthProvider.POWCH in `auth_providers`; a missing field refuses, PASSKEY_NOT_LEGACY_POWCH_ACCOUNT),
807
+ * and holds no passkey key (PASSKEY_KEY_ALREADY_ON_FILE).
808
+ * @param {{ exists: boolean, data: () => Object }} snap - the USERS doc snapshot
809
+ * @param {string} credential_id
810
+ * @param {string} user_id
811
+ */
812
+ static _refuseUnlessPasskeyRecoverable(snap, credential_id, user_id) {
813
+ if (!snap.exists) {
814
+ throw new PasskeyRecordError(PasskeyRecordRefusal.ACCOUNT_NOT_FOUND, `no account ${user_id}; no recovered passkey can be attached`);
815
+ }
816
+ const doc = snap.data();
817
+ const powch = doc?.user_info?.credentialId === credential_id
818
+ && Array.isArray(doc?.auth_providers) && doc.auth_providers.includes(AuthProvider.POWCH);
819
+ if (!powch) {
820
+ throw new PasskeyRecordError(PasskeyRecordRefusal.NOT_LEGACY_POWCH_ACCOUNT, `account ${user_id} is not a Powch passkey account of credential ${credential_id} (user_info.credentialId and the ${AuthProvider.POWCH} auth provider); no recovered passkey can be attached`);
821
+ }
822
+ if (doc.passkey != null) {
823
+ throw new PasskeyRecordError(PasskeyRecordRefusal.KEY_ALREADY_ON_FILE, `account ${user_id} already holds a passkey public key; no recovered passkey can be attached`);
824
+ }
825
+ }
826
+
827
+ /**
828
+ * Create the account for a newly registered passkey, holding its public key (PASSKEY_FIELDS), in ONE
829
+ * create: the write fails when a USERS doc already exists for the credential, so a registration can
830
+ * never overwrite another account's passkey, wallet or anything else (PASSKEY_ALREADY_REGISTERED).
831
+ * Any other write failure throws. Returns the account id.
832
+ * @param {Object} passkey - a PASSKEY_FIELDS bag (normalizePasskey)
833
+ * @returns {Promise<string>}
834
+ */
835
+ static async createForPasskey(passkey) {
836
+ const bag = passkeyWrittenAs(passkey, PasskeySource.REGISTERED);
837
+ const user_id = sanitizeCredentialId(bag.credential_id);
838
+ const data = {
839
+ ...User._newDocData(user_id, { credentialId: bag.credential_id }, AuthProvider.POWCH, null, null),
840
+ passkey: bag,
841
+ };
842
+ const ref = new CacheFirestore().db.collection(FirestoreCollections.USERS()).doc(user_id);
843
+ try {
844
+ await ref.create(data);
845
+ } catch (e) {
846
+ // gRPC ALREADY_EXISTS: Firestore's create() refuses an existing document.
847
+ if (e?.code === 6) {
848
+ throw new PasskeyRecordError(PasskeyRecordRefusal.ALREADY_REGISTERED, `An account is already registered for credential ${bag.credential_id}; nothing was written`);
849
+ }
850
+ throw new Error(`User.createForPasskey: the USERS create for ${user_id} failed (${e?.message || e}); no account was created`);
851
+ }
852
+ return user_id;
853
+ }
854
+
855
+ /**
856
+ * Where a credential stands (PasskeyState) and, when REGISTERED, its normalized passkey bag. A failed
857
+ * read throws: an unanswerable question is never read as "not registered".
858
+ * @param {string} credential_id
859
+ * @returns {Promise<{ state: string, user_id: string, passkey: Object|null }>}
860
+ */
861
+ static async passkeyOf(credential_id) {
862
+ const user_id = passkeyAccountId(credential_id, 'User.passkeyOf');
863
+ const snap = await new CacheFirestore().db.collection(FirestoreCollections.USERS()).doc(user_id).get();
864
+ if (!snap.exists) return { state: PasskeyState.NOT_REGISTERED, user_id, passkey: null };
865
+ const stored = snap.data()?.passkey;
866
+ if (stored == null) return { state: PasskeyState.NO_PUBLIC_KEY, user_id, passkey: null };
867
+ const passkey = normalizePasskey(stored);
868
+ if (passkey.credential_id !== credential_id) {
869
+ throw new PasskeyRecordError(PasskeyRecordRefusal.INVALID, `User.passkeyOf: the account ${user_id} holds the passkey of another credential`);
870
+ }
871
+ return { state: PasskeyState.REGISTERED, user_id, passkey };
872
+ }
873
+
874
+ /**
875
+ * Store the signature counter a verified sign-in reported, in one transaction that never lowers it:
876
+ * two concurrent sign-ins (counters n+1 and n+2) leave n+2 whichever commits last. Throws when the
877
+ * account holds no passkey or the write fails; refuses (PASSKEY_RECORD_INVALID) a stored record that is
878
+ * not a valid PASSKEY_FIELDS bag (e.g. a non-integer counter) or belongs to another credential.
879
+ * @param {string} credential_id
880
+ * @param {number} counter
881
+ */
882
+ static async recordPasskeyCounter(credential_id, counter) {
883
+ if (!Number.isInteger(counter) || counter < 0) {
884
+ throw new PasskeyRecordError(PasskeyRecordRefusal.INVALID, 'passkey.counter must be a non-negative integer');
885
+ }
886
+ const user_id = sanitizeCredentialId(credential_id);
887
+ const db = new CacheFirestore().db;
888
+ const ref = db.collection(FirestoreCollections.USERS()).doc(user_id);
889
+ try {
890
+ await db.runTransaction(async (tx) => {
891
+ const snap = await tx.get(ref);
892
+ const stored = snap.exists ? snap.data()?.passkey : null;
893
+ if (stored == null) throw new Error(`account ${user_id} holds no passkey`);
894
+ const held = normalizePasskey(stored);
895
+ if (held.credential_id !== credential_id) {
896
+ throw new PasskeyRecordError(PasskeyRecordRefusal.INVALID, `User.recordPasskeyCounter: the account ${user_id} holds the passkey of another credential; the counter was not stored`);
897
+ }
898
+ if (held.counter >= counter) return;
899
+ tx.update(ref, { 'passkey.counter': counter });
900
+ });
901
+ } catch (e) {
902
+ if (e instanceof PasskeyRecordError) throw e;
903
+ throw new Error(`User.recordPasskeyCounter: the USERS write for ${user_id} failed (${e?.message || e}); the counter was not stored`);
904
+ }
905
+ }
906
+
907
+ /**
908
+ * The one-time operator upgrade of an account registered before passkey public keys were stored
909
+ * (PasskeyState.NO_PUBLIC_KEY): writes `passkey` (a PASSKEY_FIELDS bag the operator re-key recovered
910
+ * and verified) in ONE transaction that refuses when the account does not exist
911
+ * (PASSKEY_ACCOUNT_NOT_FOUND), is not the Powch passkey account of this credential
912
+ * (PASSKEY_NOT_LEGACY_POWCH_ACCOUNT) or already holds a key (PASSKEY_KEY_ALREADY_ON_FILE), the check
913
+ * passkeyRecoveryStatus reads ahead (_refuseUnlessPasskeyRecoverable). No other field is
914
+ * touched. Reached only by the operator re-key owner (the Powch operator passkey re-key module);
915
+ * no command, route or tool calls it.
916
+ * @param {Object} passkey - a PASSKEY_FIELDS bag (normalizePasskey)
917
+ * @returns {Promise<string>} the account id
918
+ */
919
+ static async attachRecoveredPasskey(passkey) {
920
+ const bag = passkeyWrittenAs(passkey, PasskeySource.RECOVERED);
921
+ const user_id = sanitizeCredentialId(bag.credential_id);
922
+ const db = new CacheFirestore().db;
923
+ const ref = db.collection(FirestoreCollections.USERS()).doc(user_id);
924
+ await db.runTransaction(async (tx) => {
925
+ User._refuseUnlessPasskeyRecoverable(await tx.get(ref), bag.credential_id, user_id);
926
+ tx.update(ref, { passkey: bag });
927
+ });
928
+ return user_id;
929
+ }
930
+
931
+ /**
932
+ * One USERS doc as the operator upgrade sees it (passkeyRecoveryStatus and passkeyRecoveryCandidates):
933
+ * its account id, the credential id it is the Powch account of (user_info.credentialId when that is a
934
+ * base64url id whose account id is this doc's, else null), its normalized `verified_email` (the one address
935
+ * the upgrade judges an account by; the unverified `email` is not part of it),
936
+ * when the doc was created (the snapshot's createTime as an ISO string; null when the read carries none),
937
+ * and `refusal`: null when attachRecoveredPasskey would accept a key for it now, else the
938
+ * PasskeyRecordRefusal code its check (_refuseUnlessPasskeyRecoverable) answers.
939
+ * @param {{ exists: boolean, data: () => Object, createTime?: { toDate: () => Date } }} snap
940
+ * @param {string} user_id
941
+ */
942
+ static _passkeyRecoveryStatusOf(snap, user_id) {
943
+ const doc = snap.exists ? (snap.data() || {}) : null;
944
+ const cid = doc?.user_info?.credentialId;
945
+ const credential_id = typeof cid === 'string' && BASE64URL.test(cid) && sanitizeCredentialId(cid) === user_id ? cid : null;
946
+ let refusal = null;
947
+ if (!snap.exists) {
948
+ refusal = PasskeyRecordRefusal.ACCOUNT_NOT_FOUND;
949
+ } else if (credential_id === null) {
950
+ refusal = PasskeyRecordRefusal.NOT_LEGACY_POWCH_ACCOUNT;
951
+ } else {
952
+ try {
953
+ User._refuseUnlessPasskeyRecoverable(snap, credential_id, user_id);
954
+ } catch (e) {
955
+ if (!(e instanceof PasskeyRecordError)) throw e;
956
+ refusal = e.code;
957
+ }
958
+ }
959
+ return {
960
+ user_id,
961
+ credential_id,
962
+ verified_email: typeof doc?.verified_email === 'string' ? normalizeEmail(doc.verified_email) : null,
963
+ created_at: snap.createTime ? snap.createTime.toDate().toISOString() : null,
964
+ refusal,
965
+ };
966
+ }
967
+
968
+ /**
969
+ * Read-only: where the account of `credential_id` stands for the operator upgrade, by the check
970
+ * attachRecoveredPasskey runs in its transaction (see _passkeyRecoveryStatusOf for the shape; `refusal`
971
+ * is null, PASSKEY_ACCOUNT_NOT_FOUND, PASSKEY_NOT_LEGACY_POWCH_ACCOUNT or PASSKEY_KEY_ALREADY_ON_FILE).
972
+ * Throws PASSKEY_RECORD_INVALID for a credential id that is not base64url, and when the read fails.
973
+ * Writes nothing. Reached only by the operator re-key owner (the Powch operator passkey re-key module).
974
+ * @param {string} credential_id
975
+ * @returns {Promise<{ user_id: string, credential_id: string|null, verified_email: string|null, created_at: string|null, refusal: string|null }>}
976
+ */
977
+ static async passkeyRecoveryStatus(credential_id) {
978
+ const user_id = passkeyAccountId(credential_id, 'User.passkeyRecoveryStatus');
979
+ const snap = await new CacheFirestore().db.collection(FirestoreCollections.USERS()).doc(user_id).get();
980
+ return User._passkeyRecoveryStatusOf(snap, user_id);
981
+ }
982
+
983
+ /**
984
+ * Read-only: every USERS doc whose `verified_email` starts with one of `emailPrefixes`, each as
985
+ * _passkeyRecoveryStatusOf describes it (eligible or not), sorted by account id. A prefix is a lowercase
986
+ * local part ending in '@' or '+' (e.g. 'operator@', 'operator+'): there is no unfiltered listing, and an empty or
987
+ * malformed prefix list is refused (PASSKEY_RECORD_INVALID). The range reads compare the stored value as
988
+ * written, case-sensitively: a verified_email stored with uppercase letters or surrounding spaces is not reached.
989
+ * A failed read throws. Writes nothing. Reached only by the operator re-key owner.
990
+ * @param {{ emailPrefixes: string[] }} args
991
+ * @returns {Promise<Array<ReturnType<typeof User._passkeyRecoveryStatusOf>>>}
992
+ */
993
+ static async passkeyRecoveryCandidates({ emailPrefixes } = {}) {
994
+ if (!Array.isArray(emailPrefixes) || emailPrefixes.length === 0 || emailPrefixes.some((p) => typeof p !== 'string' || !EMAIL_PREFIX.test(p))) {
995
+ throw new PasskeyRecordError(PasskeyRecordRefusal.INVALID, `User.passkeyRecoveryCandidates: emailPrefixes must be a non-empty array of lowercase local parts ending in '@' or '+' (got ${JSON.stringify(emailPrefixes)}); there is no unfiltered listing`);
996
+ }
997
+ const users = new CacheFirestore().db.collection(FirestoreCollections.USERS());
998
+ const byId = new Map();
999
+ for (const prefix of new Set(emailPrefixes)) {
1000
+ let snap;
1001
+ try {
1002
+ snap = await users.where('verified_email', '>=', prefix).where('verified_email', '<', `${prefix}`).get();
1003
+ } catch (e) {
1004
+ throw new Error(`User.passkeyRecoveryCandidates: the USERS read on verified_email for '${prefix}' failed (${e?.message || e}); no listing`);
1005
+ }
1006
+ for (const doc of snap.docs) byId.set(doc.id, doc);
1007
+ }
1008
+ return [...byId.keys()].sort().map((id) => User._passkeyRecoveryStatusOf(byId.get(id), id));
1009
+ }
1010
+
1011
+ /**
1012
+ * The rollback of attachRecoveredPasskey: deletes `passkey` ONLY when the stored record's source is
1013
+ * PasskeySource.RECOVERED and it is exactly the record the operator wrote (every PASSKEY_FIELDS key
1014
+ * except `counter`), returning the account to PasskeyState.NO_PUBLIC_KEY. Anything else is refused
1015
+ * (PASSKEY_ACCOUNT_NOT_FOUND, PASSKEY_NOT_RECOVERED, PASSKEY_ROLLBACK_MISMATCH) and nothing is written.
1016
+ * Reached only by the operator re-key owner (the Powch operator passkey re-key module).
1017
+ * @param {Object} passkey - the bag attachRecoveredPasskey wrote (the script's receipt)
1018
+ * @returns {Promise<string>} the account id
1019
+ */
1020
+ static async removeRecoveredPasskey(passkey) {
1021
+ const bag = passkeyWrittenAs(passkey, PasskeySource.RECOVERED);
1022
+ const user_id = sanitizeCredentialId(bag.credential_id);
1023
+ const db = new CacheFirestore().db;
1024
+ const ref = db.collection(FirestoreCollections.USERS()).doc(user_id);
1025
+ await db.runTransaction(async (tx) => {
1026
+ const snap = await tx.get(ref);
1027
+ if (!snap.exists) {
1028
+ throw new PasskeyRecordError(PasskeyRecordRefusal.ACCOUNT_NOT_FOUND, `User.removeRecoveredPasskey: no account ${user_id}; nothing was written`);
1029
+ }
1030
+ const stored = snap.data()?.passkey;
1031
+ if (stored == null) {
1032
+ throw new PasskeyRecordError(PasskeyRecordRefusal.ROLLBACK_MISMATCH, `User.removeRecoveredPasskey: account ${user_id} holds no passkey key; nothing was written`);
1033
+ }
1034
+ if (stored.source !== PasskeySource.RECOVERED) {
1035
+ throw new PasskeyRecordError(PasskeyRecordRefusal.NOT_RECOVERED, `User.removeRecoveredPasskey: account ${user_id} holds a passkey record whose source is ${JSON.stringify(stored.source)}, not ${PasskeySource.RECOVERED}; only a record attachRecoveredPasskey wrote is removed; nothing was written`);
1036
+ }
1037
+ const differing = recoveredPasskeyDifferences(stored, bag);
1038
+ if (differing.length > 0) {
1039
+ throw new PasskeyRecordError(PasskeyRecordRefusal.ROLLBACK_MISMATCH, `User.removeRecoveredPasskey: account ${user_id} holds another passkey record (differs in ${differing.join(', ')}); nothing was written`);
1040
+ }
1041
+ tx.update(ref, { passkey: FieldValue.delete() });
1042
+ });
1043
+ return user_id;
1044
+ }
1045
+
619
1046
  static async to_firestore(user_id, user_info, auth_provider = 'discord') {
620
1047
  const db = new CacheFirestore();
621
1048
  const user = await db.get_doc(FirestoreCollections.USERS(), user_id);
@@ -623,7 +1050,6 @@ export class User {
623
1050
 
624
1051
  let discord_user_id = null;
625
1052
  let google_user_id = null;
626
- let auth_providers = [auth_provider];
627
1053
 
628
1054
  if (auth_provider === 'discord') {
629
1055
  discord_user_id = user_id;
@@ -636,26 +1062,7 @@ export class User {
636
1062
  }
637
1063
  }
638
1064
 
639
- const dataToStore = {
640
- id: user_id,
641
- email: email,
642
- discord_user_id: discord_user_id,
643
- google_user_id: google_user_id,
644
- auth_providers: auth_providers,
645
- user_info: user_info,
646
- wallet_address: null,
647
- signature: null,
648
- roles: {},
649
- nfts: {},
650
- ad_campaigns: {},
651
- total_rep: 0,
652
- total_ref_generic: 0,
653
- total_dip: 0,
654
- claimed_promotions: [],
655
- accumulated_ref_commission: 0,
656
- accumulated_rep_commission: 0,
657
- accumulated_dip_commission: 0
658
- };
1065
+ const dataToStore = User._newDocData(user_id, user_info, auth_provider, discord_user_id, google_user_id);
659
1066
 
660
1067
  if (!user) {
661
1068
  return await db.put_doc(FirestoreCollections.USERS(), user_id, dataToStore);
@@ -702,7 +1109,8 @@ export class User {
702
1109
  * account other than `uid` holds `email`. "Holds" = the email ProviderIndex row points at
703
1110
  * another account, another USERS doc carries the email as `email` or `verified_email`
704
1111
  * (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
1112
+ * legacy email-keyed form, which has no passkey). A USERS doc migrated into `uid` (migrated_to, the
1113
+ * operator merge) is not another holder. Throws EmailIdentityError
706
1114
  * ALREADY_REGISTERED_LEGACY when every other holder is that legacy form, else
707
1115
  * ALREADY_REGISTERED. A failed read throws: an unanswerable question is never read as "free".
708
1116
  */
@@ -713,14 +1121,17 @@ export class User {
713
1121
  const db = new CacheFirestore();
714
1122
  const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), User.emailIndexKey(normalized));
715
1123
  const holders = new Set();
1124
+ // A record migrated INTO uid (markMigrated) is uid's own past, not another holder.
1125
+ const migratedIntoUid = (doc) => doc?.migrated_to === uid;
716
1126
  if (index?.descix_user_id) holders.add(index.descix_user_id);
717
- if (await db.get_doc(FirestoreCollections.USERS(), normalized)) holders.add(normalized);
1127
+ const keyed = await db.get_doc(FirestoreCollections.USERS(), normalized);
1128
+ if (keyed && !migratedIntoUid(keyed)) holders.add(normalized);
718
1129
  for (const field of ['email', 'verified_email']) {
719
1130
  const docs = await db.get_docs_with_ids(FirestoreCollections.USERS(), null, [[field, '==', normalized]]);
720
1131
  if (!Array.isArray(docs)) {
721
1132
  throw new Error(`User.assertEmailFreeFor: the USERS query on ${field} failed; cannot tell whether the email is free`);
722
1133
  }
723
- for (const d of docs) holders.add(d._id);
1134
+ for (const d of docs) if (!migratedIntoUid(d)) holders.add(d._id);
724
1135
  }
725
1136
  holders.delete(uid);
726
1137
  if (holders.size === 0) return;
@@ -1050,7 +1461,7 @@ export class User {
1050
1461
  return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1051
1462
  }
1052
1463
 
1053
- // --- User-Domain Owner Methods (ws-user-domain-owners) ---
1464
+ // --- User-Domain Owner Methods ---
1054
1465
  async commitTosAndConnect({ tos_version, gate_source, verified_email } = {}) {
1055
1466
  const updates = {
1056
1467
  tos_accepted_at: Timestamp.now(),
@@ -1140,7 +1551,7 @@ export class User {
1140
1551
 
1141
1552
  async clearPendingReferral() {
1142
1553
  // Symmetric with setPendingReferral(code, guild_id): clears BOTH fields it can set.
1143
- // Mirrors Cloud ipStorageUtils.js User.clearPendingReferral (commit 111318e).
1554
+ // Mirrors Cloud ipStorageUtils.js User.clearPendingReferral.
1144
1555
  const updates = { pending_referral_code: null, pending_referral_guild_id: null };
1145
1556
  this.pending_referral_code = null;
1146
1557
  this.pending_referral_guild_id = null;
@@ -1153,11 +1564,55 @@ export class User {
1153
1564
  return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1154
1565
  }
1155
1566
 
1567
+ /**
1568
+ * Mark this record as migrated into account `to` (the merge of a legacy record into its passkey
1569
+ * account): writes `migrated_to` and `migrated_at`, in ONE transaction that refuses when this USERS doc
1570
+ * does not exist (ACCOUNT_NOT_FOUND) or is already migrated (ACCOUNT_MERGE_ALREADY_MIGRATED). Any other
1571
+ * failure throws ACCOUNT_STORE_WRITE_FAILED. Reached by the operator account admin (userAccountOwner).
1572
+ * @param {string} to - the surviving account id
1573
+ * @returns {Promise<true>}
1574
+ */
1156
1575
  async markMigrated(to) {
1157
- const updates = { migrated_to: to, migrated_at: Timestamp.now() };
1158
- this.migrated_to = updates.migrated_to;
1159
- this.migrated_at = updates.migrated_at;
1160
- return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1576
+ if (typeof to !== 'string' || !to || to === this.id) {
1577
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_MERGE_SAME_RECORD, `User.markMigrated: ${this.id} can only be migrated into another account id (got ${JSON.stringify(to)}); nothing was written`);
1578
+ }
1579
+ const USERS = FirestoreCollections.USERS();
1580
+ const db = new CacheFirestore().db;
1581
+ const ref = db.collection(USERS).doc(this.id);
1582
+ const migrated_at = Timestamp.now();
1583
+ await userStoreWrite(USERS, `${this.id} migrated_to`, () => db.runTransaction(async (tx) => {
1584
+ const snap = await tx.get(ref);
1585
+ if (!snap.exists) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `User.markMigrated: no USERS doc ${this.id}; nothing was written`);
1586
+ const current = snap.data()?.migrated_to ?? null;
1587
+ if (current !== null) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_MERGE_ALREADY_MIGRATED, `User.markMigrated: ${this.id} is already migrated to ${current}; nothing was written`);
1588
+ tx.update(ref, { migrated_to: to, migrated_at });
1589
+ }));
1590
+ this.migrated_to = to;
1591
+ this.migrated_at = migrated_at;
1592
+ return true;
1593
+ }
1594
+
1595
+ /**
1596
+ * The rollback of markMigrated: deletes `migrated_to` and `migrated_at` ONLY when this record is migrated
1597
+ * into exactly `to`, in one transaction; anything else refuses (ACCOUNT_NOT_FOUND, ACCOUNT_PLAN_STALE)
1598
+ * and writes nothing. Reached by the operator account admin (userAccountOwner).
1599
+ * @param {string} to - the account id the merge receipt says this record was migrated into
1600
+ * @returns {Promise<true>}
1601
+ */
1602
+ async unmarkMigrated(to) {
1603
+ const USERS = FirestoreCollections.USERS();
1604
+ const db = new CacheFirestore().db;
1605
+ const ref = db.collection(USERS).doc(this.id);
1606
+ await userStoreWrite(USERS, `${this.id} migrated_to`, () => db.runTransaction(async (tx) => {
1607
+ const snap = await tx.get(ref);
1608
+ if (!snap.exists) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `User.unmarkMigrated: no USERS doc ${this.id}; nothing was written`);
1609
+ const current = snap.data()?.migrated_to ?? null;
1610
+ if (current !== to) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_PLAN_STALE, `User.unmarkMigrated: ${this.id} is migrated to ${JSON.stringify(current)}, not ${to}; nothing was written`);
1611
+ tx.update(ref, { migrated_to: FieldValue.delete(), migrated_at: FieldValue.delete() });
1612
+ }));
1613
+ this.migrated_to = null;
1614
+ this.migrated_at = null;
1615
+ return true;
1161
1616
  }
1162
1617
  // --- End User-Domain Owner Methods ---
1163
1618
 
@@ -1403,6 +1858,749 @@ export class User {
1403
1858
  }
1404
1859
  }
1405
1860
 
1861
+ // --- The User account owner (operator account admin: delete and merge) ---
1862
+ //
1863
+ // The User-owned store of the operator account admin (src/account-admin): the USERS doc, its Sessions
1864
+ // subcollection, the ProviderIndex / WalletIndex / SignatureIndex rows that point at the account, and the
1865
+ // merge of a legacy record into its passkey account. Every read and write of those collections the
1866
+ // account admin makes is here; the orchestrator holds no Firestore client. Reached only by the operator
1867
+ // account admin (no command, route or tool).
1868
+
1869
+ /** A read that failed, as ACCOUNT_STORE_READ_FAILED naming the collection. Coded errors pass through. */
1870
+ async function userStoreRead(collection, what, fn) {
1871
+ try {
1872
+ return await fn();
1873
+ } catch (e) {
1874
+ if (e instanceof AccountAdminError) throw e;
1875
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_STORE_READ_FAILED, `the ${collection} read (${what}) failed (${e?.message || e}); nothing was decided from it`, { cause: e });
1876
+ }
1877
+ }
1878
+
1879
+ /** A write that failed, as ACCOUNT_STORE_WRITE_FAILED naming the collection. Coded errors pass through. */
1880
+ async function userStoreWrite(collection, what, fn) {
1881
+ try {
1882
+ return await fn();
1883
+ } catch (e) {
1884
+ if (e instanceof AccountAdminError) throw e;
1885
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_STORE_WRITE_FAILED, `the ${collection} write (${what}) failed (${e?.message || e})`, { cause: e });
1886
+ }
1887
+ }
1888
+
1889
+ const USER_SESSIONS_COLLECTION_ID = 'Sessions';
1890
+
1891
+ /**
1892
+ * A session's footprint path. Its document id IS the live access token, so the path a plan, receipt or
1893
+ * hand-back shows names it by the contract's digest (secretPath): `UserCache/<id>/Sessions/redacted-<16 hex>`.
1894
+ */
1895
+ function sessionEntryPath(user_id, token) {
1896
+ return secretPath(FirestoreCollections.USER_SESSIONS(user_id), String(token));
1897
+ }
1898
+
1899
+ /** The USERS doc's operator delete stamp: written and cleared only by stampDelete / clearDeleteStamp. */
1900
+ const ADMIN_DELETE_FIELD = 'admin_delete';
1901
+
1902
+ /**
1903
+ * The USERS doc as a delete plan records it: its data without the delete stamp this tool writes itself (so the
1904
+ * stamp never makes its own plan stale, and a re-plan of a stamped account plans the same data).
1905
+ */
1906
+ function usersEntryData(doc) {
1907
+ const { [ADMIN_DELETE_FIELD]: _stamp, ...rest } = doc || {};
1908
+ return receiptData(rest);
1909
+ }
1910
+
1911
+ const PLAN_HASH = /^[0-9a-f]{64}$/;
1912
+
1913
+ /** The delete stamp on a USERS doc, or null: { planHash, startedAt }. */
1914
+ function adminDeleteOf(doc) {
1915
+ const s = doc?.[ADMIN_DELETE_FIELD];
1916
+ return s && typeof s === 'object' && typeof s.planHash === 'string' ? Object.freeze({ planHash: s.planHash, startedAt: typeof s.startedAt === 'string' ? s.startedAt : null }) : null;
1917
+ }
1918
+
1919
+ function requireUserId(user, what) {
1920
+ const id = user?.user_id;
1921
+ if (typeof id !== 'string' || !id || id.includes('/')) {
1922
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `${what}: a user { user_id } naming one USERS doc is required (got ${JSON.stringify(id)})`);
1923
+ }
1924
+ return id;
1925
+ }
1926
+
1927
+ /** One USERS doc as the account admin lists and judges it. */
1928
+ function accountViewOf(id, snap) {
1929
+ const doc = snap.exists ? (snap.data() || {}) : null;
1930
+ if (!doc) return Object.freeze({ accountId: id, exists: false });
1931
+ const providers = Array.isArray(doc.auth_providers) ? [...doc.auth_providers] : [];
1932
+ const cid = doc.user_info?.credentialId;
1933
+ const verifiedEmail = typeof doc.verified_email === 'string' && doc.verified_email ? normalizeEmail(doc.verified_email) : null;
1934
+ const emailKeyed = id.includes('@');
1935
+ return Object.freeze({
1936
+ accountId: id,
1937
+ exists: true,
1938
+ email: verifiedEmail ?? (emailKeyed ? normalizeEmail(id) : null),
1939
+ verifiedEmail,
1940
+ emailKeyed,
1941
+ createdAt: snap.createTime ? snap.createTime.toDate().toISOString() : null,
1942
+ providers,
1943
+ hasPasskeyCredential: typeof cid === 'string' && BASE64URL.test(cid) && sanitizeCredentialId(cid) === id && providers.includes(AuthProvider.POWCH),
1944
+ hasPasskeyKey: doc.passkey != null,
1945
+ walletAddress: typeof doc.wallet_address === 'string' && doc.wallet_address ? doc.wallet_address.toLowerCase() : null,
1946
+ roles: Object.keys(doc.roles && typeof doc.roles === 'object' ? doc.roles : {}).sort(),
1947
+ migratedTo: doc.migrated_to || null,
1948
+ adminDelete: adminDeleteOf(doc),
1949
+ });
1950
+ }
1951
+
1952
+ /** Unique, sorted. */
1953
+ const sortedUnique = (xs) => [...new Set(xs)].sort();
1954
+
1955
+ /** Refuse (ACCOUNT_PLAN_STALE, before any write) unless the owner's current paths are exactly the plan's. */
1956
+ function assertExpectedPaths(current, expectPaths, what) {
1957
+ if (!Array.isArray(expectPaths) || expectPaths.some((p) => typeof p !== 'string')) {
1958
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_PLAN_STALE, `${what}: expectPaths (the plan's paths) is required; nothing was written`);
1959
+ }
1960
+ const want = sortedUnique(expectPaths);
1961
+ const have = sortedUnique(current);
1962
+ const added = have.filter((p) => !want.includes(p));
1963
+ const gone = want.filter((p) => !have.includes(p));
1964
+ if (added.length || gone.length) {
1965
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_PLAN_STALE, `${what}: the store changed since the plan (${added.length} new path(s), ${gone.length} gone: ${[...added, ...gone].slice(0, 5).join(', ')}); nothing was written`);
1966
+ }
1967
+ }
1968
+
1969
+ /**
1970
+ * Every document under the USERS doc outside its Sessions subcollection (Purchases, CommunityStats,
1971
+ * RoomConversation/..., any other), at any depth: the user owner never deletes them, and the USERS doc is
1972
+ * not deleted while one remains (a deleted doc does not delete its subcollections). Bounded: past
1973
+ * ACCOUNT_READ_LIMIT documents the walk stops with an ACCOUNT_FOOTPRINT_UNBOUNDED blocker.
1974
+ */
1975
+ async function nestedDocumentPaths(userRef, blockers) {
1976
+ const out = [];
1977
+ let visited = 0;
1978
+ async function walk(ref, top) {
1979
+ const collections = await userStoreRead(ref.path, 'listCollections', () => ref.listCollections());
1980
+ for (const c of collections) {
1981
+ if (top && c.id === USER_SESSIONS_COLLECTION_ID) continue;
1982
+ const refs = await userStoreRead(c.path, 'listDocuments', () => c.listDocuments());
1983
+ for (const d of refs) {
1984
+ visited += 1;
1985
+ if (visited > ACCOUNT_READ_LIMIT) {
1986
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_FOOTPRINT_UNBOUNDED, `more than ${ACCOUNT_READ_LIMIT} documents under ${userRef.path}`));
1987
+ return false;
1988
+ }
1989
+ const snap = await userStoreRead(c.path, d.id, () => d.get());
1990
+ if (snap.exists) out.push(d.path);
1991
+ if ((await walk(d, false)) === false) return false;
1992
+ }
1993
+ }
1994
+ return true;
1995
+ }
1996
+ await walk(userRef, true);
1997
+ return out.sort();
1998
+ }
1999
+
2000
+ /** One bounded query's documents; reaching the limit adds an ACCOUNT_FOOTPRINT_UNBOUNDED blocker. */
2001
+ async function boundedDocs(query, collection, what, blockers) {
2002
+ const snap = await userStoreRead(collection, what, () => query.limit(ACCOUNT_READ_LIMIT).get());
2003
+ if (snap.docs.length >= ACCOUNT_READ_LIMIT) {
2004
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_FOOTPRINT_UNBOUNDED, `${collection} (${what}) reached ${ACCOUNT_READ_LIMIT} documents`));
2005
+ }
2006
+ return snap.docs;
2007
+ }
2008
+
2009
+ /**
2010
+ * The index rows the User owner deletes, with the field that names their account. A row is deleted only in a
2011
+ * transaction that re-reads it and finds that field still naming the account (S3).
2012
+ */
2013
+ const USER_INDEX_ROWS = Object.freeze([
2014
+ { kind: 'provider-index', collection: () => FirestoreCollections.PROVIDER_INDEX(), field: 'descix_user_id' },
2015
+ { kind: 'wallet-index', collection: () => FirestoreCollections.WALLET_INDEX(), field: 'descix_user_id', walletMaterial: true },
2016
+ { kind: 'signature-index', collection: () => FirestoreCollections.SIGNATURE_INDEX(), field: 'user_id' },
2017
+ ]);
2018
+
2019
+ /**
2020
+ * Top-level collections that hold rows about an account by something other than its USERS doc, that the
2021
+ * User owner never deletes and ACCOUNT_STORE_UNOWNED (which sees only documents UNDER the USERS doc) cannot
2022
+ * see. Every delete plan lists them as leftovers.
2023
+ */
2024
+ const USER_STATIC_LEFTOVERS = Object.freeze([
2025
+ { what: 'EmailVerifications/<the account\'s email>', why: 'keyed by the email address, not the account (another account may hold the same verified email); owned by the email-verification module; never removed' },
2026
+ ]);
2027
+
2028
+ /** The user owner's sessions, read bounded: [{ path (by digest), ref, data }]. */
2029
+ async function userSessions(db, id, blockers) {
2030
+ const sessionsPath = FirestoreCollections.USER_SESSIONS(id);
2031
+ return (await boundedDocs(db.collection(sessionsPath), sessionsPath, 'sessions', blockers))
2032
+ .map((d) => ({ path: sessionEntryPath(id, d.id), ref: d.ref, data: d.data() || {} }));
2033
+ }
2034
+
2035
+ const isSessionPath = (id, p) => p.startsWith(`${FirestoreCollections.USER_SESSIONS(id)}/`);
2036
+
2037
+ /** The user owner's delete footprint, with the refs it deletes through (never handed out). */
2038
+ async function userDeleteFootprint(user) {
2039
+ const id = requireUserId(user, 'userAccountOwner.footprintForUser');
2040
+ const db = new CacheFirestore().db;
2041
+ const USERS = FirestoreCollections.USERS();
2042
+ const WALLET_INDEX = FirestoreCollections.WALLET_INDEX();
2043
+ const entries = [];
2044
+ const leftovers = USER_STATIC_LEFTOVERS.map((l) => ({ ...l }));
2045
+ const blockers = [];
2046
+ const refs = new Map();
2047
+ const rows = new Map(); // index-row path -> the USER_INDEX_ROWS spec it was found by
2048
+ const add = (path, ref, kind, summary, raw, flags = {}, data = receiptData(raw)) => {
2049
+ entries.push({ path, kind, summary, data, ...flags });
2050
+ refs.set(path, ref);
2051
+ };
2052
+
2053
+ const userRef = db.collection(USERS).doc(id);
2054
+ const snap = await userStoreRead(USERS, id, () => userRef.get());
2055
+ const doc = snap.exists ? (snap.data() || {}) : null;
2056
+ const walletAddress = typeof doc?.wallet_address === 'string' && doc.wallet_address ? doc.wallet_address.toLowerCase() : null;
2057
+ if (!doc) {
2058
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `no USERS doc ${id}`));
2059
+ } else {
2060
+ const providers = Array.isArray(doc.auth_providers) ? doc.auth_providers.join(', ') : 'no providers';
2061
+ add(`${USERS}/${id}`, userRef, 'user', `the USERS doc (${providers})`, doc, {}, usersEntryData(doc));
2062
+ if (id.includes('@')) {
2063
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_EMAIL_KEYED_LEGACY, `${id} is a legacy email-keyed record; merge it into its passkey account instead of deleting it`));
2064
+ }
2065
+ const roles = Object.keys(doc.roles && typeof doc.roles === 'object' ? doc.roles : {}).sort();
2066
+ if (roles.length) blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_HOLDS_ROLES, `holds role(s) ${roles.join(', ')}`));
2067
+ if (walletAddress) {
2068
+ const row = await userStoreRead(WALLET_INDEX, walletAddress, () => db.collection(WALLET_INDEX).doc(walletAddress).get());
2069
+ const holder = row.exists ? row.data()?.descix_user_id : null;
2070
+ if (holder && holder !== id) {
2071
+ leftovers.push({ what: `${WALLET_INDEX}/${walletAddress}`, why: `points at account ${holder}, not this one; never removed` });
2072
+ }
2073
+ }
2074
+ }
2075
+
2076
+ for (const s of await userSessions(db, id, blockers)) {
2077
+ add(s.path, s.ref, 'session', `a ${s.data.provider || 'unknown-provider'} session (deleted by query at delete time)`, s.data, { volatile: true, pathIsSecret: true });
2078
+ }
2079
+ for (const spec of USER_INDEX_ROWS) {
2080
+ const collection = spec.collection();
2081
+ for (const d of await boundedDocs(db.collection(collection).where(spec.field, '==', id), collection, `${spec.field} == ${id}`, blockers)) {
2082
+ const data = d.data() || {};
2083
+ const path = `${collection}/${d.id}`;
2084
+ add(path, d.ref, spec.kind, `${spec.kind} row${data.provider_type ? ` (${data.provider_type})` : ''}`, data, spec.walletMaterial ? { walletMaterial: true } : {});
2085
+ rows.set(path, spec);
2086
+ // A wallet indexed to this account that is not its wallet_address: nobody measures its value.
2087
+ if (collection === WALLET_INDEX && d.id.toLowerCase() !== walletAddress) {
2088
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_WALLET_VALUE_UNMEASURED, `wallet ${d.id} is indexed to this account but is not its wallet_address; its value is not measured`));
2089
+ }
2090
+ }
2091
+ }
2092
+ const nested = await nestedDocumentPaths(userRef, blockers);
2093
+ return { entries, leftovers, blockers, nested, refs, rows, userRef };
2094
+ }
2095
+
2096
+ /** Refuse (the first blocker's code, all in details) before any write while the footprint has a blocker. */
2097
+ function refuseUserBlockers(blockers, what) {
2098
+ if (!blockers.length) return;
2099
+ throw new AccountAdminError(blockers[0].code, `${what}: ${blockers.map((b) => `${b.code} (${b.detail})`).join('; ')}; nothing was written`, { details: blockers });
2100
+ }
2101
+
2102
+ /**
2103
+ * The User owner's own re-check of a delete plan, writing nothing: its blockers, its non-volatile paths and
2104
+ * their data exactly the plan's (`expectPaths`, `expectData`; sessions are volatile: deleted by query), and no
2105
+ * document under the USERS doc outside `coveredNested` (the dependents' planned paths).
2106
+ */
2107
+ function assertUserDeletePlan(fp, { expectPaths, expectData, coveredNested }, what) {
2108
+ refuseUserBlockers(fp.blockers, what);
2109
+ assertDeletePlanCurrent(what, fp.entries, { expectPaths, expectData });
2110
+ const covered = new Set(coveredNested ?? []);
2111
+ const orphaned = fp.nested.filter((p) => !covered.has(p));
2112
+ if (orphaned.length) {
2113
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_STORE_UNOWNED, `${what}: ${orphaned.length} document(s) under ${fp.userRef.path} that no planned delete covers (${orphaned.slice(0, 5).join(', ')}); the USERS doc is not deleted while they would be orphaned; nothing was written`);
2114
+ }
2115
+ }
2116
+
2117
+ /** Why the from-record keeps its sign-in rows on a merge (merge v1 revokes nothing). */
2118
+ const MERGE_SIGN_IN_STAYS = 'the legacy wallet remains a sign-in identity until its services are re-keyed';
2119
+
2120
+ /** The user owner's merge footprint: the moves, and what stays on the from-record. */
2121
+ async function userMergeFootprint({ from, into } = {}) {
2122
+ const fromId = requireUserId(from, 'userAccountOwner.footprintForMerge (from)');
2123
+ const intoId = requireUserId(into, 'userAccountOwner.footprintForMerge (into)');
2124
+ const db = new CacheFirestore().db;
2125
+ const USERS = FirestoreCollections.USERS();
2126
+ const PROVIDER_INDEX = FirestoreCollections.PROVIDER_INDEX();
2127
+ const entries = [];
2128
+ const leftovers = [];
2129
+ const blockers = [];
2130
+ const raw = new Map();
2131
+
2132
+ const fromSnap = await userStoreRead(USERS, fromId, () => db.collection(USERS).doc(fromId).get());
2133
+ const intoSnap = await userStoreRead(USERS, intoId, () => db.collection(USERS).doc(intoId).get());
2134
+ const fromDoc = fromSnap.exists ? (fromSnap.data() || {}) : null;
2135
+ const intoDoc = intoSnap.exists ? (intoSnap.data() || {}) : null;
2136
+ if (!fromDoc) blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `no USERS doc ${fromId} (the record to merge)`));
2137
+ if (!intoDoc) blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `no USERS doc ${intoId} (the surviving account)`));
2138
+ if (fromId === intoId) blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_MERGE_SAME_RECORD, `${fromId} cannot be merged into itself`));
2139
+
2140
+ if (fromDoc) {
2141
+ const fromView = accountViewOf(fromId, fromSnap);
2142
+ if (fromView.hasPasskeyCredential || fromView.providers.includes(AuthProvider.POWCH)) {
2143
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_MERGE_SOURCE_NOT_LEGACY, `${fromId} is not a legacy record (${fromView.hasPasskeyCredential ? 'it has a passkey credential' : 'it has the powch provider'}); only a legacy record is merged into a passkey account`));
2144
+ }
2145
+ }
2146
+
2147
+ if (fromDoc && intoDoc && fromId !== intoId) {
2148
+ const fromRoles = fromDoc.roles && typeof fromDoc.roles === 'object' ? fromDoc.roles : {};
2149
+ const intoRoles = intoDoc.roles && typeof intoDoc.roles === 'object' ? intoDoc.roles : {};
2150
+ for (const key of Object.keys(fromRoles).sort()) {
2151
+ if (Object.prototype.hasOwnProperty.call(intoRoles, key)) {
2152
+ leftovers.push({ what: `role ${key}`, why: 'the surviving account already holds it; its own grant is kept and the record\'s stays on the record' });
2153
+ continue;
2154
+ }
2155
+ const entry = { path: `${USERS}/${intoId}`, field: 'roles', key, from: null, to: encodeStoreValue(fromRoles[key]), summary: `role ${key} added to the surviving account` };
2156
+ raw.set(entry, fromRoles[key]);
2157
+ entries.push(entry);
2158
+ }
2159
+
2160
+ const email = typeof intoDoc.verified_email === 'string' && intoDoc.verified_email ? normalizeEmail(intoDoc.verified_email) : null;
2161
+ if (email) {
2162
+ const key = User.emailIndexKey(email);
2163
+ const row = await userStoreRead(PROVIDER_INDEX, key, () => db.collection(PROVIDER_INDEX).doc(key).get());
2164
+ const holder = row.exists ? (row.data()?.descix_user_id ?? null) : null;
2165
+ if (holder === null || holder === fromId) {
2166
+ const entry = { path: `${PROVIDER_INDEX}/${key}`, field: 'descix_user_id', from: holder, to: intoId, summary: `the email row for ${email} ${holder ? `moves from ${fromId}` : 'is created'} to the surviving account` };
2167
+ raw.set(entry, { email });
2168
+ entries.push(entry);
2169
+ } else if (holder !== intoId) {
2170
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_MERGE_EMAIL_MISMATCH, `the email row ${key} points at a third account ${holder}`));
2171
+ }
2172
+ }
2173
+
2174
+ // A migrated record is a done merge: a blocker, never a pending migrated_to move.
2175
+ if (fromDoc.migrated_to) {
2176
+ blockers.push(accountAdminBlocker(AccountAdminRefusal.ACCOUNT_MERGE_ALREADY_MIGRATED, `${fromId} is already migrated to ${fromDoc.migrated_to}`));
2177
+ } else {
2178
+ entries.push({ path: `${USERS}/${fromId}`, field: 'migrated_to', from: null, to: intoId, summary: `${fromId} is marked migrated to ${intoId} (with migrated_at)` });
2179
+ }
2180
+
2181
+ // What stays: the record's sign-in identity (sessions, wallet, its wallet and signature rows) and its other provider rows.
2182
+ if (typeof fromDoc.wallet_address === 'string' && fromDoc.wallet_address) {
2183
+ leftovers.push({ what: `wallet_address ${fromDoc.wallet_address.toLowerCase()}`, why: MERGE_SIGN_IN_STAYS });
2184
+ }
2185
+ const sessionsPath = FirestoreCollections.USER_SESSIONS(fromId);
2186
+ for (const d of await boundedDocs(db.collection(sessionsPath), sessionsPath, 'sessions', blockers)) {
2187
+ leftovers.push({ what: sessionEntryPath(fromId, d.id), why: MERGE_SIGN_IN_STAYS });
2188
+ }
2189
+ for (const [collection, field, why] of [
2190
+ [FirestoreCollections.WALLET_INDEX(), 'descix_user_id', MERGE_SIGN_IN_STAYS],
2191
+ [FirestoreCollections.SIGNATURE_INDEX(), 'user_id', MERGE_SIGN_IN_STAYS],
2192
+ [PROVIDER_INDEX, 'descix_user_id', 'stays on the migrated record'],
2193
+ ]) {
2194
+ for (const d of await boundedDocs(db.collection(collection).where(field, '==', fromId), collection, `${field} == ${fromId}`, blockers)) {
2195
+ if (entries.some((e) => e.path === `${collection}/${d.id}`)) continue;
2196
+ leftovers.push({ what: `${collection}/${d.id}`, why });
2197
+ }
2198
+ }
2199
+ }
2200
+ return { entries, leftovers, blockers, raw };
2201
+ }
2202
+
2203
+ /** The value stored at a move's path/field(/key), encoded; null when the document or field is absent. */
2204
+ async function readMoveValue(db, move) {
2205
+ const i = move.path.lastIndexOf('/');
2206
+ const collection = move.path.slice(0, i);
2207
+ const snap = await userStoreRead(collection, `re-read ${move.path}`, () => db.collection(collection).doc(move.path.slice(i + 1)).get());
2208
+ if (!snap.exists) return null;
2209
+ const doc = snap.data() || {};
2210
+ const value = move.key === undefined ? doc[move.field] : doc[move.field]?.[move.key];
2211
+ return encodeStoreValue(value ?? null);
2212
+ }
2213
+
2214
+ const sameValue = (a, b) => canonicalJson(a ?? null) === canonicalJson(b ?? null);
2215
+ const moveRef = (m) => (m.key === undefined ? { path: m.path, field: m.field } : { path: m.path, field: m.field, key: m.key });
2216
+ const publicMove = (m) => ({ ...moveRef(m), from: m.from, to: m.to });
2217
+
2218
+ /**
2219
+ * THE User owner of the operator account admin (`name: 'user'`): the store-owner contract
2220
+ * (src/account-admin/contract.js) for the User-owned collections, plus the account reads the orchestrator
2221
+ * judges by. Every method fails loud with an AccountAdminError code.
2222
+ */
2223
+ export const userAccountOwner = Object.freeze({
2224
+ name: 'user',
2225
+ /** A session's document id is its access token: every Sessions entry is a secretPath (pathIsSecret). */
2226
+ credentialIdCollections: Object.freeze([USER_SESSIONS_COLLECTION_ID]),
2227
+
2228
+ /**
2229
+ * Read-only: one account as the admin judges it ({ accountId, exists:false } when there is no USERS doc).
2230
+ * @param {string} accountId
2231
+ */
2232
+ async account(accountId) {
2233
+ if (typeof accountId !== 'string' || !accountId || accountId.includes('/')) {
2234
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `an account id is required (got ${JSON.stringify(accountId)})`);
2235
+ }
2236
+ const USERS = FirestoreCollections.USERS();
2237
+ const snap = await userStoreRead(USERS, accountId, () => new CacheFirestore().db.collection(USERS).doc(accountId).get());
2238
+ return accountViewOf(accountId, snap);
2239
+ },
2240
+
2241
+ /**
2242
+ * Read-only: every USERS doc whose `verified_email`, or whose document id (the legacy email-keyed form),
2243
+ * starts with one of `emailPrefixes` (lowercase local parts ending in '@' or '+'), sorted by id. The caller
2244
+ * filters by its rule. No unfiltered listing; a read reaching ACCOUNT_READ_LIMIT refuses (no partial list).
2245
+ * @param {string[]} emailPrefixes
2246
+ */
2247
+ async accountsByEmailPrefixes(emailPrefixes) {
2248
+ if (!Array.isArray(emailPrefixes) || emailPrefixes.length === 0 || emailPrefixes.some((p) => typeof p !== 'string' || !EMAIL_PREFIX.test(p))) {
2249
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_RULE_INVALID, `emailPrefixes must be a non-empty array of lowercase local parts ending in '@' or '+' (got ${JSON.stringify(emailPrefixes)}); there is no unfiltered listing`);
2250
+ }
2251
+ const USERS = FirestoreCollections.USERS();
2252
+ const users = new CacheFirestore().db.collection(USERS);
2253
+ const byId = new Map();
2254
+ for (const prefix of new Set(emailPrefixes)) {
2255
+ for (const [field, label] of [['verified_email', 'verified_email'], [Firestore.FieldPath.documentId(), 'document id']]) {
2256
+ const snap = await userStoreRead(USERS, `${label} range '${prefix}'`, () => users.where(field, '>=', prefix).where(field, '<', `${prefix}`).limit(ACCOUNT_READ_LIMIT).get());
2257
+ if (snap.docs.length >= ACCOUNT_READ_LIMIT) {
2258
+ throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_FOOTPRINT_UNBOUNDED, `the ${USERS} ${label} range '${prefix}' reached ${ACCOUNT_READ_LIMIT} documents; no partial listing`);
2259
+ }
2260
+ for (const d of snap.docs) byId.set(d.id, d);
2261
+ }
2262
+ }
2263
+ return [...byId.keys()].sort().map((id) => accountViewOf(id, byId.get(id)));
2264
+ },
2265
+
2266
+ /**
2267
+ * The database of the Firestore client every User-owner read and write goes through (CacheFirestore's
2268
+ * client of the @descix/cloud-core this package resolves), read from the client itself.
2269
+ * @returns {{ databaseId: string, projectId?: string }}
2270
+ */
2271
+ storeTarget() {
2272
+ const db = new CacheFirestore().db;
2273
+ let projectId;
2274
+ try {
2275
+ projectId = db.projectId;
2276
+ } catch {
2277
+ projectId = undefined; // not known before the client's first request; databaseId is
2278
+ }
2279
+ return { databaseId: db.databaseId, ...(typeof projectId === 'string' && projectId ? { projectId } : {}) };
2280
+ },
2281
+
2282
+ /**
2283
+ * Read-only delete footprint: the USERS doc, its Sessions (paths name each by a digest, never the
2284
+ * token; `volatile`: deleted by query at delete time), the ProviderIndex / WalletIndex rows whose
2285
+ * descix_user_id is this id (WalletIndex rows `walletMaterial`), the SignatureIndex rows whose user_id is
2286
+ * this id. A WalletIndex row for an address other than the account's wallet_address is an
2287
+ * ACCOUNT_WALLET_VALUE_UNMEASURED blocker. `leftovers` include USER_STATIC_LEFTOVERS. `nested` lists
2288
+ * every other document under the USERS doc (another owner's; the orchestrator refuses unless another
2289
+ * owner's footprint covers each one).
2290
+ * @param {{ user_id: string }} user
2291
+ */
2292
+ async footprintForUser(user) {
2293
+ const { entries, leftovers, blockers, nested } = await userDeleteFootprint(user);
2294
+ return { entries, leftovers, blockers, nested };
2295
+ },
2296
+
2297
+ /**
2298
+ * Read-only: the User owner's own re-check of a delete plan before the orchestrator's FIRST dependent
2299
+ * write (and again before an irrecoverable owner). Throws, writing nothing: the first blocker's code
2300
+ * (roles, email-keyed, not found, an unmeasured wallet), ACCOUNT_PLAN_STALE when its non-session paths
2301
+ * are not exactly `expectPaths`, ACCOUNT_STORE_UNOWNED when a document under the USERS doc is not in
2302
+ * `coveredNested` (the paths the dependents will delete).
2303
+ * @param {{ user_id: string }} user
2304
+ * @param {{ expectPaths: string[], coveredNested: string[] }} opts
2305
+ * @returns {Promise<true>}
2306
+ */
2307
+ async preflightDelete(user, { expectPaths, expectData, coveredNested } = {}) {
2308
+ assertUserDeletePlan(await userDeleteFootprint(user), { expectPaths, expectData, coveredNested }, 'userAccountOwner.preflightDelete');
2309
+ return true;
2310
+ },
2311
+
2312
+ /**
2313
+ * Stamp the USERS doc `admin_delete: { planHash, startedAt }` (the operator account admin's commitDelete,
2314
+ * before its first dependent write), in ONE transaction that reads the doc and refuses, writing nothing:
2315
+ * no doc (ACCOUNT_NOT_FOUND), data other than the plan's (ACCOUNT_PLAN_STALE; the stamp itself is not part
2316
+ * of a plan's data, so a re-commit over an earlier stamp proceeds and replaces it). restoreDelete honours a
2317
+ * receipt only while the stamp names that receipt's plan. No reader branches on the stamp: the account
2318
+ * stays usable by its owner.
2319
+ * @param {{ user_id: string }} user
2320
+ * @param {{ planHash: string, startedAt: string, expectData: Object<string, string> }} opts
2321
+ * @returns {Promise<true>}
2322
+ */
2323
+ async stampDelete(user, { planHash, startedAt, expectData } = {}) {
2324
+ const id = requireUserId(user, 'userAccountOwner.stampDelete');
2325
+ const what = 'userAccountOwner.stampDelete';
2326
+ if (typeof planHash !== 'string' || !PLAN_HASH.test(planHash)) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_PLAN_STALE, `${what}: planHash (the plan's sha256) is required; nothing was written`);
2327
+ if (typeof startedAt !== 'string' || Number.isNaN(Date.parse(startedAt))) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_PLAN_STALE, `${what}: startedAt (an ISO time) is required; nothing was written`);
2328
+ const USERS = FirestoreCollections.USERS();
2329
+ const db = new CacheFirestore().db;
2330
+ const ref = db.collection(USERS).doc(id);
2331
+ await userStoreWrite(USERS, `${id} ${ADMIN_DELETE_FIELD}`, () => db.runTransaction(async (tx) => {
2332
+ const snap = await tx.get(ref);
2333
+ if (!snap.exists) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `${what}: no USERS doc ${id}; nothing was written`);
2334
+ assertDocumentAsPlanned(what, `${USERS}/${id}`, usersEntryData(snap.data()), expectData);
2335
+ tx.update(ref, { [ADMIN_DELETE_FIELD]: { planHash, startedAt } });
2336
+ }));
2337
+ return true;
2338
+ },
2339
+
2340
+ /**
2341
+ * Remove the USERS doc's `admin_delete` stamp (restoreDelete, once every restorable entry is back), in ONE
2342
+ * transaction, only while it names `planHash`. Returns true when removed, false when the doc carries no
2343
+ * stamp or another plan's (left in place). ACCOUNT_NOT_FOUND when there is no USERS doc.
2344
+ * @param {{ user_id: string }} user
2345
+ * @param {{ planHash: string }} opts
2346
+ * @returns {Promise<boolean>}
2347
+ */
2348
+ async clearDeleteStamp(user, { planHash } = {}) {
2349
+ const id = requireUserId(user, 'userAccountOwner.clearDeleteStamp');
2350
+ const USERS = FirestoreCollections.USERS();
2351
+ const db = new CacheFirestore().db;
2352
+ const ref = db.collection(USERS).doc(id);
2353
+ return userStoreWrite(USERS, `${id} ${ADMIN_DELETE_FIELD}`, () => db.runTransaction(async (tx) => {
2354
+ const snap = await tx.get(ref);
2355
+ if (!snap.exists) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `userAccountOwner.clearDeleteStamp: no USERS doc ${id}; nothing was written`);
2356
+ if (adminDeleteOf(snap.data())?.planHash !== planHash) return false;
2357
+ tx.update(ref, { [ADMIN_DELETE_FIELD]: FieldValue.delete() });
2358
+ return true;
2359
+ }));
2360
+ },
2361
+
2362
+ /**
2363
+ * Delete the account's User-owned documents. Refused before any write: a blocker (re-checked at this
2364
+ * turn), non-session paths other than `expectPaths` (ACCOUNT_PLAN_STALE), any document left under the
2365
+ * USERS doc (ACCOUNT_STORE_UNOWNED). Sessions are deleted BY QUERY (every session of this id, bounded),
2366
+ * so a sign-in or an expiry since the plan does not make it stale; `alsoDeleted` names sessions the plan
2367
+ * did not know. Each index row is deleted in a transaction that re-reads it and deletes it only while it
2368
+ * still names this account; otherwise it is left, reported in `remaining` and `reasons`. The USERS doc
2369
+ * goes LAST. Then every expected path is re-read.
2370
+ * @param {{ user_id: string }} user
2371
+ * @param {{ expectPaths: string[] }} opts
2372
+ * @returns {Promise<{ deleted: string[], remaining: string[], alsoDeleted: string[], reasons: Array<{ path: string, reason: string }> }>}
2373
+ */
2374
+ async deleteForUser(user, { expectPaths, expectData } = {}) {
2375
+ const fp = await userDeleteFootprint(user);
2376
+ const what = 'userAccountOwner.deleteForUser';
2377
+ assertUserDeletePlan(fp, { expectPaths, expectData, coveredNested: [] }, what);
2378
+ const id = fp.userRef.id;
2379
+ const db = new CacheFirestore().db;
2380
+ const reasons = [];
2381
+ const planned = new Set(expectPaths);
2382
+ const sessions = fp.entries.filter((e) => e.kind === 'session');
2383
+ for (const e of sessions) await userStoreWrite(FirestoreCollections.USER_SESSIONS(id), `delete ${e.path}`, () => fp.refs.get(e.path).delete());
2384
+ for (const e of fp.entries.filter((x) => fp.rows.has(x.path))) {
2385
+ const { field } = fp.rows.get(e.path);
2386
+ const ref = fp.refs.get(e.path);
2387
+ const left = await userStoreWrite(e.path.split('/')[0], `delete ${e.path}`, () => db.runTransaction(async (tx) => {
2388
+ const snap = await tx.get(ref);
2389
+ if (!snap.exists) return null;
2390
+ const holder = snap.data()?.[field] ?? null;
2391
+ if (holder !== id) return `its ${field} now names ${JSON.stringify(holder)}, not ${id}; left in place`;
2392
+ // Read, compare and delete in one transaction: a row changed since the plan stops the delete here.
2393
+ assertDocumentAsPlanned(what, e.path, receiptData(snap.data()), expectData);
2394
+ tx.delete(ref);
2395
+ return null;
2396
+ }));
2397
+ if (left) reasons.push({ path: e.path, reason: left });
2398
+ }
2399
+ const userEntry = fp.entries.find((e) => e.kind === 'user');
2400
+ if (userEntry) {
2401
+ const ref = fp.refs.get(userEntry.path);
2402
+ // The USERS doc goes in one transaction that re-reads it: a save since the plan leaves it (ACCOUNT_PLAN_STALE).
2403
+ await userStoreWrite(FirestoreCollections.USERS(), `delete ${userEntry.path}`, () => db.runTransaction(async (tx) => {
2404
+ const snap = await tx.get(ref);
2405
+ if (!snap.exists) return;
2406
+ assertDocumentAsPlanned(what, userEntry.path, usersEntryData(snap.data()), expectData);
2407
+ tx.delete(ref);
2408
+ }));
2409
+ }
2410
+
2411
+ const sessionsNow = new Set((await userSessions(db, id, [])).map((s) => s.path));
2412
+ const deleted = [];
2413
+ const remaining = [];
2414
+ for (const p of expectPaths) {
2415
+ let present;
2416
+ if (isSessionPath(id, p)) present = sessionsNow.has(p);
2417
+ else present = (await userStoreRead(p.split('/')[0], `re-read ${p}`, () => fp.refs.get(p).get())).exists;
2418
+ (present ? remaining : deleted).push(p);
2419
+ }
2420
+ const alsoDeleted = sessions.map((e) => e.path).filter((p) => !planned.has(p) && !sessionsNow.has(p));
2421
+ return { deleted, remaining, alsoDeleted, reasons };
2422
+ },
2423
+
2424
+ /**
2425
+ * Read-only merge footprint. `entries` are the moves: { path, field, key?, from, to, summary } (`from`
2426
+ * null = absent; `key` names a map entry of `field`, e.g. one role). `leftovers` stay on the from-record:
2427
+ * its sessions (by digest), wallet_address, WalletIndex and SignatureIndex rows (the legacy wallet
2428
+ * remains a sign-in identity until its services are re-keyed), its other ProviderIndex rows, and roles
2429
+ * the surviving account already holds. A record already migrated is a blocker, not a move.
2430
+ * @param {{ from: { user_id: string }, into: { user_id: string } }} pair
2431
+ */
2432
+ async footprintForMerge(pair) {
2433
+ const { entries, leftovers, blockers } = await userMergeFootprint(pair);
2434
+ return { entries: entries.map((e) => ({ ...publicMove(e), summary: e.summary })), leftovers, blockers };
2435
+ },
2436
+
2437
+ /**
2438
+ * Merge: roles the surviving account lacks are added to it (one transaction, only keys still absent);
2439
+ * the email ProviderIndex row is pointed at it (only while it still names the plan's holder; created
2440
+ * when absent); the from-record is marked migrated LAST (User.markMigrated). Nothing else is written:
2441
+ * the from-record's sessions, wallet and index rows stay (it remains a sign-in identity). Refuses before
2442
+ * any write on a blocker or ACCOUNT_PLAN_STALE. Then re-reads.
2443
+ * @param {{ from: { user_id: string }, into: { user_id: string } }} pair
2444
+ * @param {{ expectPaths: string[] }} opts - the plan's move paths
2445
+ * @returns {Promise<{ moved: Array<{path, field, key?, from, to}>, remaining: Array<{path, field, key?}> }>}
2446
+ */
2447
+ async mergeForUser(pair, { expectPaths } = {}) {
2448
+ const fp = await userMergeFootprint(pair);
2449
+ if (fp.blockers.length) {
2450
+ throw new AccountAdminError(fp.blockers[0].code, `userAccountOwner.mergeForUser: ${fp.blockers.map((b) => `${b.code} (${b.detail})`).join('; ')}; nothing was written`, { details: fp.blockers });
2451
+ }
2452
+ assertExpectedPaths(fp.entries.map((e) => e.path), expectPaths, 'userAccountOwner.mergeForUser');
2453
+ const fromId = pair.from.user_id;
2454
+ const intoId = pair.into.user_id;
2455
+ const db = new CacheFirestore().db;
2456
+ const USERS = FirestoreCollections.USERS();
2457
+ const PROVIDER_INDEX = FirestoreCollections.PROVIDER_INDEX();
2458
+
2459
+ const roleMoves = fp.entries.filter((e) => e.field === 'roles');
2460
+ if (roleMoves.length) {
2461
+ const ref = db.collection(USERS).doc(intoId);
2462
+ await userStoreWrite(USERS, `${intoId} roles`, () => db.runTransaction(async (tx) => {
2463
+ const snap = await tx.get(ref);
2464
+ if (!snap.exists) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_NOT_FOUND, `no USERS doc ${intoId}; nothing was written`);
2465
+ const roles = { ...(snap.data()?.roles || {}) };
2466
+ let added = 0;
2467
+ for (const m of roleMoves) {
2468
+ if (Object.prototype.hasOwnProperty.call(roles, m.key)) continue;
2469
+ roles[m.key] = fp.raw.get(m);
2470
+ added += 1;
2471
+ }
2472
+ if (added) tx.update(ref, { roles });
2473
+ }));
2474
+ }
2475
+ const reasons = new Map();
2476
+ for (const m of fp.entries.filter((e) => e.path.startsWith(`${PROVIDER_INDEX}/`))) {
2477
+ const ref = db.collection(PROVIDER_INDEX).doc(m.path.slice(PROVIDER_INDEX.length + 1));
2478
+ const { email } = fp.raw.get(m);
2479
+ const left = await userStoreWrite(PROVIDER_INDEX, m.path, () => db.runTransaction(async (tx) => {
2480
+ const snap = await tx.get(ref);
2481
+ const holder = snap.exists ? (snap.data()?.descix_user_id ?? null) : null;
2482
+ // Moved only while it still names the plan's holder (the record, or nobody): never a third account's row.
2483
+ if (holder !== m.from) return `the email row now names ${JSON.stringify(holder)}, not ${JSON.stringify(m.from)}; left in place`;
2484
+ if (snap.exists) tx.update(ref, { descix_user_id: intoId });
2485
+ else tx.set(ref, { descix_user_id: intoId, provider_type: 'email', provider_id: email, linked_at: Timestamp.now() });
2486
+ return null;
2487
+ }));
2488
+ if (left) reasons.set(moveKey(m), left);
2489
+ }
2490
+ // markMigrated reads the doc in its own transaction (never CacheFirestore.get_doc, which answers a failed read as null).
2491
+ await new User(fromId).markMigrated(intoId);
2492
+
2493
+ const moved = [];
2494
+ const remaining = [];
2495
+ for (const m of fp.entries) {
2496
+ (sameValue(await readMoveValue(db, m), m.to) ? moved : remaining).push(m);
2497
+ }
2498
+ return { moved: moved.map(publicMove), remaining: remaining.map((m) => ({ ...moveRef(m), ...(reasons.has(moveKey(m)) ? { reason: reasons.get(moveKey(m)) } : {}) })) };
2499
+ },
2500
+
2501
+ /**
2502
+ * Throws ACCOUNT_RECEIPT_INVALID, writing nothing, unless every move is one mergeForUser makes for
2503
+ * `pair`: the migration mark on USERS/<from> (from null, to <into>), a role added to USERS/<into> (from
2504
+ * null, a key), or the email row of the surviving account's verified email (field descix_user_id, from
2505
+ * null or <from>, to <into>).
2506
+ * @param {Array<{ path: string, field: string, key?: string, from: unknown, to: unknown }>} moves
2507
+ * @param {{ from: { user_id: string }, into: { user_id: string, verified_email?: string|null } }} pair
2508
+ */
2509
+ validateRollbackMoves(moves, pair) {
2510
+ const fromId = requireUserId(pair?.from, 'userAccountOwner.validateRollbackMoves (from)');
2511
+ const intoId = requireUserId(pair?.into, 'userAccountOwner.validateRollbackMoves (into)');
2512
+ const USERS = FirestoreCollections.USERS();
2513
+ const email = typeof pair.into.verified_email === 'string' && pair.into.verified_email ? normalizeEmail(pair.into.verified_email) : null;
2514
+ const emailRow = email ? `${FirestoreCollections.PROVIDER_INDEX()}/${User.emailIndexKey(email)}` : null;
2515
+ if (!Array.isArray(moves)) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_RECEIPT_INVALID, 'userAccountOwner: the receipt\'s user moves are required; nothing was written');
2516
+ for (const m of moves) {
2517
+ const why = (() => {
2518
+ if (typeof m?.path !== 'string' || typeof m?.field !== 'string') return 'it names no path/field';
2519
+ if (m.path === `${USERS}/${fromId}`) {
2520
+ return m.field === 'migrated_to' && m.key === undefined && m.from === null && m.to === intoId ? null : `the only move on ${m.path} is its migrated_to mark to ${intoId}`;
2521
+ }
2522
+ if (m.path === `${USERS}/${intoId}`) {
2523
+ return m.field === 'roles' && typeof m.key === 'string' && m.key && m.from === null ? null : `the only move on ${m.path} is a role it lacked`;
2524
+ }
2525
+ if (emailRow && m.path === emailRow) {
2526
+ return m.field === 'descix_user_id' && m.key === undefined && (m.from === null || m.from === fromId) && m.to === intoId ? null : `the email row moves from ${fromId} (or nobody) to ${intoId}`;
2527
+ }
2528
+ return `${m.path} is not USERS/${fromId}, USERS/${intoId} or the surviving account's email row`;
2529
+ })();
2530
+ if (why) throw new AccountAdminError(AccountAdminRefusal.ACCOUNT_RECEIPT_INVALID, `userAccountOwner: receipt move ${JSON.stringify(m)?.slice(0, 200)} is not one a merge of ${fromId} into ${intoId} makes (${why}); nothing was written`);
2531
+ }
2532
+ },
2533
+
2534
+ /**
2535
+ * The rollback of mergeForUser from its receipt's user moves. In reverse order: the migration mark (User.unmarkMigrated, only while it names
2536
+ * the receipt's account), the email row (only while it names the surviving account: back to the record,
2537
+ * or deleted when the merge created it), the roles the merge added (only while each still equals what
2538
+ * was added). A move whose current value is not the receipt's `to` is left and reported remaining.
2539
+ * Every move is validated (validateRollbackMoves) before the first write.
2540
+ * @param {Array<{ path: string, field: string, key?: string, from: unknown, to: unknown }>} moves
2541
+ * @param {{ from: { user_id: string }, into: { user_id: string, verified_email?: string|null } }} pair
2542
+ * @returns {Promise<{ restored: Array<{path, field, key?}>, remaining: Array<{path, field, key?}> }>}
2543
+ */
2544
+ async rollbackMergeForUser(moves, pair) {
2545
+ userAccountOwner.validateRollbackMoves(moves, pair);
2546
+ const db = new CacheFirestore().db;
2547
+ const USERS = FirestoreCollections.USERS();
2548
+ const PROVIDER_INDEX = FirestoreCollections.PROVIDER_INDEX();
2549
+ const errors = [];
2550
+ const attempt = async (fn) => { try { await fn(); } catch (e) { errors.push(e); } };
2551
+
2552
+ for (const m of moves.filter((x) => x.field === 'migrated_to')) {
2553
+ const id = m.path.slice(USERS.length + 1);
2554
+ await attempt(() => new User(id).unmarkMigrated(m.to));
2555
+ }
2556
+ for (const m of moves.filter((x) => x.path.startsWith(`${PROVIDER_INDEX}/`))) {
2557
+ const ref = db.collection(PROVIDER_INDEX).doc(m.path.slice(PROVIDER_INDEX.length + 1));
2558
+ await attempt(() => userStoreWrite(PROVIDER_INDEX, m.path, () => db.runTransaction(async (tx) => {
2559
+ const snap = await tx.get(ref);
2560
+ if (!snap.exists || snap.data()?.descix_user_id !== m.to) return;
2561
+ if (m.from === null) tx.delete(ref);
2562
+ else tx.update(ref, { descix_user_id: m.from });
2563
+ })));
2564
+ }
2565
+ const roleMoves = moves.filter((x) => x.field === 'roles');
2566
+ for (const path of sortedUnique(roleMoves.map((m) => m.path))) {
2567
+ const ref = db.collection(USERS).doc(path.slice(USERS.length + 1));
2568
+ await attempt(() => userStoreWrite(USERS, `${path} roles`, () => db.runTransaction(async (tx) => {
2569
+ const snap = await tx.get(ref);
2570
+ if (!snap.exists) return;
2571
+ const roles = { ...(snap.data()?.roles || {}) };
2572
+ let removed = 0;
2573
+ for (const m of roleMoves.filter((x) => x.path === path)) {
2574
+ if (Object.prototype.hasOwnProperty.call(roles, m.key) && sameValue(encodeStoreValue(roles[m.key]), m.to)) {
2575
+ delete roles[m.key];
2576
+ removed += 1;
2577
+ }
2578
+ }
2579
+ if (removed) tx.update(ref, { roles });
2580
+ })));
2581
+ }
2582
+
2583
+ const restored = [];
2584
+ const remaining = [];
2585
+ for (const m of moves) {
2586
+ (sameValue(await readMoveValue(db, m), m.from) ? restored : remaining).push(moveRef(m));
2587
+ }
2588
+ return { restored, remaining, errors: errors.map((e) => ({ code: e.code ?? null, message: e.message })) };
2589
+ },
2590
+
2591
+ /**
2592
+ * Read-only: the current value at each move's path/field(/key), encoded (null when absent).
2593
+ * @param {Array<{ path: string, field: string, key?: string }>} moves
2594
+ * @returns {Promise<Array<{ path: string, field: string, key?: string, value: unknown }>>}
2595
+ */
2596
+ async readMergeFields(moves) {
2597
+ const db = new CacheFirestore().db;
2598
+ const out = [];
2599
+ for (const m of moves) out.push({ ...moveRef(m), value: await readMoveValue(db, m) });
2600
+ return out;
2601
+ },
2602
+ });
2603
+
1406
2604
  // --- Community Class ---
1407
2605
 
1408
2606
  export class Community {