@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.
- package/LICENSE.md +80 -71
- package/README.md +71 -0
- package/package.json +7 -4
- package/src/account-admin/conformance.js +526 -0
- package/src/account-admin/contract.js +513 -0
- package/src/account-admin/index.js +913 -0
- package/src/email/index.js +50 -5
- package/src/fabric/vocab.js +12 -12
- package/src/index.js +64 -0
- package/src/manifest/index.js +1 -1
- package/src/mcp-tools/chatMedia.js +1 -1
- package/src/mcp-tools/cli-verbs.generated.json +101 -26
- package/src/mcp-tools/cli-verbs.js +2 -2
- package/src/mcp-tools/evidence-contract.js +7 -7
- package/src/mcp-tools/handshake.js +2 -3
- package/src/mcp-tools/index.js +7 -7
- package/src/mcp-tools/nativeTools.js +24 -24
- package/src/mcp-tools/paramValidation.js +4 -5
- package/src/mcp-tools/platform-basics.js +1 -1
- package/src/mcp-tools/setup-playbook.js +6 -6
- package/src/models/index.js +1231 -33
- package/src/naming/index.js +1 -1
- package/src/operator/booted-database.js +48 -0
- package/src/operator/index.js +142 -0
- package/src/permissions/index.js +1 -1
- package/src/service-bootstrap/index.js +1 -1
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE operator account admin: DELETE a test account (and restore the absent entries of a PARTIAL delete),
|
|
3
|
+
* MERGE a legacy record into its passkey account, roll a merge back. In-process only: a local operator app
|
|
4
|
+
* builds it with createAccountAdmin and the store owners it booted; no command, route or tool
|
|
5
|
+
* reaches it.
|
|
6
|
+
*
|
|
7
|
+
* It holds no Firestore client. Every read and write goes through a store owner (contract.js): the User
|
|
8
|
+
* owner (`userAccountOwner`, @descix/platform-api) and the dependent store owners the caller passes (Cloud's,
|
|
9
|
+
* Powch's). Owners never call each other; this module sequences them. A delete runs: the User owner's
|
|
10
|
+
* pre-flight (writes nothing), the dependents, the User owner's pre-flight again, the `irrecoverable`
|
|
11
|
+
* dependents, the User owner LAST, so a failed dependent never leaves an orphaned USERS doc behind and the
|
|
12
|
+
* User owner refusing at its turn never strands an irrecoverable delete.
|
|
13
|
+
*
|
|
14
|
+
* Every act first measures the database each owner's client targets (storeTarget) against the target this
|
|
15
|
+
* instance was built for, which the factory measured against the booted cloud-core config of the env.
|
|
16
|
+
*
|
|
17
|
+
* Every refusal THROWS an AccountAdminError and has written nothing. A commit RETURNS once a write was
|
|
18
|
+
* attempted, with an ending decided only from a read-back through the owners.
|
|
19
|
+
*/
|
|
20
|
+
import crypto from 'node:crypto';
|
|
21
|
+
import {
|
|
22
|
+
normalizeOperatorEmailRule,
|
|
23
|
+
operatorEmailAllowed,
|
|
24
|
+
operatorEmailRulePrefixes,
|
|
25
|
+
assertOperatorTarget,
|
|
26
|
+
OperatorGuardError,
|
|
27
|
+
OperatorGuardRefusal,
|
|
28
|
+
} from '../operator/index.js';
|
|
29
|
+
import { bootedEnvDatabaseId } from '../operator/booted-database.js';
|
|
30
|
+
import { normalizeEmail } from '../email/index.js';
|
|
31
|
+
import {
|
|
32
|
+
AccountAdminRefusal as R,
|
|
33
|
+
AccountAdminError,
|
|
34
|
+
deletePlanHash,
|
|
35
|
+
mergePlanHash,
|
|
36
|
+
accountAdminHash,
|
|
37
|
+
DELETE_OUTCOME,
|
|
38
|
+
MERGE_OUTCOME,
|
|
39
|
+
MERGE_ROLLBACK_OUTCOME,
|
|
40
|
+
RESTORE_OUTCOME,
|
|
41
|
+
STORE_OWNER_METHODS,
|
|
42
|
+
STORE_OWNER_MERGE_METHODS,
|
|
43
|
+
STORE_OWNER_RESTORE_METHOD,
|
|
44
|
+
USER_OWNER_METHODS,
|
|
45
|
+
nonJsonValuePath,
|
|
46
|
+
footprintViolation,
|
|
47
|
+
moveKey,
|
|
48
|
+
entryDataHash,
|
|
49
|
+
deleteExpectations,
|
|
50
|
+
} from './contract.js';
|
|
51
|
+
|
|
52
|
+
export * from './contract.js';
|
|
53
|
+
export * from './conformance.js';
|
|
54
|
+
|
|
55
|
+
/** How long a plan stays committable after it was made. */
|
|
56
|
+
export const ACCOUNT_PLAN_TTL_SECONDS = 600;
|
|
57
|
+
|
|
58
|
+
const refuse = (code, message, opts) => new AccountAdminError(code, message, opts);
|
|
59
|
+
|
|
60
|
+
function assertOwner(owner, label, { user = false } = {}) {
|
|
61
|
+
if (!owner || typeof owner !== 'object') throw new Error(`createAccountAdmin: ${label} is required`);
|
|
62
|
+
if (typeof owner.name !== 'string' || !owner.name) throw new Error(`createAccountAdmin: ${label} has no name`);
|
|
63
|
+
const missing = STORE_OWNER_METHODS.filter((m) => typeof owner[m] !== 'function');
|
|
64
|
+
if (missing.length) throw new Error(`createAccountAdmin: store owner '${owner.name}' lacks ${missing.join(', ')} (the store-owner contract: ${STORE_OWNER_METHODS.join(', ')})`);
|
|
65
|
+
if (owner.credentialKeys !== undefined && (!Array.isArray(owner.credentialKeys) || owner.credentialKeys.some((k) => typeof k !== 'string' || !k))) {
|
|
66
|
+
throw new Error(`createAccountAdmin: store owner '${owner.name}' credentialKeys must be an array of key names`);
|
|
67
|
+
}
|
|
68
|
+
if (owner.credentialIdCollections !== undefined && (!Array.isArray(owner.credentialIdCollections) || owner.credentialIdCollections.some((k) => typeof k !== 'string' || !k || k.includes('/')))) {
|
|
69
|
+
throw new Error(`createAccountAdmin: store owner '${owner.name}' credentialIdCollections must be an array of collection ids`);
|
|
70
|
+
}
|
|
71
|
+
if (owner.irrecoverable !== undefined && typeof owner.irrecoverable !== 'boolean') {
|
|
72
|
+
throw new Error(`createAccountAdmin: store owner '${owner.name}' irrecoverable must be true or false (got ${JSON.stringify(owner.irrecoverable)})`);
|
|
73
|
+
}
|
|
74
|
+
if (owner[STORE_OWNER_RESTORE_METHOD] !== undefined && typeof owner[STORE_OWNER_RESTORE_METHOD] !== 'function') {
|
|
75
|
+
throw new Error(`createAccountAdmin: store owner '${owner.name}' ${STORE_OWNER_RESTORE_METHOD} is not a function`);
|
|
76
|
+
}
|
|
77
|
+
const merge = STORE_OWNER_MERGE_METHODS.filter((m) => typeof owner[m] === 'function');
|
|
78
|
+
if (merge.length && merge.length !== STORE_OWNER_MERGE_METHODS.length) {
|
|
79
|
+
throw new Error(`createAccountAdmin: store owner '${owner.name}' implements ${merge.join(', ')} but not ${STORE_OWNER_MERGE_METHODS.filter((m) => !merge.includes(m)).join(', ')}; a merge owner implements all of ${STORE_OWNER_MERGE_METHODS.join(', ')} or none`);
|
|
80
|
+
}
|
|
81
|
+
if (user) {
|
|
82
|
+
if (owner.name !== 'user') throw new Error(`createAccountAdmin: userOwner must be the User owner (name 'user'), got '${owner.name}'`);
|
|
83
|
+
const lacking = [...STORE_OWNER_MERGE_METHODS, ...USER_OWNER_METHODS].filter((m) => typeof owner[m] !== 'function');
|
|
84
|
+
if (lacking.length) throw new Error(`createAccountAdmin: userOwner lacks ${lacking.join(', ')}; pass userAccountOwner from @descix/platform-api, not a mirror of it`);
|
|
85
|
+
if (owner.irrecoverable === true || owner[STORE_OWNER_RESTORE_METHOD] !== undefined) {
|
|
86
|
+
throw new Error(`createAccountAdmin: the User owner declares neither irrecoverable nor ${STORE_OWNER_RESTORE_METHOD} (it always goes last and restores nothing in v1)`);
|
|
87
|
+
}
|
|
88
|
+
} else if (owner.name === 'user') {
|
|
89
|
+
throw new Error('createAccountAdmin: a dependent store owner cannot be named \'user\' (that is the User owner)');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A footprint as the contract shapes it (footprintViolation), or a loud error naming the owner. */
|
|
94
|
+
function checkFootprint(owner, fp, { merge = false } = {}) {
|
|
95
|
+
const why = footprintViolation(fp, { merge, credentialKeys: owner.credentialKeys, credentialIdCollections: owner.credentialIdCollections });
|
|
96
|
+
if (why) throw new Error(`store owner '${owner.name}' returned a malformed ${merge ? 'merge ' : ''}footprint: ${why}`);
|
|
97
|
+
return fp;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const moveOf = (owner, m) => ({ owner, path: m.path, field: m.field, ...(m.key === undefined ? {} : { key: m.key }), from: m.from ?? null, to: m.to ?? null });
|
|
101
|
+
const sortedUnique = (xs) => [...new Set(xs)].sort();
|
|
102
|
+
const describe = (e) => `${e?.code ? `${e.code}: ` : ''}${e?.message ?? e}`;
|
|
103
|
+
const isWalletCode = (code) => code === R.ACCOUNT_WALLET_VALUE_UNMEASURED || code === R.ACCOUNT_WALLET_HOLDS_VALUE;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* THE statement of what a delete plan's wallet reading did NOT measure, built only here and shown with every
|
|
107
|
+
* delete plan (its top-level `notMeasured`, and `wallet.notMeasured`): value outside the reading's scope (the
|
|
108
|
+
* reader's own `scope` sentence is referenced, not restated), an address that was not read, and each
|
|
109
|
+
* wallet-material entry's owner-supplied `unmeasuredNote` (e.g. a vault's imported wallets on other chains).
|
|
110
|
+
* @param {{ address: string|null, measured: boolean }} reading
|
|
111
|
+
* @param {Array<{ owner: string, path: string, unmeasuredNote?: string }>} walletMaterial
|
|
112
|
+
* @returns {string[]}
|
|
113
|
+
*/
|
|
114
|
+
function walletNotMeasured(reading, walletMaterial) {
|
|
115
|
+
const out = [];
|
|
116
|
+
if (reading.measured === true) out.push(`wallet ${reading.address}: value outside the reading's scope (wallet.scope) was not measured: any EVM network the scope does not name, and any token it does not cover`);
|
|
117
|
+
else if (reading.address) out.push(`wallet ${reading.address}: not measured at all (wallet.failure)`);
|
|
118
|
+
else out.push('the account has no wallet_address: no wallet reading was taken');
|
|
119
|
+
for (const w of walletMaterial) if (w.unmeasuredNote) out.push(`${w.owner}: ${w.path}: ${w.unmeasuredNote}`);
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The operator account admin bound to ONE environment, Firestore target and operator email rule. Throws,
|
|
125
|
+
* before any read, when an owner lacks a contract method, the wallet reader is missing, the env is not
|
|
126
|
+
* dev|demo|prod, the booted cloud-core config is not that env or names no database for it, or the target is
|
|
127
|
+
* not the database the env's own defaults-config-<env>.json names (bootedEnvDatabaseId; ACCOUNT_TARGET_INVALID),
|
|
128
|
+
* or the rule is missing/invalid (ACCOUNT_RULE_INVALID). The expected database is never caller-supplied.
|
|
129
|
+
*
|
|
130
|
+
* @param {{
|
|
131
|
+
* userOwner: typeof import('../models/index.js').userAccountOwner,
|
|
132
|
+
* storeOwners: Array<{ name: string, footprintForUser: Function, deleteForUser: Function, storeTarget: Function,
|
|
133
|
+
* irrecoverable?: boolean, restoreForUser?: Function, credentialKeys?: string[],
|
|
134
|
+
* footprintForMerge?: Function, mergeForUser?: Function, rollbackMergeForUser?: Function, validateRollbackMoves?: Function }>,
|
|
135
|
+
* walletValueReader: (address: string) => Promise<{ measured: true, holdsValue: boolean, summary: string, scope: string, details?: object }>,
|
|
136
|
+
* env: 'dev'|'demo'|'prod',
|
|
137
|
+
* target: { projectId: string, databaseId: string, secretName: string },
|
|
138
|
+
* rule: { localPart: string, plusAddressing: boolean, domains: string[] },
|
|
139
|
+
* now?: () => number,
|
|
140
|
+
* }} args
|
|
141
|
+
*/
|
|
142
|
+
export function createAccountAdmin(args = {}) {
|
|
143
|
+
if (Object.prototype.hasOwnProperty.call(args, 'expectedDatabaseIdFor')) {
|
|
144
|
+
throw new Error('createAccountAdmin: expectedDatabaseIdFor is not an option: the expected database is measured from the booted @descix/cloud-core config (bootedEnvDatabaseId), never supplied by the caller. Remove it.');
|
|
145
|
+
}
|
|
146
|
+
const { userOwner, storeOwners, walletValueReader, env, target, rule, now } = args;
|
|
147
|
+
assertOwner(userOwner, 'userOwner', { user: true });
|
|
148
|
+
if (!Array.isArray(storeOwners)) throw new Error('createAccountAdmin: storeOwners (the dependent store owners, possibly none) must be an array');
|
|
149
|
+
const names = new Set(['user']);
|
|
150
|
+
for (const [i, o] of storeOwners.entries()) {
|
|
151
|
+
assertOwner(o, `storeOwners[${i}]`);
|
|
152
|
+
if (names.has(o.name)) throw new Error(`createAccountAdmin: two store owners are named '${o.name}'`);
|
|
153
|
+
names.add(o.name);
|
|
154
|
+
}
|
|
155
|
+
if (typeof walletValueReader !== 'function') throw new Error('createAccountAdmin: walletValueReader (address) => { measured, holdsValue, summary, scope } is required');
|
|
156
|
+
let normalizedRule;
|
|
157
|
+
let measured;
|
|
158
|
+
try {
|
|
159
|
+
measured = bootedEnvDatabaseId(env);
|
|
160
|
+
assertOperatorTarget({ env, target, expectedDatabaseId: measured.databaseId });
|
|
161
|
+
normalizedRule = normalizeOperatorEmailRule(rule);
|
|
162
|
+
} catch (e) {
|
|
163
|
+
if (!(e instanceof OperatorGuardError)) throw e;
|
|
164
|
+
const code = e.code === OperatorGuardRefusal.RULE_INVALID ? R.ACCOUNT_RULE_INVALID : R.ACCOUNT_TARGET_INVALID;
|
|
165
|
+
throw refuse(code, `${e.message}${/Nothing was read or written\.$/.test(e.message) ? '' : ' Nothing was read or written.'}`, { cause: e });
|
|
166
|
+
}
|
|
167
|
+
const owners = Object.freeze([...storeOwners, userOwner]);
|
|
168
|
+
const ownerByName = new Map(owners.map((o) => [o.name, o]));
|
|
169
|
+
// The delete sequence: dependents, then irrecoverable dependents, then the User owner.
|
|
170
|
+
const deleteOrder = Object.freeze([...storeOwners.filter((o) => o.irrecoverable !== true), ...storeOwners.filter((o) => o.irrecoverable === true), userOwner]);
|
|
171
|
+
const clock = now ?? (() => Date.now());
|
|
172
|
+
const ttlMs = ACCOUNT_PLAN_TTL_SECONDS * 1000;
|
|
173
|
+
const plans = new Map();
|
|
174
|
+
const boundTarget = Object.freeze({ projectId: target.projectId, databaseId: target.databaseId, secretName: target.secretName });
|
|
175
|
+
|
|
176
|
+
// ------------------------------------------------------------------ the target each owner's client measures
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Refuse (ACCOUNT_TARGET_INVALID, nothing read) unless every owner's own client targets the bound
|
|
180
|
+
* database (and project, when the owner reports one). Two @descix/cloud-core instances in one process
|
|
181
|
+
* (a service's and this package's) build two clients from two configs: this is where they disagree.
|
|
182
|
+
*/
|
|
183
|
+
async function assertStoreTargets() {
|
|
184
|
+
for (const owner of owners) {
|
|
185
|
+
let t;
|
|
186
|
+
try {
|
|
187
|
+
t = await owner.storeTarget();
|
|
188
|
+
} catch (e) {
|
|
189
|
+
throw refuse(R.ACCOUNT_TARGET_INVALID, `store owner '${owner.name}' could not report the database its client targets (${describe(e)}). Nothing was read or written.`, { cause: e });
|
|
190
|
+
}
|
|
191
|
+
if (!t || typeof t.databaseId !== 'string' || !t.databaseId) {
|
|
192
|
+
throw refuse(R.ACCOUNT_TARGET_INVALID, `store owner '${owner.name}' storeTarget() answered ${JSON.stringify(t ?? null)?.slice(0, 200)}, not { databaseId: string }. Nothing was read or written.`);
|
|
193
|
+
}
|
|
194
|
+
if (t.databaseId !== boundTarget.databaseId) {
|
|
195
|
+
throw refuse(R.ACCOUNT_TARGET_INVALID, `store owner '${owner.name}' reads and writes database '${t.databaseId}', not '${boundTarget.databaseId}' (env ${env}, ${measured.file}): its client was built from another config or another @descix/cloud-core instance. Nothing was read or written.`);
|
|
196
|
+
}
|
|
197
|
+
if (t.projectId !== undefined && t.projectId !== boundTarget.projectId) {
|
|
198
|
+
throw refuse(R.ACCOUNT_TARGET_INVALID, `store owner '${owner.name}' targets project '${t.projectId}', not '${boundTarget.projectId}'. Nothing was read or written.`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ------------------------------------------------------------------ the rule and the accounts
|
|
204
|
+
|
|
205
|
+
const inRule = (view) => (view.verifiedEmail
|
|
206
|
+
? operatorEmailAllowed(normalizedRule, view.verifiedEmail)
|
|
207
|
+
: view.emailKeyed && operatorEmailAllowed(normalizedRule, view.accountId));
|
|
208
|
+
|
|
209
|
+
/** The account's view, refused unless it exists and the rule names it (the refusal never prints its address). */
|
|
210
|
+
async function accountInRule(accountId, role = 'account') {
|
|
211
|
+
if (typeof accountId !== 'string' || !accountId.trim()) throw refuse(R.ACCOUNT_NOT_FOUND, `an ${role} id is required; nothing was read`);
|
|
212
|
+
const view = await userOwner.account(accountId.trim());
|
|
213
|
+
if (!view.exists) throw refuse(R.ACCOUNT_NOT_FOUND, `no account ${accountId} (${role}); nothing was written`);
|
|
214
|
+
if (!inRule(view)) {
|
|
215
|
+
throw refuse(R.ACCOUNT_NOT_IN_RULE, `account ${view.accountId} (${role}): ${view.verifiedEmail ? 'its verified email is not one the operator email rule names' : 'it has no verified email the operator email rule names'}; nothing was written`);
|
|
216
|
+
}
|
|
217
|
+
return view;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const storeUser = (view) => Object.freeze({ user_id: view.accountId, verified_email: view.verifiedEmail, wallet_address: view.walletAddress });
|
|
221
|
+
|
|
222
|
+
// ------------------------------------------------------------------ plans and receipts
|
|
223
|
+
|
|
224
|
+
function keepPlan(plan) {
|
|
225
|
+
const t = clock();
|
|
226
|
+
for (const [id, p] of plans) if (t - p.since > ttlMs) plans.delete(id);
|
|
227
|
+
const planId = crypto.randomBytes(16).toString('base64url');
|
|
228
|
+
plans.set(planId, { ...plan, since: t });
|
|
229
|
+
return { planId, expiresAt: new Date(t + ttlMs).toISOString() };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function takePlan(planId, kind) {
|
|
233
|
+
const p = typeof planId === 'string' ? plans.get(planId) : undefined;
|
|
234
|
+
if (!p || p.kind !== kind) throw refuse(R.ACCOUNT_PLAN_STALE, `this ${kind} plan is unknown, already used or expired; plan again. Nothing was written.`);
|
|
235
|
+
if (clock() - p.since > ttlMs) {
|
|
236
|
+
plans.delete(planId);
|
|
237
|
+
throw refuse(R.ACCOUNT_PLAN_STALE, `this ${kind} plan expired (${ACCOUNT_PLAN_TTL_SECONDS}s); plan again. Nothing was written.`);
|
|
238
|
+
}
|
|
239
|
+
return p;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const confirmMismatch = (typed, id) => typeof typed !== 'string' || typed.trim() !== id;
|
|
243
|
+
|
|
244
|
+
function requireReceiptKeeper(receipt) {
|
|
245
|
+
if (typeof receipt?.save !== 'function') throw refuse(R.ACCOUNT_RECEIPT_INVALID, 'commit needs receipt.save(r) -> label: the receipt is kept before any write. Nothing was written.');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function saveReceipt(keeper, r) {
|
|
249
|
+
const label = await keeper.save(structuredClone(r));
|
|
250
|
+
if (typeof label !== 'string' || !label) throw refuse(R.ACCOUNT_RECEIPT_INVALID, 'receipt.save returned no label for the kept receipt; nothing was written.');
|
|
251
|
+
return label;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Refuse a kept receipt of another env or target (ACCOUNT_RECEIPT_INVALID). */
|
|
255
|
+
function assertReceiptHere(r) {
|
|
256
|
+
if (r.env !== env || r.target?.databaseId !== boundTarget.databaseId || r.target?.projectId !== boundTarget.projectId) {
|
|
257
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, `The receipt is for env ${r.env} / database ${r.target?.databaseId}, not ${env} / ${boundTarget.databaseId}. Nothing was written.`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function refuseUnknownOwners(names) {
|
|
262
|
+
const unknown = sortedUnique(names).filter((n) => !ownerByName.has(n));
|
|
263
|
+
if (unknown.length) throw refuse(R.ACCOUNT_RECEIPT_INVALID, `The receipt names store owner(s) ${unknown.join(', ')} that this instance does not hold. Nothing was written.`);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function refuseForBlockers(blockers, act) {
|
|
267
|
+
throw refuse(blockers[0].code, `${act} refused: ${blockers.map((b) => `${b.code}${b.owner ? ` [${b.owner}]` : ''} (${b.detail})`).join('; ')}. Nothing was written.`, { details: blockers });
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ------------------------------------------------------------------ delete
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* One wallet reading as the plan shows it: { address, measured: true, holdsValue, summary, scope, details }
|
|
274
|
+
* or { address, measured: false, failure }. Unmeasured is a throw, an answer other than measured === true
|
|
275
|
+
* with a BOOLEAN holdsValue, a string summary and a non-empty string scope (what exactly was measured), or
|
|
276
|
+
* `details` that is not plain JSON; never read as empty.
|
|
277
|
+
*/
|
|
278
|
+
async function readWallet(address) {
|
|
279
|
+
let answer;
|
|
280
|
+
try {
|
|
281
|
+
answer = await walletValueReader(address);
|
|
282
|
+
} catch (e) {
|
|
283
|
+
return { address, measured: false, failure: `the value read failed (${e?.message ?? e})` };
|
|
284
|
+
}
|
|
285
|
+
if (!answer || answer.measured !== true || typeof answer.holdsValue !== 'boolean' || typeof answer.summary !== 'string') {
|
|
286
|
+
return { address, measured: false, failure: `the value read answered no measurement (${JSON.stringify(answer ?? null)?.slice(0, 200)}); a reading is { measured: true, holdsValue: boolean, summary: string, scope: string, details? }` };
|
|
287
|
+
}
|
|
288
|
+
if (typeof answer.scope !== 'string' || !answer.scope.trim()) {
|
|
289
|
+
return { address, measured: false, failure: 'the reading names no scope (what exactly was measured: which assets, on which chains, for this address); a reading without a scope is not a measurement' };
|
|
290
|
+
}
|
|
291
|
+
const details = answer.details ?? null;
|
|
292
|
+
const bad = details === null ? null : nonJsonValuePath(details);
|
|
293
|
+
if (bad) return { address, measured: false, failure: `the reading's details.${bad === '(value)' ? '' : bad} is not plain JSON (amounts are decimal strings)` };
|
|
294
|
+
return { address, measured: true, holdsValue: answer.holdsValue, summary: answer.summary, scope: answer.scope, details };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The plan's wallet section and its blockers. The account's wallet_address is read by the wallet value
|
|
299
|
+
* reader; an account without one whose stores hold wallet material (an entry marked walletMaterial) is
|
|
300
|
+
* ACCOUNT_WALLET_VALUE_UNMEASURED; every owner's own wallet blocker (e.g. a derived-address chain nobody
|
|
301
|
+
* measures) is shown with the section. Null when there is nothing to show.
|
|
302
|
+
*/
|
|
303
|
+
async function walletSection(view, entries, ownerBlockers) {
|
|
304
|
+
const walletMaterial = entries.filter((e) => e.walletMaterial === true).map((e) => ({ owner: e.owner, path: e.path, ...(e.unmeasuredNote ? { unmeasuredNote: e.unmeasuredNote } : {}) }));
|
|
305
|
+
const own = [];
|
|
306
|
+
let reading;
|
|
307
|
+
if (view.walletAddress) {
|
|
308
|
+
reading = await readWallet(view.walletAddress);
|
|
309
|
+
if (!reading.measured) own.push({ owner: 'wallet', code: R.ACCOUNT_WALLET_VALUE_UNMEASURED, detail: `wallet ${reading.address}: ${reading.failure}; an unmeasured wallet is never read as empty` });
|
|
310
|
+
else if (reading.holdsValue) own.push({ owner: 'wallet', code: R.ACCOUNT_WALLET_HOLDS_VALUE, detail: `wallet ${reading.address}: ${reading.summary || 'holds value'} (${reading.scope})` });
|
|
311
|
+
} else {
|
|
312
|
+
reading = { address: null, measured: false, failure: 'the account has no wallet_address; no reading was taken' };
|
|
313
|
+
if (walletMaterial.length) {
|
|
314
|
+
own.push({ owner: 'wallet', code: R.ACCOUNT_WALLET_VALUE_UNMEASURED, detail: `the account has no wallet_address, but its stores hold wallet material (${walletMaterial.map((w) => `${w.owner}: ${w.path}`).join(', ')}); nobody measured its value` });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const fromOwners = ownerBlockers.filter((b) => isWalletCode(b.code));
|
|
318
|
+
const notMeasured = walletNotMeasured(reading, walletMaterial);
|
|
319
|
+
if (!view.walletAddress && !walletMaterial.length && !fromOwners.length) return { wallet: null, blockers: [], notMeasured };
|
|
320
|
+
return { wallet: { ...reading, walletMaterial, blockers: [...own, ...fromOwners], notMeasured }, blockers: own, notMeasured };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Every owner's delete footprint, the coverage check and the wallet section; never stops at the first blocker. */
|
|
324
|
+
async function gatherDelete(view) {
|
|
325
|
+
const user = storeUser(view);
|
|
326
|
+
const perOwner = [];
|
|
327
|
+
const blockers = [];
|
|
328
|
+
const leftovers = [];
|
|
329
|
+
let nestedKnown = true;
|
|
330
|
+
for (const owner of owners) {
|
|
331
|
+
let fp;
|
|
332
|
+
try {
|
|
333
|
+
fp = checkFootprint(owner, await owner.footprintForUser(user));
|
|
334
|
+
} catch (e) {
|
|
335
|
+
if (!(e instanceof AccountAdminError)) throw e;
|
|
336
|
+
blockers.push({ owner: owner.name, code: R.ACCOUNT_STORE_READ_FAILED, detail: e.message });
|
|
337
|
+
perOwner.push({ owner: owner.name, entries: [], nested: [] });
|
|
338
|
+
if (owner === userOwner) nestedKnown = false;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
for (const b of fp.blockers) blockers.push({ owner: owner.name, code: b.code, detail: b.detail });
|
|
342
|
+
for (const l of fp.leftovers) leftovers.push({ owner: owner.name, what: l.what, why: l.why });
|
|
343
|
+
perOwner.push({
|
|
344
|
+
owner: owner.name,
|
|
345
|
+
entries: fp.entries.map((e) => ({
|
|
346
|
+
owner: owner.name, path: e.path, kind: e.kind ?? null, summary: e.summary ?? '', data: e.data ?? null,
|
|
347
|
+
// The plan's record of this document's data: every owner refuses to delete it once it differs.
|
|
348
|
+
...(e.volatile === true ? { volatile: true } : { dataHash: entryDataHash(e.data ?? null) }),
|
|
349
|
+
...(e.walletMaterial === true ? { walletMaterial: true } : {}),
|
|
350
|
+
...(e.unmeasuredNote ? { unmeasuredNote: e.unmeasuredNote } : {}),
|
|
351
|
+
...(e.pathIsSecret === true ? { pathIsSecret: true } : {}),
|
|
352
|
+
})),
|
|
353
|
+
nested: owner === userOwner ? (fp.nested ?? []) : [],
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
const claimed = new Map();
|
|
357
|
+
for (const o of perOwner) {
|
|
358
|
+
for (const e of o.entries) {
|
|
359
|
+
if (claimed.has(e.path)) throw new Error(`store owners '${claimed.get(e.path)}' and '${o.owner}' both claim ${e.path}; one path has one owner`);
|
|
360
|
+
claimed.set(e.path, o.owner);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
// null = unknown (the User owner's footprint, which lists the documents under the USERS doc, failed: a blocker).
|
|
364
|
+
const unowned = nestedKnown ? perOwner.flatMap((o) => o.nested).filter((p) => !claimed.has(p)).sort() : null;
|
|
365
|
+
if (unowned?.length) {
|
|
366
|
+
const byCollection = new Map();
|
|
367
|
+
for (const p of unowned) {
|
|
368
|
+
const c = p.split('/').slice(0, -1).join('/');
|
|
369
|
+
byCollection.set(c, (byCollection.get(c) ?? 0) + 1);
|
|
370
|
+
}
|
|
371
|
+
blockers.push({ owner: 'user', code: R.ACCOUNT_STORE_UNOWNED, detail: `no store owner covers ${[...byCollection].map(([c, n]) => `${c} (${n})`).join(', ')}; deleting the USERS doc would orphan them` });
|
|
372
|
+
}
|
|
373
|
+
const entries = perOwner.flatMap((o) => o.entries);
|
|
374
|
+
const w = await walletSection(view, entries, blockers);
|
|
375
|
+
blockers.push(...w.blockers);
|
|
376
|
+
const expectations = Object.fromEntries(perOwner.map((o) => [o.owner, deleteExpectations(o.entries)]));
|
|
377
|
+
const ownerPaths = Object.fromEntries(perOwner.map((o) => [o.owner, expectations[o.owner].expectPaths]));
|
|
378
|
+
const ownerData = Object.fromEntries(perOwner.map((o) => [o.owner, expectations[o.owner].expectData]));
|
|
379
|
+
const coveredNested = perOwner.filter((o) => o.owner !== userOwner.name).flatMap((o) => o.entries.map((e) => e.path));
|
|
380
|
+
return { user, entries, leftovers, blockers, unowned, wallet: w.wallet, notMeasured: w.notMeasured, hash: deletePlanHash(view.accountId, entries), ownerPaths, ownerData, coveredNested };
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* The read-back of a delete: EVERY owner's fresh footprint of the planned account (planned or not: a document
|
|
385
|
+
* re-created during the delete shows here), and whether its USERS doc is gone; readFailures when a re-read fails.
|
|
386
|
+
*/
|
|
387
|
+
async function readBackDelete(user) {
|
|
388
|
+
const presentByOwner = new Map();
|
|
389
|
+
const readFailures = [];
|
|
390
|
+
for (const owner of owners) {
|
|
391
|
+
try {
|
|
392
|
+
presentByOwner.set(owner.name, checkFootprint(owner, await owner.footprintForUser(user)).entries.map((e) => e.path));
|
|
393
|
+
} catch (e) {
|
|
394
|
+
readFailures.push(`${owner.name}: ${e?.message ?? e}`);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
let accountGone = null;
|
|
398
|
+
try {
|
|
399
|
+
accountGone = (await userOwner.account(user.user_id)).exists !== true;
|
|
400
|
+
} catch (e) {
|
|
401
|
+
readFailures.push(`user (USERS doc): ${e?.message ?? e}`);
|
|
402
|
+
}
|
|
403
|
+
return { presentByOwner, readFailures, accountGone };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** The plan's expectations of one owner: its paths and their planned data hashes. */
|
|
407
|
+
const expectOf = (g, name) => ({ expectPaths: g.ownerPaths[name] ?? [], expectData: g.ownerData[name] ?? {} });
|
|
408
|
+
|
|
409
|
+
/** The User owner's pre-flight of its own part of the plan; writes nothing. */
|
|
410
|
+
const preflight = (g) => userOwner.preflightDelete(g.user, { ...expectOf(g, userOwner.name), coveredNested: g.coveredNested });
|
|
411
|
+
|
|
412
|
+
// ------------------------------------------------------------------ merge
|
|
413
|
+
|
|
414
|
+
function mergeBlockers(fromView, intoView) {
|
|
415
|
+
const blockers = [];
|
|
416
|
+
const intoEmail = intoView.verifiedEmail;
|
|
417
|
+
const fromEmail = fromView.verifiedEmail;
|
|
418
|
+
const keyedBy = fromView.emailKeyed ? normalizeEmail(fromView.accountId) : null;
|
|
419
|
+
if (!intoEmail || !(fromEmail === intoEmail || keyedBy === intoEmail)) {
|
|
420
|
+
blockers.push({ owner: 'user', code: R.ACCOUNT_MERGE_EMAIL_MISMATCH, detail: `${fromView.accountId} and ${intoView.accountId} do not share one verified email (or a record keyed by the surviving account's verified email)` });
|
|
421
|
+
}
|
|
422
|
+
if (!intoView.hasPasskeyCredential) {
|
|
423
|
+
blockers.push({ owner: 'user', code: R.ACCOUNT_MERGE_TARGET_NOT_PASSKEY, detail: `${intoView.accountId} is not a Powch passkey account (the powch provider and a passkey credential)` });
|
|
424
|
+
}
|
|
425
|
+
if (intoView.migratedTo) blockers.push({ owner: 'user', code: R.ACCOUNT_MERGE_ALREADY_MIGRATED, detail: `the surviving account ${intoView.accountId} is itself migrated to ${intoView.migratedTo}` });
|
|
426
|
+
return blockers;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function gatherMerge(fromView, intoView) {
|
|
430
|
+
const pair = Object.freeze({ from: storeUser(fromView), into: storeUser(intoView) });
|
|
431
|
+
const blockers = mergeBlockers(fromView, intoView);
|
|
432
|
+
const leftovers = [];
|
|
433
|
+
const leftoversIncomplete = [];
|
|
434
|
+
const moves = [];
|
|
435
|
+
const ownerPaths = {};
|
|
436
|
+
for (const owner of owners) {
|
|
437
|
+
const merges = typeof owner.mergeForUser === 'function';
|
|
438
|
+
try {
|
|
439
|
+
if (merges) {
|
|
440
|
+
const fp = checkFootprint(owner, await owner.footprintForMerge(pair), { merge: true });
|
|
441
|
+
for (const b of fp.blockers) blockers.push({ owner: owner.name, code: b.code, detail: b.detail });
|
|
442
|
+
for (const l of fp.leftovers) leftovers.push({ owner: owner.name, what: l.what, why: l.why });
|
|
443
|
+
for (const m of fp.entries) moves.push({ ...moveOf(owner.name, m), summary: m.summary ?? '' });
|
|
444
|
+
ownerPaths[owner.name] = sortedUnique(fp.entries.map((m) => m.path));
|
|
445
|
+
} else {
|
|
446
|
+
// An owner that moves nothing: its footprint of the from-record stays on it, entries and leftovers
|
|
447
|
+
// alike. Its delete blockers do not bear on a merge, except that an UNBOUNDED read means this
|
|
448
|
+
// list of what stays is incomplete: shown, not a blocker.
|
|
449
|
+
const fp = checkFootprint(owner, await owner.footprintForUser(pair.from));
|
|
450
|
+
for (const e of fp.entries) leftovers.push({ owner: owner.name, what: e.path, why: `${e.summary || e.kind || 'a record'}: this owner moves nothing on merge; it stays on the from-record` });
|
|
451
|
+
for (const l of fp.leftovers) leftovers.push({ owner: owner.name, what: l.what, why: l.why });
|
|
452
|
+
for (const b of fp.blockers) if (b.code === R.ACCOUNT_FOOTPRINT_UNBOUNDED) leftoversIncomplete.push({ owner: owner.name, detail: b.detail });
|
|
453
|
+
}
|
|
454
|
+
} catch (e) {
|
|
455
|
+
if (!(e instanceof AccountAdminError)) throw e;
|
|
456
|
+
blockers.push({ owner: owner.name, code: R.ACCOUNT_STORE_READ_FAILED, detail: e.message });
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
const seen = new Set();
|
|
460
|
+
for (const m of moves) {
|
|
461
|
+
if (seen.has(moveKey(m))) throw new Error(`two store owners both move ${moveKey(m)}; one field has one owner`);
|
|
462
|
+
seen.add(moveKey(m));
|
|
463
|
+
}
|
|
464
|
+
return { pair, moves, leftovers, leftoversIncomplete, blockers, hash: mergePlanHash(fromView.accountId, intoView.accountId, moves), ownerPaths };
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// ------------------------------------------------------------------ the instance
|
|
468
|
+
|
|
469
|
+
return Object.freeze({
|
|
470
|
+
env,
|
|
471
|
+
target: boundTarget,
|
|
472
|
+
rule: normalizedRule,
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Read-only. Every account the rule names: by its verified_email, or (a legacy record with no
|
|
476
|
+
* verified_email) by its email-shaped document id, flagged emailKeyed.
|
|
477
|
+
*/
|
|
478
|
+
async listAccounts() {
|
|
479
|
+
await assertStoreTargets();
|
|
480
|
+
const views = await userOwner.accountsByEmailPrefixes(operatorEmailRulePrefixes(normalizedRule));
|
|
481
|
+
const named = views.filter((v) => v.exists && inRule(v));
|
|
482
|
+
const byEmail = new Map();
|
|
483
|
+
for (const v of named) byEmail.set(v.email, [...(byEmail.get(v.email) ?? []), v.accountId]);
|
|
484
|
+
return named.map((v) => ({
|
|
485
|
+
accountId: v.accountId,
|
|
486
|
+
email: v.email,
|
|
487
|
+
createdAt: v.createdAt,
|
|
488
|
+
providers: v.providers,
|
|
489
|
+
hasPasskeyCredential: v.hasPasskeyCredential,
|
|
490
|
+
hasPasskeyKey: v.hasPasskeyKey,
|
|
491
|
+
walletAddress: v.walletAddress,
|
|
492
|
+
emailKeyed: v.emailKeyed,
|
|
493
|
+
migratedTo: v.migratedTo,
|
|
494
|
+
roles: v.roles,
|
|
495
|
+
duplicatesOf: (byEmail.get(v.email) ?? []).filter((id) => id !== v.accountId),
|
|
496
|
+
}));
|
|
497
|
+
},
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Dry run of a delete (writes nothing): every owner's footprint, every blocker, the leftovers and the
|
|
501
|
+
* wallet section. The plan lives in this instance for ACCOUNT_PLAN_TTL_SECONDS and answers once.
|
|
502
|
+
* @param {{ accountId: string }} args
|
|
503
|
+
*/
|
|
504
|
+
async planDelete({ accountId } = {}) {
|
|
505
|
+
await assertStoreTargets();
|
|
506
|
+
const view = await accountInRule(accountId);
|
|
507
|
+
const g = await gatherDelete(view);
|
|
508
|
+
const { planId, expiresAt } = keepPlan({ kind: 'delete', accountId: view.accountId, email: view.email, hash: g.hash, blockers: g.blockers });
|
|
509
|
+
return { planId, planHash: g.hash, accountId: view.accountId, email: view.email, notMeasured: g.notMeasured, entries: g.entries, leftovers: g.leftovers, blockers: g.blockers, unowned: g.unowned, wallet: g.wallet, refused: g.blockers.length > 0, expiresAt };
|
|
510
|
+
},
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Delete what the plan showed. Refused, writing nothing: an unknown/used/expired plan or a store that
|
|
514
|
+
* changed (ACCOUNT_PLAN_STALE), a wrong typed id (ACCOUNT_CONFIRMATION_MISMATCH; the plan stays), a
|
|
515
|
+
* plan with blockers (the first blocker's code, all of them in `details`), an account the rule no longer
|
|
516
|
+
* names, the User owner's pre-flight. The receipt is saved BEFORE any write; then the User owner stamps
|
|
517
|
+
* the USERS doc (`admin_delete`: this plan's hash; what restoreDelete later requires), the dependents, the
|
|
518
|
+
* User owner's pre-flight again, the irrecoverable dependents, the User owner LAST (a failure stops the
|
|
519
|
+
* sequence). Every owner gets the plan's paths AND each document's planned data hash, and refuses
|
|
520
|
+
* ACCOUNT_PLAN_STALE when a document changed since. A read-back through EVERY owner decides the ending.
|
|
521
|
+
* A PARTIAL ending while the USERS doc stands names the two ways on: finish forward (plan and commit
|
|
522
|
+
* again) or restoreDelete for the restorable entries. A PARTIAL ending whose USERS doc is gone names the
|
|
523
|
+
* documents left behind (`orphaned`, per owner) and offers neither.
|
|
524
|
+
* @param {{ planId: string, confirmAccountId: string, receipt: { save: (r: Object) => string|Promise<string> } }} args
|
|
525
|
+
*/
|
|
526
|
+
async commitDelete({ planId, confirmAccountId, receipt } = {}) {
|
|
527
|
+
await assertStoreTargets();
|
|
528
|
+
const p = takePlan(planId, 'delete');
|
|
529
|
+
requireReceiptKeeper(receipt);
|
|
530
|
+
if (confirmMismatch(confirmAccountId, p.accountId)) throw refuse(R.ACCOUNT_CONFIRMATION_MISMATCH, 'The typed account id does not match the plan; nothing was written.');
|
|
531
|
+
plans.delete(planId);
|
|
532
|
+
if (p.blockers.length) refuseForBlockers(p.blockers, `delete of ${p.accountId}`);
|
|
533
|
+
const view = await accountInRule(p.accountId);
|
|
534
|
+
const g = await gatherDelete(view);
|
|
535
|
+
if (g.blockers.length) refuseForBlockers(g.blockers, `delete of ${p.accountId}`);
|
|
536
|
+
if (g.hash !== p.hash) throw refuse(R.ACCOUNT_PLAN_STALE, `the stores changed since the plan for ${p.accountId}; plan again. Nothing was written.`);
|
|
537
|
+
|
|
538
|
+
const startedAt = new Date(clock()).toISOString();
|
|
539
|
+
const kept = { kind: 'delete', env, target: boundTarget, planId, planHash: p.hash, accountId: p.accountId, email: p.email, entries: g.entries, leftovers: g.leftovers, notMeasured: g.notMeasured, createdAt: startedAt };
|
|
540
|
+
const receiptLabel = await saveReceipt(receipt, kept);
|
|
541
|
+
try {
|
|
542
|
+
await preflight(g);
|
|
543
|
+
// The stamp binds restoreDelete to THIS plan: a receipt is honoured only for an account whose delete this tool began with it.
|
|
544
|
+
await userOwner.stampDelete(g.user, { planHash: p.hash, startedAt, expectData: g.ownerData[userOwner.name] ?? {} });
|
|
545
|
+
} catch (e) {
|
|
546
|
+
if (!(e instanceof AccountAdminError)) throw e;
|
|
547
|
+
throw refuse(e.code, `delete of ${p.accountId} refused by the User owner before any dependent write (${e.message}). Receipt ${receiptLabel} was kept; nothing was written.`, { cause: e, ...(e.details === undefined ? {} : { details: e.details }) });
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const notes = [];
|
|
551
|
+
const reportedRemaining = new Map();
|
|
552
|
+
let failure = null;
|
|
553
|
+
let checkedBeforeIrrecoverable = false;
|
|
554
|
+
for (const owner of deleteOrder) {
|
|
555
|
+
const expect = expectOf(g, owner.name);
|
|
556
|
+
if (!expect.expectPaths.length) continue;
|
|
557
|
+
if (owner.irrecoverable === true && !checkedBeforeIrrecoverable) {
|
|
558
|
+
checkedBeforeIrrecoverable = true;
|
|
559
|
+
try {
|
|
560
|
+
await preflight(g);
|
|
561
|
+
} catch (e) {
|
|
562
|
+
failure = { owner: userOwner.name, error: e };
|
|
563
|
+
notes.push(`the User owner's pre-flight before the irrecoverable owner '${owner.name}' refused (${describe(e)}); '${owner.name}' and the User owner did not run`);
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
try {
|
|
568
|
+
const r = await owner.deleteForUser(g.user, expect);
|
|
569
|
+
if (Array.isArray(r?.remaining) && r.remaining.length) {
|
|
570
|
+
notes.push(`${owner.name} reported ${r.remaining.length} path(s) remaining`);
|
|
571
|
+
for (const x of r.remaining) if (expect.expectPaths.includes(x)) reportedRemaining.set(x, owner.name);
|
|
572
|
+
}
|
|
573
|
+
for (const x of Array.isArray(r?.reasons) ? r.reasons : []) notes.push(`${owner.name}: ${x.path}: ${x.reason}`);
|
|
574
|
+
if (Array.isArray(r?.alsoDeleted) && r.alsoDeleted.length) notes.push(`${owner.name} also deleted ${r.alsoDeleted.length} path(s) that appeared since the plan (deleted by query): ${r.alsoDeleted.join(', ')}`);
|
|
575
|
+
} catch (e) {
|
|
576
|
+
failure = { owner: owner.name, error: e };
|
|
577
|
+
notes.push(`${owner.name} failed (${describe(e)}); no later owner ran`);
|
|
578
|
+
break;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
const planned = g.entries.map((e) => e.path);
|
|
582
|
+
const readBack = await readBackDelete(g.user);
|
|
583
|
+
const { readFailures, accountGone } = readBack;
|
|
584
|
+
const presentNow = new Set([...readBack.presentByOwner.values()].flat());
|
|
585
|
+
// A path an owner reports it left (e.g. an index row that now names another account) remains, even
|
|
586
|
+
// when the account's fresh footprint no longer lists it.
|
|
587
|
+
const present = planned.filter((x) => presentNow.has(x) || reportedRemaining.has(x));
|
|
588
|
+
// The USERS doc is gone: every document any owner still lists for the account, planned or not, is orphaned.
|
|
589
|
+
const orphaned = !readFailures.length && accountGone
|
|
590
|
+
? [
|
|
591
|
+
...owners.flatMap((o) => (readBack.presentByOwner.get(o.name) ?? []).map((path) => ({ owner: o.name, path }))),
|
|
592
|
+
...[...reportedRemaining].filter(([x]) => !presentNow.has(x)).map(([path, owner]) => ({ owner, path, reason: 'its owner reported it left in place' })),
|
|
593
|
+
]
|
|
594
|
+
: [];
|
|
595
|
+
let outcome;
|
|
596
|
+
if (readFailures.length) outcome = DELETE_OUTCOME.UNVERIFIED;
|
|
597
|
+
else if (accountGone) outcome = orphaned.length ? DELETE_OUTCOME.PARTIAL : DELETE_OUTCOME.DELETED;
|
|
598
|
+
else if (present.length === 0) outcome = DELETE_OUTCOME.PARTIAL; // every planned path is gone, yet the USERS doc stands: never DELETED
|
|
599
|
+
else if (present.length === planned.length) outcome = DELETE_OUTCOME.NOT_DELETED;
|
|
600
|
+
else outcome = DELETE_OUTCOME.PARTIAL;
|
|
601
|
+
const deleted = readFailures.length ? [] : planned.filter((x) => !present.includes(x));
|
|
602
|
+
const restorable = outcome === DELETE_OUTCOME.PARTIAL && !accountGone
|
|
603
|
+
? g.entries.filter((e) => deleted.includes(e.path) && e.volatile !== true && e.pathIsSecret !== true && typeof ownerByName.get(e.owner)?.[STORE_OWNER_RESTORE_METHOD] === 'function').map((e) => ({ owner: e.owner, path: e.path }))
|
|
604
|
+
: [];
|
|
605
|
+
let line;
|
|
606
|
+
if (outcome === DELETE_OUTCOME.UNVERIFIED) {
|
|
607
|
+
line = `UNVERIFIED: the read-back failed (${readFailures.join('; ')}). Receipt kept: ${receiptLabel}. Verify the account's stores before acting on it.`;
|
|
608
|
+
} else if (accountGone && orphaned.length) {
|
|
609
|
+
line = `PARTIAL: account ${p.accountId} is deleted (its USERS doc is gone), but ${orphaned.length} document(s) were left behind: ${orphaned.map((x) => `${x.owner}: ${x.path}`).join(', ')}. They are orphaned: neither finish forward nor restoreDelete applies to a deleted account. Receipt kept: ${receiptLabel}.`;
|
|
610
|
+
notes.push(line);
|
|
611
|
+
} else {
|
|
612
|
+
line = `${outcome}: account ${p.accountId}: ${deleted.length} of ${planned.length} planned path(s) read back gone${present.length ? `, ${present.length} remain` : ''}${accountGone ? '' : '; its USERS doc stands'}. Receipt kept: ${receiptLabel}.`;
|
|
613
|
+
}
|
|
614
|
+
if (outcome === DELETE_OUTCOME.NOT_DELETED) {
|
|
615
|
+
// Nothing planned was deleted: the delete never took hold, and its stamp comes off.
|
|
616
|
+
try {
|
|
617
|
+
if (await userOwner.clearDeleteStamp(g.user, { planHash: p.hash })) notes.push('nothing was deleted; the admin_delete stamp was cleared');
|
|
618
|
+
} catch (e) {
|
|
619
|
+
notes.push(`nothing was deleted, but the admin_delete stamp could not be cleared (${describe(e)})`);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
if (outcome === DELETE_OUTCOME.PARTIAL && !accountGone) {
|
|
623
|
+
const ways = `Two ways on: finish forward (planDelete again, then commitDelete), or restoreDelete({ receipt, confirmAccountId }) to re-create ${restorable.length ? `the ${restorable.length} restorable entr${restorable.length === 1 ? 'y' : 'ies'} (${restorable.map((x) => `${x.owner}: ${x.path}`).join(', ')})` : 'nothing: no owner of a deleted entry can restore it'}.`;
|
|
624
|
+
line = `${line} ${ways}`;
|
|
625
|
+
notes.push(ways);
|
|
626
|
+
}
|
|
627
|
+
return { outcome, deleted, remaining: present, orphaned, accountDeleted: accountGone === true && !readFailures.length, restorable, receiptLabel, line, notes, cause: failure?.error ?? null };
|
|
628
|
+
},
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Re-create the absent entries of a PARTIAL delete from its receipt: every owner that implements
|
|
632
|
+
* restoreForUser re-creates its receipt entries that a fresh footprint does not list (never
|
|
633
|
+
* overwriting an existing document); entries of owners without it, volatile entries and entries whose
|
|
634
|
+
* path is a credential digest stay absent and are reported. Refused, writing nothing: a receipt that is
|
|
635
|
+
* not a delete receipt of this env and target, whose entries no longer hash to its planHash or whose
|
|
636
|
+
* dataHash does not match its data (edited), or that names an owner this instance lacks
|
|
637
|
+
* (ACCOUNT_RECEIPT_INVALID); a typed id other than the receipt's account (ACCOUNT_CONFIRMATION_MISMATCH);
|
|
638
|
+
* an account whose USERS doc is gone (ACCOUNT_NOT_FOUND: the delete completed, and a full delete is not
|
|
639
|
+
* undone by this act); an account the rule does not name; an account whose USERS doc does not carry the
|
|
640
|
+
* `admin_delete` stamp of THIS receipt's plan (ACCOUNT_RECEIPT_INVALID: restore re-creates documents only
|
|
641
|
+
* for an account whose delete this tool began with this plan); a footprint read that fails before the
|
|
642
|
+
* first write (ACCOUNT_STORE_READ_FAILED). A read-back decides the ending (RESTORE_OUTCOME); once every
|
|
643
|
+
* restorable entry reads back restored, the stamp is cleared.
|
|
644
|
+
* @param {{ receipt: Object, confirmAccountId: string }} args
|
|
645
|
+
*/
|
|
646
|
+
async restoreDelete({ receipt, confirmAccountId } = {}) {
|
|
647
|
+
await assertStoreTargets();
|
|
648
|
+
const r = receipt;
|
|
649
|
+
if (!r || r.kind !== 'delete' || !Array.isArray(r.entries) || typeof r.accountId !== 'string' || !r.accountId || typeof r.planHash !== 'string'
|
|
650
|
+
|| r.entries.some((e) => typeof e?.owner !== 'string' || typeof e?.path !== 'string')) {
|
|
651
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, 'This is not a delete receipt (kind, accountId, planHash, entries of { owner, path, kind, data, dataHash }). Nothing was written.');
|
|
652
|
+
}
|
|
653
|
+
assertReceiptHere(r);
|
|
654
|
+
if (deletePlanHash(r.accountId, r.entries) !== r.planHash) {
|
|
655
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, `The receipt's entries do not hash to its planHash: it was edited after it was kept. Nothing was written.`);
|
|
656
|
+
}
|
|
657
|
+
const badData = r.entries.filter((e) => e.volatile !== true && e.dataHash !== entryDataHash(e.data ?? null)).map((e) => e.path);
|
|
658
|
+
if (badData.length) throw refuse(R.ACCOUNT_RECEIPT_INVALID, `The receipt's dataHash does not match its data for ${badData.slice(0, 5).join(', ')}: it was edited after it was kept. Nothing was written.`);
|
|
659
|
+
if (confirmMismatch(confirmAccountId, r.accountId)) throw refuse(R.ACCOUNT_CONFIRMATION_MISMATCH, 'The typed account id does not match the receipt; nothing was written.');
|
|
660
|
+
refuseUnknownOwners(r.entries.map((e) => e.owner));
|
|
661
|
+
const exists = await userOwner.account(r.accountId);
|
|
662
|
+
if (!exists.exists) {
|
|
663
|
+
throw refuse(R.ACCOUNT_NOT_FOUND, `account ${r.accountId}'s USERS doc is gone: that delete completed. restoreDelete re-creates the absent entries of a PARTIAL delete only; a full delete is not undone by this act. Nothing was written.`);
|
|
664
|
+
}
|
|
665
|
+
const view = await accountInRule(r.accountId);
|
|
666
|
+
if (view.adminDelete?.planHash !== r.planHash) {
|
|
667
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, `account ${r.accountId} carries ${view.adminDelete ? 'the admin_delete stamp of another plan' : 'no admin_delete stamp'}: restoreDelete re-creates documents only for an account whose delete this tool began with this receipt's plan. Nothing was written.`);
|
|
668
|
+
}
|
|
669
|
+
const user = storeUser(view);
|
|
670
|
+
const byOwner = (name) => r.entries.filter((e) => e.owner === name);
|
|
671
|
+
const holders = owners.filter((o) => byOwner(o.name).length);
|
|
672
|
+
|
|
673
|
+
/** The receipt paths a fresh footprint of each holder lists; a failed read before any write refuses. */
|
|
674
|
+
const presentNow = async (when) => {
|
|
675
|
+
const present = new Set();
|
|
676
|
+
const failures = [];
|
|
677
|
+
for (const owner of holders) {
|
|
678
|
+
try {
|
|
679
|
+
for (const e of checkFootprint(owner, await owner.footprintForUser(user)).entries) present.add(e.path);
|
|
680
|
+
} catch (e) {
|
|
681
|
+
if (when === 'before') throw refuse(R.ACCOUNT_STORE_READ_FAILED, `restoreDelete: ${owner.name}'s footprint read failed (${describe(e)}); nothing was written.`, { cause: e });
|
|
682
|
+
failures.push(`${owner.name}: ${e?.message ?? e}`);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return { present, failures };
|
|
686
|
+
};
|
|
687
|
+
const before = await presentNow('before');
|
|
688
|
+
const absent = r.entries.filter((e) => !before.present.has(e.path));
|
|
689
|
+
const notes = [];
|
|
690
|
+
const reasons = new Map();
|
|
691
|
+
const canRestore = (e) => e.volatile !== true && e.pathIsSecret !== true && typeof ownerByName.get(e.owner)?.[STORE_OWNER_RESTORE_METHOD] === 'function';
|
|
692
|
+
for (const owner of [...deleteOrder].reverse()) {
|
|
693
|
+
const mine = absent.filter((e) => e.owner === owner.name);
|
|
694
|
+
if (!mine.length) continue;
|
|
695
|
+
for (const e of mine) {
|
|
696
|
+
if (e.volatile === true) reasons.set(e.path, 'deleted by query (volatile); never restored');
|
|
697
|
+
else if (e.pathIsSecret === true) reasons.set(e.path, 'its document id is a credential (the path is a digest); never restored');
|
|
698
|
+
else if (!canRestore(e)) reasons.set(e.path, `${owner.name} implements no ${STORE_OWNER_RESTORE_METHOD}`);
|
|
699
|
+
}
|
|
700
|
+
const restorable = mine.filter(canRestore);
|
|
701
|
+
if (!restorable.length) continue;
|
|
702
|
+
try {
|
|
703
|
+
await owner[STORE_OWNER_RESTORE_METHOD](user, restorable.map(({ owner: _o, ...e }) => structuredClone(e)));
|
|
704
|
+
} catch (e) {
|
|
705
|
+
notes.push(`${owner.name} failed (${describe(e)})`);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const after = await presentNow('after');
|
|
709
|
+
const restored = after.failures.length ? [] : absent.filter((e) => after.present.has(e.path)).map((e) => e.path);
|
|
710
|
+
const remaining = absent.filter((e) => !restored.includes(e.path)).map((e) => ({ owner: e.owner, path: e.path, ...(reasons.has(e.path) ? { reason: reasons.get(e.path) } : {}) }));
|
|
711
|
+
let outcome;
|
|
712
|
+
if (after.failures.length) outcome = RESTORE_OUTCOME.UNVERIFIED;
|
|
713
|
+
else if (restored.length === absent.length) outcome = RESTORE_OUTCOME.RESTORED;
|
|
714
|
+
else if (restored.length === 0) outcome = RESTORE_OUTCOME.NOT_RESTORED;
|
|
715
|
+
else outcome = RESTORE_OUTCOME.PARTIAL;
|
|
716
|
+
// Everything restorable is back: the delete this tool began is over, and its stamp comes off.
|
|
717
|
+
let stamp = 'kept';
|
|
718
|
+
if (!after.failures.length && absent.filter(canRestore).every((e) => restored.includes(e.path))) {
|
|
719
|
+
try {
|
|
720
|
+
stamp = (await userOwner.clearDeleteStamp(user, { planHash: r.planHash })) === true ? 'cleared' : 'kept';
|
|
721
|
+
} catch (e) {
|
|
722
|
+
notes.push(`the admin_delete stamp could not be cleared (${describe(e)})`);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const line = outcome === RESTORE_OUTCOME.UNVERIFIED
|
|
726
|
+
? `UNVERIFIED: the read-back failed (${after.failures.join('; ')}). Verify account ${r.accountId}'s stores before acting on it.`
|
|
727
|
+
: `${outcome}: account ${r.accountId}: ${absent.length ? `${restored.length} of ${absent.length} absent receipt entr${absent.length === 1 ? 'y' : 'ies'} read back restored${remaining.length ? `, ${remaining.length} not` : ''}` : 'no receipt entry was absent; nothing to restore'}; the admin_delete stamp is ${stamp}.`;
|
|
728
|
+
return { outcome, restored, remaining, stamp, line, notes };
|
|
729
|
+
},
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* Dry run of a merge of the legacy record `fromAccountId` into the passkey account `intoAccountId`
|
|
733
|
+
* (writes nothing). The plan lists the moves (each owner's, one per field, `from` null = absent), what
|
|
734
|
+
* stays on the from-record (its sessions, wallet and index rows: the legacy wallet remains a sign-in
|
|
735
|
+
* identity until its services are re-keyed; and the stores of owners that move nothing), where that
|
|
736
|
+
* list is incomplete (`leftoversIncomplete`), and every blocker.
|
|
737
|
+
* @param {{ fromAccountId: string, intoAccountId: string }} args
|
|
738
|
+
*/
|
|
739
|
+
async planMerge({ fromAccountId, intoAccountId } = {}) {
|
|
740
|
+
await assertStoreTargets();
|
|
741
|
+
if (typeof fromAccountId === 'string' && fromAccountId.trim() && fromAccountId.trim() === intoAccountId?.trim?.()) {
|
|
742
|
+
throw refuse(R.ACCOUNT_MERGE_SAME_RECORD, `${fromAccountId} cannot be merged into itself; nothing was read`);
|
|
743
|
+
}
|
|
744
|
+
const fromView = await accountInRule(fromAccountId, 'record to merge');
|
|
745
|
+
const intoView = await accountInRule(intoAccountId, 'surviving account');
|
|
746
|
+
const g = await gatherMerge(fromView, intoView);
|
|
747
|
+
const { planId, expiresAt } = keepPlan({ kind: 'merge', fromAccountId: fromView.accountId, intoAccountId: intoView.accountId, email: intoView.verifiedEmail, hash: g.hash, blockers: g.blockers });
|
|
748
|
+
return { planId, planHash: g.hash, fromAccountId: fromView.accountId, intoAccountId: intoView.accountId, email: intoView.verifiedEmail, moves: g.moves, leftovers: g.leftovers, leftoversIncomplete: g.leftoversIncomplete, blockers: g.blockers, refused: g.blockers.length > 0, expiresAt };
|
|
749
|
+
},
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* Merge as planned. Refusals as commitDelete (both typed ids must match). The receipt (every move, the
|
|
753
|
+
* leftovers, planHash) is saved BEFORE any write; no session is revoked; owners that move anything run
|
|
754
|
+
* first, the User owner last (its migration mark is its last write); a read-back decides the ending.
|
|
755
|
+
* @param {{ planId: string, confirmFromAccountId: string, confirmIntoAccountId: string, receipt: { save: Function } }} args
|
|
756
|
+
*/
|
|
757
|
+
async commitMerge({ planId, confirmFromAccountId, confirmIntoAccountId, receipt } = {}) {
|
|
758
|
+
await assertStoreTargets();
|
|
759
|
+
const p = takePlan(planId, 'merge');
|
|
760
|
+
requireReceiptKeeper(receipt);
|
|
761
|
+
if (confirmMismatch(confirmFromAccountId, p.fromAccountId) || confirmMismatch(confirmIntoAccountId, p.intoAccountId)) {
|
|
762
|
+
throw refuse(R.ACCOUNT_CONFIRMATION_MISMATCH, 'The typed account ids do not match the plan; nothing was written.');
|
|
763
|
+
}
|
|
764
|
+
plans.delete(planId);
|
|
765
|
+
if (p.blockers.length) refuseForBlockers(p.blockers, `merge of ${p.fromAccountId} into ${p.intoAccountId}`);
|
|
766
|
+
const fromView = await accountInRule(p.fromAccountId, 'record to merge');
|
|
767
|
+
const intoView = await accountInRule(p.intoAccountId, 'surviving account');
|
|
768
|
+
const g = await gatherMerge(fromView, intoView);
|
|
769
|
+
if (g.blockers.length) refuseForBlockers(g.blockers, `merge of ${p.fromAccountId} into ${p.intoAccountId}`);
|
|
770
|
+
if (g.hash !== p.hash) throw refuse(R.ACCOUNT_PLAN_STALE, `the stores changed since the merge plan; plan again. Nothing was written.`);
|
|
771
|
+
|
|
772
|
+
const kept = { kind: 'merge', env, target: boundTarget, planId, planHash: p.hash, fromAccountId: p.fromAccountId, intoAccountId: p.intoAccountId, email: p.email, moves: g.moves.map((m) => moveOf(m.owner, m)), leftovers: g.leftovers, leftoversIncomplete: g.leftoversIncomplete, createdAt: new Date(clock()).toISOString() };
|
|
773
|
+
const receiptLabel = await saveReceipt(receipt, kept);
|
|
774
|
+
|
|
775
|
+
const notes = [];
|
|
776
|
+
let failure = null;
|
|
777
|
+
for (const owner of owners) {
|
|
778
|
+
if (typeof owner.mergeForUser !== 'function') continue;
|
|
779
|
+
const expectPaths = g.ownerPaths[owner.name] ?? [];
|
|
780
|
+
if (!expectPaths.length) continue;
|
|
781
|
+
try {
|
|
782
|
+
const r = await owner.mergeForUser(g.pair, { expectPaths });
|
|
783
|
+
for (const x of Array.isArray(r?.remaining) ? r.remaining : []) if (x?.reason) notes.push(`${owner.name}: ${moveKey(x)}: ${x.reason}`);
|
|
784
|
+
} catch (e) {
|
|
785
|
+
failure = { owner: owner.name, error: e };
|
|
786
|
+
notes.push(`${owner.name} failed (${describe(e)}); no later owner ran`);
|
|
787
|
+
break;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// Read-back: the User owner's moves by value; the other owners by a fresh merge footprint (a move
|
|
792
|
+
// done is no longer a move to make).
|
|
793
|
+
const readFailures = [];
|
|
794
|
+
const notMoved = [];
|
|
795
|
+
const userMoves = g.moves.filter((m) => m.owner === userOwner.name);
|
|
796
|
+
try {
|
|
797
|
+
const values = await userOwner.readMergeFields(userMoves);
|
|
798
|
+
userMoves.forEach((m, i) => { if (accountAdminHash(values[i]?.value ?? null) !== accountAdminHash(m.to ?? null)) notMoved.push(moveKey(m)); });
|
|
799
|
+
} catch (e) {
|
|
800
|
+
readFailures.push(`user: ${e?.message ?? e}`);
|
|
801
|
+
}
|
|
802
|
+
for (const owner of storeOwners) {
|
|
803
|
+
if (typeof owner.mergeForUser !== 'function') continue;
|
|
804
|
+
const planned = g.moves.filter((m) => m.owner === owner.name);
|
|
805
|
+
if (!planned.length) continue;
|
|
806
|
+
try {
|
|
807
|
+
const fp = checkFootprint(owner, await owner.footprintForMerge(g.pair), { merge: true });
|
|
808
|
+
const still = new Set(fp.entries.map(moveKey));
|
|
809
|
+
for (const m of planned) if (still.has(moveKey(m))) notMoved.push(moveKey(m));
|
|
810
|
+
} catch (e) {
|
|
811
|
+
readFailures.push(`${owner.name}: ${e?.message ?? e}`);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
const total = g.moves.length;
|
|
815
|
+
let outcome;
|
|
816
|
+
if (readFailures.length) outcome = MERGE_OUTCOME.UNVERIFIED;
|
|
817
|
+
else if (notMoved.length === 0) outcome = MERGE_OUTCOME.MERGED;
|
|
818
|
+
else if (notMoved.length === total) outcome = MERGE_OUTCOME.NOT_MERGED;
|
|
819
|
+
else outcome = MERGE_OUTCOME.PARTIAL;
|
|
820
|
+
const line = outcome === MERGE_OUTCOME.UNVERIFIED
|
|
821
|
+
? `UNVERIFIED: the read-back failed (${readFailures.join('; ')}). Receipt kept: ${receiptLabel}. Verify both accounts before acting on them.`
|
|
822
|
+
: `${outcome}: ${p.fromAccountId} into ${p.intoAccountId}: ${total - notMoved.length} of ${total} planned move(s) read back done${notMoved.length ? `, ${notMoved.length} not` : ''}. Receipt kept: ${receiptLabel}.`;
|
|
823
|
+
return { outcome, notMoved, receiptLabel, line, notes, cause: failure?.error ?? null };
|
|
824
|
+
},
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Undo a merge from its receipt. Refused, writing nothing: a receipt that is not a merge receipt of
|
|
828
|
+
* this env and target, whose moves no longer hash to its planHash (edited), or that names an owner
|
|
829
|
+
* this instance does not hold (ACCOUNT_RECEIPT_INVALID); typed ids other than the receipt's
|
|
830
|
+
* (ACCOUNT_CONFIRMATION_MISMATCH); either account missing or outside the rule; ANY move an owner's
|
|
831
|
+
* validateRollbackMoves rejects for this pair (every owner is asked before the first write). Then the
|
|
832
|
+
* User owner runs first (the migration mark comes off first), the other owners in reverse; every owner
|
|
833
|
+
* runs even when one fails. A read-back decides the ending.
|
|
834
|
+
* @param {{ receipt: Object, confirmFromAccountId: string, confirmIntoAccountId: string }} args
|
|
835
|
+
*/
|
|
836
|
+
async rollbackMerge({ receipt, confirmFromAccountId, confirmIntoAccountId } = {}) {
|
|
837
|
+
await assertStoreTargets();
|
|
838
|
+
const r = receipt;
|
|
839
|
+
if (!r || r.kind !== 'merge' || !Array.isArray(r.moves) || typeof r.fromAccountId !== 'string' || typeof r.intoAccountId !== 'string' || typeof r.planHash !== 'string'
|
|
840
|
+
|| r.moves.some((m) => typeof m?.owner !== 'string' || typeof m?.path !== 'string' || typeof m?.field !== 'string')) {
|
|
841
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, 'This is not a merge receipt (kind, fromAccountId, intoAccountId, planHash, moves of { owner, path, field, from, to }). Nothing was written.');
|
|
842
|
+
}
|
|
843
|
+
assertReceiptHere(r);
|
|
844
|
+
if (mergePlanHash(r.fromAccountId, r.intoAccountId, r.moves) !== r.planHash) {
|
|
845
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, 'The receipt\'s moves do not hash to its planHash: it was edited after it was kept. Nothing was written.');
|
|
846
|
+
}
|
|
847
|
+
if (confirmMismatch(confirmFromAccountId, r.fromAccountId) || confirmMismatch(confirmIntoAccountId, r.intoAccountId)) {
|
|
848
|
+
throw refuse(R.ACCOUNT_CONFIRMATION_MISMATCH, 'The typed account ids do not match the receipt; nothing was written.');
|
|
849
|
+
}
|
|
850
|
+
refuseUnknownOwners(r.moves.map((m) => m.owner));
|
|
851
|
+
const fromView = await accountInRule(r.fromAccountId, 'merged record');
|
|
852
|
+
const intoView = await accountInRule(r.intoAccountId, 'surviving account');
|
|
853
|
+
const pair = Object.freeze({ from: storeUser(fromView), into: storeUser(intoView) });
|
|
854
|
+
const byOwner = (name) => r.moves.filter((m) => m.owner === name).map(({ owner, ...m }) => m);
|
|
855
|
+
const order = [userOwner, ...[...storeOwners].reverse()];
|
|
856
|
+
for (const owner of order) {
|
|
857
|
+
const moves = byOwner(owner.name);
|
|
858
|
+
if (!moves.length) continue;
|
|
859
|
+
if (typeof owner.validateRollbackMoves !== 'function') {
|
|
860
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, `The receipt has ${moves.length} move(s) for '${owner.name}', which moves nothing on merge. Nothing was written.`);
|
|
861
|
+
}
|
|
862
|
+
try {
|
|
863
|
+
await owner.validateRollbackMoves(structuredClone(moves), pair);
|
|
864
|
+
} catch (e) {
|
|
865
|
+
if (!(e instanceof AccountAdminError)) throw e;
|
|
866
|
+
throw refuse(R.ACCOUNT_RECEIPT_INVALID, `'${owner.name}' rejected the receipt's moves (${describe(e)}). Nothing was written.`, { cause: e });
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
const notes = [];
|
|
870
|
+
for (const owner of order) {
|
|
871
|
+
const moves = byOwner(owner.name);
|
|
872
|
+
if (!moves.length) continue;
|
|
873
|
+
try {
|
|
874
|
+
await owner.rollbackMergeForUser(moves, pair);
|
|
875
|
+
} catch (e) {
|
|
876
|
+
notes.push(`${owner.name} failed (${describe(e)})`);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
const readFailures = [];
|
|
880
|
+
const notRestored = [];
|
|
881
|
+
const userMoves = byOwner(userOwner.name);
|
|
882
|
+
if (userMoves.length) {
|
|
883
|
+
try {
|
|
884
|
+
const values = await userOwner.readMergeFields(userMoves);
|
|
885
|
+
userMoves.forEach((m, i) => { if (accountAdminHash(values[i]?.value ?? null) !== accountAdminHash(m.from ?? null)) notRestored.push(moveKey(m)); });
|
|
886
|
+
} catch (e) {
|
|
887
|
+
readFailures.push(`user: ${e?.message ?? e}`);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
for (const owner of storeOwners) {
|
|
891
|
+
const moves = byOwner(owner.name);
|
|
892
|
+
if (!moves.length) continue;
|
|
893
|
+
try {
|
|
894
|
+
const fp = checkFootprint(owner, await owner.footprintForMerge(pair), { merge: true });
|
|
895
|
+
const again = new Set(fp.entries.map(moveKey));
|
|
896
|
+
for (const m of moves) if (!again.has(moveKey(m))) notRestored.push(moveKey(m));
|
|
897
|
+
} catch (e) {
|
|
898
|
+
readFailures.push(`${owner.name}: ${e?.message ?? e}`);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const total = r.moves.length;
|
|
902
|
+
let outcome;
|
|
903
|
+
if (readFailures.length) outcome = MERGE_ROLLBACK_OUTCOME.UNVERIFIED;
|
|
904
|
+
else if (notRestored.length === 0) outcome = MERGE_ROLLBACK_OUTCOME.ROLLED_BACK;
|
|
905
|
+
else if (notRestored.length === total) outcome = MERGE_ROLLBACK_OUTCOME.NOT_ROLLED_BACK;
|
|
906
|
+
else outcome = MERGE_ROLLBACK_OUTCOME.PARTIAL;
|
|
907
|
+
const line = outcome === MERGE_ROLLBACK_OUTCOME.UNVERIFIED
|
|
908
|
+
? `UNVERIFIED: the read-back failed (${readFailures.join('; ')}). Verify both accounts before acting on them.`
|
|
909
|
+
: `${outcome}: ${r.fromAccountId} / ${r.intoAccountId}: ${total - notRestored.length} of ${total} move(s) read back restored${notRestored.length ? `, ${notRestored.length} not` : ''}.`;
|
|
910
|
+
return { outcome, notRestored, line, notes };
|
|
911
|
+
},
|
|
912
|
+
});
|
|
913
|
+
}
|