@mdbase-dev/sdk 0.2.98 → 0.2.99

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.
@@ -27198,6 +27198,243 @@ ${end.comment}` : end.comment;
27198
27198
  }
27199
27199
  });
27200
27200
 
27201
+ // src/app-host/log-token-cache.ts
27202
+ function open() {
27203
+ return new Promise((resolve2) => {
27204
+ let request3;
27205
+ try {
27206
+ request3 = indexedDB.open(LOG_TOKEN_DATABASE, 1);
27207
+ } catch {
27208
+ resolve2(null);
27209
+ return;
27210
+ }
27211
+ request3.onupgradeneeded = () => {
27212
+ try {
27213
+ request3.result.createObjectStore(STORE2);
27214
+ } catch {
27215
+ }
27216
+ };
27217
+ request3.onsuccess = () => {
27218
+ const db = request3.result;
27219
+ db.onversionchange = () => db.close();
27220
+ resolve2(db.objectStoreNames.contains(STORE2) ? db : (db.close(), null));
27221
+ };
27222
+ request3.onerror = request3.onblocked = () => resolve2(null);
27223
+ });
27224
+ }
27225
+ function run(mode, work) {
27226
+ return open().then((db) => new Promise((resolve2) => {
27227
+ if (!db) {
27228
+ resolve2(null);
27229
+ return;
27230
+ }
27231
+ let result2 = null;
27232
+ try {
27233
+ const tx = db.transaction(STORE2, mode), request3 = work(tx.objectStore(STORE2));
27234
+ if (request3) request3.onsuccess = () => {
27235
+ result2 = request3.result ?? null;
27236
+ };
27237
+ tx.oncomplete = () => {
27238
+ db.close();
27239
+ resolve2(result2);
27240
+ };
27241
+ tx.onerror = tx.onabort = () => {
27242
+ db.close();
27243
+ resolve2(null);
27244
+ };
27245
+ } catch {
27246
+ db.close();
27247
+ resolve2(null);
27248
+ }
27249
+ }));
27250
+ }
27251
+ function idbLogTokenCache() {
27252
+ if (typeof indexedDB === "undefined") return null;
27253
+ return Object.freeze({
27254
+ async read(key3, now) {
27255
+ const v = await run("readonly", (store2) => store2.get(key3)).catch(() => null);
27256
+ 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;
27257
+ return Object.freeze({ value: v.value, expires: v.expires });
27258
+ },
27259
+ async write(key3, token) {
27260
+ await run("readwrite", (store2) => store2.put({ value: token.value, expires: token.expires }, key3)).catch(() => null);
27261
+ },
27262
+ async drop(key3) {
27263
+ await run("readwrite", (store2) => store2.delete(key3)).catch(() => null);
27264
+ }
27265
+ });
27266
+ }
27267
+ async function eraseAppLogTokens(scope) {
27268
+ const { cpOrigin, connectorId, deviceId } = scope;
27269
+ if (!connectorId || !deviceId) return true;
27270
+ const db = await open();
27271
+ if (!db) return false;
27272
+ return new Promise((resolve2) => {
27273
+ try {
27274
+ const tx = db.transaction(STORE2, "readwrite"), cursor = tx.objectStore(STORE2).openCursor();
27275
+ cursor.onsuccess = () => {
27276
+ const row3 = cursor.result;
27277
+ if (!row3) return;
27278
+ if (typeof row3.key === "string") {
27279
+ const parts = row3.key.split(" ");
27280
+ if (parts.length === 5 && parts[0] === cpOrigin && parts[2] === connectorId && parts[3] === deviceId) row3.delete();
27281
+ }
27282
+ row3.continue();
27283
+ };
27284
+ tx.oncomplete = () => {
27285
+ db.close();
27286
+ resolve2(true);
27287
+ };
27288
+ tx.onerror = tx.onabort = () => {
27289
+ db.close();
27290
+ resolve2(false);
27291
+ };
27292
+ } catch {
27293
+ db.close();
27294
+ resolve2(false);
27295
+ }
27296
+ });
27297
+ }
27298
+ var LOG_TOKEN_DATABASE, STORE2, MIN_LEFT_MS;
27299
+ var init_log_token_cache = __esm({
27300
+ "src/app-host/log-token-cache.ts"() {
27301
+ "use strict";
27302
+ LOG_TOKEN_DATABASE = "mdbase.app.log-token.v1";
27303
+ STORE2 = "tokens";
27304
+ MIN_LEFT_MS = 6e4;
27305
+ }
27306
+ });
27307
+
27308
+ // src/app-host/sign-out-erase.ts
27309
+ function bounded(work, fallback2, ms = SIGN_OUT_ERASE_TIMEOUT_MS) {
27310
+ let timer2;
27311
+ return Promise.race([work.catch(() => fallback2), new Promise((resolve2) => {
27312
+ timer2 = setTimeout(() => resolve2(fallback2), ms);
27313
+ })]).finally(() => clearTimeout(timer2));
27314
+ }
27315
+ function deleteDatabase(name3) {
27316
+ return bounded(new Promise((resolve2) => {
27317
+ const request3 = indexedDB.deleteDatabase(name3);
27318
+ request3.onsuccess = () => resolve2(true);
27319
+ request3.onerror = () => resolve2(false);
27320
+ }), false);
27321
+ }
27322
+ function deviceCustodyDatabaseNames(scope) {
27323
+ const { accountId, connectorId, deviceId, installationId } = scope;
27324
+ const keyIds = [accountId, connectorId, deviceId, installationId].map(hex2).join(".");
27325
+ return [
27326
+ `mdbase.app.device-key-kek.v1.${keyIds}`,
27327
+ `mdbase.app.device-keys.v1.${keyIds}`,
27328
+ `mdbase.app.noise.v1.${lower(installationId)}.${lower(connectorId)}.${lower(deviceId)}`
27329
+ ];
27330
+ }
27331
+ async function eraseUnattestedDeviceCustody(scope) {
27332
+ try {
27333
+ if (!globalThis.indexedDB) return false;
27334
+ return (await Promise.all(deviceCustodyDatabaseNames(scope).map(deleteDatabase))).every(Boolean);
27335
+ } catch {
27336
+ return false;
27337
+ }
27338
+ }
27339
+ function ledgerNames(scope) {
27340
+ const cp = encodeURIComponent(scope.cpOrigin), unlabelled = `mdbase.app.installation.v1.${cp}.${scope.appId}`;
27341
+ return [scope.owner === void 0 ? unlabelled : `mdbase.app.installation.v2.${cp}.${encodeURIComponent(scope.owner)}.${scope.appId}`, unlabelled];
27342
+ }
27343
+ async function installationDatabaseNames(scope) {
27344
+ const others = /* @__PURE__ */ new Set();
27345
+ const { accountId: account, connectorId: connector, deviceId: device, installationId: installation } = scope;
27346
+ if (account && connector && device && installation) {
27347
+ for (const name3 of deviceCustodyDatabaseNames({ accountId: account, connectorId: connector, deviceId: device, installationId: installation })) others.add(name3);
27348
+ const prefix = [account, connector, device, installation].map(lower).join(".");
27349
+ const scoped = [`mdbase.app.cloud-copy-outcome.v1.${prefix}.`, `mdbase.app.private-bootstrap.v1.${prefix}.`];
27350
+ for (const collection2 of scope.collectionIds) {
27351
+ const id6 = lower(collection2);
27352
+ for (const purpose of ["create", "join"]) others.add(`${scoped[0]}${id6}.${purpose}`);
27353
+ for (const purpose of ["create", "enrol"]) others.add(`${scoped[1]}${id6}.${purpose}`);
27354
+ }
27355
+ const list5 = indexedDB.databases;
27356
+ if (typeof list5 === "function") {
27357
+ const found = await bounded(list5.call(indexedDB), []);
27358
+ for (const { name: name3 } of found) if (name3 && scoped.some((p) => name3.startsWith(p))) others.add(name3);
27359
+ }
27360
+ }
27361
+ return [...others];
27362
+ }
27363
+ async function removeReplicas(account, installation) {
27364
+ const storage = globalThis.navigator?.storage;
27365
+ if (typeof storage?.getDirectory !== "function") return true;
27366
+ return bounded((async () => {
27367
+ const root = await storage.getDirectory();
27368
+ const prefix = `.mdbase-app-${lower(account)}-${lower(installation)}-`, names = [];
27369
+ for await (const name3 of root.keys()) if (name3.startsWith(prefix)) names.push(name3);
27370
+ let ok = true;
27371
+ for (const name3 of names) {
27372
+ try {
27373
+ await root.removeEntry(name3, { recursive: true });
27374
+ } catch {
27375
+ ok = false;
27376
+ }
27377
+ }
27378
+ return ok;
27379
+ })(), false);
27380
+ }
27381
+ async function eraseAppCollectionAccess(scope, collectionId) {
27382
+ try {
27383
+ if (!globalThis.indexedDB || !scope.accountId || !scope.connectorId || !scope.deviceId || !scope.installationId) return false;
27384
+ const collection2 = lower(collectionId), prefix = [scope.accountId, scope.connectorId, scope.deviceId, scope.installationId].map(lower).join(".");
27385
+ const names = ["create", "join"].map((purpose) => `mdbase.app.cloud-copy-outcome.v1.${prefix}.${collection2}.${purpose}`);
27386
+ names.push(...["create", "enrol"].map((purpose) => `mdbase.app.private-bootstrap.v1.${prefix}.${collection2}.${purpose}`));
27387
+ const results2 = await Promise.all(names.map(deleteDatabase));
27388
+ const storage = globalThis.navigator?.storage;
27389
+ if (typeof storage?.getDirectory === "function") {
27390
+ const root = await storage.getDirectory();
27391
+ try {
27392
+ await root.removeEntry(`.mdbase-app-${lower(scope.accountId)}-${lower(scope.installationId)}-${collection2}`, { recursive: true });
27393
+ } catch (error5) {
27394
+ if (!(error5 instanceof DOMException && error5.name === "NotFoundError")) return false;
27395
+ }
27396
+ }
27397
+ return results2.every(Boolean);
27398
+ } catch {
27399
+ return false;
27400
+ }
27401
+ }
27402
+ async function eraseAppInstallationData(scope) {
27403
+ if (!globalThis.indexedDB) return Object.freeze({ ledger: false, complete: false });
27404
+ const [current3, unlabelled] = ledgerNames(scope);
27405
+ const ledger = await deleteDatabase(current3);
27406
+ const others = new Set(scope.isolated ? [] : scope.databases);
27407
+ if (!scope.isolated && scope.storageNamespace === void 0) others.add(unlabelled);
27408
+ others.delete(current3);
27409
+ if (!scope.isolated && scope.storageNamespace === void 0) others.add(LOG_TOKEN_DATABASE);
27410
+ const [results2, complete2] = await Promise.all([
27411
+ Promise.all([...others].map(deleteDatabase)),
27412
+ eraseInstallationStores(scope, scope.storageNamespace !== void 0)
27413
+ ]);
27414
+ return Object.freeze({ ledger, complete: ledger && complete2 && results2.every(Boolean) });
27415
+ }
27416
+ async function eraseInstallationStores(scope, scopedTokens = true) {
27417
+ if (!globalThis.indexedDB) return false;
27418
+ const databases = installationDatabaseNames(scope).then((names) => Promise.all(names.map(deleteDatabase))).then((results2) => results2.every(Boolean), () => false);
27419
+ const tokens2 = scopedTokens ? bounded(eraseAppLogTokens(scope), false) : true;
27420
+ const replicas = scope.accountId && scope.installationId ? removeReplicas(scope.accountId, scope.installationId).catch(() => false) : true;
27421
+ return (await Promise.all([databases, tokens2, replicas])).every(Boolean);
27422
+ }
27423
+ var SIGN_OUT_ERASE_TIMEOUT_MS, hex2, lower;
27424
+ var init_sign_out_erase = __esm({
27425
+ "src/app-host/sign-out-erase.ts"() {
27426
+ "use strict";
27427
+ init_log_token_cache();
27428
+ init_codec();
27429
+ SIGN_OUT_ERASE_TIMEOUT_MS = 5e3;
27430
+ hex2 = (id6) => Array.from(uuidToBytes(id6), (b) => b.toString(16).padStart(2, "0")).join("");
27431
+ lower = (id6) => {
27432
+ uuidToBytes(id6);
27433
+ return id6.toLowerCase();
27434
+ };
27435
+ }
27436
+ });
27437
+
27201
27438
  // src/app-host/installation-sign-in.ts
27202
27439
  function unknownPrivateDeviceField(status, error5) {
27203
27440
  if (status !== 400 || !error5 || typeof error5 !== "object" || Array.isArray(error5)) return false;
@@ -27300,7 +27537,7 @@ ${end.comment}` : end.comment;
27300
27537
  function verificationUri(value2, base, hint) {
27301
27538
  return value2 === base || hint !== null && value2 === `${base}?collection_hint=${hint}` ? value2 : null;
27302
27539
  }
