@mdbase-dev/sdk 0.1.13 → 0.1.17

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.
Files changed (41) hide show
  1. package/dist/app-host/cloud-copy-host.js +6 -0
  2. package/dist/app-host/cloud-copy-host.js.map +1 -1
  3. package/dist/app-host/device-custody-error.d.ts +9 -0
  4. package/dist/app-host/device-custody-error.js +10 -0
  5. package/dist/app-host/device-custody-error.js.map +1 -0
  6. package/dist/app-host/device-key-idb.js +2 -1
  7. package/dist/app-host/device-key-idb.js.map +1 -1
  8. package/dist/app-host/device-key-provider.js +2 -1
  9. package/dist/app-host/device-key-provider.js.map +1 -1
  10. package/dist/app-host/installation-sign-in.d.ts +6 -2
  11. package/dist/app-host/installation-sign-in.js +7 -3
  12. package/dist/app-host/installation-sign-in.js.map +1 -1
  13. package/dist/app-host/noise-idb.js +2 -1
  14. package/dist/app-host/noise-idb.js.map +1 -1
  15. package/dist/app-host/sign-out-erase.d.ts +11 -0
  16. package/dist/app-host/sign-out-erase.js +27 -4
  17. package/dist/app-host/sign-out-erase.js.map +1 -1
  18. package/dist/app-host/web-sign-in-problem.js +3 -0
  19. package/dist/app-host/web-sign-in-problem.js.map +1 -1
  20. package/dist/application/asset-loader.js +6 -2
  21. package/dist/application/asset-loader.js.map +1 -1
  22. package/dist/application/asset-pins.json +4 -4
  23. package/dist/application/private-collections.d.ts +2 -1
  24. package/dist/application/private-collections.js +10 -3
  25. package/dist/application/private-collections.js.map +1 -1
  26. package/dist/application/worker.js +152 -120
  27. package/dist/browser/mdbase-sdk.js +222 -138
  28. package/dist/browser/mdbase-sdk.min.js +60 -60
  29. package/dist/client.d.ts +4 -3
  30. package/dist/client.js +6 -3
  31. package/dist/client.js.map +1 -1
  32. package/dist/describe-error.d.ts +1 -1
  33. package/dist/describe-error.js +7 -3
  34. package/dist/describe-error.js.map +1 -1
  35. package/dist/native/provenance.json +5 -5
  36. package/dist/native/runtime.wasm +0 -0
  37. package/dist/transport/noise-session.js +20 -5
  38. package/dist/transport/noise-session.js.map +1 -1
  39. package/dist/transport/relay-pipe.js +19 -4
  40. package/dist/transport/relay-pipe.js.map +1 -1
  41. package/package.json +1 -1
