@descix/platform-api 5.1.1 → 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.
@@ -0,0 +1,513 @@
1
+ /**
2
+ * The account-admin contract every store owner implements and the orchestrator (./index.js) consumes:
3
+ * the refusal code table, the error, the outcome tables, the store-owner method lists, and the receipt
4
+ * value rules (credential redaction, a JSON-safe encoding of store values, a canonical hash). Pure: no
5
+ * Firestore, no file, no network. Store owners in Cloud and Powch import these from
6
+ * @descix/platform-api; none re-enumerates them.
7
+ */
8
+ import crypto from 'node:crypto';
9
+
10
+ /** Why an account-admin act refused or a store owner failed. A consumer branches on the code, never the message. */
11
+ export const AccountAdminRefusal = Object.freeze({
12
+ ACCOUNT_RULE_INVALID: 'ACCOUNT_RULE_INVALID',
13
+ ACCOUNT_TARGET_INVALID: 'ACCOUNT_TARGET_INVALID',
14
+ ACCOUNT_NOT_IN_RULE: 'ACCOUNT_NOT_IN_RULE',
15
+ ACCOUNT_NOT_FOUND: 'ACCOUNT_NOT_FOUND',
16
+ ACCOUNT_EMAIL_KEYED_LEGACY: 'ACCOUNT_EMAIL_KEYED_LEGACY',
17
+ ACCOUNT_OWNS_PRODUCTS: 'ACCOUNT_OWNS_PRODUCTS',
18
+ ACCOUNT_HOLDS_ROLES: 'ACCOUNT_HOLDS_ROLES',
19
+ ACCOUNT_PAID_PURCHASES: 'ACCOUNT_PAID_PURCHASES',
20
+ ACCOUNT_WALLET_VALUE_UNMEASURED: 'ACCOUNT_WALLET_VALUE_UNMEASURED',
21
+ ACCOUNT_WALLET_HOLDS_VALUE: 'ACCOUNT_WALLET_HOLDS_VALUE',
22
+ ACCOUNT_REFERRAL_DEPENDENTS: 'ACCOUNT_REFERRAL_DEPENDENTS',
23
+ ACCOUNT_KYC_OR_STRIPE_ON_FILE: 'ACCOUNT_KYC_OR_STRIPE_ON_FILE',
24
+ ACCOUNT_PENDING_TRANSFERS: 'ACCOUNT_PENDING_TRANSFERS',
25
+ /** Documents exist under the USERS doc that no store owner's footprint covers (deleting it would orphan them). */
26
+ ACCOUNT_STORE_UNOWNED: 'ACCOUNT_STORE_UNOWNED',
27
+ /** A footprint read reached ACCOUNT_READ_LIMIT: the footprint is not provably complete. */
28
+ ACCOUNT_FOOTPRINT_UNBOUNDED: 'ACCOUNT_FOOTPRINT_UNBOUNDED',
29
+ /** The store changed since the plan, or the plan is unknown, used or expired. */
30
+ ACCOUNT_PLAN_STALE: 'ACCOUNT_PLAN_STALE',
31
+ ACCOUNT_CONFIRMATION_MISMATCH: 'ACCOUNT_CONFIRMATION_MISMATCH',
32
+ ACCOUNT_STORE_READ_FAILED: 'ACCOUNT_STORE_READ_FAILED',
33
+ ACCOUNT_STORE_WRITE_FAILED: 'ACCOUNT_STORE_WRITE_FAILED',
34
+ /** A receipt that is missing, malformed, for another env/target, or that a save did not label. */
35
+ ACCOUNT_RECEIPT_INVALID: 'ACCOUNT_RECEIPT_INVALID',
36
+ ACCOUNT_MERGE_SAME_RECORD: 'ACCOUNT_MERGE_SAME_RECORD',
37
+ ACCOUNT_MERGE_EMAIL_MISMATCH: 'ACCOUNT_MERGE_EMAIL_MISMATCH',
38
+ ACCOUNT_MERGE_TARGET_NOT_PASSKEY: 'ACCOUNT_MERGE_TARGET_NOT_PASSKEY',
39
+ ACCOUNT_MERGE_ALREADY_MIGRATED: 'ACCOUNT_MERGE_ALREADY_MIGRATED',
40
+ /** The record to merge is not a legacy record: it has a passkey credential or the powch provider. */
41
+ ACCOUNT_MERGE_SOURCE_NOT_LEGACY: 'ACCOUNT_MERGE_SOURCE_NOT_LEGACY',
42
+ });
43
+
44
+ const CODES = new Set(Object.values(AccountAdminRefusal));
45
+
46
+ /** The brand every AccountAdminError carries, global so a second copy of this package recognises the first's errors. */
47
+ const ACCOUNT_ADMIN_ERROR = Symbol.for('@descix/platform-api/AccountAdminError');
48
+
49
+ /**
50
+ * A refusal or a store failure. `code` is an AccountAdminRefusal value; `details` (optional) is extra
51
+ * structured data (e.g. the plan's blockers when a commit is refused for them). `instanceof` holds across
52
+ * two installed copies of @descix/platform-api (Cloud's and Powch's node_modules vs the orchestrator's);
53
+ * a plain Error carrying a code is not one.
54
+ */
55
+ export class AccountAdminError extends Error {
56
+ constructor(code, message, { cause, details } = {}) {
57
+ if (!CODES.has(code)) throw new Error(`AccountAdminError: unknown code ${code}`);
58
+ super(message, cause ? { cause } : undefined);
59
+ this.name = 'AccountAdminError';
60
+ this.code = code;
61
+ if (details !== undefined) this.details = details;
62
+ Object.defineProperty(this, ACCOUNT_ADMIN_ERROR, { value: true });
63
+ }
64
+
65
+ static [Symbol.hasInstance](value) {
66
+ return value?.[ACCOUNT_ADMIN_ERROR] === true;
67
+ }
68
+ }
69
+
70
+ /** A blocker a footprint reports: { code, detail }, the code from AccountAdminRefusal. */
71
+ export function accountAdminBlocker(code, detail) {
72
+ if (!CODES.has(code)) throw new Error(`accountAdminBlocker: unknown code ${code}`);
73
+ return Object.freeze({ code, detail: String(detail) });
74
+ }
75
+
76
+ /** The endings of a delete commit that reached its first write. Decided from a read-back only. */
77
+ export const DELETE_OUTCOME = Object.freeze({ DELETED: 'DELETED', NOT_DELETED: 'NOT_DELETED', PARTIAL: 'PARTIAL', UNVERIFIED: 'UNVERIFIED' });
78
+ /** The endings of a merge commit that reached its first write. */
79
+ export const MERGE_OUTCOME = Object.freeze({ MERGED: 'MERGED', NOT_MERGED: 'NOT_MERGED', PARTIAL: 'PARTIAL', UNVERIFIED: 'UNVERIFIED' });
80
+ /** The endings of a merge rollback that reached its first write. */
81
+ export const MERGE_ROLLBACK_OUTCOME = Object.freeze({ ROLLED_BACK: 'ROLLED_BACK', NOT_ROLLED_BACK: 'NOT_ROLLED_BACK', PARTIAL: 'PARTIAL', UNVERIFIED: 'UNVERIFIED' });
82
+ /** The endings of a restore of a PARTIAL delete that reached its first write. */
83
+ export const RESTORE_OUTCOME = Object.freeze({ RESTORED: 'RESTORED', NOT_RESTORED: 'NOT_RESTORED', PARTIAL: 'PARTIAL', UNVERIFIED: 'UNVERIFIED' });
84
+
85
+ /** The most documents one footprint read returns; a read that reaches it is ACCOUNT_FOOTPRINT_UNBOUNDED. */
86
+ export const ACCOUNT_READ_LIMIT = 500;
87
+
88
+ /**
89
+ * Every store owner implements these:
90
+ * - footprintForUser(user) -> { entries, leftovers, blockers } (footprintViolation is the shape rule);
91
+ * - deleteForUser(user, { expectPaths, expectData }) -> { deleted, remaining }: refuses ACCOUNT_PLAN_STALE,
92
+ * before any write, unless its current footprint is the plan's, paths AND data (assertDeletePlanCurrent);
93
+ * an `irrecoverable` owner re-reads each document, compares its data and deletes it INSIDE ONE transaction
94
+ * (assertDocumentAsPlanned);
95
+ * - storeTarget() -> { databaseId: string, projectId?: string } (sync or async): the database of the
96
+ * Firestore client this owner ACTUALLY reads and writes through, read from the client itself.
97
+ * Optional:
98
+ * - `credentialKeys: string[]`: a credential of the store the redactCredentials name rule cannot see
99
+ * (e.g. ['device_code']), passed to receiptData too; the orchestrator and the conformance check enforce it;
100
+ * - `credentialIdCollections: string[]`: collection ids whose document id IS a credential (a session token, a
101
+ * device code, an auth code): every entry of such a collection carries `pathIsSecret: true` and a secretPath;
102
+ * - `irrecoverable: true`: a store whose delete cannot be undone by anyone else (the Powch vault: client-
103
+ * encrypted wallet material); deleted AFTER every other dependent and immediately before the User owner;
104
+ * - restoreForUser(user, entries) -> { restored: [path], remaining: [path] }: re-creates, from a delete
105
+ * receipt's entries, those currently absent, never overwriting an existing document (restoreDelete); it
106
+ * refuses ACCOUNT_RECEIPT_INVALID, writing nothing, an entry its footprintForUser(user) would not list once
107
+ * written (another account's document, another store's path).
108
+ * A footprint entry may carry `walletMaterial: true` (it holds or derives a wallet: a vault, an xPub, a
109
+ * wallet index row), with `unmeasuredNote` (what that material may hold that nobody measured; shown in the
110
+ * plan's notMeasured), `volatile: true` (an entry the owner deletes BY QUERY at delete time, e.g. sessions:
111
+ * its set may change between plan and delete without making the plan stale; never restored) and
112
+ * `pathIsSecret: true` (its `path` is secretPath(collection, id): the document id is a credential; the owner
113
+ * keeps the real path privately and resolves it at delete time by re-reading its own footprint; never restored).
114
+ */
115
+ export const STORE_OWNER_METHODS = Object.freeze(['footprintForUser', 'deleteForUser', 'storeTarget']);
116
+ /** Optional store-owner method: re-create a PARTIAL delete's absent entries (restoreDelete). */
117
+ export const STORE_OWNER_RESTORE_METHOD = 'restoreForUser';
118
+ /**
119
+ * A store owner that moves anything on merge implements ALL of these (or none). validateRollbackMoves(moves,
120
+ * pair) throws ACCOUNT_RECEIPT_INVALID, writing nothing, for any receipt move this owner would not have made
121
+ * for that pair; rollbackMerge calls it on EVERY owner before the first rollback write.
122
+ */
123
+ export const STORE_OWNER_MERGE_METHODS = Object.freeze(['footprintForMerge', 'mergeForUser', 'rollbackMergeForUser', 'validateRollbackMoves']);
124
+ /**
125
+ * The User owner (`name: 'user'`) implements the store-owner methods, the merge methods, and these.
126
+ * preflightDelete(user, { expectPaths, expectData, coveredNested }) re-checks the User owner's own part of a
127
+ * delete plan (its paths and data, its blockers, no document under the USERS doc outside `coveredNested`) and
128
+ * writes nothing. stampDelete(user, { planHash, startedAt, expectData }) writes the USERS doc's `admin_delete`
129
+ * stamp in one transaction that refuses a changed doc; clearDeleteStamp(user, { planHash }) removes the stamp
130
+ * only while it names that plan. It implements no restoreForUser.
131
+ */
132
+ export const USER_OWNER_METHODS = Object.freeze(['account', 'accountsByEmailPrefixes', 'readMergeFields', 'preflightDelete', 'stampDelete', 'clearDeleteStamp']);
133
+
134
+ /**
135
+ * The credential name rule: a key is a credential when, case-insensitively, the whole key or its last
136
+ * `_`/`-` segment(s) is token, secret, password, passphrase, passwd, private_key/privatekey, mnemonic, seed,
137
+ * signature, api_key/apikey, code or otp (access_token, client_secret, device_code, user_code, totp_otp), or,
138
+ * camelCase, it ends in one of those capitalised after a lowercase letter or digit (accessToken, apiKey,
139
+ * privateKey, deviceCode).
140
+ */
141
+ const CREDENTIAL_KEY = /(^|[_-])(token|secret|password|passphrase|passwd|private[_-]?key|mnemonic|seed|signature|api[_-]?key|code|otp)$/i;
142
+ const CREDENTIAL_KEY_CAMEL = /[a-z0-9](Token|Secret|Password|Passphrase|Passwd|PrivateKey|Mnemonic|Seed|Signature|ApiKey|Apikey|Code|Otp)$/;
143
+ export const REDACTED = '[redacted]';
144
+
145
+ /** A credential-key predicate: the name rule, plus the exact extra key names a store owner declares. */
146
+ function credentialKey(keys) {
147
+ if (keys !== undefined && (!Array.isArray(keys) || keys.some((k) => typeof k !== 'string' || !k))) {
148
+ throw new Error(`account-admin redaction: keys must be an array of key names (got ${JSON.stringify(keys)})`);
149
+ }
150
+ const extra = new Set(keys ?? []);
151
+ return (k) => CREDENTIAL_KEY.test(k) || CREDENTIAL_KEY_CAMEL.test(k) || extra.has(k);
152
+ }
153
+
154
+ /**
155
+ * A copy of a store value with every live credential replaced by "[redacted]": any key the credential name
156
+ * rule (CREDENTIAL_KEY above) names, and any key in `keys` (a store's own credential that the name rule
157
+ * cannot see), at any depth. The one redaction rule every owner's receipt data passes through.
158
+ * @param {unknown} value
159
+ * @param {{ keys?: string[] }} [opts]
160
+ */
161
+ export function redactCredentials(value, { keys } = {}) {
162
+ const isCredential = credentialKey(keys);
163
+ const walk = (v) => {
164
+ if (Array.isArray(v)) return v.map(walk);
165
+ if (v && typeof v === 'object' && Object.getPrototypeOf(v) === Object.prototype) {
166
+ const out = {};
167
+ for (const [k, x] of Object.entries(v)) out[k] = isCredential(k) && x != null ? REDACTED : walk(x);
168
+ return out;
169
+ }
170
+ return v;
171
+ };
172
+ return walk(value);
173
+ }
174
+
175
+ const NANOS_PER_SECOND = 1e9;
176
+ const isTimestampParts = (s, n) => Number.isSafeInteger(s) && Number.isInteger(n) && n >= 0 && n < NANOS_PER_SECOND;
177
+
178
+ /**
179
+ * A store value as plain JSON: a Firestore Timestamp (anything with toDate()) becomes
180
+ * { __timestamp: { seconds, nanoseconds } } (exact: Firestore keeps nanoseconds), a Date the same from its
181
+ * milliseconds, bytes become { __bytes: '<base64>' }, a DocumentReference becomes { __ref: '<path>' }, a Map
182
+ * becomes an object; everything else is copied. A timestamp-like value without integer seconds/nanoseconds is
183
+ * refused, never rounded. A receipt holds only this encoding; an owner restoring a timestamp decodes it with
184
+ * decodeStoreTimestamp and its own Timestamp class.
185
+ */
186
+ export function encodeStoreValue(value) {
187
+ if (value === undefined) return null;
188
+ if (value === null || typeof value !== 'object') return value;
189
+ if (typeof value.toDate === 'function') {
190
+ const { seconds, nanoseconds } = value;
191
+ if (!isTimestampParts(seconds, nanoseconds)) {
192
+ throw new TypeError(`encodeStoreValue: a timestamp value without integer seconds/nanoseconds (got ${JSON.stringify({ seconds, nanoseconds })}); it is not encoded through toDate(), which drops sub-millisecond precision`);
193
+ }
194
+ return { __timestamp: { seconds, nanoseconds } };
195
+ }
196
+ if (value instanceof Date) {
197
+ const ms = value.getTime();
198
+ if (!Number.isFinite(ms)) throw new TypeError('encodeStoreValue: an invalid Date');
199
+ const seconds = Math.floor(ms / 1000);
200
+ return { __timestamp: { seconds, nanoseconds: (ms - seconds * 1000) * 1e6 } };
201
+ }
202
+ if (value instanceof Uint8Array) return { __bytes: Buffer.from(value).toString('base64') };
203
+ if (typeof value.path === 'string' && value.firestore) return { __ref: value.path };
204
+ if (value instanceof Map) return encodeStoreValue(Object.fromEntries(value));
205
+ if (Array.isArray(value)) return value.map(encodeStoreValue);
206
+ const out = {};
207
+ for (const [k, v] of Object.entries(value)) out[k] = encodeStoreValue(v);
208
+ return out;
209
+ }
210
+
211
+ /**
212
+ * The Timestamp an encodeStoreValue `{ __timestamp: { seconds, nanoseconds } }` encodes, built with the CALLER's
213
+ * Timestamp class (each owner writes with its own Firestore client's class): exact to the nanosecond. Throws on
214
+ * anything else (another shape, extra keys, out-of-range parts, no Timestamp class); never guesses.
215
+ * @param {unknown} value
216
+ * @param {new (seconds: number, nanoseconds: number) => unknown} Timestamp
217
+ */
218
+ export function decodeStoreTimestamp(value, Timestamp) {
219
+ if (typeof Timestamp !== 'function') throw new TypeError('decodeStoreTimestamp: pass the store client\'s Timestamp class');
220
+ const t = value !== null && typeof value === 'object' && !Array.isArray(value) ? value.__timestamp : undefined;
221
+ const ok = t !== null && typeof t === 'object' && !Array.isArray(t)
222
+ && Object.keys(value).length === 1
223
+ && Object.keys(t).sort().join(',') === 'nanoseconds,seconds'
224
+ && isTimestampParts(t.seconds, t.nanoseconds);
225
+ if (!ok) throw new TypeError(`decodeStoreTimestamp: ${JSON.stringify(value ?? null)?.slice(0, 200)} is not an encoded timestamp { __timestamp: { seconds, nanoseconds } }`);
226
+ return new Timestamp(t.seconds, t.nanoseconds);
227
+ }
228
+
229
+ /**
230
+ * A stored document as a footprint entry's `data`: encoded (encodeStoreValue), then redacted
231
+ * (redactCredentials, with the store's extra credential `keys`).
232
+ * @param {unknown} raw
233
+ * @param {{ keys?: string[] }} [opts]
234
+ */
235
+ export function receiptData(raw, { keys } = {}) {
236
+ return redactCredentials(encodeStoreValue(raw), { keys });
237
+ }
238
+
239
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && [Object.prototype, null].includes(Object.getPrototypeOf(v));
240
+
241
+ /**
242
+ * The dotted path of the first value in `value` that is not plain JSON (null, boolean, string, finite
243
+ * number, array, plain object): a Timestamp, Date, BigInt, undefined, Map, class instance, NaN. Null when
244
+ * the whole value is plain JSON. A receipt, a footprint entry's `data`, a move's from/to and a wallet
245
+ * reading's `details` are plain JSON.
246
+ * @param {unknown} value
247
+ * @param {string} [at] - the label of `value` itself
248
+ * @returns {string|null}
249
+ */
250
+ export function nonJsonValuePath(value, at = '') {
251
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return null;
252
+ if (typeof value === 'number') return Number.isFinite(value) ? null : at || '(value)';
253
+ if (Array.isArray(value)) {
254
+ for (const [i, v] of value.entries()) {
255
+ const bad = nonJsonValuePath(v, `${at}[${i}]`);
256
+ if (bad) return bad;
257
+ }
258
+ return null;
259
+ }
260
+ if (isPlainObject(value)) {
261
+ for (const [k, v] of Object.entries(value)) {
262
+ const bad = nonJsonValuePath(v, at ? `${at}.${k}` : k);
263
+ if (bad) return bad;
264
+ }
265
+ return null;
266
+ }
267
+ return at || '(value)';
268
+ }
269
+
270
+ /**
271
+ * The dotted path of every credential key (the redactCredentials rule, with the same extra `keys`) that
272
+ * holds a value other than null or "[redacted]": an empty array means `value` is redacted.
273
+ * @param {unknown} value
274
+ * @param {{ keys?: string[] }} [opts]
275
+ * @returns {string[]}
276
+ */
277
+ export function unredactedCredentialPaths(value, { keys } = {}) {
278
+ const isCredential = credentialKey(keys);
279
+ const walk = (v, at) => {
280
+ if (Array.isArray(v)) return v.flatMap((x, i) => walk(x, `${at}[${i}]`));
281
+ if (!v || typeof v !== 'object') return [];
282
+ return Object.entries(v).flatMap(([k, x]) => {
283
+ const here = at ? `${at}.${k}` : k;
284
+ if (isCredential(k) && x != null && x !== REDACTED) return [here];
285
+ return walk(x, here);
286
+ });
287
+ };
288
+ return walk(value, '');
289
+ }
290
+
291
+ /**
292
+ * Every string value held under a credential key (the redactCredentials rule, with the same extra `keys`), at
293
+ * any depth, of a RAW store value: what a receipt redacts. The conformance check uses it to refuse a path that
294
+ * names one of them.
295
+ * @param {unknown} value
296
+ * @param {{ keys?: string[] }} [opts]
297
+ * @returns {string[]}
298
+ */
299
+ export function credentialValues(value, { keys } = {}) {
300
+ const isCredential = credentialKey(keys);
301
+ const out = [];
302
+ const strings = (v) => {
303
+ if (typeof v === 'string' && v) out.push(v);
304
+ else if (Array.isArray(v)) v.forEach(strings);
305
+ else if (v && typeof v === 'object') Object.values(v).forEach(strings);
306
+ };
307
+ const walk = (v) => {
308
+ if (Array.isArray(v)) return v.forEach(walk);
309
+ if (!v || typeof v !== 'object') return undefined;
310
+ for (const [k, x] of Object.entries(v)) (isCredential(k) ? strings : walk)(x);
311
+ return undefined;
312
+ };
313
+ walk(value);
314
+ return [...new Set(out)];
315
+ }
316
+
317
+ const SECRET_SEGMENT = /^redacted-[0-9a-f]{16}$/;
318
+
319
+ /**
320
+ * THE public path of a document whose id is a credential (a session token, a device code, an auth code):
321
+ * `<collection>/redacted-<first 16 hex of sha256(id)>`. A plan, receipt, log or error names such a document only
322
+ * this way; the owner keeps the real path privately. One implementation for every owner.
323
+ * @param {string} collection - the collection path (e.g. 'UserCache/<id>/Sessions', 'DeviceLoginRequests')
324
+ * @param {string} id - the document id (the credential)
325
+ */
326
+ export function secretPath(collection, id) {
327
+ if (typeof collection !== 'string' || !collection || collection.startsWith('/') || collection.endsWith('/') || collection.split('/').length % 2 !== 1) {
328
+ throw new TypeError(`secretPath: a collection path is required (got ${JSON.stringify(collection)})`);
329
+ }
330
+ if (typeof id !== 'string' || !id) throw new TypeError('secretPath: the document id is required');
331
+ return `${collection}/redacted-${crypto.createHash('sha256').update(id).digest('hex').slice(0, 16)}`;
332
+ }
333
+
334
+ /** True when `path`'s document id is a secretPath digest. */
335
+ export const isSecretPath = (path) => typeof path === 'string' && SECRET_SEGMENT.test(path.split('/').pop());
336
+
337
+ /**
338
+ * THE hash of one footprint entry's `data` (the receipt form: encoded, redacted): what a plan records per entry
339
+ * as `dataHash` and what an owner compares the document's current data against before deleting it.
340
+ * @param {unknown} data
341
+ */
342
+ export function entryDataHash(data) {
343
+ return accountAdminHash({ data: data ?? null });
344
+ }
345
+
346
+ /**
347
+ * THE expectations a delete hands one owner for its footprint entries: `expectPaths` (every entry's path) and
348
+ * `expectData` ({ [path]: entryDataHash(data) } of every non-volatile entry). The orchestrator builds each
349
+ * owner's from the plan; the conformance check builds them the same way.
350
+ * @param {Array<{ path: string, data: unknown, volatile?: boolean }>} entries
351
+ */
352
+ export function deleteExpectations(entries) {
353
+ return {
354
+ expectPaths: entries.map((e) => e.path),
355
+ expectData: Object.fromEntries(entries.filter((e) => e.volatile !== true).map((e) => [e.path, entryDataHash(e.data ?? null)])),
356
+ };
357
+ }
358
+
359
+ const HASH = /^[0-9a-f]{64}$/;
360
+ const stale = (what, why) => new AccountAdminError(AccountAdminRefusal.ACCOUNT_PLAN_STALE, `${what}: ${why}; nothing was written. Plan again.`);
361
+
362
+ /**
363
+ * Refuse (ACCOUNT_PLAN_STALE, before any write) unless an owner's CURRENT footprint entries are the plan's:
364
+ * `expectPaths` (an array of the plan's paths) and `expectData` ({ [path]: dataHash } of every non-volatile
365
+ * planned entry) are required; the current non-volatile paths are exactly expectData's keys, each in
366
+ * expectPaths, and each entry's entryDataHash(data) equals its planned hash. Volatile entries (deleted by query)
367
+ * are exempt. THE plan-freshness rule of a delete; every owner applies it to the footprint it re-reads.
368
+ * @param {string} what - the owner (and act) named in the refusal
369
+ * @param {Array<{ path: string, data: unknown, volatile?: boolean }>} entries - the owner's current footprint entries
370
+ * @param {{ expectPaths?: string[], expectData?: Object<string, string> }} plan
371
+ */
372
+ export function assertDeletePlanCurrent(what, entries, { expectPaths, expectData } = {}) {
373
+ if (!Array.isArray(expectPaths) || expectPaths.some((p) => typeof p !== 'string' || !p)) throw stale(what, 'expectPaths (the plan\'s paths) is required');
374
+ if (!expectData || typeof expectData !== 'object' || Array.isArray(expectData) || Object.values(expectData).some((h) => typeof h !== 'string' || !HASH.test(h))) {
375
+ throw stale(what, 'expectData ({ [path]: dataHash } of the plan\'s entries) is required');
376
+ }
377
+ const planned = new Set(Object.keys(expectData));
378
+ const outside = [...planned].filter((p) => !expectPaths.includes(p));
379
+ if (outside.length) throw stale(what, `expectData names ${outside.slice(0, 5).join(', ')}, which expectPaths does not`);
380
+ const now = entries.filter((e) => e.volatile !== true);
381
+ const added = now.map((e) => e.path).filter((p) => !planned.has(p));
382
+ const gone = [...planned].filter((p) => !now.some((e) => e.path === p));
383
+ if (added.length || gone.length) {
384
+ throw stale(what, `the store changed since the plan (${added.length} new path(s), ${gone.length} gone: ${[...added, ...gone].slice(0, 5).join(', ')})`);
385
+ }
386
+ const changed = now.filter((e) => entryDataHash(e.data) !== expectData[e.path]).map((e) => e.path);
387
+ if (changed.length) throw stale(what, `${changed.length} document(s) changed since the plan (${changed.slice(0, 5).join(', ')})`);
388
+ }
389
+
390
+ /**
391
+ * Refuse (ACCOUNT_PLAN_STALE) unless ONE document's current data is the plan's: `data` is the entry form
392
+ * (receiptData of the snapshot, as the owner's footprint builds it; null when the document is absent) read
393
+ * INSIDE the transaction that deletes it. An `irrecoverable` owner calls it for every document it deletes.
394
+ * @param {string} what
395
+ * @param {string} path - the entry's public path (a secretPath for a credential id)
396
+ * @param {unknown} data
397
+ * @param {Object<string, string>} expectData
398
+ */
399
+ export function assertDocumentAsPlanned(what, path, data, expectData) {
400
+ const want = expectData?.[path];
401
+ if (typeof want !== 'string' || !HASH.test(want)) throw stale(what, `${path} has no planned dataHash in expectData`);
402
+ if (entryDataHash(data) !== want) throw stale(what, `${path} changed since the plan (read in the transaction that would delete it)`);
403
+ }
404
+
405
+ const nonEmptyString = (v) => typeof v === 'string' && v.length > 0;
406
+ /** A merge move's identity: path, field and (for a map entry) key. */
407
+ export const moveKey = (m) => `${m.path}#${m.field}${m.key === undefined ? '' : `#${m.key}`}`;
408
+
409
+ /**
410
+ * Why `fp` is not a footprint of the contract, or null when it is. THE shape rule the orchestrator
411
+ * enforces on every owner's answer and assertAccountStoreOwnerConforms checks:
412
+ * - { entries, leftovers, blockers }, all arrays;
413
+ * - `walletMaterial`, `volatile` and `pathIsSecret`, when an entry carries them, are booleans; a
414
+ * `pathIsSecret` entry's path is a secretPath digest; an `unmeasuredNote` is a non-empty string on a
415
+ * walletMaterial entry;
416
+ * - a delete entry is { path, kind, summary, data }: `data` plain JSON (nonJsonValuePath) with no
417
+ * un-redacted credential (unredactedCredentialPaths, with the owner's `credentialKeys`) — build it with
418
+ * receiptData(raw, { keys: owner.credentialKeys });
419
+ * - a merge entry (merge: true) is { path, field, key?, from, to, summary }: from/to plain JSON (null = absent);
420
+ * - no path (delete) or move (merge) listed twice; every leftover { what, why } strings;
421
+ * - every blocker built by accountAdminBlocker(code, detail): frozen, code in AccountAdminRefusal.
422
+ * @param {unknown} fp
423
+ * - an entry of a collection the owner declares in `credentialIdCollections` is pathIsSecret.
424
+ * @param {{ merge?: boolean, credentialKeys?: string[], credentialIdCollections?: string[] }} [opts]
425
+ * @returns {string|null}
426
+ */
427
+ export function footprintViolation(fp, { merge = false, credentialKeys, credentialIdCollections } = {}) {
428
+ for (const k of ['entries', 'leftovers', 'blockers']) {
429
+ if (!Array.isArray(fp?.[k])) return `no ${k} array${merge && Array.isArray(fp?.moves) ? ' (it answered `moves`; the contract key is `entries`)' : ''}`;
430
+ }
431
+ const seen = new Set();
432
+ for (const e of fp.entries) {
433
+ if (!nonEmptyString(e?.path)) return `an entry has no path (${JSON.stringify(e)?.slice(0, 200)})`;
434
+ if (merge && !nonEmptyString(e.field)) return `move ${e.path} has no field`;
435
+ const id = merge ? moveKey(e) : e.path;
436
+ if (seen.has(id)) return `${id} is listed twice`;
437
+ seen.add(id);
438
+ if (typeof e.summary !== 'string') return `entry ${id} has no summary string`;
439
+ for (const flag of ['walletMaterial', 'volatile', 'pathIsSecret']) {
440
+ if (flag in e && typeof e[flag] !== 'boolean') return `entry ${id} ${flag} is ${JSON.stringify(e[flag])}, not a boolean`;
441
+ }
442
+ if (e.pathIsSecret === true && !isSecretPath(e.path)) return `entry ${id} is pathIsSecret but its path is not a secretPath(collection, id) digest`;
443
+ if (!merge && e.pathIsSecret !== true && (credentialIdCollections ?? []).includes(e.path.split('/').slice(-2)[0])) {
444
+ return `entry ${id} is in ${e.path.split('/').slice(-2)[0]}, a collection whose document id is a credential (credentialIdCollections): its path must be secretPath(collection, id) with pathIsSecret: true`;
445
+ }
446
+ if ('unmeasuredNote' in e) {
447
+ if (!nonEmptyString(e.unmeasuredNote) || !e.unmeasuredNote.trim()) return `entry ${id} unmeasuredNote is ${JSON.stringify(e.unmeasuredNote)}, not a non-empty string`;
448
+ if (e.walletMaterial !== true) return `entry ${id} carries an unmeasuredNote but is not walletMaterial`;
449
+ }
450
+ if (merge) {
451
+ if (e.key !== undefined && !nonEmptyString(e.key)) return `move ${id} has a key that is not a non-empty string`;
452
+ for (const side of ['from', 'to']) {
453
+ if (!(side in e)) return `move ${id} has no ${side} (null = absent)`;
454
+ const bad = nonJsonValuePath(e[side]);
455
+ if (bad) return `move ${id} ${side}${bad === '(value)' ? '' : `.${bad}`} is not plain JSON (encode it with encodeStoreValue)`;
456
+ }
457
+ } else {
458
+ if (!nonEmptyString(e.kind)) return `entry ${id} has no kind`;
459
+ if (!('data' in e)) return `entry ${id} has no data (the receipt copy, receiptData(raw))`;
460
+ const bad = nonJsonValuePath(e.data);
461
+ if (bad) return `entry ${id} data${bad === '(value)' ? '' : `.${bad}`} is not plain JSON (build data with receiptData)`;
462
+ const creds = unredactedCredentialPaths(e.data, { keys: credentialKeys });
463
+ if (creds.length) return `entry ${id} carries un-redacted credential(s) ${creds.map((c) => `data.${c}`).join(', ')} (build data with receiptData)`;
464
+ }
465
+ }
466
+ for (const l of fp.leftovers) {
467
+ if (!nonEmptyString(l?.what) || !nonEmptyString(l?.why)) return `a leftover is not { what, why } strings (${JSON.stringify(l)?.slice(0, 200)})`;
468
+ }
469
+ for (const b of fp.blockers) {
470
+ if (!CODES.has(b?.code)) return `blocker code ${JSON.stringify(b?.code)} is not in AccountAdminRefusal`;
471
+ if (typeof b.detail !== 'string') return `blocker ${b.code} has no detail string`;
472
+ if (!Object.isFrozen(b)) return `blocker ${b.code} was not built by accountAdminBlocker(code, detail)`;
473
+ }
474
+ return null;
475
+ }
476
+
477
+ /** JSON with object keys sorted at every depth: equal values give equal strings. */
478
+ export function canonicalJson(value) {
479
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
480
+ if (value && typeof value === 'object') {
481
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
482
+ }
483
+ return JSON.stringify(value === undefined ? null : value);
484
+ }
485
+
486
+ /** sha256 hex of canonicalJson(value). */
487
+ export function accountAdminHash(value) {
488
+ return crypto.createHash('sha256').update(canonicalJson(value)).digest('hex');
489
+ }
490
+
491
+ /**
492
+ * THE hash of a delete plan: the account id and every non-volatile entry's owner, path, kind and data
493
+ * (a volatile entry is deleted by query, so its set never makes a plan stale). A delete receipt carries
494
+ * it as `planHash`; restoreDelete recomputes it from the receipt's entries to refuse an edited receipt.
495
+ * @param {string} accountId
496
+ * @param {Array<{ owner: string, path: string, kind: string|null, data: unknown, volatile?: boolean }>} entries
497
+ */
498
+ export function deletePlanHash(accountId, entries) {
499
+ const stable = entries.filter((e) => e.volatile !== true).map((e) => [e.owner, e.path, e.kind ?? null, e.data ?? null]);
500
+ return accountAdminHash({ kind: 'delete', accountId, entries: stable.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)) });
501
+ }
502
+
503
+ /**
504
+ * THE hash of a merge plan: both account ids and every move's owner, identity, from and to. A merge receipt
505
+ * carries it as `planHash`; rollbackMerge recomputes it from the receipt's moves to refuse an edited receipt.
506
+ * @param {string} fromAccountId
507
+ * @param {string} intoAccountId
508
+ * @param {Array<{ owner: string, path: string, field: string, key?: string, from: unknown, to: unknown }>} moves
509
+ */
510
+ export function mergePlanHash(fromAccountId, intoAccountId, moves) {
511
+ const rows = moves.map((m) => [m.owner, moveKey(m), m.from ?? null, m.to ?? null]);
512
+ return accountAdminHash({ kind: 'merge', from: fromAccountId, into: intoAccountId, moves: rows.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)) });
513
+ }