27303
- var AppInstallationSignInError, fail3, nonOkResponses, privateDeviceFieldRefused, hex2, UUID4, FILE_ACTIONS, replaceRefusedAppInstallation, AppProtectedInstallationSignIn;
27540
+ var AppInstallationSignInError, fail3, nonOkResponses, privateDeviceFieldRefused, hex3, UUID4, MAX_SCOPED_INSTALLATIONS, FILE_ACTIONS, replaceRefusedAppInstallation, installationRecovery, AppProtectedInstallationSignIn;
27304
27541
  var init_installation_sign_in = __esm({
27305
27542
  "src/app-host/installation-sign-in.ts"() {
27306
27543
  "use strict";
@@ -27313,6 +27550,7 @@ ${end.comment}` : end.comment;
27313
27550
  init_installation_store();
27314
27551
  init_owner();
27315
27552
  init_cp_problem();
27553
+ init_sign_out_erase();
27316
27554
  AppInstallationSignInError = class extends Error {
27317
27555
  constructor(reason, server) {
27318
27556
  super(`app installation sign-in: ${reason}`);
@@ -27326,8 +27564,9 @@ ${end.comment}` : end.comment;
27326
27564
  fail3 = (reason) => new AppInstallationSignInError(reason);
27327
27565
  nonOkResponses = /* @__PURE__ */ new WeakSet();
27328
27566
  privateDeviceFieldRefused = /* @__PURE__ */ new WeakSet();
27329
- hex2 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
27567
+ hex3 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
27330
27568
  UUID4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
27569
+ MAX_SCOPED_INSTALLATIONS = 1e3;
27331
27570
  FILE_ACTIONS = ["list", "read", "add", "replace", "move", "delete"];
27332
27571
  AppProtectedInstallationSignIn = class _AppProtectedInstallationSignIn {
27333
27572
  constructor(store2, state2, options) {
@@ -27343,7 +27582,12 @@ ${end.comment}` : end.comment;
27343
27582
  state;
27344
27583
  options;
27345
27584
  static {
27346
- replaceRefusedAppInstallation = (flow, stop) => flow.replaceRefusedInstallation(stop);
27585
+ replaceRefusedAppInstallation = (flow, stop, childPaired) => flow.replaceRefusedInstallation(stop, childPaired);
27586
+ installationRecovery = {
27587
+ replacementPending: (flow) => flow.replacementPending(),
27588
+ references: (flow) => flow.scopedInstallationReferences(),
27589
+ replaceRetained: (flow, installation, collection2, expected) => flow.replaceRetainedCollectionInstallation(installation, collection2, expected)
27590
+ };
27347
27591
  }
27348
27592
  closed = false;
27349
27593
  busy = false;
@@ -27405,7 +27649,7 @@ ${end.comment}` : end.comment;
27405
27649
  const base = "version,requestId,installationId,deviceId,secret,appId,kind,origin,cpOrigin,environment,selection,confirmed,nativeStarted,proof,token";
27406
27650
  const legacy = parsed?.version === 1;
27407
27651
  const fields3 = `${base},requestedCreateCollections,collectionIds,createCollections,consentRequest`;
27408
- const r = legacy ? { ...object5(parsed, base), version: 3, renewal: null, requestedCreateCollections: false, collectionIds: [], createCollections: false, consentRequest: null } : parsed?.version === 2 ? { ...object5(parsed, fields3), version: 3, renewal: null } : object5(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" : ""}`);
27652
+ const r = legacy ? { ...object5(parsed, base), version: 3, renewal: null, requestedCreateCollections: false, collectionIds: [], createCollections: false, consentRequest: null } : parsed?.version === 2 ? { ...object5(parsed, fields3), version: 3, renewal: null } : object5(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" : ""}`);
27409
27653
  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");
27410
27654
  const s = r;
27411
27655
  if (typeof s.requestedCreateCollections !== "boolean" || typeof s.createCollections !== "boolean" || p.requestedCreateCollections !== void 0 && p.requestedCreateCollections !== s.requestedCreateCollections) throw fail3("binding");
@@ -27486,7 +27730,27 @@ ${end.comment}` : end.comment;
27486
27730
  if (s.collectionRecoveries !== void 0) {
27487
27731
  if (!s.token || !s.confirmed || !s.selection || !s.proof || !s.collectionRecoveries || typeof s.collectionRecoveries !== "object" || Array.isArray(s.collectionRecoveries)) throw fail3("recovery_required");
27488
27732
  const entries = Object.entries(s.collectionRecoveries);
27489
- if (entries.length > 1e3 || entries.some(([collection2, replacement]) => !(s.collectionIds.includes(id2(collection2)) || s.nativeGrants?.some((c) => c.collection_id === collection2)) || replacement !== null && !id2(replacement))) throw fail3("recovery_required");
27733
+ if (entries.length > MAX_SCOPED_INSTALLATIONS || entries.some(([collection2, replacement]) => !(s.collectionIds.includes(id2(collection2)) || s.nativeGrants?.some((c) => c.collection_id === collection2)) || replacement !== null && !id2(replacement))) throw fail3("recovery_required");
27734
+ }
27735
+ if (s.replacementPending !== void 0 && (s.replacementPending !== true || !s.token || !s.confirmed)) throw fail3("recovery_required");
27736
+ if (s.retainedCollectionRecoveries !== void 0) {
27737
+ const retained = s.retainedCollectionRecoveries;
27738
+ if (s.recoveryFor || !retained || typeof retained !== "object" || Array.isArray(retained)) throw fail3("recovery_required");
27739
+ const references = Object.values(s.collectionRecoveries ?? {}).filter((reference) => reference !== null);
27740
+ const seen2 = new Set(references);
27741
+ if (seen2.size !== references.length) throw fail3("recovery_required");
27742
+ for (const [account, collections] of Object.entries(retained)) {
27743
+ id2(account);
27744
+ if (!collections || typeof collections !== "object" || Array.isArray(collections)) throw fail3("recovery_required");
27745
+ const entries = Object.entries(collections);
27746
+ if (!entries.length || seen2.size + entries.length > MAX_SCOPED_INSTALLATIONS) throw fail3("recovery_required");
27747
+ for (const [collection2, reference] of entries) {
27748
+ id2(collection2);
27749
+ id2(reference);
27750
+ if (seen2.has(reference) || account === s.selection?.accountId && Object.hasOwn(s.collectionRecoveries ?? {}, collection2)) throw fail3("recovery_required");
27751
+ seen2.add(reference);
27752
+ }
27753
+ }
27490
27754
  }
27491
27755
  if (s.nativeAuthorization) {
27492
27756
  const a = object5(s.nativeAuthorization, "requestId,authorizationId,applicationId,manifestDigest");
@@ -27641,19 +27905,37 @@ ${end.comment}` : end.comment;
27641
27905
  }
27642
27906
  return this.exclusive(() => this.startRequest(hint));
27643
27907
  }
27644
- /** Replace the protected identity in place under the sign-in ledger lease.
27645
- * The old replica and custody stores remain under the original IDs.
27646
- */
27647
- replaceRefusedInstallation(stop) {
27908
+ /** Replace the protected identity under the same sign-in ledger lease. */
27909
+ replaceRefusedInstallation(stop, childPaired) {
27648
27910
  return this.exclusive(async () => {
27649
- if (!this.credentialRefused || !this.state.token || Object.values(this.state.collectionRecoveries ?? {}).some((reference) => reference !== null)) throw fail3("recovery_required");
27911
+ const state2 = this.state;
27912
+ if (!(this.credentialRefused || state2.replacementPending) || !state2.token) throw fail3("recovery_required");
27913
+ const scoped = this.scopedInstallationReferences();
27914
+ if (scoped.some((reference) => !childPaired?.(reference))) throw fail3("recovery_required");
27915
+ const selected = this.confirmedSelection();
27916
+ const collectionIds = [...state2.collectionIds, ...(state2.nativeGrants ?? []).map((grant) => grant.collection_id)];
27917
+ if (!state2.replacementPending) {
27918
+ await this.saveWithRecoveryMetadata({ ...state2, replacementPending: true });
27919
+ }
27650
27920
  await stop();
27651
- await this.save(_AppProtectedInstallationSignIn.freshState(this.options));
27921
+ if (!await eraseInstallationStores({ ...selected, collectionIds })) throw fail3("recovery_required");
27922
+ if (scoped.some((reference) => !childPaired?.(reference))) throw fail3("recovery_required");
27923
+ const fresh = _AppProtectedInstallationSignIn.freshState(this.options);
27924
+ if (scoped.length) {
27925
+ const retained = {};
27926
+ for (const { accountId, collectionId, reference } of scoped) (retained[accountId] ??= {})[collectionId] = reference;
27927
+ fresh.retainedCollectionRecoveries = retained;
27928
+ }
27929
+ await this.save(fresh);
27652
27930
  this.credentialRefused = false;
27653
27931
  this.nativeAcknowledged = false;
27654
27932
  this.closedPairing = null;
27655
27933
  });
27656
27934
  }
27935
+ replacementPending() {
27936
+ this.check();
27937
+ return this.state.replacementPending === true;
27938
+ }
27657
27939
  /** Explicit user retry after an exact typed expiry. Renew ONLY the pairing
27658
27940
  * window; installation/device/account/challenge/keys/proof remain original.
27659
27941
  * Persist the new request and its parent capability BEFORE HTTP. Unknown
@@ -28064,7 +28346,41 @@ ${end.comment}` : end.comment;
28064
28346
  * separate original installation ledger, never a replacement credential. */
28065
28347
  collectionRecoveries() {
28066
28348
  this.check();
28067
- return Object.freeze({ ...this.state.collectionRecoveries });
28349
+ return Object.freeze({ ...this.retainedRecoveriesForAccount(), ...this.state.collectionRecoveries });
28350
+ }
28351
+ scopedInstallationReferences() {
28352
+ this.check();
28353
+ const refs = [];
28354
+ for (const [accountId2, collections] of Object.entries(this.state.retainedCollectionRecoveries ?? {})) {
28355
+ for (const [collectionId, reference] of Object.entries(collections)) refs.push({ accountId: accountId2, collectionId, reference });
28356
+ }
28357
+ const accountId = this.state.selection?.accountId;
28358
+ if (accountId) for (const [collectionId, reference] of Object.entries(this.state.collectionRecoveries ?? {})) {
28359
+ if (reference !== null) refs.push({ accountId, collectionId, reference });
28360
+ }
28361
+ return refs;
28362
+ }
28363
+ retainedRecoveriesForAccount() {
28364
+ const { token, selection, retainedCollectionRecoveries } = this.state;
28365
+ return token && selection ? retainedCollectionRecoveries?.[selection.accountId] : void 0;
28366
+ }
28367
+ replaceRetainedCollectionInstallation(installation, collection2, expected) {
28368
+ const check3 = this.consentGuard(installation);
28369
+ return this.exclusive(async () => {
28370
+ check3();
28371
+ id2(collection2);
28372
+ id2(expected);
28373
+ const retained = this.retainedRecoveriesForAccount();
28374
+ if (!retained?.[collection2]) return null;
28375
+ if (retained[collection2] !== expected) throw fail3("fenced");
28376
+ const reference = crypto.randomUUID();
28377
+ await this.saveWithRecoveryMetadata({ ...this.state, retainedCollectionRecoveries: {
28378
+ ...this.state.retainedCollectionRecoveries,
28379
+ [installation.scope.account]: { ...retained, [collection2]: reference }
28380
+ } });
28381
+ check3();
28382
+ return reference;
28383
+ });
28068
28384
  }
28069
28385
  retireCollectionScope(installation, collection2, expectedReplacement = null) {
28070
28386
  const check3 = this.consentGuard(installation);
@@ -28090,14 +28406,17 @@ ${end.comment}` : end.comment;
28090
28406
  if (!Object.hasOwn(this.state.collectionRecoveries ?? {}, collection2)) throw fail3("binding");
28091
28407
  const existing = this.state.collectionRecoveries[collection2];
28092
28408
  if (existing !== null) return existing;
28409
+ if (this.scopedInstallationReferences().length >= MAX_SCOPED_INSTALLATIONS) throw fail3("recovery_required");
28093
28410
  const replacement = crypto.randomUUID();
28094
28411
  await this.saveRecovery(collection2, replacement);
28095
28412
  check3();
28096
28413
  return replacement;
28097
28414
  });
28098
28415
  }
28099
- async saveRecovery(collection2, replacement) {
28100
- const state2 = { ...this.state, collectionRecoveries: { ...this.state.collectionRecoveries, [collection2]: replacement } };
28416
+ saveRecovery(collection2, replacement) {
28417
+ return this.saveWithRecoveryMetadata({ ...this.state, collectionRecoveries: { ...this.state.collectionRecoveries, [collection2]: replacement } });
28418
+ }
28419
+ async saveWithRecoveryMetadata(state2) {
28101
28420
  if (new TextEncoder().encode(JSON.stringify(state2)).length > 128 * 1024) delete state2.collectionListing;
28102
28421
  await this.save(state2);
28103
28422
  }
@@ -28329,7 +28648,7 @@ ${end.comment}` : end.comment;
28329
28648
  const proof2 = runtime2.signCpEnrol(challenge);
28330
28649
  signature = proof2.signature;
28331
28650
  check3();
28332
- 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) }) });
28651
+ await this.save({ ...this.state, proof: _AppProtectedInstallationSignIn.proof({ sign_pk: hex3(proof2.signPublicKey), kem_pk: hex3(proof2.kemPublicKey), noise_pk: hex3(proof2.noisePublicKey), sig: hex3(signature) }) });
28333
28652
  check3();
28334
28653
  } finally {
28335
28654
  challenge.fill(0);
@@ -28337,7 +28656,7 @@ ${end.comment}` : end.comment;
28337
28656
  }
28338
28657
  }
28339
28658
  const p = this.state.proof;
28340
- if (p.sign_pk !== hex2(custody.signPublicKey) || p.kem_pk !== hex2(custody.kemPublicKey) || p.noise_pk !== hex2(custody.noisePublicKey)) throw fail3("binding");
28659
+ if (p.sign_pk !== hex3(custody.signPublicKey) || p.kem_pk !== hex3(custody.kemPublicKey) || p.noise_pk !== hex3(custody.noisePublicKey)) throw fail3("binding");
28341
28660
  const { status, value: value2 } = await this.json(`/v1/pairing-requests/${this.state.requestId}/attest`, true, p);
28342
28661
  check3();
28343
28662
  object5(value2, "ok");
@@ -28364,7 +28683,7 @@ ${end.comment}` : end.comment;
28364
28683
  return this.exclusive(async () => {
28365
28684
  check3();
28366
28685
  const r = this.receipt();
28367
- if (hex2(r.signPublicKey) !== hex2(custody.signPublicKey) || hex2(r.kemPublicKey) !== hex2(custody.kemPublicKey) || hex2(r.noisePublicKey) !== hex2(custody.noisePublicKey)) throw fail3("binding");
28686
+ if (hex3(r.signPublicKey) !== hex3(custody.signPublicKey) || hex3(r.kemPublicKey) !== hex3(custody.kemPublicKey) || hex3(r.noisePublicKey) !== hex3(custody.noisePublicKey)) throw fail3("binding");
28368
28687
  await persistence.registered(r, { signal: this.lifetime.signal });
28369
28688
  check3();
28370
28689
  runtime2.acknowledgeDeviceRegistration(r);
@@ -28503,7 +28822,7 @@ ${end.comment}` : end.comment;
28503
28822
  function equal4(a, b) {
28504
28823
  return a.length === b.length && a.every((v, i) => v === b[i]);
28505
28824
  }
28506
- function hex3(b) {
28825
+ function hex4(b) {
28507
28826
  return [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
28508
28827
  }
28509
28828
  function base64(b) {
@@ -28741,7 +29060,7 @@ ${end.comment}` : end.comment;
28741
29060
  signature = await this.authority.signLogProof(p, { signal });
28742
29061
  this.check(signal);
28743
29062
  if (!(signature instanceof Uint8Array) || signature.length !== 64) throw error2("shape");
28744
- 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);
29063
+ const r = await this.fetch(`${this.base}/v1/rpc`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/cbor", "x-mdbase-nonce": hex4(p.nonce), "x-mdbase-sig": hex4(signature) }, body: frame }, signal, 15e3);
28745
29064
  this.spares.keep(r.headers);
28746
29065
  if (r.status === 401) this.authority.invalidateToken?.(token);
28747
29066
  if (!r.ok) throw await this.refusal(r, signal, receive);
@@ -29011,7 +29330,7 @@ ${end.comment}` : end.comment;
29011
29330
  if (n < 0n || n > (1n << 64n) - 1n) throw fail4("binding");
29012
29331
  return n;
29013
29332
  }
29014
- function hex4(b) {
29333
+ function hex5(b) {
29015
29334
  return [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
29016
29335
  }
29017
29336
  function object6(v) {
@@ -29195,7 +29514,7 @@ ${end.comment}` : end.comment;
29195
29514
  signature = this.runtime.signCpLogToken(challenge);
29196
29515
  this.check(options.signal);
29197
29516
  if (!(signature instanceof Uint8Array) || signature.length !== 64) throw fail4("response");
29198
- const body = JSON.stringify({ device_id: this.deviceId, challenge: issued.challenge, sig: hex4(signature), capabilities: ["collection_mode_switch_v2"] });
29517
+ const body = JSON.stringify({ device_id: this.deviceId, challenge: issued.challenge, sig: hex5(signature), capabilities: ["collection_mode_switch_v2"] });
29199
29518
  const minted = await this.json(`/v1/next/collections/${this.collection}/log-token`, bearer, body, options.signal);
29200
29519
  this.check(options.signal);
29201
29520
  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");
@@ -29243,7 +29562,7 @@ ${end.comment}` : end.comment;
29243
29562
  if (!v || typeof v !== "object" || Array.isArray(v)) throw fail5("response");
29244
29563
  return v;
29245
29564
  }
29246
- var AppCloudCopyBootstrapError, fail5, transientHttp, equal5, hex5, AppCpCloudCopyBootstrap;
29565
+ var AppCloudCopyBootstrapError, fail5, transientHttp, equal5, hex6, AppCpCloudCopyBootstrap;
29247
29566
  var init_cloud_copy_bootstrap = __esm({
29248
29567
  "src/app-host/cloud-copy-bootstrap.ts"() {
29249
29568
  "use strict";
@@ -29266,7 +29585,7 @@ ${end.comment}` : end.comment;
29266
29585
  fail5 = (r, retryable = false) => new AppCloudCopyBootstrapError(r, retryable);
29267
29586
  transientHttp = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
29268
29587
  equal5 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
29269
- hex5 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
29588
+ hex6 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
29270
29589
  AppCpCloudCopyBootstrap = class {
29271
29590
  constructor(runtime2, session, trust, persistence, options = {}) {
29272
29591
  this.runtime = runtime2;
@@ -29436,7 +29755,7 @@ ${end.comment}` : end.comment;
29436
29755
  await crypto.subtle.digest("SHA-256", input)
29437
29756
  );
29438
29757
  this.check(signal);
29439
- return `sha256:${hex5(result2)}`;
29758
+ return `sha256:${hex6(result2)}`;
29440
29759
  }
29441
29760
  async json(path, bearer, body, signal) {
29442
29761
  this.check(signal);
@@ -29660,7 +29979,7 @@ ${end.comment}` : end.comment;
29660
29979
  device_id: this.scope.deviceId,
29661
29980
  capabilities: ["collection_mode_switch_v2"],
29662
29981
  challenge: challenge.challenge,
29663
- sig: hex5(signature),
29982
+ sig: hex6(signature),
29664
29983
  ...create ? {
29665
29984
  collection_id: this.scope.collection,
29666
29985
  ...this.operation.displayName === void 0 ? {} : {
@@ -31711,7 +32030,7 @@ ${end.comment}` : end.comment;
31711
32030
  if (Object.values(scope).some((id6) => !uuid6.test(id6) || /^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(id6)) || !uuid6.test(source.generation)) throw fail8("binding");
31712
32031
  return { scope, generation: source.generation, binding: JSON.stringify([scope.account, scope.installation, scope.collection]) };
31713
32032
  }
31714
- function bounded(value2) {
32033
+ function bounded2(value2) {
31715
32034
  try {
31716
32035
  return new TextEncoder().encode(JSON.stringify(value2)).byteLength <= MAX2;
31717
32036
  } catch {
@@ -31732,7 +32051,7 @@ ${end.comment}` : end.comment;
31732
32051
  const reply = (id6, kind, value2) => {
31733
32052
  current3();
31734
32053
  const packet = [1, original.binding, original.generation, id6, kind, value2];
31735
- if (!bounded(packet)) throw fail8("binding");
32054
+ if (!bounded2(packet)) throw fail8("binding");
31736
32055
  port.postMessage(packet);
31737
32056
  };
31738
32057
  const stop = () => {
@@ -31762,7 +32081,7 @@ ${end.comment}` : end.comment;
31762
32081
  bad11();
31763
32082
  return;
31764
32083
  }
31765
- 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 fail8("binding");
32084
+ 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 fail8("binding");
31766
32085
  const id6 = packet[3], action = packet[4], payload = packet[5];
31767
32086
  if (id6 <= lastId) throw fail8("binding");
31768
32087
  lastId = id6;
@@ -31830,7 +32149,7 @@ ${end.comment}` : end.comment;
31830
32149
  checkAuthority();
31831
32150
  result2 = collectionPeopleDto(resource2, value2);
31832
32151
  checkAuthority();
31833
- if (!bounded([1, original.binding, original.generation, id6, "result", result2])) throw mdbaseError("unavailable", "invalid people response", "people_response");
32152
+ if (!bounded2([1, original.binding, original.generation, id6, "result", result2])) throw mdbaseError("unavailable", "invalid people response", "people_response");
31834
32153
  break;
31835
32154
  }
31836
32155
  // The owner starting a new recovery pass ends its turn: any tab may recover.
@@ -31942,7 +32261,7 @@ ${end.comment}` : end.comment;
31942
32261
  try {
31943
32262
  current3();
31944
32263
  const packet = event.data;
31945
- if (!Array.isArray(packet) || packet.length !== 6 || packet[0] !== 1 || packet[1] !== original.binding || packet[2] !== original.generation || !bounded(packet)) throw fail8();
32264
+ if (!Array.isArray(packet) || packet.length !== 6 || packet[0] !== 1 || packet[1] !== original.binding || packet[2] !== original.generation || !bounded2(packet)) throw fail8();
31946
32265
  if (packet[3] === 0 && packet[4] === "closed" && packet[5] === null) {
31947
32266
  close();
31948
32267
  return;
@@ -31990,7 +32309,7 @@ ${end.comment}` : end.comment;
31990
32309
  signal.addEventListener("abort", abort, { once: true });
31991
32310
  try {
31992
32311
  const packet = [1, original.binding, original.generation, id6, action, payload];
31993
- if (!bounded(packet)) throw fail8("binding");
32312
+ if (!bounded2(packet)) throw fail8("binding");
31994
32313
  port.postMessage(packet);
31995
32314
  } catch (error5) {
31996
32315
  pending = null;
@@ -32014,7 +32333,7 @@ ${end.comment}` : end.comment;
32014
32333
  side.set(id6, (value2, error5) => error5 ? reject(error5) : resolve2(value2));
32015
32334
  try {
32016
32335
  const packet = [1, original.binding, original.generation, id6, action, payload];
32017
- if (!bounded(packet)) throw fail8("binding");
32336
+ if (!bounded2(packet)) throw fail8("binding");
32018
32337
  port.postMessage(packet);
32019
32338
  } catch (error5) {
32020
32339
  side.delete(id6);
@@ -34215,7 +34534,7 @@ ${end.comment}` : end.comment;
34215
34534
  conflicts.push({
34216
34535
  target: r.target,
34217
34536
  ...canAdopt ? { adoptable: { digest: r.currentDigest } } : {},
34218
- message: seed && r.kind === "type" && !r.installed ? `The existing note type at "${r.target}" differs from the one this app needs. ${canAdopt ? "You can replace it with this app's version." : "Change the existing type to support this app, or rename it and update the notes that use it. Then run setup again."}` : canAdopt && seed ? `Your ${thing.bare} has changes that can't be combined with the version this app needs. You can replace it with this app's version.` : canAdopt && r.installed ? `${The} was changed after this app set it up. You can replace it with this app's version.` : canAdopt ? `This collection already has a ${thing.bare} that differs from the one this app needs. You can replace it with this app's version.` : r.installed ? `${The} was changed after this app set it up, so it can't be updated automatically.` : `${The} can't be set up automatically.`
34537
+ message: seed && r.kind === "type" && !r.installed ? `The existing note type at "${r.target}" differs from the one this app needs. ${canAdopt ? "You can replace it with this app's version." : "Existing notes use this type, so setup won't replace it automatically. Change the existing type to support this app, or rename it and update the notes that use it. Then run setup again."}` : seed && r.kind === "type" && !canAdopt ? `Your ${thing.bare} has changes that can't be updated automatically while existing notes use it. Update "${r.target}" to support this app (for example, in the app or editor that manages it), then try setup again.` : canAdopt && seed ? `Your ${thing.bare} has changes that can't be combined with the version this app needs. You can replace it with this app's version.` : canAdopt && r.installed ? `${The} was changed after this app set it up. You can replace it with this app's version.` : canAdopt ? `This collection already has a ${thing.bare} that differs from the one this app needs. You can replace it with this app's version.` : r.installed ? `${The} was changed after this app set it up, so it can't be updated automatically.` : `${The} can't be set up automatically.`
34219
34538
  });
34220
34539
  break;
34221
34540
  }
@@ -37879,19 +38198,19 @@ ${end.comment}` : end.comment;
37879
38198
  kind,
37880
38199
  ticket,
37881
38200
  revision: fixed(m2.get(4), 32),
37882
- declaration: hex6(fixed(m2.get(7), 32)),
38201
+ declaration: hex7(fixed(m2.get(7), 32)),
37883
38202
  application: m2.get(8),
37884
38203
  promoted: impact.get(0),
37885
38204
  retained: impact.get(1),
37886
38205
  records: Object.freeze(records2),
37887
- assessment: resourceAssessment({ status: m2.get(3) === "ready" ? "current" : m2.get(3) === "incompatible" ? "conflict" : "provision", assessmentDigest: "sha256:" + hex6(fixed(m2.get(5), 32)), review: object9(m2.get(6)) }, true)
38206
+ assessment: resourceAssessment({ status: m2.get(3) === "ready" ? "current" : m2.get(3) === "incompatible" ? "conflict" : "provision", assessmentDigest: "sha256:" + hex7(fixed(m2.get(5), 32)), review: object9(m2.get(6)) }, true)
37888
38207
  };
37889
38208
  } finally {
37890
38209
  input.fill(0);
37891
38210
  bytes10?.fill(0);
37892
38211
  }
37893
38212
  }
37894
- var bad4, hex6;
38213
+ var bad4, hex7;
37895
38214
  var init_setup_producer = __esm({
37896
38215
  "src/app-grant/setup-producer.ts"() {
37897
38216
  "use strict";
@@ -37900,7 +38219,7 @@ ${end.comment}` : end.comment;
37900
38219
  init_collection_control();
37901
38220
  init_wire();
37902
38221
  bad4 = () => mdbaseError("internal", "Invalid Native setup reply.", "declared_setup_codec");
37903
- hex6 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
38222
+ hex7 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
37904
38223
  }
37905
38224
  });
37906
38225
 
@@ -38441,7 +38760,7 @@ ${end.comment}` : end.comment;
38441
38760
  }
38442
38761
  };
38443
38762
  }
38444
- function bounded2(signal, ms) {
38763
+ function bounded3(signal, ms) {
38445
38764
  const control = new AbortController();
38446
38765
  const abort = () => control.abort();
38447
38766
  const timer2 = setTimeout(abort, ms);
@@ -38600,7 +38919,7 @@ ${end.comment}` : end.comment;
38600
38919
  return store2.putIdentityIfAbsent({ version: 1, privateKey: created.privateKey, publicKey: created.publicKey });
38601
38920
  }
38602
38921
  async request(path, init, signal) {
38603
- const budget = bounded2(signal, REQUEST_MS2);
38922
+ const budget = bounded3(signal, REQUEST_MS2);
38604
38923
  try {
38605
38924
  let res;
38606
38925
  try {
@@ -39305,113 +39624,6 @@ ${end.comment}` : end.comment;
39305
39624
  }
39306
39625
  });
39307
39626
 
39308
- // src/app-host/log-token-cache.ts
39309
- function open() {
39310
- return new Promise((resolve2) => {
39311
- let request3;
39312
- try {
39313
- request3 = indexedDB.open(LOG_TOKEN_DATABASE, 1);
39314
- } catch {
39315
- resolve2(null);
39316
- return;
39317
- }
39318
- request3.onupgradeneeded = () => {
39319
- try {
39320
- request3.result.createObjectStore(STORE3);
39321
- } catch {
39322
- }
39323
- };
39324
- request3.onsuccess = () => {
39325
- const db = request3.result;
39326
- db.onversionchange = () => db.close();
39327
- resolve2(db.objectStoreNames.contains(STORE3) ? db : (db.close(), null));
39328
- };
39329
- request3.onerror = request3.onblocked = () => resolve2(null);
39330
- });
39331
- }
39332
- function run(mode, work) {
39333
- return open().then((db) => new Promise((resolve2) => {
39334
- if (!db) {
39335
- resolve2(null);
39336
- return;
39337
- }
39338
- let result2 = null;
39339
- try {
39340
- const tx = db.transaction(STORE3, mode), request3 = work(tx.objectStore(STORE3));
39341
- if (request3) request3.onsuccess = () => {
39342
- result2 = request3.result ?? null;
39343
- };
39344
- tx.oncomplete = () => {
39345
- db.close();
39346
- resolve2(result2);
39347
- };
39348
- tx.onerror = tx.onabort = () => {
39349
- db.close();
39350
- resolve2(null);
39351
- };
39352
- } catch {
39353
- db.close();
39354
- resolve2(null);
39355
- }
39356
- }));
39357
- }
39358
- function idbLogTokenCache() {
39359
- if (typeof indexedDB === "undefined") return null;
39360
- return Object.freeze({
39361
- async read(key3, now) {
39362
- const v = await run("readonly", (store2) => store2.get(key3)).catch(() => null);
39363
- 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;
39364
- return Object.freeze({ value: v.value, expires: v.expires });
39365
- },
39366
- async write(key3, token) {
39367
- await run("readwrite", (store2) => store2.put({ value: token.value, expires: token.expires }, key3)).catch(() => null);
39368
- },
39369
- async drop(key3) {
39370
- await run("readwrite", (store2) => store2.delete(key3)).catch(() => null);
39371
- }
39372
- });
39373
- }
39374
- async function eraseAppLogTokens(scope) {
39375
- const { cpOrigin, connectorId, deviceId } = scope;
39376
- if (!connectorId || !deviceId) return true;
39377
- const db = await open();
39378
- if (!db) return false;
39379
- return new Promise((resolve2) => {
39380
- try {
39381
- const tx = db.transaction(STORE3, "readwrite"), cursor = tx.objectStore(STORE3).openCursor();
39382
- cursor.onsuccess = () => {
39383
- const row3 = cursor.result;
39384
- if (!row3) return;
39385
- if (typeof row3.key === "string") {
39386
- const parts = row3.key.split(" ");
39387
- if (parts.length === 5 && parts[0] === cpOrigin && parts[2] === connectorId && parts[3] === deviceId) row3.delete();
39388
- }
39389
- row3.continue();
39390
- };
39391
- tx.oncomplete = () => {
39392
- db.close();
39393
- resolve2(true);
39394
- };
39395
- tx.onerror = tx.onabort = () => {
39396
- db.close();
39397
- resolve2(false);
39398
- };
39399
- } catch {
39400
- db.close();
39401
- resolve2(false);
39402
- }
39403
- });
39404
- }
39405
- var LOG_TOKEN_DATABASE, STORE3, MIN_LEFT_MS;
39406
- var init_log_token_cache = __esm({
39407
- "src/app-host/log-token-cache.ts"() {
39408
- "use strict";
39409
- LOG_TOKEN_DATABASE = "mdbase.app.log-token.v1";
39410
- STORE3 = "tokens";
39411
- MIN_LEFT_MS = 6e4;
39412
- }
39413
- });
39414
-
39415
39627
  // src/app-host/open-wait.ts
39416
39628
  function waitForOpenRetry(milliseconds, signal) {
39417
39629
  return new Promise((resolve2, reject) => {
@@ -39449,7 +39661,7 @@ ${end.comment}` : end.comment;
39449
39661
  const code = e.get(0), reason = e.get(1);
39450
39662
  return { code: typeof code === "string" ? code : "unavailable", reason: typeof reason === "string" ? reason : "" };
39451
39663
  }
39452
- var LOG_CLOSE_EXPIRED, LOG_CLOSE_FORBIDDEN, LOG_CLOSE_GONE, PING_MS, PONG_MS, HEALTHY_MS, MAX_BACKOFF_MS, OPEN_MS, UNSIGNED_ATTEMPTS, INLINE_BYTES, MAX_FRAME4, hex7, request2, AppLogPushChannel;
39664
+ var LOG_CLOSE_EXPIRED, LOG_CLOSE_FORBIDDEN, LOG_CLOSE_GONE, PING_MS, PONG_MS, HEALTHY_MS, MAX_BACKOFF_MS, OPEN_MS, UNSIGNED_ATTEMPTS, INLINE_BYTES, MAX_FRAME4, hex8, request2, AppLogPushChannel;
39453
39665
  var init_log_push = __esm({
39454
39666
  "src/app-host/log-push.ts"() {
39455
39667
  "use strict";
@@ -39467,7 +39679,7 @@ ${end.comment}` : end.comment;
39467
39679
  UNSIGNED_ATTEMPTS = 4;
39468
39680
  INLINE_BYTES = 64 * 1024;
39469
39681
  MAX_FRAME4 = 1024 * 1024;
39470
- hex7 = (b) => [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
39682
+ hex8 = (b) => [...b].map((v) => v.toString(16).padStart(2, "0")).join("");
39471
39683
  request2 = (id6, method, params2) => encode(/* @__PURE__ */ new Map([[0, 0], [1, id6], [2, method], [3, params2]]));
39472
39684
  AppLogPushChannel = class {
39473
39685
  constructor(source, events, options = {}) {
@@ -39635,7 +39847,7 @@ ${end.comment}` : end.comment;
39635
39847
  this.token = token;
39636
39848
  let s;
39637
39849
  try {
39638
- s = new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${hex7(nonce)}`);
39850
+ s = new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${hex8(nonce)}`);
39639
39851
  } catch {
39640
39852
  this.schedule();
39641
39853
  return;
@@ -40406,7 +40618,7 @@ ${end.comment}` : end.comment;
40406
40618
  });
40407
40619
 
40408
40620
  // src/app-host/cloud-copy-persistence.ts
40409
- var APP_CLOUD_COPY_OUTCOME_MAX, MAX_PLAIN, bad5, same, hex8, AppWebCloudCopyBootstrapPersistence;
40621
+ var APP_CLOUD_COPY_OUTCOME_MAX, MAX_PLAIN, bad5, same, hex9, AppWebCloudCopyBootstrapPersistence;
40410
40622
  var init_cloud_copy_persistence = __esm({
40411
40623
  "src/app-host/cloud-copy-persistence.ts"() {
40412
40624
  "use strict";
@@ -40419,7 +40631,7 @@ ${end.comment}` : end.comment;
40419
40631
  "app cloud copy outcome unavailable; preserve storage and reopen"
40420
40632
  );
40421
40633
  same = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
40422
- hex8 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
40634
+ hex9 = (v) => Array.from(v, (b) => b.toString(16).padStart(2, "0")).join("");
40423
40635
  AppWebCloudCopyBootstrapPersistence = class {
40424
40636
  constructor(source, receipt4, key3, store2, options) {
40425
40637
  this.source = source;
@@ -40553,7 +40765,7 @@ ${end.comment}` : end.comment;
40553
40765
  await crypto.subtle.digest("SHA-256", input)
40554
40766
  );
40555
40767
  this.check(signal);
40556
- if (metadata2.expectedGenesis !== `sha256:${hex8(digest2)}`) throw bad5();
40768
+ if (metadata2.expectedGenesis !== `sha256:${hex9(digest2)}`) throw bad5();
40557
40769
  }
40558
40770
  async read(signal) {
40559
40771
  let plain2 = null;
@@ -40953,7 +41165,7 @@ ${end.comment}` : end.comment;
40953
41165
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) throw fail10("response");
40954
41166
  return value2;
40955
41167
  }
40956
- var AppPrivateBootstrapError, fail10, hex9, equal7, AppCpPrivateBootstrap;
41168
+ var AppPrivateBootstrapError, fail10, hex10, equal7, AppCpPrivateBootstrap;
40957
41169
  var init_private_bootstrap = __esm({
40958
41170
  "src/app-host/private-bootstrap.ts"() {
40959
41171
  "use strict";
@@ -40969,7 +41181,7 @@ ${end.comment}` : end.comment;
40969
41181
  reason;
40970
41182
  };
40971
41183
  fail10 = (r) => new AppPrivateBootstrapError(r);
40972
- hex9 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
41184
+ hex10 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
40973
41185
  equal7 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
40974
41186
  AppCpPrivateBootstrap = class {
40975
41187
  constructor(runtime2, session, persistence, options = {}) {
@@ -41116,7 +41328,7 @@ ${end.comment}` : end.comment;
41116
41328
  const enrol = this.scope.purpose === "enrol";
41117
41329
  signature = enrol ? this.runtime.signPrivateDeviceEnrol(nonce).signature : this.runtime.signPrivateCreate(nonce);
41118
41330
  this.check(options.signal);
41119
- 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: hex9(signature), ...enrol ? { sas_commit: hex9(this.marker.sasCommitment) } : { collection_id: this.scope.collection, ...this.displayName === void 0 ? {} : { display_name: this.displayName } } }), options.signal);
41331
+ 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: hex10(signature), ...enrol ? { sas_commit: hex10(this.marker.sasCommitment) } : { collection_id: this.scope.collection, ...this.displayName === void 0 ? {} : { display_name: this.displayName } } }), options.signal);
41120
41332
  this.check(options.signal);
41121
41333
  if (result2.collection_id !== this.scope.collection || this.origin(result2.log_url) !== this.origin(this.scope.logOrigin)) throw fail10("response");
41122
41334
  if (enrol) {
@@ -41133,7 +41345,7 @@ ${end.comment}` : end.comment;
41133
41345
  message3.set(item, 1 + domain.length);
41134
41346
  const digest2 = new Uint8Array(await crypto.subtle.digest("SHA-256", message3));
41135
41347
  this.check(options.signal);
41136
- const metadata2 = this.copy({ collection: this.scope.collection, deviceId: this.scope.deviceId, logOrigin: this.scope.logOrigin, rootPublicKey: this.root, genesisItem: item, expectedGenesis: `sha256:${hex9(digest2)}`, approval: enrol ? "pending" : "creator", ...this.displayName === void 0 ? {} : { displayName: this.displayName } });
41348
+ const metadata2 = this.copy({ collection: this.scope.collection, deviceId: this.scope.deviceId, logOrigin: this.scope.logOrigin, rootPublicKey: this.root, genesisItem: item, expectedGenesis: `sha256:${hex10(digest2)}`, approval: enrol ? "pending" : "creator", ...this.displayName === void 0 ? {} : { displayName: this.displayName } });
41137
41349
  await this.persistence.completed(this.copy(metadata2), options);
41138
41350
  this.check(options.signal);
41139
41351
  if (this.marker) {
@@ -41159,7 +41371,7 @@ ${end.comment}` : end.comment;
41159
41371
  });
41160
41372
 
41161
41373
  // src/app-host/private-persistence.ts
41162
- var MAX_PLAIN2, APP_PRIVATE_BOOTSTRAP_CIPHER_MAX, bad7, equal8, hex10, AppWebPrivateBootstrapPersistence;
41374
+ var MAX_PLAIN2, APP_PRIVATE_BOOTSTRAP_CIPHER_MAX, bad7, equal8, hex11, AppWebPrivateBootstrapPersistence;
41163
41375
  var init_private_persistence = __esm({
41164
41376
  "src/app-host/private-persistence.ts"() {
41165
41377
  "use strict";
@@ -41171,7 +41383,7 @@ ${end.comment}` : end.comment;
41171
41383
  APP_PRIVATE_BOOTSTRAP_CIPHER_MAX = MAX_PLAIN2 + 256;
41172
41384
  bad7 = () => new Error("app private bootstrap custody unavailable; preserve storage and reopen");
41173
41385
  equal8 = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
41174
- hex10 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
41386
+ hex11 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
41175
41387
  AppWebPrivateBootstrapPersistence = class {
41176
41388
  constructor(source, receipt4, key3, store2, noise, options = {}) {
41177
41389
  this.source = source;
@@ -41271,7 +41483,7 @@ ${end.comment}` : end.comment;
41271
41483
  bytes10.set(metadata2.genesisItem, 1 + domain.length);
41272
41484
  const hash4 = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes10));
41273
41485
  this.check(signal);
41274
- if (metadata2.expectedGenesis !== `sha256:${hex10(hash4)}`) throw bad7();
41486
+ if (metadata2.expectedGenesis !== `sha256:${hex11(hash4)}`) throw bad7();
41275
41487
  }
41276
41488
  async read(options) {
41277
41489
  let plain2 = null;
@@ -43856,7 +44068,7 @@ ${end.comment}` : end.comment;
43856
44068
  }
43857
44069
  }
43858
44070
  }
43859
- var AppAccountKeyUnlockError, AppAccountKeySealedBundle, MAX_BODY, REQUEST_MS3, SETTLE_MS, unavailable7, cancelled2, unsupported2, hex11, HEX322, AppCpAccountKeyControl;
44071
+ var AppAccountKeyUnlockError, AppAccountKeySealedBundle, MAX_BODY, REQUEST_MS3, SETTLE_MS, unavailable7, cancelled2, unsupported2, hex12, HEX322, AppCpAccountKeyControl;
43860
44072
  var init_account_key_host = __esm({
43861
44073
  "src/app-host/account-key-host.ts"() {
43862
44074
  "use strict";
@@ -43913,7 +44125,7 @@ ${end.comment}` : end.comment;
43913
44125
  unavailable7 = (reason) => new AccountKeyError("unavailable", "The account key service refused or was unreachable.", { reason });
43914
44126
  cancelled2 = () => new AccountKeyError("cancelled", "Account key request cancelled.");
43915
44127
  unsupported2 = () => unavailable7("not_supported");
43916
- hex11 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
44128
+ hex12 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
43917
44129
  HEX322 = /^[0-9a-f]{64}$/;
43918
44130
  AppCpAccountKeyControl = class {
43919
44131
  constructor(session, sign, options = {}) {
@@ -44035,7 +44247,7 @@ ${end.comment}` : end.comment;
44035
44247
  throw unavailable7("proof");
44036
44248
  }
44037
44249
  if (!(signature instanceof Uint8Array) || signature.length !== 64) throw unavailable7("proof");
44038
- return await this.request("GET", "/v1/next/account-key", { "x-mdbase-device-id": this.deviceId, "x-mdbase-challenge": text9, "x-mdbase-signature": hex11(signature) }, options);
44250
+ return await this.request("GET", "/v1/next/account-key", { "x-mdbase-device-id": this.deviceId, "x-mdbase-challenge": text9, "x-mdbase-signature": hex12(signature) }, options);
44039
44251
  } finally {
44040
44252
  nonce?.fill(0);
44041
44253
  signature?.fill(0);
@@ -44770,131 +44982,6 @@ ${end.comment}` : end.comment;
44770
44982
  }
44771
44983
  });
44772
44984
 
44773
- // src/app-host/sign-out-erase.ts
44774
- function bounded3(work, fallback2, ms = SIGN_OUT_ERASE_TIMEOUT_MS) {
44775
- let timer2;
44776
- return Promise.race([work.catch(() => fallback2), new Promise((resolve2) => {
44777
- timer2 = setTimeout(() => resolve2(fallback2), ms);
44778
- })]).finally(() => clearTimeout(timer2));
44779
- }
44780
- function deleteDatabase(name3) {
44781
- return bounded3(new Promise((resolve2) => {
44782
- const request3 = indexedDB.deleteDatabase(name3);
44783
- request3.onsuccess = () => resolve2(true);
44784
- request3.onerror = () => resolve2(false);
44785
- }), false);
44786
- }
44787
- function deviceCustodyDatabaseNames(scope) {
44788
- const { accountId, connectorId, deviceId, installationId } = scope;
44789
- const keyIds = [accountId, connectorId, deviceId, installationId].map(hex12).join(".");
44790
- return [
44791
- `mdbase.app.device-key-kek.v1.${keyIds}`,
44792
- `mdbase.app.device-keys.v1.${keyIds}`,
44793
- `mdbase.app.noise.v1.${lower(installationId)}.${lower(connectorId)}.${lower(deviceId)}`
44794
- ];
44795
- }
44796
- async function eraseUnattestedDeviceCustody(scope) {
44797
- try {
44798
- if (!globalThis.indexedDB) return false;
44799
- return (await Promise.all(deviceCustodyDatabaseNames(scope).map(deleteDatabase))).every(Boolean);
44800
- } catch {
44801
- return false;
44802
- }
44803
- }
44804
- function ledgerNames(scope) {
44805
- const cp = encodeURIComponent(scope.cpOrigin), unlabelled = `mdbase.app.installation.v1.${cp}.${scope.appId}`;
44806
- return [scope.owner === void 0 ? unlabelled : `mdbase.app.installation.v2.${cp}.${encodeURIComponent(scope.owner)}.${scope.appId}`, unlabelled];
44807
- }
44808
- async function otherDatabaseNames(scope, ledger, unlabelled) {
44809
- const others = new Set(scope.isolated ? [] : scope.databases);
44810
- if (!scope.isolated && scope.storageNamespace === void 0) others.add(unlabelled);
44811
- const { accountId: account, connectorId: connector, deviceId: device, installationId: installation } = scope;
44812
- if (account && connector && device && installation) {
44813
- for (const name3 of deviceCustodyDatabaseNames({ accountId: account, connectorId: connector, deviceId: device, installationId: installation })) others.add(name3);
44814
- const prefix = [account, connector, device, installation].map(lower).join(".");
44815
- const scoped = [`mdbase.app.cloud-copy-outcome.v1.${prefix}.`, `mdbase.app.private-bootstrap.v1.${prefix}.`];
44816
- for (const collection2 of scope.collectionIds) {
44817
- const id6 = lower(collection2);
44818
- for (const purpose of ["create", "join"]) others.add(`${scoped[0]}${id6}.${purpose}`);
44819
- for (const purpose of ["create", "enrol"]) others.add(`${scoped[1]}${id6}.${purpose}`);
44820
- }
44821
- const list5 = indexedDB.databases;
44822
- if (typeof list5 === "function") {
44823
- const found = await bounded3(list5.call(indexedDB), []);
44824
- for (const { name: name3 } of found) if (name3 && scoped.some((p) => name3.startsWith(p))) others.add(name3);
44825
- }
44826
- }
44827
- others.delete(ledger);
44828
- return [...others];
44829
- }
44830
- async function removeReplicas(account, installation) {
44831
- const storage = globalThis.navigator?.storage;
44832
- if (typeof storage?.getDirectory !== "function") return true;
44833
- return bounded3((async () => {
44834
- const root = await storage.getDirectory();
44835
- const prefix = `.mdbase-app-${lower(account)}-${lower(installation)}-`, names = [];
44836
- for await (const name3 of root.keys()) if (name3.startsWith(prefix)) names.push(name3);
44837
- let ok = true;
44838
- for (const name3 of names) {
44839
- try {
44840
- await root.removeEntry(name3, { recursive: true });
44841
- } catch {
44842
- ok = false;
44843
- }
44844
- }
44845
- return ok;
44846
- })(), false);
44847
- }
44848
- async function eraseAppCollectionAccess(scope, collectionId) {
44849
- try {
44850
- if (!globalThis.indexedDB || !scope.accountId || !scope.connectorId || !scope.deviceId || !scope.installationId) return false;
44851
- const collection2 = lower(collectionId), prefix = [scope.accountId, scope.connectorId, scope.deviceId, scope.installationId].map(lower).join(".");
44852
- const names = ["create", "join"].map((purpose) => `mdbase.app.cloud-copy-outcome.v1.${prefix}.${collection2}.${purpose}`);
44853
- names.push(...["create", "enrol"].map((purpose) => `mdbase.app.private-bootstrap.v1.${prefix}.${collection2}.${purpose}`));
44854
- const results2 = await Promise.all(names.map(deleteDatabase));
44855
- const storage = globalThis.navigator?.storage;
44856
- if (typeof storage?.getDirectory === "function") {
44857
- const root = await storage.getDirectory();
44858
- try {
44859
- await root.removeEntry(`.mdbase-app-${lower(scope.accountId)}-${lower(scope.installationId)}-${collection2}`, { recursive: true });
44860
- } catch (error5) {
44861
- if (!(error5 instanceof DOMException && error5.name === "NotFoundError")) return false;
44862
- }
44863
- }
44864
- return results2.every(Boolean);
44865
- } catch {
44866
- return false;
44867
- }
44868
- }
44869
- async function eraseAppInstallationData(scope) {
44870
- if (!globalThis.indexedDB) return Object.freeze({ ledger: false, complete: false });
44871
- const [current3, unlabelled] = ledgerNames(scope);
44872
- const ledger = await deleteDatabase(current3);
44873
- let others = null;
44874
- try {
44875
- others = await otherDatabaseNames(scope, current3, unlabelled);
44876
- } catch {
44877
- }
44878
- const results2 = others ? await Promise.all([...others, ...scope.isolated || scope.storageNamespace !== void 0 ? [] : [LOG_TOKEN_DATABASE]].map(deleteDatabase)) : [false];
44879
- const tokens2 = scope.storageNamespace === void 0 ? true : await bounded3(eraseAppLogTokens(scope), false);
44880
- const replicas = scope.accountId && scope.installationId ? await removeReplicas(scope.accountId, scope.installationId).catch(() => false) : true;
44881
- return Object.freeze({ ledger, complete: ledger && tokens2 && replicas && results2.every(Boolean) });
44882
- }
44883
- var SIGN_OUT_ERASE_TIMEOUT_MS, hex12, lower;
44884
- var init_sign_out_erase = __esm({
44885
- "src/app-host/sign-out-erase.ts"() {
44886
- "use strict";
44887
- init_log_token_cache();
44888
- init_codec();
44889
- SIGN_OUT_ERASE_TIMEOUT_MS = 5e3;
44890
- hex12 = (id6) => Array.from(uuidToBytes(id6), (b) => b.toString(16).padStart(2, "0")).join("");
44891
- lower = (id6) => {
44892
- uuidToBytes(id6);
44893
- return id6.toLowerCase();
44894
- };
44895
- }
44896
- });
44897
-
44898
44985
  // src/app-host/noise-custody.ts
44899
44986
  var bad10, equal9, AppWebNoiseCustody;
44900
44987
  var init_noise_custody = __esm({
@@ -51301,12 +51388,12 @@ ${end.comment}` : end.comment;
51301
51388
  // src/application/asset-pins.json
51302
51389
  var asset_pins_default = {
51303
51390
  runtime: {
51304
- sha256: "2f6dadfde367cb098f20ca0e2f95cb8ebca250ce7525755a0f56686a89822c3d",
51305
- bytes: 4203391,
51306
- maxBytes: 4203391,
51391
+ sha256: "22ab599e9f32fe8e72c42c388824380c90ab54ddccf331f4eaf695d47e54ea0b",
51392
+ bytes: 4201671,
51393
+ maxBytes: 4201671,
51307
51394
  source: {
51308
51395
  repository: "mdbase-dev/mdbase-connect",
51309
- commit: "b3505a0e268e9c97b1e46688311d66f7c9b70c2d"
51396
+ commit: "c106d4a6b427e2b9b39e725e5053d119d76833fd"
51310
51397
  }
51311
51398
  },
51312
51399
  sqlite: {
@@ -52055,7 +52142,7 @@ ${end.comment}` : end.comment;
52055
52142
 
52056
52143
  // src/app-host/unsynced-collection.ts
52057
52144
  init_collection_timezone();
52058
- var STORE2 = "unsynced";
52145
+ var STORE3 = "unsynced";
52059
52146
  var KEY2 = "current";
52060
52147
  var MOVED = "moved.";
52061
52148
  var UUID8 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
@@ -52097,7 +52184,7 @@ ${end.comment}` : end.comment;
52097
52184
  request3.onupgradeneeded = () => {
52098
52185
  try {
52099
52186
  if (abandoned || request3.result.objectStoreNames.length) throw fail9();
52100
- request3.result.createObjectStore(STORE2);
52187
+ request3.result.createObjectStore(STORE3);
52101
52188
  } catch {
52102
52189
  try {
52103
52190
  request3.transaction?.abort();
@@ -52107,7 +52194,7 @@ ${end.comment}` : end.comment;
52107
52194
  };
52108
52195
  request3.onsuccess = () => {
52109
52196
  finish();
52110
- if (abandoned || request3.result.objectStoreNames.length !== 1 || !request3.result.objectStoreNames.contains(STORE2)) {
52197
+ if (abandoned || request3.result.objectStoreNames.length !== 1 || !request3.result.objectStoreNames.contains(STORE3)) {
52111
52198
  request3.result.close();
52112
52199
  reject(fail9());
52113
52200
  return;
@@ -52120,11 +52207,11 @@ ${end.comment}` : end.comment;
52120
52207
  const db = await database(databaseName, signal);
52121
52208
  try {
52122
52209
  return await new Promise((resolve2, reject) => {
52123
- const tx = db.transaction(STORE2, make ? "readwrite" : "readonly", { durability: "strict" });
52210
+ const tx = db.transaction(STORE3, make ? "readwrite" : "readonly", { durability: "strict" });
52124
52211
  let result2 = null, problem7 = null;
52125
52212
  tx.onabort = tx.onerror = () => reject(problem7 ?? fail9());
52126
52213
  tx.oncomplete = () => resolve2(result2);
52127
- const rows2 = tx.objectStore(STORE2), read2 = rows2.get(key3);
52214
+ const rows2 = tx.objectStore(STORE3), read2 = rows2.get(key3);
52128
52215
  read2.onsuccess = () => {
52129
52216
  try {
52130
52217
  if (read2.result !== void 0) {
@@ -52149,11 +52236,11 @@ ${end.comment}` : end.comment;
52149
52236
  const db = await database(databaseName, signal);
52150
52237
  try {
52151
52238
  return await new Promise((resolve2, reject) => {
52152
- const tx = db.transaction(STORE2, "readwrite", { durability: "strict" });
52239
+ const tx = db.transaction(STORE3, "readwrite", { durability: "strict" });
52153
52240
  let result2, problem7 = null;
52154
52241
  tx.onabort = tx.onerror = () => reject(problem7 ?? fail9());
52155
52242
  tx.oncomplete = () => resolve2(result2);
52156
- work(tx.objectStore(STORE2), (value2) => {
52243
+ work(tx.objectStore(STORE3), (value2) => {
52157
52244
  result2 = value2;
52158
52245
  }, (error5) => {
52159
52246
  problem7 = error5;
@@ -55288,9 +55375,14 @@ ${end.comment}` : end.comment;
55288
55375
  var keptDetail = (update, previous, detail) => update.problem === void 0 || update.problem === previous ? detail : void 0;
55289
55376
  var liveOutcomes = /* @__PURE__ */ new Set(["collection_not_yet_migrated", "collection_migrating", "account_suspended", "update_required"]);
55290
55377
  var authorizeAppWebInstallation;
55378
+ var webSignInRecovery;
55291
55379
  var AppWebSignInSession = class {
55292
55380
  static {
55293
- authorizeAppWebInstallation = (session, options, recoverScope) => session.authorizeInstallation(options, recoverScope);
55381
+ authorizeAppWebInstallation = (session, options, recoverScope, scoped) => session.authorizeInstallation(options, recoverScope, scoped);
55382
+ webSignInRecovery = {
55383
+ references: (session) => session.flow ? installationRecovery.references(session.flow) : [],
55384
+ paired: (session, accountId) => session.scopedInstallationPaired(accountId)
55385
+ };
55294
55386
  }
55295
55387
  lifetime = new AbortController();
55296
55388
  // Origin store closes only AFTER native shutdown, not on the host abort.
@@ -55523,7 +55615,10 @@ ${end.comment}` : end.comment;
55523
55615
  });
55524
55616
  this.check();
55525
55617
  const view2 = this.flow.view();
55526
- if (view2.state === "paired") {
55618
+ if (installationRecovery.replacementPending(this.flow)) {
55619
+ for (const id6 of view2.collectionIds) this.removedScopes.add(id6);
55620
+ this.publish({ status: "blocked", problem: "installation_removed", collections: Object.freeze([]) });
55621
+ } else if (view2.state === "paired") {
55527
55622
  await this.openDevice(false, this.options.recoveryFor !== void 0);
55528
55623
  await this.abandonUnfinishedNativeChoice();
55529
55624
  if (this.flow.collectionConsentView()?.state === "pending") {
@@ -55550,13 +55645,13 @@ ${end.comment}` : end.comment;
55550
55645
  authorize(options = {}) {
55551
55646
  return this.authorizeInstallation(options, false);
55552
55647
  }
55553
- authorizeInstallation(options, recoverScope) {
55648
+ authorizeInstallation(options, recoverScope, scoped) {
55554
55649
  this.check();
55555
55650
  if (this.authorizationRateLimit && Date.now() < this.authorizationRetryAt) return Promise.reject(this.authorizationRateLimit);
55556
55651
  const poll = this.pending !== null && this.pending === this.polling ? this.pending : null;
55557
55652
  if (!this.flow || this.pending && !poll) return Promise.reject(failure2("busy"));
55558
55653
  const portal = this.options.openPortal();
55559
- if (!poll) return this.beginAuthorization(portal, options, recoverScope);
55654
+ if (!poll) return this.beginAuthorization(portal, options, recoverScope, scoped);
55560
55655
  return poll.catch(() => {
55561
55656
  }).then(() => {
55562
55657
  try {
@@ -55574,17 +55669,17 @@ ${end.comment}` : end.comment;
55574
55669
  portal.close();
55575
55670
  return this.getSnapshot();
55576
55671
  }
55577
- return this.beginAuthorization(portal, options, recoverScope);
55672
+ return this.beginAuthorization(portal, options, recoverScope, scoped);
55578
55673
  });
55579
55674
  }
55580
- beginAuthorization(portal, options, recoverScope) {
55675
+ beginAuthorization(portal, options, recoverScope, scoped) {
55581
55676
  const hint = { collectionHint: options.collectionHint ?? null };
55582
55677
  this.restoredPending = false;
55583
55678
  this.authorizationStartedAt = performance.now();
55584
55679
  this.publish({ timing: Object.freeze({ firstScreenMs: null, readyMs: null }), approval: null });
55585
55680
  return this.operation(async () => {
55586
55681
  try {
55587
- if (this.base.problem === "installation_removed") await this.replaceRemovedInstallation();
55682
+ if (this.base.problem === "installation_removed" || installationRecovery.replacementPending(this.flow)) await this.replaceRemovedInstallation(scoped);
55588
55683
  let verificationUri2 = null;
55589
55684
  if (this.flow.view().state === "paired") {
55590
55685
  await this.openDevice();
@@ -55600,7 +55695,7 @@ ${end.comment}` : end.comment;
55600
55695
  portal.close();
55601
55696
  return this.getSnapshot();
55602
55697
  }
55603
- await this.replaceRemovedInstallation();
55698
+ await this.replaceRemovedInstallation(scoped);
55604
55699
  }
55605
55700
  }
55606
55701
  if (verificationUri2 === null) {
@@ -56048,22 +56143,23 @@ ${end.comment}` : end.comment;
56048
56143
  this.changed();
56049
56144
  return true;
56050
56145
  }
56051
- async replaceRemovedInstallation() {
56146
+ async replaceRemovedInstallation(scoped) {
56052
56147
  const flow = this.flow;
56053
56148
  try {
56054
56149
  await replaceRefusedAppInstallation(flow, async () => {
56150
+ await scoped?.stopChildren();
56055
56151
  await this.closeSlots();
56056
56152
  this.check();
56057
- await this.installationLease?.release();
56058
- this.installationLease = null;
56059
- this.installation = null;
56060
- this.check();
56061
- });
56153
+ }, scoped?.childPaired);
56062
56154
  } catch (error5) {
56063
56155
  if (!flow.isCurrent()) this.flow = null;
56064
56156
  throw error5;
56065
56157
  }
56066
56158
  this.check();
56159
+ await this.installationLease?.release();
56160
+ this.installationLease = null;
56161
+ this.installation = null;
56162
+ this.check();
56067
56163
  this.attested = false;
56068
56164
  this.acknowledged = false;
56069
56165
  this.freshApproval = false;
@@ -56552,10 +56648,16 @@ ${end.comment}` : end.comment;
56552
56648
  /** SDK composition metadata only. Protected references never loan the
56553
56649
  * original credential/keys or carry consent into a fresh installation. */
56554
56650
  scopeRecoveryContext() {
56555
- if (!this.flow || !this.installation || this.flow.view().state !== "paired") return null;
56651
+ if (!this.flow || !this.installation || installationRecovery.replacementPending(this.flow)) return null;
56556
56652
  const view2 = this.flow.view();
56653
+ if (view2.state !== "paired") return null;
56557
56654
  return Object.freeze({ accountId: this.installation.scope.account, accountLabel: view2.accountEmail ?? (view2.accountLogin ? `@${view2.accountLogin}` : null), references: this.flow.collectionRecoveries() });
56558
56655
  }
56656
+ scopedInstallationPaired(accountId) {
56657
+ if (this.pending || !this.flow || installationRecovery.replacementPending(this.flow)) return false;
56658
+ const view2 = this.flow.view();
56659
+ return view2.state === "paired" && view2.accountId === accountId;
56660
+ }
56559
56661
  /** Explicit recovery gesture, after terminal access removal. Stop/fence and
56560
56662
  * erase ONLY the old collection scope before allocating its fresh local slot.
56561
56663
  * A failed stop/erase refuses recovery rather than releasing old authority. */
@@ -56564,7 +56666,13 @@ ${end.comment}` : end.comment;
56564
56666
  if (this.pending) return this.pending.catch(() => {
56565
56667
  }).then(() => this.prepareScopedRecovery(collectionId, expectedReplacement));
56566
56668
  return this.operation(async () => {
56567
- if (!this.flow || !this.installation || this.consentPending || this.flow.view().state !== "paired" || !this.flow.view().collectionIds.includes(collectionId)) throw failure2("binding");
56669
+ if (!this.flow || !this.installation || this.consentPending || this.flow.view().state !== "paired" || installationRecovery.replacementPending(this.flow)) throw failure2("binding");
56670
+ if (expectedReplacement !== void 0) {
56671
+ const reference2 = await installationRecovery.replaceRetained(this.flow, this.installation, collectionId, expectedReplacement);
56672
+ this.check();
56673
+ if (reference2 !== null) return Object.freeze({ accountId: this.installation.scope.account, reference: reference2 });
56674
+ }
56675
+ if (!this.flow.view().collectionIds.includes(collectionId)) throw failure2("binding");
56568
56676
  const refs = this.flow.collectionRecoveries(), slot = this.slots.get(collectionId);
56569
56677
  if (expectedReplacement === void 0 && !Object.hasOwn(refs, collectionId) && !this.scopeWasRemoved(collectionId)) throw failure2("binding");
56570
56678
  if (slot) {