@@ -6970,7 +6970,7 @@ var MdbaseSDK = (() => {
6970
6970
  function connect(opts) {
6971
6971
  return MdbaseClient.connect(opts);
6972
6972
  }
6973
- var CHANGES_PAGE, VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, Write, LiveQuery, READ_METHODS, MdbaseClient;
6973
+ var CHANGES_PAGE, DEVICE_WAITS, VALIDATE_PAGE, BASES_DISCOVERY_UNREADABLE, Write, LiveQuery, READ_METHODS, MdbaseClient;
6974
6974
  var init_client = __esm({
6975
6975
  "src/client.ts"() {
6976
6976
  "use strict";
@@ -7004,6 +7004,7 @@ var MdbaseSDK = (() => {
7004
7004
  init_codec();
7005
7005
  init_wire();
7006
7006
  CHANGES_PAGE = 1e3;
7007
+ DEVICE_WAITS = /* @__PURE__ */ new Set(["no_device_online", "not_served"]);
7007
7008
  VALIDATE_PAGE = "validate-page-v1";
7008
7009
  BASES_DISCOVERY_UNREADABLE = "bases-discovery-unreadable-v1";
7009
7010
  Write = class {
@@ -7290,8 +7291,9 @@ var MdbaseSDK = (() => {
7290
7291
  if (this.ledgerStarted) this.updateDeferred();
7291
7292
  }
7292
7293
  /**
7293
- * Connect to a replica and say hello. With `waitForDevice`, a private collection with
7294
- * no device online keeps retrying (calling `onWaiting`) instead of failing.
7294
+ * Connect to a replica and say hello. With `waitForDevice`, a private collection whose
7295
+ * computer is offline or not serving it right now keeps retrying (calling `onWaiting`)
7296
+ * instead of failing.
7295
7297
  * A next-relay pre-live grant waits up to 30 seconds on this same connector.
7296
7298
  * This is initial hello only: no application request or unknown write is replayed.
7297
7299
  */
@@ -7337,7 +7339,7 @@ var MdbaseSDK = (() => {
7337
7339
  } catch (e) {
7338
7340
  if (signal?.aborted) throw stopped();
7339
7341
  const pending = nextRelay2 && isMdbaseError(e, "unavailable") && (e.reason === "grant_lease_expired" || e.reason === "authorization_unavailable");
7340
- if (!(pending || opts.waitForDevice && isMdbaseError(e, "unavailable") && e.reason === "no_device_online")) throw e;
7342
+ if (!(pending || opts.waitForDevice && isMdbaseError(e, "unavailable") && DEVICE_WAITS.has(e.reason ?? ""))) throw e;
7341
7343
  if (pending && !deadline2) {
7342
7344
  deadline2 = new AbortController();
7343
7345
  timeout2 = mdbaseError("unavailable", "The approved grant did not become live within 30 seconds", { reason: "grant_activation_timeout", details: e.toProblem().details });
@@ -9623,6 +9625,7 @@ var MdbaseSDK = (() => {
9623
9625
  PROBLEM_CODES = [
9624
9626
  // Collection availability.
9625
9627
  "device_offline",
9628
+ "device_not_serving",
9626
9629
  "desktop_update_required",
9627
9630
  "old_connector_running",
9628
9631
  "sync_required",
@@ -9661,6 +9664,7 @@ var MdbaseSDK = (() => {
9661
9664
  "account_confirmation_required",
9662
9665
  "recovery_required",
9663
9666
  "open_failed",
9667
+ "device_keys_unavailable",
9664
9668
  "busy",
9665
9669
  "open_in_another_tab",
9666
9670
  "not_authorized",
@@ -9761,6 +9765,7 @@ var MdbaseSDK = (() => {
9761
9765
  COPY = {
9762
9766
  // Private collections served by one of the account's computers (collection availability).
9763
9767
  device_offline: ["Your computer isn't online", "This collection is kept on your computer. Open the mdbase desktop app on a computer that has it, and this app connects as soon as it's online.", "wait", "info", true],
9768
+ device_not_serving: ["Your computer can't open this collection", "Your computer is online, but mdbase there isn't serving this collection right now. Open the mdbase desktop app on that computer to see why. This app connects as soon as it can.", "wait", "warning", true],
9764
9769
  desktop_update_required: ["Update mdbase on your computer", "The mdbase desktop app on the computer that has this collection is out of date. Update it there, then try again.", "update_app", "warning", false, "Get the update"],
9765
9770
  old_connector_running: ["Quit the old mdbase Connect app", "The old mdbase Connect app is still running on the computer that has this collection. Quit it there (including its menu-bar or tray icon), then open the mdbase desktop app.", "retry", "warning"],
9766
9771
  sync_required: ["Give this app access again", "Access to this collection changed since you approved this app. Approve it again to keep using the collection.", "approve", "warning", false, "Approve again"],
@@ -9798,6 +9803,7 @@ var MdbaseSDK = (() => {
9798
9803
  recovery_account_mismatch: ["Use a different account", "Sign in with the account you originally used for this collection to continue.", "approve", "info", false, "Use a different account"],
9799
9804
  recovery_required: ["Reload required", "The app stopped to keep your data safe. Reload to continue.", "reload", "error"],
9800
9805
  open_failed: ["Couldn't open your collection", "Something went wrong while opening it. Reload the app to try again.", "reload", "error"],
9806
+ device_keys_unavailable: ["Couldn't read this device's sign-in", "This browser couldn't open the keys this app uses to sign in to mdbase. Reload to try again. If it keeps happening, sign out of mdbase in this app and sign in again.", "reload", "error"],
9801
9807
  busy: BUSY,
9802
9808
  file_read_failed: ["Couldn't load the file", "mdbase couldn't finish downloading this file. Check your connection and try opening the collection again.", "retry", "warning"],
9803
9809
  file_read_idle: ["File download timed out", "The file download stopped making progress. Try opening the collection again.", "retry", "warning"],
@@ -9886,6 +9892,7 @@ var MdbaseSDK = (() => {
9886
9892
  };
9887
9893
  ALIASES = Object.assign(/* @__PURE__ */ Object.create(null), {
9888
9894
  no_device_online: "device_offline",
9895
+ not_served: "device_not_serving",
9889
9896
  collection_moved: "moved_to_next_runtime",
9890
9897
  client_update_required: "update_required",
9891
9898
  upgrade_required: "update_required",
@@ -9990,6 +9997,7 @@ var MdbaseSDK = (() => {
9990
9997
  NON_PROBLEMS = new Set(NON_PROBLEM_CODES);
9991
9998
  DEVELOPER = Object.assign(/* @__PURE__ */ Object.create(null), {
9992
9999
  device_offline: "Collection availability device_offline: no device serving this Private collection is connected to the relay.",
10000
+ device_not_serving: "Relay close not_served: the device holds a current grant for this Private collection but is not serving it (paused, opening, recovering or failed). Check the collection's status in mdbase on that computer; connect with waitForDevice keeps retrying.",
9993
10001
  desktop_update_required: "Collection availability desktop_update_required: the serving device's last relay connection was refused as incompatible.",
9994
10002
  old_connector_running: "Collection availability old_connector_running: the serving device reports a legacy connector still holding its collections.",
9995
10003
  device_approval_required: "Collection availability approval_required: no device has signed an approval for this app's grant yet.",
@@ -10011,6 +10019,7 @@ var MdbaseSDK = (() => {
10011
10019
  browser_unsupported: "browser_unsupported: the SDK's upfront capability probe found a required browser feature missing (Web Crypto/X25519, AbortSignal.any, Web Locks, BroadcastChannel, IndexedDB, Worker/MessageChannel or crypto.randomUUID); see the MdbaseError details for the missing tokens.",
10012
10020
  application_storage_unavailable: "application_storage_unavailable: navigator.storage.getDirectory() (OPFS) is absent or rejected, as in private browsing; the local replica cannot be kept on this device.",
10013
10021
  storage_may_be_evicted: "storage_may_be_evicted: replica edits are pending for at least 30 seconds or while disconnected on nonpersistent storage (`storage_may_be_evicted` in snapshot.sync.attention); only a log-confirmed receipt counts as saved.",
10022
+ device_keys_unavailable: "device_keys_unavailable: this installation's device custody in IndexedDB (key encryption key, device keys or Noise vault) could not be opened or did not hold the attested device. Before attestation the SDK recreates it by itself; after attestation only signOut() and a fresh sign-in replace it.",
10014
10023
  sign_out_pending_writes: "sign_out_pending_writes: unconfirmed writes are still queued on this device; signOut({discard: true}) discards them."
10015
10024
  });
10016
10025
  NAME2 = /^[a-z][a-z0-9_-]{0,127}$/;
@@ -27886,8 +27895,12 @@ ${end.comment}` : end.comment;
27886
27895
  if (installation.isCurrent() !== true || installation.scope.account !== s.accountId || installation.scope.installation !== s.installationId) throw fail3("fenced");
27887
27896
  }
27888
27897
  /** Commit the explicit original native attempt BEFORE KEK/provider/keys/native.
27889
- * Once attempted, even missing/partial stores require EXISTING restore or visible
27890
- * recovery; never infer fresh from a null key/Noise record. */
27898
+ * The durable proof decides the mode, never a null key/Noise record: once the
27899
+ * device signed its enrolment (proof saved before the attest request), its
27900
+ * keys are the installation's and only an EXISTING restore may use them.
27901
+ * Before that nothing of the device has left this browser, so an attempt that
27902
+ * was cut off (a reload, a closed tab, an aborted request) starts over FRESH
27903
+ * from empty stores instead of being stuck with half of them. */
27891
27904
  prepareOriginalDevice(installation) {
27892
27905
  const callback = installation.isCurrent;
27893
27906
  const current3 = () => {
@@ -27901,7 +27914,7 @@ ${end.comment}` : end.comment;
27901
27914
  };
27902
27915
  return this.exclusive(async () => {
27903
27916
  if (!current3()) throw fail3("fenced");
27904
- const mode = this.state.nativeStarted ? "existing" : "fresh";
27917
+ const mode = this.state.proof ? "existing" : "fresh";
27905
27918
  if (!this.state.nativeStarted) await this.save({ ...this.state, nativeStarted: true });
27906
27919
  if (!current3()) throw fail3("fenced");
27907
27920
  return Object.freeze({ mode, pin: Object.freeze({ ...this.confirmedSelection(), isCurrent: current3, installationOwned: current3 }) });
@@ -36731,9 +36744,21 @@ ${end.comment}` : end.comment;
36731
36744
  }
36732
36745
  ws.binaryType = "arraybuffer";
36733
36746
  let open2 = false;
36747
+ let onmessage = null;
36748
+ let onclose = null;
36734
36749
  const carrier = {
36735
- onmessage: null,
36736
- onclose: null,
36750
+ get onmessage() {
36751
+ return onmessage;
36752
+ },
36753
+ set onmessage(f) {
36754
+ onmessage = f;
36755
+ },
36756
+ get onclose() {
36757
+ return onclose;
36758
+ },
36759
+ set onclose(f) {
36760
+ onclose = f;
36761
+ },
36737
36762
  send(m2) {
36738
36763
  ws.send(m2);
36739
36764
  },
@@ -36756,8 +36781,8 @@ ${end.comment}` : end.comment;
36756
36781
  };
36757
36782
  ws.onmessage = (ev) => {
36758
36783
  const d = ev.data;
36759
- if (d instanceof ArrayBuffer) carrier.onmessage?.(new Uint8Array(d));
36760
- else if (ArrayBuffer.isView(d)) carrier.onmessage?.(new Uint8Array(d.buffer, d.byteOffset, d.byteLength));
36784
+ if (d instanceof ArrayBuffer) onmessage?.(new Uint8Array(d));
36785
+ else if (ArrayBuffer.isView(d)) onmessage?.(new Uint8Array(d.buffer, d.byteOffset, d.byteLength));
36761
36786
  };
36762
36787
  ws.onerror = () => {
36763
36788
  };
@@ -36766,7 +36791,7 @@ ${end.comment}` : end.comment;
36766
36791
  if (!open2) {
36767
36792
  signal?.removeEventListener("abort", onAbort);
36768
36793
  reject(err2 ?? mdbaseError("unavailable", `cannot connect to ${url2}`));
36769
- } else carrier.onclose?.(err2);
36794
+ } else onclose?.(err2);
36770
36795
  };
36771
36796
  });
36772
36797
  }
@@ -36888,9 +36913,21 @@ ${end.comment}` : end.comment;
36888
36913
  let opened = false;
36889
36914
  let settled2 = false;
36890
36915
  let buf = new Uint8Array(0);
36916
+ let onmessage = null;
36917
+ let onclose = null;
36891
36918
  const carrier = {
36892
- onmessage: null,
36893
- onclose: null,
36919
+ get onmessage() {
36920
+ return onmessage;
36921
+ },
36922
+ set onmessage(f) {
36923
+ onmessage = f;
36924
+ },
36925
+ get onclose() {
36926
+ return onclose;
36927
+ },
36928
+ set onclose(f) {
36929
+ onclose = f;
36930
+ },
36894
36931
  send(m2) {
36895
36932
  if (m2.length > 65535) throw mdbaseError("too_large", "Noise message over 65535 bytes");
36896
36933
  const f = new Uint8Array(4 + m2.length);
@@ -36910,7 +36947,7 @@ ${end.comment}` : end.comment;
36910
36947
  settled2 = true;
36911
36948
  signal?.removeEventListener("abort", onAbort);
36912
36949
  reject(e);
36913
- } else carrier.onclose?.(e);
36950
+ } else onclose?.(e);
36914
36951
  };
36915
36952
  const onAbort = () => {
36916
36953
  ws.close();
@@ -36969,7 +37006,7 @@ ${end.comment}` : end.comment;
36969
37006
  return;
36970
37007
  }
36971
37008
  if (b.length - off - 4 < len) break;
36972
- carrier.onmessage?.(b.slice(off + 4, off + 4 + len));
37009
+ onmessage?.(b.slice(off + 4, off + 4 + len));
36973
37010
  off += 4 + len;
36974
37011
  }
36975
37012
  buf = b.slice(off);
@@ -43412,6 +43449,21 @@ ${end.comment}` : end.comment;
43412
43449
  }
43413
43450
  });
43414
43451
 
43452
+ // src/app-host/device-custody-error.ts
43453
+ var AppDeviceCustodyError;
43454
+ var init_device_custody_error = __esm({
43455
+ "src/app-host/device-custody-error.ts"() {
43456
+ "use strict";
43457
+ AppDeviceCustodyError = class extends Error {
43458
+ reason = "device_keys_unavailable";
43459
+ constructor(message3) {
43460
+ super(message3);
43461
+ this.name = "AppDeviceCustodyError";
43462
+ }
43463
+ };
43464
+ }
43465
+ });
43466
+
43415
43467
  // src/app-host/device-key-provider.ts
43416
43468
  function key2(value2) {
43417
43469
  if (typeof globalThis.CryptoKey !== "function" || !(value2 instanceof CryptoKey) || value2.type !== "secret" || value2.extractable || value2.algorithm.name !== "AES-GCM" || value2.algorithm.length !== 256 || value2.usages.length !== 2 || !value2.usages.includes("encrypt") || !value2.usages.includes("decrypt")) throw fail11();
@@ -43428,9 +43480,10 @@ ${end.comment}` : end.comment;
43428
43480
  "use strict";
43429
43481
  init_app_origin();
43430
43482
  init_codec();
43483
+ init_device_custody_error();
43431
43484
  STORE6 = "device-key-kek";
43432
43485
  KEY5 = "original-device-kek";
43433
- fail11 = () => new Error("app device key provider unavailable; preserve storage and reopen");
43486
+ fail11 = () => new AppDeviceCustodyError("app device key provider unavailable; preserve storage and reopen");
43434
43487
  AppIndexedDbDeviceKeyProvider = class _AppIndexedDbDeviceKeyProvider {
43435
43488
  constructor(source, origin4, lifetime) {
43436
43489
  this.source = source;
@@ -43616,10 +43669,11 @@ ${end.comment}` : end.comment;
43616
43669
  "use strict";
43617
43670
  init_app_origin();
43618
43671
  init_codec();
43672
+ init_device_custody_error();
43619
43673
  STORE7 = "original-device-keys";
43620
43674
  KEY6 = "custody";
43621
43675
  MAX5 = 256;
43622
- fail12 = () => new Error("app device key custody store unavailable");
43676
+ fail12 = () => new AppDeviceCustodyError("app device key custody store unavailable");
43623
43677
  AppIndexedDbDeviceKeyProtectedStore = class _AppIndexedDbDeviceKeyProtectedStore {
43624
43678
  constructor(db, source, scope, namespace2, origin4) {
43625
43679
  this.db = db;
@@ -43941,10 +43995,11 @@ ${end.comment}` : end.comment;
43941
43995
  "use strict";
43942
43996
  init_app_origin();
43943
43997
  init_codec();
43998
+ init_device_custody_error();
43944
43999
  STORE8 = "opaque-noise";
43945
44000
  KEY7 = "custody";
43946
44001
  MAX6 = 4096;
43947
- fail14 = () => new Error("app noise custody store unavailable");
44002
+ fail14 = () => new AppDeviceCustodyError("app noise custody store unavailable");
43948
44003
  AppIndexedDbNoiseProtectedStore = class _AppIndexedDbNoiseProtectedStore {
43949
44004
  constructor(db, source, pins, origin4) {
43950
44005
  this.db = db;
@@ -44107,6 +44162,131 @@ ${end.comment}` : end.comment;
44107
44162
  }
44108
44163
  });
44109
44164
 
44165
+ // src/app-host/sign-out-erase.ts
44166
+ function bounded3(work, fallback2, ms = SIGN_OUT_ERASE_TIMEOUT_MS) {
44167
+ let timer2;
44168
+ return Promise.race([work.catch(() => fallback2), new Promise((resolve2) => {
44169
+ timer2 = setTimeout(() => resolve2(fallback2), ms);
44170
+ })]).finally(() => clearTimeout(timer2));
44171
+ }
44172
+ function deleteDatabase(name3) {
44173
+ return bounded3(new Promise((resolve2) => {
44174
+ const request3 = indexedDB.deleteDatabase(name3);
44175
+ request3.onsuccess = () => resolve2(true);
44176
+ request3.onerror = () => resolve2(false);
44177
+ }), false);
44178
+ }
44179
+ function deviceCustodyDatabaseNames(scope) {
44180
+ const { accountId, connectorId, deviceId, installationId } = scope;
44181
+ const keyIds = [accountId, connectorId, deviceId, installationId].map(hex12).join(".");
44182
+ return [
44183
+ `mdbase.app.device-key-kek.v1.${keyIds}`,
44184
+ `mdbase.app.device-keys.v1.${keyIds}`,
44185
+ `mdbase.app.noise.v1.${lower(installationId)}.${lower(connectorId)}.${lower(deviceId)}`
44186
+ ];
44187
+ }
44188
+ async function eraseUnattestedDeviceCustody(scope) {
44189
+ try {
44190
+ if (!globalThis.indexedDB) return false;
44191
+ return (await Promise.all(deviceCustodyDatabaseNames(scope).map(deleteDatabase))).every(Boolean);
44192
+ } catch {
44193
+ return false;
44194
+ }
44195
+ }
44196
+ function ledgerNames(scope) {
44197
+ const cp = encodeURIComponent(scope.cpOrigin), unlabelled = `mdbase.app.installation.v1.${cp}.${scope.appId}`;
44198
+ return [scope.owner === void 0 ? unlabelled : `mdbase.app.installation.v2.${cp}.${encodeURIComponent(scope.owner)}.${scope.appId}`, unlabelled];
44199
+ }
44200
+ async function otherDatabaseNames(scope, ledger, unlabelled) {
44201
+ const others = new Set(scope.isolated ? [] : scope.databases);
44202
+ if (!scope.isolated && scope.storageNamespace === void 0) others.add(unlabelled);
44203
+ const { accountId: account, connectorId: connector, deviceId: device, installationId: installation } = scope;
44204
+ if (account && connector && device && installation) {
44205
+ for (const name3 of deviceCustodyDatabaseNames({ accountId: account, connectorId: connector, deviceId: device, installationId: installation })) others.add(name3);
44206
+ const prefix = [account, connector, device, installation].map(lower).join(".");
44207
+ const scoped = [`mdbase.app.cloud-copy-outcome.v1.${prefix}.`, `mdbase.app.private-bootstrap.v1.${prefix}.`];
44208
+ for (const collection2 of scope.collectionIds) {
44209
+ const id6 = lower(collection2);
44210
+ for (const purpose of ["create", "join"]) others.add(`${scoped[0]}${id6}.${purpose}`);
44211
+ for (const purpose of ["create", "enrol"]) others.add(`${scoped[1]}${id6}.${purpose}`);
44212
+ }
44213
+ const list5 = indexedDB.databases;
44214
+ if (typeof list5 === "function") {
44215
+ const found = await bounded3(list5.call(indexedDB), []);
44216
+ for (const { name: name3 } of found) if (name3 && scoped.some((p) => name3.startsWith(p))) others.add(name3);
44217
+ }
44218
+ }
44219
+ others.delete(ledger);
44220
+ return [...others];
44221
+ }
44222
+ async function removeReplicas(account, installation) {
44223
+ const storage = globalThis.navigator?.storage;
44224
+ if (typeof storage?.getDirectory !== "function") return true;
44225
+ return bounded3((async () => {
44226
+ const root = await storage.getDirectory();
44227
+ const prefix = `.mdbase-app-${lower(account)}-${lower(installation)}-`, names = [];
44228
+ for await (const name3 of root.keys()) if (name3.startsWith(prefix)) names.push(name3);
44229
+ let ok = true;
44230
+ for (const name3 of names) {
44231
+ try {
44232
+ await root.removeEntry(name3, { recursive: true });
44233
+ } catch {
44234
+ ok = false;
44235
+ }
44236
+ }
44237
+ return ok;
44238
+ })(), false);
44239
+ }
44240
+ async function eraseAppCollectionAccess(scope, collectionId) {
44241
+ try {
44242
+ if (!globalThis.indexedDB || !scope.accountId || !scope.connectorId || !scope.deviceId || !scope.installationId) return false;
44243
+ const collection2 = lower(collectionId), prefix = [scope.accountId, scope.connectorId, scope.deviceId, scope.installationId].map(lower).join(".");
44244
+ const names = ["create", "join"].map((purpose) => `mdbase.app.cloud-copy-outcome.v1.${prefix}.${collection2}.${purpose}`);
44245
+ names.push(...["create", "enrol"].map((purpose) => `mdbase.app.private-bootstrap.v1.${prefix}.${collection2}.${purpose}`));
44246
+ const results2 = await Promise.all(names.map(deleteDatabase));
44247
+ const storage = globalThis.navigator?.storage;
44248
+ if (typeof storage?.getDirectory === "function") {
44249
+ const root = await storage.getDirectory();
44250
+ try {
44251
+ await root.removeEntry(`.mdbase-app-${lower(scope.accountId)}-${lower(scope.installationId)}-${collection2}`, { recursive: true });
44252
+ } catch (error5) {
44253
+ if (!(error5 instanceof DOMException && error5.name === "NotFoundError")) return false;
44254
+ }
44255
+ }
44256
+ return results2.every(Boolean);
44257
+ } catch {
44258
+ return false;
44259
+ }
44260
+ }
44261
+ async function eraseAppInstallationData(scope) {
44262
+ if (!globalThis.indexedDB) return Object.freeze({ ledger: false, complete: false });
44263
+ const [current3, unlabelled] = ledgerNames(scope);
44264
+ const ledger = await deleteDatabase(current3);
44265
+ let others = null;
44266
+ try {
44267
+ others = await otherDatabaseNames(scope, current3, unlabelled);
44268
+ } catch {
44269
+ }
44270
+ const results2 = others ? await Promise.all([...others, ...scope.isolated || scope.storageNamespace !== void 0 ? [] : [LOG_TOKEN_DATABASE]].map(deleteDatabase)) : [false];
44271
+ const tokens2 = scope.storageNamespace === void 0 ? true : await bounded3(eraseAppLogTokens(scope), false);
44272
+ const replicas = scope.accountId && scope.installationId ? await removeReplicas(scope.accountId, scope.installationId).catch(() => false) : true;
44273
+ return Object.freeze({ ledger, complete: ledger && tokens2 && replicas && results2.every(Boolean) });
44274
+ }
44275
+ var SIGN_OUT_ERASE_TIMEOUT_MS, hex12, lower;
44276
+ var init_sign_out_erase = __esm({
44277
+ "src/app-host/sign-out-erase.ts"() {
44278
+ "use strict";
44279
+ init_log_token_cache();
44280
+ init_codec();
44281
+ SIGN_OUT_ERASE_TIMEOUT_MS = 5e3;
44282
+ hex12 = (id6) => Array.from(uuidToBytes(id6), (b) => b.toString(16).padStart(2, "0")).join("");
44283
+ lower = (id6) => {
44284
+ uuidToBytes(id6);
44285
+ return id6.toLowerCase();
44286
+ };
44287
+ }
44288
+ });
44289
+
44110
44290
  // src/app-host/noise-custody.ts
44111
44291
  var bad10, equal9, AppWebNoiseCustody;
44112
44292
  var init_noise_custody = __esm({
@@ -44302,7 +44482,7 @@ ${end.comment}` : end.comment;
44302
44482
  });
44303
44483
 
44304
44484
  // src/app-host/device-registration.ts
44305
- var AppDeviceRegistrationError, fail15, hex12, AppCpDeviceRegistration;
44485
+ var AppDeviceRegistrationError, fail15, hex13, AppCpDeviceRegistration;
44306
44486
  var init_device_registration = __esm({
44307
44487
  "src/app-host/device-registration.ts"() {
44308
44488
  "use strict";
@@ -44317,7 +44497,7 @@ ${end.comment}` : end.comment;
44317
44497
  reason;
44318
44498
  };
44319
44499
  fail15 = (r) => new AppDeviceRegistrationError(r);
44320
- hex12 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
44500
+ hex13 = (b) => Array.from(b, (v) => v.toString(16).padStart(2, "0")).join("");
44321
44501
  AppCpDeviceRegistration = class {
44322
44502
  constructor(runtime2, session, custody, persistence, options = {}) {
44323
44503
  this.runtime = runtime2;
@@ -44437,7 +44617,7 @@ ${end.comment}` : end.comment;
44437
44617
  const proof2 = this.runtime.signCpEnrol(challenge);
44438
44618
  this.check(options.signal);
44439
44619
  signature = proof2.signature;
44440
- const result2 = await this.json("/v1/next/devices", bearer, JSON.stringify({ device_id: this.scope.deviceId, kind: this.scope.kind, capabilities: ["collection_mode_switch_v1"], challenge: issued.challenge, sign_pk: hex12(proof2.signPublicKey), kem_pk: hex12(proof2.kemPublicKey), noise_pk: hex12(proof2.noisePublicKey), sig: hex12(signature) }), options.signal);
44620
+ const result2 = await this.json("/v1/next/devices", bearer, JSON.stringify({ device_id: this.scope.deviceId, kind: this.scope.kind, capabilities: ["collection_mode_switch_v1"], challenge: issued.challenge, sign_pk: hex13(proof2.signPublicKey), kem_pk: hex13(proof2.kemPublicKey), noise_pk: hex13(proof2.noisePublicKey), sig: hex13(signature) }), options.signal);
44441
44621
  this.check(options.signal);
44442
44622
  if (result2.device_id !== this.scope.deviceId) throw fail15("response");
44443
44623
  const receipt4 = Object.freeze({ connectorId: this.scope.connectorId, deviceId: this.scope.deviceId, installationId: this.scope.installationId, signPublicKey: new Uint8Array(proof2.signPublicKey), kemPublicKey: new Uint8Array(proof2.kemPublicKey), noisePublicKey: new Uint8Array(proof2.noisePublicKey) });
@@ -44496,6 +44676,8 @@ ${end.comment}` : end.comment;
44496
44676
  init_device_key_idb();
44497
44677
  init_device_key_custody();
44498
44678
  init_noise_idb();
44679
+ init_device_custody_error();
44680
+ init_sign_out_erase();
44499
44681
  init_noise_custody();
44500
44682
  init_device_registration();
44501
44683
  init_wasm_runtime();
@@ -44718,6 +44900,8 @@ ${end.comment}` : end.comment;
44718
44900
  host.signIn = signIn;
44719
44901
  const prepared2 = await signIn.prepareOriginalDevice(installation);
44720
44902
  host.check(signal);
44903
+ if (prepared2.mode === "fresh" && !await eraseUnattestedDeviceCustody(prepared2.pin)) throw new AppDeviceCustodyError("an unfinished device creation could not be cleared");
44904
+ host.check(signal);
44721
44905
  const { custody, restored } = await host.openOwnedDevice({ mode: prepared2.mode, signal, loadRuntime, requireReceipt: false });
44722
44906
  host.originalCustody = custody;
44723
44907
  if (restored?.receipt && signIn.view().state !== "paired") throw fail16("recovery_required");
@@ -50518,8 +50702,8 @@ ${end.comment}` : end.comment;
50518
50702
  try {
50519
50703
  check(signal);
50520
50704
  if (!response2.ok || response2.redirected || response2.url && response2.url !== url2.href) throw error("application_asset_response");
50521
- const length = response2.headers.get("content-length");
50522
- if (length !== null && (!/^(?:0|[1-9][0-9]*)$/.test(length) || Number(length) !== asset.bytes)) throw error("application_asset_binding");
50705
+ const length = response2.headers.get("content-length"), encoding = response2.headers.get("content-encoding");
50706
+ if (length !== null && (encoding === null || encoding.trim().toLowerCase() === "identity") && (!/^(?:0|[1-9][0-9]*)$/.test(length) || Number(length) !== asset.bytes)) throw error("application_asset_binding");
50523
50707
  const bytes10 = new Uint8Array(asset.bytes);
50524
50708
  let offset = 0;
50525
50709
  while (true) {
@@ -50571,12 +50755,12 @@ ${end.comment}` : end.comment;
50571
50755
  // src/application/asset-pins.json
50572
50756
  var asset_pins_default = {
50573
50757
  runtime: {
50574
- sha256: "cba629850dfc71280d50dcad3f5f79f186f7ee3930d288f1d9ad03d70f556bec",
50575
- bytes: 3981232,
50576
- maxBytes: 3981232,
50758
+ sha256: "ce2cd92219b1102ebdfeff29b17ab128327802656c81f546510feb53b95df063",
50759
+ bytes: 3981462,
50760
+ maxBytes: 3981462,
50577
50761
  source: {
50578
50762
  repository: "mdbase-dev/mdbase-connect",
50579
- commit: "e0b0fe302125005eb093a0afe565aec364816b16"
50763
+ commit: "239edbf28e896612bd0be9493f0668394751473e"
50580
50764
  }
50581
50765
  },
50582
50766
  sqlite: {
@@ -52431,13 +52615,17 @@ ${end.comment}` : end.comment;
52431
52615
  }
52432
52616
  this.set(open2, { status: "opening", problem: null });
52433
52617
  await checkBinding();
52434
- const client = await (this.options.connect ?? defaultConnect(this.options.declaration))(grants, collectionId, signal);
52618
+ const client = await (this.options.connect ?? defaultConnect(this.options.declaration))(grants, collectionId, signal, (why) => {
52619
+ if (this.open === open2 && !signal.aborted && (why.reason === "not_served" || why.reason === "no_device_online"))
52620
+ this.set(open2, { status: "blocked", problem: problemOf3(why), problemDetail: problemDetailOf(why), readiness: readiness(false, null) });
52621
+ });
52435
52622
  if (this.open !== open2 || signal.aborted || client.collection !== collectionId) {
52436
52623
  client.close();
52437
52624
  if (this.open === open2 && !signal.aborted) throw mdbaseError("invalid_request", "a different collection opened", "collection_mismatch");
52438
52625
  return;
52439
52626
  }
52440
52627
  open2.client = client;
52628
+ if (open2.state.status === "blocked") this.set(open2, { status: "opening", problem: null, readiness: readiness(true, null) });
52441
52629
  open2.setup = grants.setup(client);
52442
52630
  open2.connection = Object.freeze({
52443
52631
  id: collectionId,
@@ -52580,9 +52768,9 @@ ${end.comment}` : end.comment;
52580
52768
  }
52581
52769
  };
52582
52770
  function defaultConnect(declaration) {
52583
- return async (grants, collectionId, signal) => {
52771
+ return async (grants, collectionId, signal, onWaiting) => {
52584
52772
  const { connect: connect2 } = await Promise.resolve().then(() => (init_client(), client_exports));
52585
- return connect2({ connector: grants.connector(collectionId), app: { name: declaration.id, version: "1" }, signal });
52773
+ return connect2({ connector: grants.connector(collectionId), app: { name: declaration.id, version: "1" }, signal, waitForDevice: true, onWaiting });
52586
52774
  };
52587
52775
  }
52588
52776
 
@@ -54329,6 +54517,7 @@ ${end.comment}` : end.comment;
54329
54517
  init_private_bootstrap();
54330
54518
  init_account_key_host();
54331
54519
  init_owner();
54520
+ init_device_custody_error();
54332
54521
  init_cp_problem();
54333
54522
  var reasons = /* @__PURE__ */ new Set(["binding", "fenced", "busy", "open_in_another_tab", "account_confirmation_required", "recovery_account_mismatch", "outcome_unknown", "response", "refused", "expired", "recovery_required", "unavailable", "collection_migrating", "collection_not_yet_migrated", "account_suspended", "update_required", "private_device_limit", "private_device_not_allowed"]);
54334
54523
  var domCodes = /* @__PURE__ */ new Set(["AbortError", "ConstraintError", "DataCloneError", "InvalidStateError", "NotAllowedError", "NotFoundError", "NotReadableError", "OperationError", "QuotaExceededError", "SecurityError", "TimeoutError", "TransactionInactiveError", "UnknownError", "VersionError"]);
@@ -54363,6 +54552,7 @@ ${end.comment}` : end.comment;
54363
54552
  return reasons.has(code) ? result(code, name3, code, extra) : result("open_failed", name3, null, extra);
54364
54553
  }
54365
54554
  }
54555
+ if (error5 instanceof AppDeviceCustodyError) return result(error5.reason, "AppDeviceCustodyError", error5.reason);
54366
54556
  if (error5 instanceof AppReplicaOwnerError && error5.reason === "busy") return result("open_in_another_tab", "AppReplicaOwnerError", "busy");
54367
54557
  if (error5 instanceof MdbaseError) {
54368
54558
  const code = isErrorCode(error5.code) ? error5.code : null;
@@ -54384,113 +54574,7 @@ ${end.comment}` : end.comment;
54384
54574
  init_cloud_copy_bootstrap();
54385
54575
  init_app_environment();
54386
54576
  init_owner();
54387
-
54388
- // src/app-host/sign-out-erase.ts
54389
- init_log_token_cache();
54390
- init_codec();
54391
- var SIGN_OUT_ERASE_TIMEOUT_MS = 5e3;
54392
- var hex13 = (id6) => Array.from(uuidToBytes(id6), (b) => b.toString(16).padStart(2, "0")).join("");
54393
- var lower = (id6) => {
54394
- uuidToBytes(id6);
54395
- return id6.toLowerCase();
54396
- };
54397
- function bounded3(work, fallback2, ms = SIGN_OUT_ERASE_TIMEOUT_MS) {
54398
- let timer2;
54399
- return Promise.race([work.catch(() => fallback2), new Promise((resolve2) => {
54400
- timer2 = setTimeout(() => resolve2(fallback2), ms);
54401
- })]).finally(() => clearTimeout(timer2));
54402
- }
54403
- function deleteDatabase(name3) {
54404
- return bounded3(new Promise((resolve2) => {
54405
- const request3 = indexedDB.deleteDatabase(name3);
54406
- request3.onsuccess = () => resolve2(true);
54407
- request3.onerror = () => resolve2(false);
54408
- }), false);
54409
- }
54410
- function ledgerNames(scope) {
54411
- const cp = encodeURIComponent(scope.cpOrigin), unlabelled = `mdbase.app.installation.v1.${cp}.${scope.appId}`;
54412
- return [scope.owner === void 0 ? unlabelled : `mdbase.app.installation.v2.${cp}.${encodeURIComponent(scope.owner)}.${scope.appId}`, unlabelled];
54413
- }
54414
- async function otherDatabaseNames(scope, ledger, unlabelled) {
54415
- const others = new Set(scope.isolated ? [] : scope.databases);
54416
- if (!scope.isolated && scope.storageNamespace === void 0) others.add(unlabelled);
54417
- const { accountId: account, connectorId: connector, deviceId: device, installationId: installation } = scope;
54418
- if (account && connector && device && installation) {
54419
- const keyIds = [account, connector, device, installation].map(hex13).join(".");
54420
- others.add(`mdbase.app.device-key-kek.v1.${keyIds}`);
54421
- others.add(`mdbase.app.device-keys.v1.${keyIds}`);
54422
- others.add(`mdbase.app.noise.v1.${lower(installation)}.${lower(connector)}.${lower(device)}`);
54423
- const prefix = [account, connector, device, installation].map(lower).join(".");
54424
- const scoped = [`mdbase.app.cloud-copy-outcome.v1.${prefix}.`, `mdbase.app.private-bootstrap.v1.${prefix}.`];
54425
- for (const collection2 of scope.collectionIds) {
54426
- const id6 = lower(collection2);
54427
- for (const purpose of ["create", "join"]) others.add(`${scoped[0]}${id6}.${purpose}`);
54428
- for (const purpose of ["create", "enrol"]) others.add(`${scoped[1]}${id6}.${purpose}`);
54429
- }
54430
- const list5 = indexedDB.databases;
54431
- if (typeof list5 === "function") {
54432
- const found = await bounded3(list5.call(indexedDB), []);
54433
- for (const { name: name3 } of found) if (name3 && scoped.some((p) => name3.startsWith(p))) others.add(name3);
54434
- }
54435
- }
54436
- others.delete(ledger);
54437
- return [...others];
54438
- }
54439
- async function removeReplicas(account, installation) {
54440
- const storage = globalThis.navigator?.storage;
54441
- if (typeof storage?.getDirectory !== "function") return true;
54442
- return bounded3((async () => {
54443
- const root = await storage.getDirectory();
54444
- const prefix = `.mdbase-app-${lower(account)}-${lower(installation)}-`, names = [];
54445
- for await (const name3 of root.keys()) if (name3.startsWith(prefix)) names.push(name3);
54446
- let ok = true;
54447
- for (const name3 of names) {
54448
- try {
54449
- await root.removeEntry(name3, { recursive: true });
54450
- } catch {
54451
- ok = false;
54452
- }
54453
- }
54454
- return ok;
54455
- })(), false);
54456
- }
54457
- async function eraseAppCollectionAccess(scope, collectionId) {
54458
- try {
54459
- if (!globalThis.indexedDB || !scope.accountId || !scope.connectorId || !scope.deviceId || !scope.installationId) return false;
54460
- const collection2 = lower(collectionId), prefix = [scope.accountId, scope.connectorId, scope.deviceId, scope.installationId].map(lower).join(".");
54461
- const names = ["create", "join"].map((purpose) => `mdbase.app.cloud-copy-outcome.v1.${prefix}.${collection2}.${purpose}`);
54462
- names.push(...["create", "enrol"].map((purpose) => `mdbase.app.private-bootstrap.v1.${prefix}.${collection2}.${purpose}`));
54463
- const results2 = await Promise.all(names.map(deleteDatabase));
54464
- const storage = globalThis.navigator?.storage;
54465
- if (typeof storage?.getDirectory === "function") {
54466
- const root = await storage.getDirectory();
54467
- try {
54468
- await root.removeEntry(`.mdbase-app-${lower(scope.accountId)}-${lower(scope.installationId)}-${collection2}`, { recursive: true });
54469
- } catch (error5) {
54470
- if (!(error5 instanceof DOMException && error5.name === "NotFoundError")) return false;
54471
- }
54472
- }
54473
- return results2.every(Boolean);
54474
- } catch {
54475
- return false;
54476
- }
54477
- }
54478
- async function eraseAppInstallationData(scope) {
54479
- if (!globalThis.indexedDB) return Object.freeze({ ledger: false, complete: false });
54480
- const [current3, unlabelled] = ledgerNames(scope);
54481
- const ledger = await deleteDatabase(current3);
54482
- let others = null;
54483
- try {
54484
- others = await otherDatabaseNames(scope, current3, unlabelled);
54485
- } catch {
54486
- }
54487
- const results2 = others ? await Promise.all([...others, ...scope.isolated || scope.storageNamespace !== void 0 ? [] : [LOG_TOKEN_DATABASE]].map(deleteDatabase)) : [false];
54488
- const tokens2 = scope.storageNamespace === void 0 ? true : await bounded3(eraseAppLogTokens(scope), false);
54489
- const replicas = scope.accountId && scope.installationId ? await removeReplicas(scope.accountId, scope.installationId).catch(() => false) : true;
54490
- return Object.freeze({ ledger, complete: ledger && tokens2 && replicas && results2.every(Boolean) });
54491
- }
54492
-
54493
- // src/app-host/web-sign-in-session.ts
54577
+ init_sign_out_erase();
54494
54578
  init_errors();
54495
54579
  var closedView = Object.freeze({ status: "unselected", problem: null, transport: null, live: null });
54496
54580
  var failure2 = (reason) => new AppInstallationSignInError(reason);