@mdbase-dev/sdk 0.2.98 → 0.2.101

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.
@@ -15703,12 +15703,12 @@ function appReleaseTrust() {
15703
15703
  // src/application/asset-pins.json
15704
15704
  var asset_pins_default = {
15705
15705
  runtime: {
15706
- sha256: "2f6dadfde367cb098f20ca0e2f95cb8ebca250ce7525755a0f56686a89822c3d",
15707
- bytes: 4203391,
15708
- maxBytes: 4203391,
15706
+ sha256: "22ab599e9f32fe8e72c42c388824380c90ab54ddccf331f4eaf695d47e54ea0b",
15707
+ bytes: 4201671,
15708
+ maxBytes: 4201671,
15709
15709
  source: {
15710
15710
  repository: "mdbase-dev/mdbase-connect",
15711
- commit: "b3505a0e268e9c97b1e46688311d66f7c9b70c2d"
15711
+ commit: "c106d4a6b427e2b9b39e725e5053d119d76833fd"
15712
15712
  }
15713
15713
  },
15714
15714
  sqlite: {
@@ -24036,6 +24036,229 @@ function appServerBody(bytes10) {
24036
24036
  }
24037
24037
  }
24038
24038
 
24039
+ // src/app-host/log-token-cache.ts
24040
+ var LOG_TOKEN_DATABASE = "mdbase.app.log-token.v1";
24041
+ var STORE2 = "tokens";
24042
+ var MIN_LEFT_MS = 6e4;
24043
+ function open() {
24044
+ return new Promise((resolve) => {
24045
+ let request3;
24046
+ try {
24047
+ request3 = indexedDB.open(LOG_TOKEN_DATABASE, 1);
24048
+ } catch {
24049
+ resolve(null);
24050
+ return;
24051
+ }
24052
+ request3.onupgradeneeded = () => {
24053
+ try {
24054
+ request3.result.createObjectStore(STORE2);
24055
+ } catch {
24056
+ }
24057
+ };
24058
+ request3.onsuccess = () => {
24059
+ const db = request3.result;
24060
+ db.onversionchange = () => db.close();
24061
+ resolve(db.objectStoreNames.contains(STORE2) ? db : (db.close(), null));
24062
+ };
24063
+ request3.onerror = request3.onblocked = () => resolve(null);
24064
+ });
24065
+ }
24066
+ function run(mode, work2) {
24067
+ return open().then((db) => new Promise((resolve) => {
24068
+ if (!db) {
24069
+ resolve(null);
24070
+ return;
24071
+ }
24072
+ let result2 = null;
24073
+ try {
24074
+ const tx = db.transaction(STORE2, mode), request3 = work2(tx.objectStore(STORE2));
24075
+ if (request3) request3.onsuccess = () => {
24076
+ result2 = request3.result ?? null;
24077
+ };
24078
+ tx.oncomplete = () => {
24079
+ db.close();
24080
+ resolve(result2);
24081
+ };
24082
+ tx.onerror = tx.onabort = () => {
24083
+ db.close();
24084
+ resolve(null);
24085
+ };
24086
+ } catch {
24087
+ db.close();
24088
+ resolve(null);
24089
+ }
24090
+ }));
24091
+ }
24092
+ function idbLogTokenCache() {
24093
+ if (typeof indexedDB === "undefined") return null;
24094
+ return Object.freeze({
24095
+ async read(key3, now) {
24096
+ const v = await run("readonly", (store2) => store2.get(key3)).catch(() => null);
24097
+ if (!v || typeof v.value !== "string" || !v.value || v.value.length > 16 * 1024 || /[^\x21-\x7e]/.test(v.value) || typeof v.expires !== "number" || !Number.isSafeInteger(v.expires) || v.expires - now < MIN_LEFT_MS || v.expires - now > 16 * 6e4) return null;
24098
+ return Object.freeze({ value: v.value, expires: v.expires });
24099
+ },
24100
+ async write(key3, token) {
24101
+ await run("readwrite", (store2) => store2.put({ value: token.value, expires: token.expires }, key3)).catch(() => null);
24102
+ },
24103
+ async drop(key3) {
24104
+ await run("readwrite", (store2) => store2.delete(key3)).catch(() => null);
24105
+ }
24106
+ });
24107
+ }
24108
+ async function eraseAppLogTokens(scope) {
24109
+ const { cpOrigin, connectorId, deviceId } = scope;
24110
+ if (!connectorId || !deviceId) return true;
24111
+ const db = await open();
24112
+ if (!db) return false;
24113
+ return new Promise((resolve) => {
24114
+ try {
24115
+ const tx = db.transaction(STORE2, "readwrite"), cursor = tx.objectStore(STORE2).openCursor();
24116
+ cursor.onsuccess = () => {
24117
+ const row3 = cursor.result;
24118
+ if (!row3) return;
24119
+ if (typeof row3.key === "string") {
24120
+ const parts = row3.key.split(" ");
24121
+ if (parts.length === 5 && parts[0] === cpOrigin && parts[2] === connectorId && parts[3] === deviceId) row3.delete();
24122
+ }
24123
+ row3.continue();
24124
+ };
24125
+ tx.oncomplete = () => {
24126
+ db.close();
24127
+ resolve(true);
24128
+ };
24129
+ tx.onerror = tx.onabort = () => {
24130
+ db.close();
24131
+ resolve(false);
24132
+ };
24133
+ } catch {
24134
+ db.close();
24135
+ resolve(false);
24136
+ }
24137
+ });
24138
+ }
24139
+
24140
+ // src/app-host/sign-out-erase.ts
24141
+ var SIGN_OUT_ERASE_TIMEOUT_MS = 5e3;
24142
+ var hex = (id4) => Array.from(uuidToBytes(id4), (b) => b.toString(16).padStart(2, "0")).join("");
24143
+ var lower = (id4) => {
24144
+ uuidToBytes(id4);
24145
+ return id4.toLowerCase();
24146
+ };
24147
+ function bounded(work2, fallback, ms = SIGN_OUT_ERASE_TIMEOUT_MS) {
24148
+ let timer;
24149
+ return Promise.race([work2.catch(() => fallback), new Promise((resolve) => {
24150
+ timer = setTimeout(() => resolve(fallback), ms);
24151
+ })]).finally(() => clearTimeout(timer));
24152
+ }
24153
+ function deleteDatabase(name2) {
24154
+ return bounded(new Promise((resolve) => {
24155
+ const request3 = indexedDB.deleteDatabase(name2);
24156
+ request3.onsuccess = () => resolve(true);
24157
+ request3.onerror = () => resolve(false);
24158
+ }), false);
24159
+ }
24160
+ function deviceCustodyDatabaseNames(scope) {
24161
+ const { accountId, connectorId, deviceId, installationId } = scope;
24162
+ const keyIds = [accountId, connectorId, deviceId, installationId].map(hex).join(".");
24163
+ return [
24164
+ `mdbase.app.device-key-kek.v1.${keyIds}`,
24165
+ `mdbase.app.device-keys.v1.${keyIds}`,
24166
+ `mdbase.app.noise.v1.${lower(installationId)}.${lower(connectorId)}.${lower(deviceId)}`
24167
+ ];
24168
+ }
24169
+ async function eraseUnattestedDeviceCustody(scope) {
24170
+ try {
24171
+ if (!globalThis.indexedDB) return false;
24172
+ return (await Promise.all(deviceCustodyDatabaseNames(scope).map(deleteDatabase))).every(Boolean);
24173
+ } catch {
24174
+ return false;
24175
+ }
24176
+ }
24177
+ function ledgerNames(scope) {
24178
+ const cp = encodeURIComponent(scope.cpOrigin), unlabelled = `mdbase.app.installation.v1.${cp}.${scope.appId}`;
24179
+ return [scope.owner === void 0 ? unlabelled : `mdbase.app.installation.v2.${cp}.${encodeURIComponent(scope.owner)}.${scope.appId}`, unlabelled];
24180
+ }
24181
+ async function installationDatabaseNames(scope) {
24182
+ const others = /* @__PURE__ */ new Set();
24183
+ const { accountId: account, connectorId: connector, deviceId: device, installationId: installation } = scope;
24184
+ if (account && connector && device && installation) {
24185
+ for (const name2 of deviceCustodyDatabaseNames({ accountId: account, connectorId: connector, deviceId: device, installationId: installation })) others.add(name2);
24186
+ const prefix = [account, connector, device, installation].map(lower).join(".");
24187
+ const scoped = [`mdbase.app.cloud-copy-outcome.v1.${prefix}.`, `mdbase.app.private-bootstrap.v1.${prefix}.`];
24188
+ for (const collection of scope.collectionIds) {
24189
+ const id4 = lower(collection);
24190
+ for (const purpose of ["create", "join"]) others.add(`${scoped[0]}${id4}.${purpose}`);
24191
+ for (const purpose of ["create", "enrol"]) others.add(`${scoped[1]}${id4}.${purpose}`);
24192
+ }
24193
+ const list4 = indexedDB.databases;
24194
+ if (typeof list4 === "function") {
24195
+ const found = await bounded(list4.call(indexedDB), []);
24196
+ for (const { name: name2 } of found) if (name2 && scoped.some((p) => name2.startsWith(p))) others.add(name2);
24197
+ }
24198
+ }
24199
+ return [...others];
24200
+ }
24201
+ async function removeReplicas(account, installation) {
24202
+ const storage = globalThis.navigator?.storage;
24203
+ if (typeof storage?.getDirectory !== "function") return true;
24204
+ return bounded((async () => {
24205
+ const root = await storage.getDirectory();
24206
+ const prefix = `.mdbase-app-${lower(account)}-${lower(installation)}-`, names = [];
24207
+ for await (const name2 of root.keys()) if (name2.startsWith(prefix)) names.push(name2);
24208
+ let ok = true;
24209
+ for (const name2 of names) {
24210
+ try {
24211
+ await root.removeEntry(name2, { recursive: true });
24212
+ } catch {
24213
+ ok = false;
24214
+ }
24215
+ }
24216
+ return ok;
24217
+ })(), false);
24218
+ }
24219
+ async function eraseAppCollectionAccess(scope, collectionId) {
24220
+ try {
24221
+ if (!globalThis.indexedDB || !scope.accountId || !scope.connectorId || !scope.deviceId || !scope.installationId) return false;
24222
+ const collection = lower(collectionId), prefix = [scope.accountId, scope.connectorId, scope.deviceId, scope.installationId].map(lower).join(".");
24223
+ const names = ["create", "join"].map((purpose) => `mdbase.app.cloud-copy-outcome.v1.${prefix}.${collection}.${purpose}`);
24224
+ names.push(...["create", "enrol"].map((purpose) => `mdbase.app.private-bootstrap.v1.${prefix}.${collection}.${purpose}`));
24225
+ const results2 = await Promise.all(names.map(deleteDatabase));
24226
+ const storage = globalThis.navigator?.storage;
24227
+ if (typeof storage?.getDirectory === "function") {
24228
+ const root = await storage.getDirectory();
24229
+ try {
24230
+ await root.removeEntry(`.mdbase-app-${lower(scope.accountId)}-${lower(scope.installationId)}-${collection}`, { recursive: true });
24231
+ } catch (error4) {
24232
+ if (!(error4 instanceof DOMException && error4.name === "NotFoundError")) return false;
24233
+ }
24234
+ }
24235
+ return results2.every(Boolean);
24236
+ } catch {
24237
+ return false;
24238
+ }
24239
+ }
24240
+ async function eraseAppInstallationData(scope) {
24241
+ if (!globalThis.indexedDB) return Object.freeze({ ledger: false, complete: false });
24242
+ const [current2, unlabelled] = ledgerNames(scope);
24243
+ const ledger = await deleteDatabase(current2);
24244
+ const others = new Set(scope.isolated ? [] : scope.databases);
24245
+ if (!scope.isolated && scope.storageNamespace === void 0) others.add(unlabelled);
24246
+ others.delete(current2);
24247
+ if (!scope.isolated && scope.storageNamespace === void 0) others.add(LOG_TOKEN_DATABASE);
24248
+ const [results2, complete2] = await Promise.all([
24249
+ Promise.all([...others].map(deleteDatabase)),
24250
+ eraseInstallationStores(scope, scope.storageNamespace !== void 0)
24251
+ ]);
24252
+ return Object.freeze({ ledger, complete: ledger && complete2 && results2.every(Boolean) });
24253
+ }
24254
+ async function eraseInstallationStores(scope, scopedTokens = true) {
24255
+ if (!globalThis.indexedDB) return false;
24256
+ const databases = installationDatabaseNames(scope).then((names) => Promise.all(names.map(deleteDatabase))).then((results2) => results2.every(Boolean), () => false);
24257
+ const tokens2 = scopedTokens ? bounded(eraseAppLogTokens(scope), false) : true;
24258
+ const replicas = scope.accountId && scope.installationId ? removeReplicas(scope.accountId, scope.installationId).catch(() => false) : true;
24259
+ return (await Promise.all([databases, tokens2, replicas])).every(Boolean);
24260
+ }
24261
+
24039
24262
  // src/app-host/installation-sign-in.ts
24040
24263
  var AppInstallationSignInError = class extends Error {
24041
24264
  constructor(reason, server) {
@@ -24055,7 +24278,7 @@ function unknownPrivateDeviceField(status, error4) {
24055
24278
  const { code, message: message2 } = error4;
24056
24279
  return code === "invalid_request" && typeof message2 === "string" && message2.length <= 512 && /unrecognized key/i.test(message2) && message2.includes("requested_private_device");
24057
24280
  }
24058
- var hex = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
24281
+ var hex2 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
24059
24282
  var UUID3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
24060
24283
  function id(v) {
24061
24284
  if (typeof v !== "string" || !UUID3.test(v) || uuidToBytes(v).every((b) => b === 0)) throw fail3("response");
@@ -24141,6 +24364,7 @@ function collectionListing(value2) {
24141
24364
  return Object.freeze({ collectionId, displayName: r.display_name, role: r.role, ...availability ? { availability } : {}, ...allowed ? { fileActions: allowed } : {}, ...r.mode === "private" ? { mode: "private" } : {} });
24142
24365
  }));
24143
24366
  }
24367
+ var MAX_SCOPED_INSTALLATIONS = 1e3;
24144
24368
  var FILE_ACTIONS = ["list", "read", "add", "replace", "move", "delete"];
24145
24369
  function fileActions(v, allowed = FILE_ACTIONS, empty = true) {
24146
24370
  if (!Array.isArray(v) || v.length > FILE_ACTIONS.length || !empty && !v.length || new Set(v).size !== v.length || v.some((a) => !allowed.includes(a))) throw fail3("response");
@@ -24155,6 +24379,7 @@ function verificationUri(value2, base, hint) {
24155
24379
  return value2 === base || hint !== null && value2 === `${base}?collection_hint=${hint}` ? value2 : null;
24156
24380
  }
24157
24381
  var replaceRefusedAppInstallation;
24382
+ var installationRecovery;
24158
24383
  var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
24159
24384
  constructor(store2, state, options) {
24160
24385
  this.store = store2;
@@ -24169,7 +24394,12 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
24169
24394
  state;
24170
24395
  options;
24171
24396
  static {
24172
- replaceRefusedAppInstallation = (flow, stop) => flow.replaceRefusedInstallation(stop);
24397
+ replaceRefusedAppInstallation = (flow, stop, childPaired) => flow.replaceRefusedInstallation(stop, childPaired);
24398
+ installationRecovery = {
24399
+ replacementPending: (flow) => flow.replacementPending(),
24400
+ references: (flow) => flow.scopedInstallationReferences(),
24401
+ replaceRetained: (flow, installation, collection, expected) => flow.replaceRetainedCollectionInstallation(installation, collection, expected)
24402
+ };
24173
24403
  }
24174
24404
  closed = false;
24175
24405
  busy = false;
@@ -24231,7 +24461,7 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
24231
24461
  const base = "version,requestId,installationId,deviceId,secret,appId,kind,origin,cpOrigin,environment,selection,confirmed,nativeStarted,proof,token";
24232
24462
  const legacy = parsed?.version === 1;
24233
24463
  const fields3 = `${base},requestedCreateCollections,collectionIds,createCollections,consentRequest`;
24234
- const r = legacy ? { ...object2(parsed, base), version: 3, renewal: null, requestedCreateCollections: false, collectionIds: [], createCollections: false, consentRequest: null } : parsed?.version === 2 ? { ...object2(parsed, fields3), version: 3, renewal: null } : object2(parsed, `${fields3},renewal${Object.hasOwn(parsed, "collectionSelection") ? ",collectionSelection" : ""}${Object.hasOwn(parsed, "timerConsent") ? ",timerConsent" : ""}${Object.hasOwn(parsed, "timerChannel") ? ",timerChannel" : ""}${Object.hasOwn(parsed, "owner") ? ",owner" : ""}${Object.hasOwn(parsed, "collectionListing") ? ",collectionListing" : ""}${Object.hasOwn(parsed, "collectionRecoveries") ? ",collectionRecoveries" : ""}${Object.hasOwn(parsed, "recoveryFor") ? ",recoveryFor" : ""}${Object.hasOwn(parsed, "nativeAuthorization") ? ",nativeAuthorization" : ""}${Object.hasOwn(parsed, "nativeSelection") ? ",nativeSelection" : ""}${Object.hasOwn(parsed, "nativeGrants") ? ",nativeGrants" : ""}${Object.hasOwn(parsed, "requestedPrivateDevice") ? ",requestedPrivateDevice" : ""}${Object.hasOwn(parsed, "privateDeviceCollectionIds") ? ",privateDeviceCollectionIds" : ""}${Object.hasOwn(parsed, "requestSent") ? ",requestSent" : ""}`);
24464
+ const r = legacy ? { ...object2(parsed, base), version: 3, renewal: null, requestedCreateCollections: false, collectionIds: [], createCollections: false, consentRequest: null } : parsed?.version === 2 ? { ...object2(parsed, fields3), version: 3, renewal: null } : object2(parsed, `${fields3},renewal${Object.hasOwn(parsed, "collectionSelection") ? ",collectionSelection" : ""}${Object.hasOwn(parsed, "timerConsent") ? ",timerConsent" : ""}${Object.hasOwn(parsed, "timerChannel") ? ",timerChannel" : ""}${Object.hasOwn(parsed, "owner") ? ",owner" : ""}${Object.hasOwn(parsed, "collectionListing") ? ",collectionListing" : ""}${Object.hasOwn(parsed, "collectionRecoveries") ? ",collectionRecoveries" : ""}${Object.hasOwn(parsed, "retainedCollectionRecoveries") ? ",retainedCollectionRecoveries" : ""}${Object.hasOwn(parsed, "replacementPending") ? ",replacementPending" : ""}${Object.hasOwn(parsed, "recoveryFor") ? ",recoveryFor" : ""}${Object.hasOwn(parsed, "nativeAuthorization") ? ",nativeAuthorization" : ""}${Object.hasOwn(parsed, "nativeSelection") ? ",nativeSelection" : ""}${Object.hasOwn(parsed, "nativeGrants") ? ",nativeGrants" : ""}${Object.hasOwn(parsed, "requestedPrivateDevice") ? ",requestedPrivateDevice" : ""}${Object.hasOwn(parsed, "privateDeviceCollectionIds") ? ",privateDeviceCollectionIds" : ""}${Object.hasOwn(parsed, "requestSent") ? ",requestSent" : ""}`);
24235
24465
  if (r.version !== 3 || r.appId !== p.appId || r.owner !== p.owner || r.kind !== (p.installationKind ?? "app-runtime") || r.origin !== p.origin || r.cpOrigin !== p.cpOrigin || r.environment !== p.environment || typeof r.confirmed !== "boolean" || typeof r.nativeStarted !== "boolean") throw fail3("recovery_required");
24236
24466
  const s = r;
24237
24467
  if (typeof s.requestedCreateCollections !== "boolean" || typeof s.createCollections !== "boolean" || p.requestedCreateCollections !== void 0 && p.requestedCreateCollections !== s.requestedCreateCollections) throw fail3("binding");
@@ -24312,7 +24542,27 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
24312
24542
  if (s.collectionRecoveries !== void 0) {
24313
24543
  if (!s.token || !s.confirmed || !s.selection || !s.proof || !s.collectionRecoveries || typeof s.collectionRecoveries !== "object" || Array.isArray(s.collectionRecoveries)) throw fail3("recovery_required");
24314
24544
  const entries = Object.entries(s.collectionRecoveries);
24315
- if (entries.length > 1e3 || entries.some(([collection, replacement]) => !(s.collectionIds.includes(id(collection)) || s.nativeGrants?.some((c) => c.collection_id === collection)) || replacement !== null && !id(replacement))) throw fail3("recovery_required");
24545
+ if (entries.length > MAX_SCOPED_INSTALLATIONS || entries.some(([collection, replacement]) => !(s.collectionIds.includes(id(collection)) || s.nativeGrants?.some((c) => c.collection_id === collection)) || replacement !== null && !id(replacement))) throw fail3("recovery_required");
24546
+ }
24547
+ if (s.replacementPending !== void 0 && (s.replacementPending !== true || !s.token || !s.confirmed)) throw fail3("recovery_required");
24548
+ if (s.retainedCollectionRecoveries !== void 0) {
24549
+ const retained = s.retainedCollectionRecoveries;
24550
+ if (s.recoveryFor || !retained || typeof retained !== "object" || Array.isArray(retained)) throw fail3("recovery_required");
24551
+ const references = Object.values(s.collectionRecoveries ?? {}).filter((reference) => reference !== null);
24552
+ const seen = new Set(references);
24553
+ if (seen.size !== references.length) throw fail3("recovery_required");
24554
+ for (const [account, collections] of Object.entries(retained)) {
24555
+ id(account);
24556
+ if (!collections || typeof collections !== "object" || Array.isArray(collections)) throw fail3("recovery_required");
24557
+ const entries = Object.entries(collections);
24558
+ if (!entries.length || seen.size + entries.length > MAX_SCOPED_INSTALLATIONS) throw fail3("recovery_required");
24559
+ for (const [collection, reference] of entries) {
24560
+ id(collection);
24561
+ id(reference);
24562
+ if (seen.has(reference) || account === s.selection?.accountId && Object.hasOwn(s.collectionRecoveries ?? {}, collection)) throw fail3("recovery_required");
24563
+ seen.add(reference);
24564
+ }
24565
+ }
24316
24566
  }
24317
24567
  if (s.nativeAuthorization) {
24318
24568
  const a = object2(s.nativeAuthorization, "requestId,authorizationId,applicationId,manifestDigest");
@@ -24467,19 +24717,37 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
24467
24717
  }
24468
24718
  return this.exclusive(() => this.startRequest(hint));
24469
24719
  }
24470
- /** Replace the protected identity in place under the sign-in ledger lease.
24471
- * The old replica and custody stores remain under the original IDs.
24472
- */
24473
- replaceRefusedInstallation(stop) {
24720
+ /** Replace the protected identity under the same sign-in ledger lease. */
24721
+ replaceRefusedInstallation(stop, childPaired) {
24474
24722
  return this.exclusive(async () => {
24475
- if (!this.credentialRefused || !this.state.token || Object.values(this.state.collectionRecoveries ?? {}).some((reference) => reference !== null)) throw fail3("recovery_required");
24723
+ const state = this.state;
24724
+ if (!(this.credentialRefused || state.replacementPending) || !state.token) throw fail3("recovery_required");
24725
+ const scoped = this.scopedInstallationReferences();
24726
+ if (scoped.some((reference) => !childPaired?.(reference))) throw fail3("recovery_required");
24727
+ const selected = this.confirmedSelection();
24728
+ const collectionIds = [...state.collectionIds, ...(state.nativeGrants ?? []).map((grant) => grant.collection_id)];
24729
+ if (!state.replacementPending) {
24730
+ await this.saveWithRecoveryMetadata({ ...state, replacementPending: true });
24731
+ }
24476
24732
  await stop();
24477
- await this.save(_AppProtectedInstallationSignIn.freshState(this.options));
24733
+ if (!await eraseInstallationStores({ ...selected, collectionIds })) throw fail3("recovery_required");
24734
+ if (scoped.some((reference) => !childPaired?.(reference))) throw fail3("recovery_required");
24735
+ const fresh = _AppProtectedInstallationSignIn.freshState(this.options);
24736
+ if (scoped.length) {
24737
+ const retained = {};
24738
+ for (const { accountId, collectionId, reference } of scoped) (retained[accountId] ??= {})[collectionId] = reference;
24739
+ fresh.retainedCollectionRecoveries = retained;
24740
+ }
24741
+ await this.save(fresh);
24478
24742
  this.credentialRefused = false;
24479
24743
  this.nativeAcknowledged = false;
24480
24744
  this.closedPairing = null;
24481
24745
  });
24482
24746
  }
24747
+ replacementPending() {
24748
+ this.check();
24749
+ return this.state.replacementPending === true;
24750
+ }
24483
24751
  /** Explicit user retry after an exact typed expiry. Renew ONLY the pairing
24484
24752
  * window; installation/device/account/challenge/keys/proof remain original.
24485
24753
  * Persist the new request and its parent capability BEFORE HTTP. Unknown
@@ -24890,7 +25158,41 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
24890
25158
  * separate original installation ledger, never a replacement credential. */
24891
25159
  collectionRecoveries() {
24892
25160
  this.check();
24893
- return Object.freeze({ ...this.state.collectionRecoveries });
25161
+ return Object.freeze({ ...this.retainedRecoveriesForAccount(), ...this.state.collectionRecoveries });
25162
+ }
25163
+ scopedInstallationReferences() {
25164
+ this.check();
25165
+ const refs = [];
25166
+ for (const [accountId2, collections] of Object.entries(this.state.retainedCollectionRecoveries ?? {})) {
25167
+ for (const [collectionId, reference] of Object.entries(collections)) refs.push({ accountId: accountId2, collectionId, reference });
25168
+ }
25169
+ const accountId = this.state.selection?.accountId;
25170
+ if (accountId) for (const [collectionId, reference] of Object.entries(this.state.collectionRecoveries ?? {})) {
25171
+ if (reference !== null) refs.push({ accountId, collectionId, reference });
25172
+ }
25173
+ return refs;
25174
+ }
25175
+ retainedRecoveriesForAccount() {
25176
+ const { token, selection, retainedCollectionRecoveries } = this.state;
25177
+ return token && selection ? retainedCollectionRecoveries?.[selection.accountId] : void 0;
25178
+ }
25179
+ replaceRetainedCollectionInstallation(installation, collection, expected) {
25180
+ const check3 = this.consentGuard(installation);
25181
+ return this.exclusive(async () => {
25182
+ check3();
25183
+ id(collection);
25184
+ id(expected);
25185
+ const retained = this.retainedRecoveriesForAccount();
25186
+ if (!retained?.[collection]) return null;
25187
+ if (retained[collection] !== expected) throw fail3("fenced");
25188
+ const reference = crypto.randomUUID();
25189
+ await this.saveWithRecoveryMetadata({ ...this.state, retainedCollectionRecoveries: {
25190
+ ...this.state.retainedCollectionRecoveries,
25191
+ [installation.scope.account]: { ...retained, [collection]: reference }
25192
+ } });
25193
+ check3();
25194
+ return reference;
25195
+ });
24894
25196
  }
24895
25197
  retireCollectionScope(installation, collection, expectedReplacement = null) {
24896
25198
  const check3 = this.consentGuard(installation);
@@ -24916,14 +25218,17 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
24916
25218
  if (!Object.hasOwn(this.state.collectionRecoveries ?? {}, collection)) throw fail3("binding");
24917
25219
  const existing = this.state.collectionRecoveries[collection];
24918
25220
  if (existing !== null) return existing;
25221
+ if (this.scopedInstallationReferences().length >= MAX_SCOPED_INSTALLATIONS) throw fail3("recovery_required");
24919
25222
  const replacement = crypto.randomUUID();
24920
25223
  await this.saveRecovery(collection, replacement);
24921
25224
  check3();
24922
25225
  return replacement;
24923
25226
  });
24924
25227
  }
24925
- async saveRecovery(collection, replacement) {
24926
- const state = { ...this.state, collectionRecoveries: { ...this.state.collectionRecoveries, [collection]: replacement } };
25228
+ saveRecovery(collection, replacement) {
25229
+ return this.saveWithRecoveryMetadata({ ...this.state, collectionRecoveries: { ...this.state.collectionRecoveries, [collection]: replacement } });
25230
+ }
25231
+ async saveWithRecoveryMetadata(state) {
24927
25232
  if (new TextEncoder().encode(JSON.stringify(state)).length > 128 * 1024) delete state.collectionListing;
24928
25233
  await this.save(state);
24929
25234
  }
@@ -25155,7 +25460,7 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
25155
25460
  const proof2 = runtime2.signCpEnrol(challenge);
25156
25461
  signature = proof2.signature;
25157
25462
  check3();
25158
- await this.save({ ...this.state, proof: _AppProtectedInstallationSignIn.proof({ sign_pk: hex(proof2.signPublicKey), kem_pk: hex(proof2.kemPublicKey), noise_pk: hex(proof2.noisePublicKey), sig: hex(signature) }) });
25463
+ await this.save({ ...this.state, proof: _AppProtectedInstallationSignIn.proof({ sign_pk: hex2(proof2.signPublicKey), kem_pk: hex2(proof2.kemPublicKey), noise_pk: hex2(proof2.noisePublicKey), sig: hex2(signature) }) });
25159
25464
  check3();
25160
25465
  } finally {
25161
25466
  challenge.fill(0);
@@ -25163,7 +25468,7 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
25163
25468
  }
25164
25469
  }
25165
25470
  const p = this.state.proof;
25166
- if (p.sign_pk !== hex(custody.signPublicKey) || p.kem_pk !== hex(custody.kemPublicKey) || p.noise_pk !== hex(custody.noisePublicKey)) throw fail3("binding");
25471
+ if (p.sign_pk !== hex2(custody.signPublicKey) || p.kem_pk !== hex2(custody.kemPublicKey) || p.noise_pk !== hex2(custody.noisePublicKey)) throw fail3("binding");
25167
25472
  const { status, value: value2 } = await this.json(`/v1/pairing-requests/${this.state.requestId}/attest`, true, p);
25168
25473
  check3();
25169
25474
  object2(value2, "ok");
@@ -25190,7 +25495,7 @@ var AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
25190
25495
  return this.exclusive(async () => {
25191
25496
  check3();
25192
25497
  const r = this.receipt();
25193
- if (hex(r.signPublicKey) !== hex(custody.signPublicKey) || hex(r.kemPublicKey) !== hex(custody.kemPublicKey) || hex(r.noisePublicKey) !== hex(custody.noisePublicKey)) throw fail3("binding");
25498
+ if (hex2(r.signPublicKey) !== hex2(custody.signPublicKey) || hex2(r.kemPublicKey) !== hex2(custody.kemPublicKey) || hex2(r.noisePublicKey) !== hex2(custody.noisePublicKey)) throw fail3("binding");
25194
25499
  await persistence.registered(r, { signal: this.lifetime.signal });
25195
25500
  check3();
25196
25501
  runtime2.acknowledgeDeviceRegistration(r);
@@ -25337,7 +25642,7 @@ function bytes3(v, length) {
25337
25642
  function equal4(a, b) {
25338
25643
  return a.length === b.length && a.every((v, i) => v === b[i]);
25339
25644
  }
25340
- function hex2(b) {
25645
+ function hex3(b) {
25341
25646
  return [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
25342
25647
  }
25343
25648
  function base64(b) {
@@ -25549,7 +25854,7 @@ var AppHttpLogTransport = class {
25549
25854
  signature = await this.authority.signLogProof(p, { signal });
25550
25855
  this.check(signal);
25551
25856
  if (!(signature instanceof Uint8Array) || signature.length !== 64) throw error("shape");
25552
- const r = await this.fetch(`${this.base}/v1/rpc`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/cbor", "x-mdbase-nonce": hex2(p.nonce), "x-mdbase-sig": hex2(signature) }, body: frame }, signal, 15e3);
25857
+ const r = await this.fetch(`${this.base}/v1/rpc`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/cbor", "x-mdbase-nonce": hex3(p.nonce), "x-mdbase-sig": hex3(signature) }, body: frame }, signal, 15e3);
25553
25858
  this.spares.keep(r.headers);
25554
25859
  if (r.status === 401) this.authority.invalidateToken?.(token);
25555
25860
  if (!r.ok) throw await this.refusal(r, signal, receive);
@@ -25829,7 +26134,7 @@ function uint2(v) {
25829
26134
  if (n < 0n || n > (1n << 64n) - 1n) throw fail4("binding");
25830
26135
  return n;
25831
26136
  }
25832
- function hex3(b) {
26137
+ function hex4(b) {
25833
26138
  return [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
25834
26139
  }
25835
26140
  function object3(v) {
@@ -25993,7 +26298,7 @@ var AppCpLogAuthority = class {
25993
26298
  signature = this.runtime.signCpLogToken(challenge);
25994
26299
  this.check(options.signal);
25995
26300
  if (!(signature instanceof Uint8Array) || signature.length !== 64) throw fail4("response");
25996
- const body = JSON.stringify({ device_id: this.deviceId, challenge: issued.challenge, sig: hex3(signature), capabilities: ["collection_mode_switch_v2"] });
26301
+ const body = JSON.stringify({ device_id: this.deviceId, challenge: issued.challenge, sig: hex4(signature), capabilities: ["collection_mode_switch_v2"] });
25997
26302
  const minted = await this.json(`/v1/next/collections/${this.collection}/log-token`, bearer, body, options.signal);
25998
26303
  this.check(options.signal);
25999
26304
  if (typeof minted.token !== "string" || !minted.token || minted.token.length > 16 * 1024 || /[^\x21-\x7e]/.test(minted.token) || typeof minted.expires_at !== "number" || !Number.isSafeInteger(minted.expires_at) || minted.expires_at - this.now() <= 5e3 || minted.expires_at - this.now() > 16 * 6e4) throw fail4("response");
@@ -26045,7 +26350,7 @@ var AppCloudCopyBootstrapError = class extends Error {
26045
26350
  var fail5 = (r, retryable = false) => new AppCloudCopyBootstrapError(r, retryable);
26046
26351
  var transientHttp = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
26047
26352
  var equal5 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
26048
- var hex4 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
26353
+ var hex5 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
26049
26354
  function bytes4(v, max) {
26050
26355
  if (typeof v !== "string" || !v.length || v.length % 2 || v.length > max * 2 || !/^[0-9a-f]+$/.test(v))
26051
26356
  throw fail5("response");
@@ -26224,7 +26529,7 @@ var AppCpCloudCopyBootstrap = class {
26224
26529
  await crypto.subtle.digest("SHA-256", input)
26225
26530
  );
26226
26531
  this.check(signal);
26227
- return `sha256:${hex4(result2)}`;
26532
+ return `sha256:${hex5(result2)}`;
26228
26533
  }
26229
26534
  async json(path, bearer, body, signal) {
26230
26535
  this.check(signal);
@@ -26448,7 +26753,7 @@ var AppCpCloudCopyBootstrap = class {
26448
26753
  device_id: this.scope.deviceId,
26449
26754
  capabilities: ["collection_mode_switch_v2"],
26450
26755
  challenge: challenge.challenge,
26451
- sig: hex4(signature),
26756
+ sig: hex5(signature),
26452
26757
  ...create ? {
26453
26758
  collection_id: this.scope.collection,
26454
26759
  ...this.operation.displayName === void 0 ? {} : {
@@ -26703,107 +27008,6 @@ function nativeAuthorizationReply(value2) {
26703
27008
  return v;
26704
27009
  }
26705
27010
 
26706
- // src/app-host/log-token-cache.ts
26707
- var LOG_TOKEN_DATABASE = "mdbase.app.log-token.v1";
26708
- var STORE2 = "tokens";
26709
- var MIN_LEFT_MS = 6e4;
26710
- function open() {
26711
- return new Promise((resolve) => {
26712
- let request3;
26713
- try {
26714
- request3 = indexedDB.open(LOG_TOKEN_DATABASE, 1);
26715
- } catch {
26716
- resolve(null);
26717
- return;
26718
- }
26719
- request3.onupgradeneeded = () => {
26720
- try {
26721
- request3.result.createObjectStore(STORE2);
26722
- } catch {
26723
- }
26724
- };
26725
- request3.onsuccess = () => {
26726
- const db = request3.result;
26727
- db.onversionchange = () => db.close();
26728
- resolve(db.objectStoreNames.contains(STORE2) ? db : (db.close(), null));
26729
- };
26730
- request3.onerror = request3.onblocked = () => resolve(null);
26731
- });
26732
- }
26733
- function run(mode, work2) {
26734
- return open().then((db) => new Promise((resolve) => {
26735
- if (!db) {
26736
- resolve(null);
26737
- return;
26738
- }
26739
- let result2 = null;
26740
- try {
26741
- const tx = db.transaction(STORE2, mode), request3 = work2(tx.objectStore(STORE2));
26742
- if (request3) request3.onsuccess = () => {
26743
- result2 = request3.result ?? null;
26744
- };
26745
- tx.oncomplete = () => {
26746
- db.close();
26747
- resolve(result2);
26748
- };
26749
- tx.onerror = tx.onabort = () => {
26750
- db.close();
26751
- resolve(null);
26752
- };
26753
- } catch {
26754
- db.close();
26755
- resolve(null);
26756
- }
26757
- }));
26758
- }
26759
- function idbLogTokenCache() {
26760
- if (typeof indexedDB === "undefined") return null;
26761
- return Object.freeze({
26762
- async read(key3, now) {
26763
- const v = await run("readonly", (store2) => store2.get(key3)).catch(() => null);
26764
- if (!v || typeof v.value !== "string" || !v.value || v.value.length > 16 * 1024 || /[^\x21-\x7e]/.test(v.value) || typeof v.expires !== "number" || !Number.isSafeInteger(v.expires) || v.expires - now < MIN_LEFT_MS || v.expires - now > 16 * 6e4) return null;
26765
- return Object.freeze({ value: v.value, expires: v.expires });
26766
- },
26767
- async write(key3, token) {
26768
- await run("readwrite", (store2) => store2.put({ value: token.value, expires: token.expires }, key3)).catch(() => null);
26769
- },
26770
- async drop(key3) {
26771
- await run("readwrite", (store2) => store2.delete(key3)).catch(() => null);
26772
- }
26773
- });
26774
- }
26775
- async function eraseAppLogTokens(scope) {
26776
- const { cpOrigin, connectorId, deviceId } = scope;
26777
- if (!connectorId || !deviceId) return true;
26778
- const db = await open();
26779
- if (!db) return false;
26780
- return new Promise((resolve) => {
26781
- try {
26782
- const tx = db.transaction(STORE2, "readwrite"), cursor = tx.objectStore(STORE2).openCursor();
26783
- cursor.onsuccess = () => {
26784
- const row3 = cursor.result;
26785
- if (!row3) return;
26786
- if (typeof row3.key === "string") {
26787
- const parts = row3.key.split(" ");
26788
- if (parts.length === 5 && parts[0] === cpOrigin && parts[2] === connectorId && parts[3] === deviceId) row3.delete();
26789
- }
26790
- row3.continue();
26791
- };
26792
- tx.oncomplete = () => {
26793
- db.close();
26794
- resolve(true);
26795
- };
26796
- tx.onerror = tx.onabort = () => {
26797
- db.close();
26798
- resolve(false);
26799
- };
26800
- } catch {
26801
- db.close();
26802
- resolve(false);
26803
- }
26804
- });
26805
- }
26806
-
26807
27011
  // src/app-host/open-wait.ts
26808
27012
  function waitForOpenRetry(milliseconds, signal) {
26809
27013
  return new Promise((resolve, reject) => {
@@ -26841,7 +27045,7 @@ function wsOrigin(input, loopback) {
26841
27045
  if (loopback && loopbackHttpOrigin(input)) return `ws://${u.host}`;
26842
27046
  throw new Error("app log push: origin");
26843
27047
  }
26844
- var hex5 = (b) => [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
27048
+ var hex6 = (b) => [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
26845
27049
  var request = (id4, method, params2) => encode(/* @__PURE__ */ new Map([[0, 0], [1, id4], [2, method], [3, params2]]));
26846
27050
  function errorOf(m2) {
26847
27051
  const e = m2.get(3);
@@ -27015,7 +27219,7 @@ var AppLogPushChannel = class {
27015
27219
  this.token = token;
27016
27220
  let s;
27017
27221
  try {
27018
- s = new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${hex5(nonce)}`);
27222
+ s = new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${hex6(nonce)}`);
27019
27223
  } catch {
27020
27224
  this.schedule();
27021
27225
  return;
@@ -27791,7 +27995,7 @@ var bad3 = () => new Error(
27791
27995
  "app cloud copy outcome unavailable; preserve storage and reopen"
27792
27996
  );
27793
27997
  var same = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
27794
- var hex6 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
27998
+ var hex7 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
27795
27999
  var AppWebCloudCopyBootstrapPersistence = class {
27796
28000
  constructor(source, receipt3, key3, store2, options) {
27797
28001
  this.source = source;
@@ -27925,7 +28129,7 @@ var AppWebCloudCopyBootstrapPersistence = class {
27925
28129
  await crypto.subtle.digest("SHA-256", input)
27926
28130
  );
27927
28131
  this.check(signal);
27928
- if (metadata2.expectedGenesis !== `sha256:${hex6(digest2)}`) throw bad3();
28132
+ if (metadata2.expectedGenesis !== `sha256:${hex7(digest2)}`) throw bad3();
27929
28133
  }
27930
28134
  async read(signal) {
27931
28135
  let plain = null;
@@ -28315,7 +28519,7 @@ var AppPrivateBootstrapError = class extends Error {
28315
28519
  reason;
28316
28520
  };
28317
28521
  var fail7 = (r) => new AppPrivateBootstrapError(r);
28318
- var hex7 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
28522
+ var hex8 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
28319
28523
  var equal6 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
28320
28524
  function bytes6(value2, max) {
28321
28525
  if (typeof value2 !== "string" || !value2.length || value2.length > max * 2 || value2.length % 2 || !/^[0-9a-f]+$/.test(value2)) throw fail7("response");
@@ -28470,7 +28674,7 @@ var AppCpPrivateBootstrap = class {
28470
28674
  const enrol = this.scope.purpose === "enrol";
28471
28675
  signature = enrol ? this.runtime.signPrivateDeviceEnrol(nonce).signature : this.runtime.signPrivateCreate(nonce);
28472
28676
  this.check(options.signal);
28473
- const result2 = await this.json(enrol ? `/v1/next/collections/${this.scope.collection}/private/devices` : "/v1/next/collections/private", bearer, JSON.stringify({ device_id: this.scope.deviceId, capabilities: ["collection_mode_switch_v2"], challenge: issued.challenge, sig: hex7(signature), ...enrol ? { sas_commit: hex7(this.marker.sasCommitment) } : { collection_id: this.scope.collection, ...this.displayName === void 0 ? {} : { display_name: this.displayName } } }), options.signal);
28677
+ const result2 = await this.json(enrol ? `/v1/next/collections/${this.scope.collection}/private/devices` : "/v1/next/collections/private", bearer, JSON.stringify({ device_id: this.scope.deviceId, capabilities: ["collection_mode_switch_v2"], challenge: issued.challenge, sig: hex8(signature), ...enrol ? { sas_commit: hex8(this.marker.sasCommitment) } : { collection_id: this.scope.collection, ...this.displayName === void 0 ? {} : { display_name: this.displayName } } }), options.signal);
28474
28678
  this.check(options.signal);
28475
28679
  if (result2.collection_id !== this.scope.collection || this.origin(result2.log_url) !== this.origin(this.scope.logOrigin)) throw fail7("response");
28476
28680
  if (enrol) {
@@ -28487,7 +28691,7 @@ var AppCpPrivateBootstrap = class {
28487
28691
  message2.set(item, 1 + domain.length);
28488
28692
  const digest2 = new Uint8Array(await crypto.subtle.digest("SHA-256", message2));
28489
28693
  this.check(options.signal);
28490
- const metadata2 = this.copy({ collection: this.scope.collection, deviceId: this.scope.deviceId, logOrigin: this.scope.logOrigin, rootPublicKey: this.root, genesisItem: item, expectedGenesis: `sha256:${hex7(digest2)}`, approval: enrol ? "pending" : "creator", ...this.displayName === void 0 ? {} : { displayName: this.displayName } });
28694
+ const metadata2 = this.copy({ collection: this.scope.collection, deviceId: this.scope.deviceId, logOrigin: this.scope.logOrigin, rootPublicKey: this.root, genesisItem: item, expectedGenesis: `sha256:${hex8(digest2)}`, approval: enrol ? "pending" : "creator", ...this.displayName === void 0 ? {} : { displayName: this.displayName } });
28491
28695
  await this.persistence.completed(this.copy(metadata2), options);
28492
28696
  this.check(options.signal);
28493
28697
  if (this.marker) {
@@ -28515,7 +28719,7 @@ var MAX_PLAIN2 = 264 * 1024;
28515
28719
  var APP_PRIVATE_BOOTSTRAP_CIPHER_MAX = MAX_PLAIN2 + 256;
28516
28720
  var bad5 = () => new Error("app private bootstrap custody unavailable; preserve storage and reopen");
28517
28721
  var equal7 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
28518
- var hex8 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
28722
+ var hex9 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
28519
28723
  var AppWebPrivateBootstrapPersistence = class {
28520
28724
  constructor(source, receipt3, key3, store2, noise, options = {}) {
28521
28725
  this.source = source;
@@ -28615,7 +28819,7 @@ var AppWebPrivateBootstrapPersistence = class {
28615
28819
  bytes10.set(metadata2.genesisItem, 1 + domain.length);
28616
28820
  const hash2 = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes10));
28617
28821
  this.check(signal);
28618
- if (metadata2.expectedGenesis !== `sha256:${hex8(hash2)}`) throw bad5();
28822
+ if (metadata2.expectedGenesis !== `sha256:${hex9(hash2)}`) throw bad5();
28619
28823
  }
28620
28824
  async read(options) {
28621
28825
  let plain = null;
@@ -34712,7 +34916,7 @@ function pin2(source) {
34712
34916
  if (Object.values(scope).some((id4) => !uuid6.test(id4) || /^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(id4)) || !uuid6.test(source.generation)) throw fail9("binding");
34713
34917
  return { scope, generation: source.generation, binding: JSON.stringify([scope.account, scope.installation, scope.collection]) };
34714
34918
  }
34715
- function bounded(value2) {
34919
+ function bounded2(value2) {
34716
34920
  try {
34717
34921
  return new TextEncoder().encode(JSON.stringify(value2)).byteLength <= MAX3;
34718
34922
  } catch {
@@ -34739,7 +34943,7 @@ function attachAppCollectionControl(port, source, options) {
34739
34943
  const reply = (id4, kind, value2) => {
34740
34944
  current2();
34741
34945
  const packet = [1, original.binding, original.generation, id4, kind, value2];
34742
- if (!bounded(packet)) throw fail9("binding");
34946
+ if (!bounded2(packet)) throw fail9("binding");
34743
34947
  port.postMessage(packet);
34744
34948
  };
34745
34949
  const stop = () => {
@@ -34769,7 +34973,7 @@ function attachAppCollectionControl(port, source, options) {
34769
34973
  bad10();
34770
34974
  return;
34771
34975
  }
34772
- if (!Array.isArray(packet) || packet.length !== 6 || packet[0] !== 1 || packet[1] !== original.binding || packet[2] !== original.generation || !Number.isInteger(packet[3]) || packet[3] < 1 || packet[3] > 4294967295 || !actions.includes(packet[4]) || !bounded(packet)) throw fail9("binding");
34976
+ if (!Array.isArray(packet) || packet.length !== 6 || packet[0] !== 1 || packet[1] !== original.binding || packet[2] !== original.generation || !Number.isInteger(packet[3]) || packet[3] < 1 || packet[3] > 4294967295 || !actions.includes(packet[4]) || !bounded2(packet)) throw fail9("binding");
34773
34977
  const id4 = packet[3], action = packet[4], payload = packet[5];
34774
34978
  if (id4 <= lastId) throw fail9("binding");
34775
34979
  lastId = id4;
@@ -34837,7 +35041,7 @@ function attachAppCollectionControl(port, source, options) {
34837
35041
  checkAuthority();
34838
35042
  result2 = collectionPeopleDto(resource2, value2);
34839
35043
  checkAuthority();
34840
- if (!bounded([1, original.binding, original.generation, id4, "result", result2])) throw mdbaseError("unavailable", "invalid people response", "people_response");
35044
+ if (!bounded2([1, original.binding, original.generation, id4, "result", result2])) throw mdbaseError("unavailable", "invalid people response", "people_response");
34841
35045
  break;
34842
35046
  }
34843
35047
  // The owner starting a new recovery pass ends its turn: any tab may recover.
@@ -35938,7 +36142,7 @@ var SETTLE_MS = 45e3;
35938
36142
  var unavailable5 = (reason) => new AccountKeyError("unavailable", "The account key service refused or was unreachable.", { reason });
35939
36143
  var cancelled2 = () => new AccountKeyError("cancelled", "Account key request cancelled.");
35940
36144
  var unsupported = () => unavailable5("not_supported");
35941
- var hex9 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
36145
+ var hex10 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
35942
36146
  var HEX322 = /^[0-9a-f]{64}$/;
35943
36147
  var AppCpAccountKeyControl = class {
35944
36148
  constructor(session, sign, options = {}) {
@@ -36060,7 +36264,7 @@ var AppCpAccountKeyControl = class {
36060
36264
  throw unavailable5("proof");
36061
36265
  }
36062
36266
  if (!(signature instanceof Uint8Array) || signature.length !== 64) throw unavailable5("proof");
36063
- return await this.request("GET", "/v1/next/account-key", { "x-mdbase-device-id": this.deviceId, "x-mdbase-challenge": text6, "x-mdbase-signature": hex9(signature) }, options);
36267
+ return await this.request("GET", "/v1/next/account-key", { "x-mdbase-device-id": this.deviceId, "x-mdbase-challenge": text6, "x-mdbase-signature": hex10(signature) }, options);
36064
36268
  } finally {
36065
36269
  nonce?.fill(0);
36066
36270
  signature?.fill(0);
@@ -36929,123 +37133,6 @@ var AppIndexedDbNoiseProtectedStore = class _AppIndexedDbNoiseProtectedStore {
36929
37133
  }
36930
37134
  };
36931
37135
 
36932
- // src/app-host/sign-out-erase.ts
36933
- var SIGN_OUT_ERASE_TIMEOUT_MS = 5e3;
36934
- var hex10 = (id4) => Array.from(uuidToBytes(id4), (b) => b.toString(16).padStart(2, "0")).join("");
36935
- var lower = (id4) => {
36936
- uuidToBytes(id4);
36937
- return id4.toLowerCase();
36938
- };
36939
- function bounded2(work2, fallback, ms = SIGN_OUT_ERASE_TIMEOUT_MS) {
36940
- let timer;
36941
- return Promise.race([work2.catch(() => fallback), new Promise((resolve) => {
36942
- timer = setTimeout(() => resolve(fallback), ms);
36943
- })]).finally(() => clearTimeout(timer));
36944
- }
36945
- function deleteDatabase(name2) {
36946
- return bounded2(new Promise((resolve) => {
36947
- const request3 = indexedDB.deleteDatabase(name2);
36948
- request3.onsuccess = () => resolve(true);
36949
- request3.onerror = () => resolve(false);
36950
- }), false);
36951
- }
36952
- function deviceCustodyDatabaseNames(scope) {
36953
- const { accountId, connectorId, deviceId, installationId } = scope;
36954
- const keyIds = [accountId, connectorId, deviceId, installationId].map(hex10).join(".");
36955
- return [
36956
- `mdbase.app.device-key-kek.v1.${keyIds}`,
36957
- `mdbase.app.device-keys.v1.${keyIds}`,
36958
- `mdbase.app.noise.v1.${lower(installationId)}.${lower(connectorId)}.${lower(deviceId)}`
36959
- ];
36960
- }
36961
- async function eraseUnattestedDeviceCustody(scope) {
36962
- try {
36963
- if (!globalThis.indexedDB) return false;
36964
- return (await Promise.all(deviceCustodyDatabaseNames(scope).map(deleteDatabase))).every(Boolean);
36965
- } catch {
36966
- return false;
36967
- }
36968
- }
36969
- function ledgerNames(scope) {
36970
- const cp = encodeURIComponent(scope.cpOrigin), unlabelled = `mdbase.app.installation.v1.${cp}.${scope.appId}`;
36971
- return [scope.owner === void 0 ? unlabelled : `mdbase.app.installation.v2.${cp}.${encodeURIComponent(scope.owner)}.${scope.appId}`, unlabelled];
36972
- }
36973
- async function otherDatabaseNames(scope, ledger, unlabelled) {
36974
- const others = new Set(scope.isolated ? [] : scope.databases);
36975
- if (!scope.isolated && scope.storageNamespace === void 0) others.add(unlabelled);
36976
- const { accountId: account, connectorId: connector, deviceId: device, installationId: installation } = scope;
36977
- if (account && connector && device && installation) {
36978
- for (const name2 of deviceCustodyDatabaseNames({ accountId: account, connectorId: connector, deviceId: device, installationId: installation })) others.add(name2);
36979
- const prefix = [account, connector, device, installation].map(lower).join(".");
36980
- const scoped = [`mdbase.app.cloud-copy-outcome.v1.${prefix}.`, `mdbase.app.private-bootstrap.v1.${prefix}.`];
36981
- for (const collection of scope.collectionIds) {
36982
- const id4 = lower(collection);
36983
- for (const purpose of ["create", "join"]) others.add(`${scoped[0]}${id4}.${purpose}`);
36984
- for (const purpose of ["create", "enrol"]) others.add(`${scoped[1]}${id4}.${purpose}`);
36985
- }
36986
- const list4 = indexedDB.databases;
36987
- if (typeof list4 === "function") {
36988
- const found = await bounded2(list4.call(indexedDB), []);
36989
- for (const { name: name2 } of found) if (name2 && scoped.some((p) => name2.startsWith(p))) others.add(name2);
36990
- }
36991
- }
36992
- others.delete(ledger);
36993
- return [...others];
36994
- }
36995
- async function removeReplicas(account, installation) {
36996
- const storage = globalThis.navigator?.storage;
36997
- if (typeof storage?.getDirectory !== "function") return true;
36998
- return bounded2((async () => {
36999
- const root = await storage.getDirectory();
37000
- const prefix = `.mdbase-app-${lower(account)}-${lower(installation)}-`, names = [];
37001
- for await (const name2 of root.keys()) if (name2.startsWith(prefix)) names.push(name2);
37002
- let ok = true;
37003
- for (const name2 of names) {
37004
- try {
37005
- await root.removeEntry(name2, { recursive: true });
37006
- } catch {
37007
- ok = false;
37008
- }
37009
- }
37010
- return ok;
37011
- })(), false);
37012
- }
37013
- async function eraseAppCollectionAccess(scope, collectionId) {
37014
- try {
37015
- if (!globalThis.indexedDB || !scope.accountId || !scope.connectorId || !scope.deviceId || !scope.installationId) return false;
37016
- const collection = lower(collectionId), prefix = [scope.accountId, scope.connectorId, scope.deviceId, scope.installationId].map(lower).join(".");
37017
- const names = ["create", "join"].map((purpose) => `mdbase.app.cloud-copy-outcome.v1.${prefix}.${collection}.${purpose}`);
37018
- names.push(...["create", "enrol"].map((purpose) => `mdbase.app.private-bootstrap.v1.${prefix}.${collection}.${purpose}`));
37019
- const results2 = await Promise.all(names.map(deleteDatabase));
37020
- const storage = globalThis.navigator?.storage;
37021
- if (typeof storage?.getDirectory === "function") {
37022
- const root = await storage.getDirectory();
37023
- try {
37024
- await root.removeEntry(`.mdbase-app-${lower(scope.accountId)}-${lower(scope.installationId)}-${collection}`, { recursive: true });
37025
- } catch (error4) {
37026
- if (!(error4 instanceof DOMException && error4.name === "NotFoundError")) return false;
37027
- }
37028
- }
37029
- return results2.every(Boolean);
37030
- } catch {
37031
- return false;
37032
- }
37033
- }
37034
- async function eraseAppInstallationData(scope) {
37035
- if (!globalThis.indexedDB) return Object.freeze({ ledger: false, complete: false });
37036
- const [current2, unlabelled] = ledgerNames(scope);
37037
- const ledger = await deleteDatabase(current2);
37038
- let others = null;
37039
- try {
37040
- others = await otherDatabaseNames(scope, current2, unlabelled);
37041
- } catch {
37042
- }
37043
- const results2 = others ? await Promise.all([...others, ...scope.isolated || scope.storageNamespace !== void 0 ? [] : [LOG_TOKEN_DATABASE]].map(deleteDatabase)) : [false];
37044
- const tokens2 = scope.storageNamespace === void 0 ? true : await bounded2(eraseAppLogTokens(scope), false);
37045
- const replicas = scope.accountId && scope.installationId ? await removeReplicas(scope.accountId, scope.installationId).catch(() => false) : true;
37046
- return Object.freeze({ ledger, complete: ledger && tokens2 && replicas && results2.every(Boolean) });
37047
- }
37048
-
37049
37136
  // src/app-host/noise-custody.ts
37050
37137
  var bad9 = () => new Error("app Noise custody unavailable; preserve storage and reopen");
37051
37138
  var equal9 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
@@ -38890,9 +38977,14 @@ var failure = (reason) => new AppInstallationSignInError(reason);
38890
38977
  var keptDetail = (update, previous, detail) => update.problem === void 0 || update.problem === previous ? detail : void 0;
38891
38978
  var liveOutcomes = /* @__PURE__ */ new Set(["collection_not_yet_migrated", "collection_migrating", "account_suspended", "update_required"]);
38892
38979
  var authorizeAppWebInstallation;
38980
+ var webSignInRecovery;
38893
38981
  var AppWebSignInSession = class {
38894
38982
  static {
38895
- authorizeAppWebInstallation = (session, options, recoverScope) => session.authorizeInstallation(options, recoverScope);
38983
+ authorizeAppWebInstallation = (session, options, recoverScope, scoped) => session.authorizeInstallation(options, recoverScope, scoped);
38984
+ webSignInRecovery = {
38985
+ references: (session) => session.flow ? installationRecovery.references(session.flow) : [],
38986
+ paired: (session, accountId) => session.scopedInstallationPaired(accountId)
38987
+ };
38896
38988
  }
38897
38989
  lifetime = new AbortController();
38898
38990
  // Origin store closes only AFTER native shutdown, not on the host abort.
@@ -39125,7 +39217,10 @@ var AppWebSignInSession = class {
39125
39217
  });
39126
39218
  this.check();
39127
39219
  const view = this.flow.view();
39128
- if (view.state === "paired") {
39220
+ if (installationRecovery.replacementPending(this.flow)) {
39221
+ for (const id4 of view.collectionIds) this.removedScopes.add(id4);
39222
+ this.publish({ status: "blocked", problem: "installation_removed", collections: Object.freeze([]) });
39223
+ } else if (view.state === "paired") {
39129
39224
  await this.openDevice(false, this.options.recoveryFor !== void 0);
39130
39225
  await this.abandonUnfinishedNativeChoice();
39131
39226
  if (this.flow.collectionConsentView()?.state === "pending") {
@@ -39152,13 +39247,13 @@ var AppWebSignInSession = class {
39152
39247
  authorize(options = {}) {
39153
39248
  return this.authorizeInstallation(options, false);
39154
39249
  }
39155
- authorizeInstallation(options, recoverScope) {
39250
+ authorizeInstallation(options, recoverScope, scoped) {
39156
39251
  this.check();
39157
39252
  if (this.authorizationRateLimit && Date.now() < this.authorizationRetryAt) return Promise.reject(this.authorizationRateLimit);
39158
39253
  const poll = this.pending !== null && this.pending === this.polling ? this.pending : null;
39159
39254
  if (!this.flow || this.pending && !poll) return Promise.reject(failure("busy"));
39160
39255
  const portal = this.options.openPortal();
39161
- if (!poll) return this.beginAuthorization(portal, options, recoverScope);
39256
+ if (!poll) return this.beginAuthorization(portal, options, recoverScope, scoped);
39162
39257
  return poll.catch(() => {
39163
39258
  }).then(() => {
39164
39259
  try {
@@ -39176,17 +39271,17 @@ var AppWebSignInSession = class {
39176
39271
  portal.close();
39177
39272
  return this.getSnapshot();
39178
39273
  }
39179
- return this.beginAuthorization(portal, options, recoverScope);
39274
+ return this.beginAuthorization(portal, options, recoverScope, scoped);
39180
39275
  });
39181
39276
  }
39182
- beginAuthorization(portal, options, recoverScope) {
39277
+ beginAuthorization(portal, options, recoverScope, scoped) {
39183
39278
  const hint = { collectionHint: options.collectionHint ?? null };
39184
39279
  this.restoredPending = false;
39185
39280
  this.authorizationStartedAt = performance.now();
39186
39281
  this.publish({ timing: Object.freeze({ firstScreenMs: null, readyMs: null }), approval: null });
39187
39282
  return this.operation(async () => {
39188
39283
  try {
39189
- if (this.base.problem === "installation_removed") await this.replaceRemovedInstallation();
39284
+ if (this.base.problem === "installation_removed" || installationRecovery.replacementPending(this.flow)) await this.replaceRemovedInstallation(scoped);
39190
39285
  let verificationUri2 = null;
39191
39286
  if (this.flow.view().state === "paired") {
39192
39287
  await this.openDevice();
@@ -39202,7 +39297,7 @@ var AppWebSignInSession = class {
39202
39297
  portal.close();
39203
39298
  return this.getSnapshot();
39204
39299
  }
39205
- await this.replaceRemovedInstallation();
39300
+ await this.replaceRemovedInstallation(scoped);
39206
39301
  }
39207
39302
  }
39208
39303
  if (verificationUri2 === null) {
@@ -39650,22 +39745,23 @@ var AppWebSignInSession = class {
39650
39745
  this.changed();
39651
39746
  return true;
39652
39747
  }
39653
- async replaceRemovedInstallation() {
39748
+ async replaceRemovedInstallation(scoped) {
39654
39749
  const flow = this.flow;
39655
39750
  try {
39656
39751
  await replaceRefusedAppInstallation(flow, async () => {
39752
+ await scoped?.stopChildren();
39657
39753
  await this.closeSlots();
39658
39754
  this.check();
39659
- await this.installationLease?.release();
39660
- this.installationLease = null;
39661
- this.installation = null;
39662
- this.check();
39663
- });
39755
+ }, scoped?.childPaired);
39664
39756
  } catch (error4) {
39665
39757
  if (!flow.isCurrent()) this.flow = null;
39666
39758
  throw error4;
39667
39759
  }
39668
39760
  this.check();
39761
+ await this.installationLease?.release();
39762
+ this.installationLease = null;
39763
+ this.installation = null;
39764
+ this.check();
39669
39765
  this.attested = false;
39670
39766
  this.acknowledged = false;
39671
39767
  this.freshApproval = false;
@@ -40154,10 +40250,16 @@ var AppWebSignInSession = class {
40154
40250
  /** SDK composition metadata only. Protected references never loan the
40155
40251
  * original credential/keys or carry consent into a fresh installation. */
40156
40252
  scopeRecoveryContext() {
40157
- if (!this.flow || !this.installation || this.flow.view().state !== "paired") return null;
40253
+ if (!this.flow || !this.installation || installationRecovery.replacementPending(this.flow)) return null;
40158
40254
  const view = this.flow.view();
40255
+ if (view.state !== "paired") return null;
40159
40256
  return Object.freeze({ accountId: this.installation.scope.account, accountLabel: view.accountEmail ?? (view.accountLogin ? `@${view.accountLogin}` : null), references: this.flow.collectionRecoveries() });
40160
40257
  }
40258
+ scopedInstallationPaired(accountId) {
40259
+ if (this.pending || !this.flow || installationRecovery.replacementPending(this.flow)) return false;
40260
+ const view = this.flow.view();
40261
+ return view.state === "paired" && view.accountId === accountId;
40262
+ }
40161
40263
  /** Explicit recovery gesture, after terminal access removal. Stop/fence and
40162
40264
  * erase ONLY the old collection scope before allocating its fresh local slot.
40163
40265
  * A failed stop/erase refuses recovery rather than releasing old authority. */
@@ -40166,7 +40268,13 @@ var AppWebSignInSession = class {
40166
40268
  if (this.pending) return this.pending.catch(() => {
40167
40269
  }).then(() => this.prepareScopedRecovery(collectionId, expectedReplacement));
40168
40270
  return this.operation(async () => {
40169
- if (!this.flow || !this.installation || this.consentPending || this.flow.view().state !== "paired" || !this.flow.view().collectionIds.includes(collectionId)) throw failure("binding");
40271
+ if (!this.flow || !this.installation || this.consentPending || this.flow.view().state !== "paired" || installationRecovery.replacementPending(this.flow)) throw failure("binding");
40272
+ if (expectedReplacement !== void 0) {
40273
+ const reference2 = await installationRecovery.replaceRetained(this.flow, this.installation, collectionId, expectedReplacement);
40274
+ this.check();
40275
+ if (reference2 !== null) return Object.freeze({ accountId: this.installation.scope.account, reference: reference2 });
40276
+ }
40277
+ if (!this.flow.view().collectionIds.includes(collectionId)) throw failure("binding");
40170
40278
  const refs = this.flow.collectionRecoveries(), slot = this.slots.get(collectionId);
40171
40279
  if (expectedReplacement === void 0 && !Object.hasOwn(refs, collectionId) && !this.scopeWasRemoved(collectionId)) throw failure("binding");
40172
40280
  if (slot) {
@@ -40396,6 +40504,7 @@ var AppScopedSignInSession = class {
40396
40504
  unsubscribe;
40397
40505
  focus = null;
40398
40506
  approvalOwner = null;
40507
+ changingIdentity = false;
40399
40508
  foreground = true;
40400
40509
  quarantined = /* @__PURE__ */ new Set();
40401
40510
  closing = null;
@@ -40415,6 +40524,16 @@ var AppScopedSignInSession = class {
40415
40524
  check() {
40416
40525
  if (this.closing || this.options.signal.aborted) throw new AppInstallationSignInError("fenced");
40417
40526
  }
40527
+ async changeIdentity(work2) {
40528
+ this.check();
40529
+ if (this.changingIdentity) throw new AppInstallationSignInError("busy");
40530
+ this.changingIdentity = true;
40531
+ try {
40532
+ return await work2();
40533
+ } finally {
40534
+ this.changingIdentity = false;
40535
+ }
40536
+ }
40418
40537
  changed() {
40419
40538
  if (!this.closing) for (const listener of [...this.listeners]) try {
40420
40539
  listener();
@@ -40430,10 +40549,22 @@ var AppScopedSignInSession = class {
40430
40549
  removed(session, id4) {
40431
40550
  return session.scopeWasRemoved(id4);
40432
40551
  }
40552
+ actor(id4) {
40553
+ const reference = this.original.scopeRecoveryContext()?.references[id4];
40554
+ return reference ? this.scoped.get(reference) : void 0;
40555
+ }
40556
+ activeChildren() {
40557
+ return Object.values(this.original.scopeRecoveryContext()?.references ?? {}).flatMap((reference) => {
40558
+ const actor = reference ? this.scoped.get(reference) : void 0;
40559
+ return actor ? [actor] : [];
40560
+ });
40561
+ }
40433
40562
  collections() {
40434
40563
  const context = this.original.scopeRecoveryContext();
40435
40564
  const rows2 = this.original.getSnapshot().collections.filter((c) => !Object.hasOwn(context?.references ?? {}, c.collectionId) && !this.removed(this.original, c.collectionId));
40436
- for (const [id4, actor] of this.scoped) if (!this.removed(actor.session, id4)) rows2.push(...actor.session.getSnapshot().collections.filter((c) => c.collectionId === id4));
40565
+ for (const { collectionId, session } of this.activeChildren()) {
40566
+ if (!this.removed(session, collectionId)) rows2.push(...session.getSnapshot().collections.filter((c) => c.collectionId === collectionId));
40567
+ }
40437
40568
  return Object.freeze(rows2);
40438
40569
  }
40439
40570
  getSnapshot() {
@@ -40443,39 +40574,36 @@ var AppScopedSignInSession = class {
40443
40574
  return this.compose(id4, options);
40444
40575
  }
40445
40576
  compose(id4, options = {}) {
40446
- const actor = id4 === null ? void 0 : this.scoped.get(id4);
40577
+ const actor = id4 === null ? void 0 : this.actor(id4);
40447
40578
  const session = actor?.session ?? this.original;
40448
40579
  let view = session.viewFor(id4, options);
40449
40580
  if (!options.bystander && this.approvalOwner?.getSnapshot().status === "authorizing") view = this.approvalOwner.viewFor(id4);
40450
40581
  if (actor && view.status === "signed_out") view = { ...this.original.viewFor(null), selectedCollectionId: null, status: "unselected", problem: null, approval: view.approval };
40451
40582
  const candidates = /* @__PURE__ */ new Set([...this.original.removedScopeIds(), ...Object.keys(this.original.scopeRecoveryContext()?.references ?? {})]);
40452
40583
  const removedScopeIds = Object.freeze([...candidates].filter((cid) => {
40453
- const scoped = this.scoped.get(cid)?.session;
40584
+ const scoped = this.actor(cid)?.session;
40454
40585
  return !scoped || this.removed(scoped, cid) || scoped.getSnapshot().status === "signed_out";
40455
40586
  }));
40456
40587
  const accountLabel = actor && view.problem === "recovery_account_mismatch" ? this.original.scopeRecoveryContext()?.accountLabel : null;
40457
40588
  const nativeGrants = new Map((this.original.getSnapshot().signIn?.nativeGrants ?? []).map((c) => [c.collection_id, c]));
40458
40589
  const account = this.original.getSnapshot().signIn?.accountId;
40459
- for (const child of this.scoped.values()) for (const c of child.session.getSnapshot().signIn?.nativeGrants ?? []) if (c.account_id === account) nativeGrants.set(c.collection_id, c);
40590
+ for (const child of this.activeChildren()) for (const c of child.session.getSnapshot().signIn?.nativeGrants ?? []) if (c.account_id === account) nativeGrants.set(c.collection_id, c);
40460
40591
  const signIn = view.signIn ? Object.freeze({ ...view.signIn, nativeGrants: Object.freeze([...nativeGrants.values()]) }) : null;
40461
40592
  return Object.freeze({ ...view, signIn, collections: this.collections(), removedScopeIds, ...accountLabel ? { recoveryAccountLabel: accountLabel } : {} });
40462
40593
  }
40463
40594
  connection(id4 = this.focus) {
40464
40595
  if (id4 === null || this.closing) return null;
40465
- const actor = this.scoped.get(id4);
40596
+ const actor = this.actor(id4);
40466
40597
  if (actor) return actor.session.connection(id4);
40467
40598
  if (Object.hasOwn(this.original.scopeRecoveryContext()?.references ?? {}, id4)) return null;
40468
40599
  return this.original.connection(id4);
40469
40600
  }
40470
40601
  heldCollections() {
40471
- return [.../* @__PURE__ */ new Set([...this.original.heldCollections(), ...[...this.scoped.values()].flatMap((actor) => actor.session.heldCollections())])];
40602
+ return [.../* @__PURE__ */ new Set([...this.original.heldCollections(), ...this.activeChildren().flatMap((actor) => actor.session.heldCollections())])];
40472
40603
  }
40473
40604
  child(id4, reference, accountId, fresh = false) {
40474
- const existing = this.scoped.get(id4);
40475
- if (existing) {
40476
- if (existing.reference !== reference) throw new AppInstallationSignInError("fenced");
40477
- return existing.session;
40478
- }
40605
+ const existing = this.scoped.get(reference);
40606
+ if (existing) return existing.session;
40479
40607
  const device = this.options.freshRequestedPrivateDevice === true && this.original.getSnapshot().signIn?.privateDeviceCollectionIds?.includes(id4) === true;
40480
40608
  const session = new AppWebSignInSession({
40481
40609
  ...this.options,
@@ -40488,7 +40616,7 @@ var AppScopedSignInSession = class {
40488
40616
  storeMode: fresh ? "fresh" : "existing"
40489
40617
  });
40490
40618
  const stop = session.subscribe(() => this.changed());
40491
- this.scoped.set(id4, { reference, session, stop });
40619
+ this.scoped.set(reference, { collectionId: id4, session, stop });
40492
40620
  session.setForeground(this.foreground);
40493
40621
  return session;
40494
40622
  }
@@ -40496,48 +40624,59 @@ var AppScopedSignInSession = class {
40496
40624
  this.check();
40497
40625
  await this.original.start();
40498
40626
  this.check();
40499
- const context = this.original.scopeRecoveryContext();
40500
- if (context) {
40501
- for (const [id4, reference] of Object.entries(context.references)) if (reference !== null) {
40502
- const session = this.child(id4, reference, context.accountId);
40503
- try {
40504
- await session.start();
40505
- } catch {
40506
- }
40507
- this.check();
40508
- }
40509
- }
40627
+ await this.restoreChildren();
40510
40628
  this.changed();
40511
40629
  return this.getSnapshot();
40512
40630
  }
40513
- async authorize(options = {}) {
40514
- this.check();
40631
+ async restoreChildren(missingOnly = false) {
40632
+ for (const { collectionId, reference, accountId } of webSignInRecovery.references(this.original)) {
40633
+ if (missingOnly && this.scoped.has(reference)) continue;
40634
+ const session = this.child(collectionId, reference, accountId);
40635
+ try {
40636
+ await session.start();
40637
+ } catch {
40638
+ }
40639
+ this.check();
40640
+ }
40641
+ }
40642
+ authorize(options = {}) {
40643
+ return this.changeIdentity(() => this.authorizeCollection(options));
40644
+ }
40645
+ async authorizeCollection(options) {
40515
40646
  const id4 = options.collectionHint ?? null;
40516
40647
  if (this.approvalOwner?.getSnapshot().status === "authorizing") throw new AppInstallationSignInError("busy");
40517
- const context = this.original.scopeRecoveryContext(), actor = id4 === null ? void 0 : this.scoped.get(id4);
40648
+ const context = this.original.scopeRecoveryContext(), actor = id4 === null ? void 0 : this.actor(id4);
40518
40649
  if (id4 === null || !context || !Object.hasOwn(context.references, id4) && !this.removed(this.original, id4)) {
40519
40650
  this.approvalOwner = this.original;
40520
40651
  const recoverScope = id4 !== null && (!this.original.collectionListCached() && this.original.connection(id4) !== null || Object.values(context?.references ?? {}).some((reference2) => reference2 !== null));
40521
- await authorizeAppWebInstallation(this.original, options, recoverScope);
40652
+ await authorizeAppWebInstallation(this.original, options, recoverScope, {
40653
+ childPaired: ({ reference: reference2, accountId }) => {
40654
+ const actor2 = this.scoped.get(reference2);
40655
+ return !!actor2 && !this.quarantined.has(reference2) && webSignInRecovery.paired(actor2.session, accountId);
40656
+ },
40657
+ stopChildren: async () => {
40658
+ for (const { collectionId, session: session2 } of this.scoped.values()) await session2.releaseCollection(collectionId);
40659
+ }
40660
+ });
40522
40661
  this.check();
40523
40662
  return this.getSnapshot();
40524
40663
  }
40525
40664
  this.focus = id4;
40526
- if (this.quarantined.has(id4)) throw new AppInstallationSignInError("recovery_required");
40527
40665
  let reference = context.references[id4], freshSlot = false;
40528
- if (actor && (this.removed(actor.session, id4) || actor.session.canAbandonWrongAccount())) {
40666
+ if (reference && this.quarantined.has(reference)) throw new AppInstallationSignInError("recovery_required");
40667
+ if (reference && actor && (this.removed(actor.session, id4) || actor.session.canAbandonWrongAccount())) {
40529
40668
  try {
40530
40669
  const result2 = await actor.session.signOut();
40531
40670
  if (result2.signOutResult?.local !== "erased") throw new AppInstallationSignInError("recovery_required");
40532
40671
  await actor.session.close();
40533
40672
  actor.stop();
40534
- this.scoped.delete(id4);
40673
+ this.scoped.delete(reference);
40535
40674
  this.check();
40536
40675
  } catch (error4) {
40537
- this.quarantined.add(id4);
40676
+ this.quarantined.add(reference);
40538
40677
  throw error4;
40539
40678
  }
40540
- const fresh = await this.original.prepareScopedRecovery(id4, actor.reference);
40679
+ const fresh = await this.original.prepareScopedRecovery(id4, reference);
40541
40680
  this.check();
40542
40681
  reference = fresh.reference;
40543
40682
  freshSlot = true;
@@ -40559,7 +40698,7 @@ var AppScopedSignInSession = class {
40559
40698
  async openCollection(id4) {
40560
40699
  this.check();
40561
40700
  this.focus = id4;
40562
- const actor = this.scoped.get(id4);
40701
+ const actor = this.actor(id4);
40563
40702
  if (!actor && Object.hasOwn(this.original.scopeRecoveryContext()?.references ?? {}, id4)) throw new AppInstallationSignInError("refused");
40564
40703
  await (actor?.session ?? this.original).openCollection(id4);
40565
40704
  this.check();
@@ -40569,38 +40708,38 @@ var AppScopedSignInSession = class {
40569
40708
  * The secret goes to that collection's own session only. */
40570
40709
  async unlockCollection(id4, secret) {
40571
40710
  this.check();
40572
- await (this.scoped.get(id4)?.session ?? this.original).unlockCollection(id4, secret);
40711
+ await (this.actor(id4)?.session ?? this.original).unlockCollection(id4, secret);
40573
40712
  this.check();
40574
40713
  return this.viewFor(id4);
40575
40714
  }
40576
40715
  async releaseCollection(id4) {
40577
- await (this.scoped.get(id4)?.session ?? this.original).releaseCollection(id4);
40716
+ await (this.actor(id4)?.session ?? this.original).releaseCollection(id4);
40578
40717
  return this.getSnapshot();
40579
40718
  }
40580
40719
  async forget(id4) {
40581
- await (this.scoped.get(id4)?.session ?? this.original).forget(id4);
40720
+ await (this.actor(id4)?.session ?? this.original).forget(id4);
40582
40721
  return this.getSnapshot();
40583
40722
  }
40584
40723
  async deleteCollection(id4, name2) {
40585
- await (this.scoped.get(id4)?.session ?? this.original).deleteCollection(id4, name2);
40724
+ await (this.actor(id4)?.session ?? this.original).deleteCollection(id4, name2);
40586
40725
  return this.getSnapshot();
40587
40726
  }
40588
40727
  async requestFileAccess(id4, actions2, reason) {
40589
- await (this.scoped.get(id4)?.session ?? this.original).requestFileAccess(id4, actions2, reason);
40728
+ await (this.actor(id4)?.session ?? this.original).requestFileAccess(id4, actions2, reason);
40590
40729
  return this.getSnapshot();
40591
40730
  }
40592
40731
  async pollFileAccess(requestId) {
40593
- const session = [...this.scoped.values()].find((actor) => actor.session.getSnapshot().fileAccess?.requestId === requestId)?.session ?? this.original;
40732
+ const session = this.activeChildren().find((actor) => actor.session.getSnapshot().fileAccess?.requestId === requestId)?.session ?? this.original;
40594
40733
  await session.pollFileAccess(requestId);
40595
40734
  return this.getSnapshot();
40596
40735
  }
40597
40736
  /** Any of the sessions still shows the list it kept (a signed-in start). */
40598
40737
  collectionListCached() {
40599
- return this.original.collectionListCached() || [...this.scoped.values()].some((actor) => actor.session.collectionListCached());
40738
+ return this.original.collectionListCached() || this.activeChildren().some((actor) => actor.session.collectionListCached());
40600
40739
  }
40601
40740
  async refreshCollectionList() {
40602
40741
  await this.original.refreshCollectionList();
40603
- for (const actor of this.scoped.values()) {
40742
+ for (const actor of this.activeChildren()) {
40604
40743
  this.check();
40605
40744
  await actor.session.refreshCollectionList();
40606
40745
  }
@@ -40630,24 +40769,26 @@ var AppScopedSignInSession = class {
40630
40769
  await (this.approvalOwner ?? this.original).renewExpiredPairing();
40631
40770
  return this.getSnapshot();
40632
40771
  }
40633
- async signOut() {
40634
- this.check();
40635
- for (const [id4, actor] of this.scoped) {
40636
- const result2 = await actor.session.signOut();
40637
- if (result2.signOutResult?.local !== "erased") {
40638
- this.quarantined.add(id4);
40639
- throw new AppInstallationSignInError("recovery_required");
40772
+ signOut() {
40773
+ return this.changeIdentity(async () => {
40774
+ await this.restoreChildren(true);
40775
+ for (const [reference, actor] of this.scoped) {
40776
+ const result2 = await actor.session.signOut();
40777
+ if (result2.signOutResult?.local !== "erased") {
40778
+ this.quarantined.add(reference);
40779
+ throw new AppInstallationSignInError("recovery_required");
40780
+ }
40781
+ await actor.session.close();
40782
+ actor.stop();
40783
+ this.scoped.delete(reference);
40640
40784
  }
40641
- await actor.session.close();
40642
- actor.stop();
40643
- this.scoped.delete(id4);
40644
- }
40645
- await this.original.signOut();
40646
- this.focus = null;
40647
- this.approvalOwner = null;
40648
- this.quarantined.clear();
40649
- this.changed();
40650
- return this.getSnapshot();
40785
+ await this.original.signOut();
40786
+ this.focus = null;
40787
+ this.approvalOwner = null;
40788
+ this.quarantined.clear();
40789
+ this.changed();
40790
+ return this.getSnapshot();
40791
+ });
40651
40792
  }
40652
40793
  close() {
40653
40794
  if (this.closing) return this.closing;