@ghostlytools/cli 1.7.4 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +12 -6
  2. package/SKILL.md +1 -1
  3. package/dist/assets/{api-Chhvpwok.js → api-Dj1yn0px.js} +2 -2
  4. package/dist/assets/{api-D3i2hwy0.js → api-I_KbuXHa.js} +62 -16
  5. package/dist/assets/api-I_KbuXHa.js.map +1 -0
  6. package/dist/assets/{apiKit-BtsHrnoo.js → apiKit-C-_PWZvy.js} +17 -5
  7. package/dist/assets/{apiKit-BtsHrnoo.js.map → apiKit-C-_PWZvy.js.map} +1 -1
  8. package/dist/assets/{apps-BHl97rHs.js → apps-DKIe8VjF.js} +8 -7
  9. package/dist/assets/apps-DKIe8VjF.js.map +1 -0
  10. package/dist/assets/{apps-BFJTqvAt.js → apps-DbEfL_3b.js} +1 -1
  11. package/dist/assets/{arkade-BFE8KkEE.js → arkade-k1bdSm70.js} +2 -2
  12. package/dist/assets/{arkade-BFE8KkEE.js.map → arkade-k1bdSm70.js.map} +1 -1
  13. package/dist/assets/{backup-Bbsr6nDi.js → backup-Cdd6-HNu.js} +1 -1
  14. package/dist/assets/{backup-CxACdtQX.js → backup-beKfbfNk.js} +6 -6
  15. package/dist/assets/{backup-CxACdtQX.js.map → backup-beKfbfNk.js.map} +1 -1
  16. package/dist/assets/buttons-BO1_7V4L.js +2 -0
  17. package/dist/assets/{buttons-CieBtXEO.js → buttons-ClI13rdv.js} +7 -6
  18. package/dist/assets/buttons-ClI13rdv.js.map +1 -0
  19. package/dist/assets/{daemonProof-QmtwDj-N.js → daemonProof-DtrL5lE5.js} +2 -2
  20. package/dist/assets/{daemonProof-QmtwDj-N.js.map → daemonProof-DtrL5lE5.js.map} +1 -1
  21. package/dist/assets/{envelope-DYiGwzq_.js → envelope-B88yiCQj.js} +2 -2
  22. package/dist/assets/{envelope-DYiGwzq_.js.map → envelope-B88yiCQj.js.map} +1 -1
  23. package/dist/assets/{errors-QUGP-jIF.js → errors-R4S2SAEM.js} +7 -2
  24. package/dist/assets/errors-R4S2SAEM.js.map +1 -0
  25. package/dist/assets/{groupFiles-CBJIEvCE.js → groupFiles-DjQc5XXv.js} +135 -24
  26. package/dist/assets/groupFiles-DjQc5XXv.js.map +1 -0
  27. package/dist/assets/{host-Va-r_KJz.js → host-CNWGB3-j.js} +44 -20
  28. package/dist/assets/host-CNWGB3-j.js.map +1 -0
  29. package/dist/assets/{hyperdhtRelay-B2uK9tJv.js → hyperdhtRelay-g7eXzf5h.js} +2 -2
  30. package/dist/assets/{hyperdhtRelay-B2uK9tJv.js.map → hyperdhtRelay-g7eXzf5h.js.map} +1 -1
  31. package/dist/assets/{irohWeb-DxeEgQ-W.js → irohWeb-Bx8dI4be.js} +2 -2
  32. package/dist/assets/{irohWeb-DxeEgQ-W.js.map → irohWeb-Bx8dI4be.js.map} +1 -1
  33. package/dist/assets/{main-BX4oPWCJ.js → main-BRxhBctJ.js} +121 -37
  34. package/dist/assets/main-BRxhBctJ.js.map +1 -0
  35. package/dist/assets/{mainline-IfWQOB-J.js → mainline-CwuS6ngj.js} +2 -2
  36. package/dist/assets/{mainline-IfWQOB-J.js.map → mainline-CwuS6ngj.js.map} +1 -1
  37. package/dist/assets/mints-BaOmx517.js +2 -0
  38. package/dist/assets/{mints-BrlY773j.js → mints-j5XAOk4f.js} +15 -3
  39. package/dist/assets/mints-j5XAOk4f.js.map +1 -0
  40. package/dist/assets/{networkReason-N2vAaoth.js → networkReason-CIAMieQm.js} +2 -2
  41. package/dist/assets/{networkReason-N2vAaoth.js.map → networkReason-CIAMieQm.js.map} +1 -1
  42. package/dist/assets/{nwc-CzyCtNK2.js → nwc-C9JLJJkL.js} +3 -3
  43. package/dist/assets/{nwc-CzyCtNK2.js.map → nwc-C9JLJJkL.js.map} +1 -1
  44. package/dist/assets/{nwcProvider-DjWmEn3j.js → nwcProvider-pFMrsUJh.js} +2 -2
  45. package/dist/assets/{nwcProvider-DjWmEn3j.js.map → nwcProvider-pFMrsUJh.js.map} +1 -1
  46. package/dist/assets/{profiles-DcCeOi7J.js → profiles-MFtCmJwK.js} +3 -3
  47. package/dist/assets/{profiles-DcCeOi7J.js.map → profiles-MFtCmJwK.js.map} +1 -1
  48. package/dist/assets/{registry-CeW8XEQc.js → registry-Cks7FA_o.js} +3 -3
  49. package/dist/assets/{registry-CeW8XEQc.js.map → registry-Cks7FA_o.js.map} +1 -1
  50. package/dist/assets/{registry-BmS02J5h.js → registry-DY2ixQfU.js} +1 -1
  51. package/dist/assets/{resolve-BvHkAhDH.js → resolve-C4Y2HPqQ.js} +15 -3
  52. package/dist/assets/resolve-C4Y2HPqQ.js.map +1 -0
  53. package/dist/assets/{restoredRows-mTTp3XNs.js → restoredRows-BCRCjhdF.js} +26 -2
  54. package/dist/assets/{restoredRows-mTTp3XNs.js.map → restoredRows-BCRCjhdF.js.map} +1 -1
  55. package/dist/assets/{server-BUcJo4vz.js → server-D9RAmGdm.js} +650 -150
  56. package/dist/assets/server-D9RAmGdm.js.map +1 -0
  57. package/dist/assets/{src-BB5-5P3s.js → src-1RU4TilT.js} +878 -77
  58. package/dist/assets/src-1RU4TilT.js.map +1 -0
  59. package/dist/assets/{translate-2WyaRVCr.js → translate-od5GbpvR.js} +11 -7
  60. package/dist/assets/translate-od5GbpvR.js.map +1 -0
  61. package/dist/assets/{usdt-BLazHiaP.js → usdt-DldXV0MR.js} +3 -3
  62. package/dist/assets/{usdt-BLazHiaP.js.map → usdt-DldXV0MR.js.map} +1 -1
  63. package/dist/assets/waitNotice-Ck3el3_Z.js +45 -0
  64. package/dist/assets/waitNotice-Ck3el3_Z.js.map +1 -0
  65. package/dist/assets/{words-BaumxjXe.js → words-BS2qq_vV.js} +6 -3
  66. package/dist/assets/words-BS2qq_vV.js.map +1 -0
  67. package/dist/ghostly.mjs +1 -1
  68. package/examples/claude-code-agent.sh +1 -1
  69. package/package.json +1 -1
  70. package/dist/assets/api-D3i2hwy0.js.map +0 -1
  71. package/dist/assets/apps-BHl97rHs.js.map +0 -1
  72. package/dist/assets/buttons-CieBtXEO.js.map +0 -1
  73. package/dist/assets/buttons-YtAj3R_E.js +0 -2
  74. package/dist/assets/errors-QUGP-jIF.js.map +0 -1
  75. package/dist/assets/groupFiles-CBJIEvCE.js.map +0 -1
  76. package/dist/assets/host-Va-r_KJz.js.map +0 -1
  77. package/dist/assets/main-BX4oPWCJ.js.map +0 -1
  78. package/dist/assets/mints-BrlY773j.js.map +0 -1
  79. package/dist/assets/mints-CqTdA4Gk.js +0 -2
  80. package/dist/assets/resolve-BvHkAhDH.js.map +0 -1
  81. package/dist/assets/server-BUcJo4vz.js.map +0 -1
  82. package/dist/assets/src-BB5-5P3s.js.map +0 -1
  83. package/dist/assets/translate-2WyaRVCr.js.map +0 -1
  84. package/dist/assets/words-BaumxjXe.js.map +0 -1
@@ -986,6 +986,14 @@ function currentRelays(relays) {
986
986
  return PREVIOUS_DEFAULT_RELAYS.some((old) => same(old, relays)) ? [...DEFAULT_RELAYS] : relays;
987
987
  }
988
988
  /**
989
+ * Of the background share, what background writes may spend in a minute on a relay (10 of the 20): the rest is kept
990
+ * for background reads. Those writes are mostly the upkeep of chats whose contacts are away (the link's heartbeat, the
991
+ * DHT floor's keep-alive, the capability record), about one a minute for every two chats. A profile with 200 such chats
992
+ * spent the share on them, and on one relay 147 of its 200 contacts were not read once in 25 minutes: a contact back
993
+ * then went unnoticed (bug hunt, 2026-11-01). Upkeep held back goes when a request of this share frees.
994
+ */
995
+ var BACKGROUND_WRITES_SHARE = 1 / 2;
996
+ /**
989
997
  * A link's write the budget refused (its presence, its offer, its answer) goes first when the minute
990
998
  * frees a request: reads on that relay wait this long after the refusal. A link that polls fast for a
991
999
  * peer while its offer waits would otherwise take every request the minute frees, and the offer (the
@@ -1252,6 +1260,8 @@ var RelayTransport = class {
1252
1260
  lastReadFrom = /* @__PURE__ */ new Map();
1253
1261
  spent = /* @__PURE__ */ new Map();
1254
1262
  spentBackground = /* @__PURE__ */ new Map();
1263
+ /** Background writes on each relay in the last minute (`BACKGROUND_WRITES_SHARE`). */
1264
+ spentBackgroundWrites = /* @__PURE__ */ new Map();
1255
1265
  /** Groups' urgent reads on each relay in the last `GROUP_BURST_MS`. */
1256
1266
  spentGroupUrgent = /* @__PURE__ */ new Map();
1257
1267
  /** Watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`WATCH_SHARE`). */
@@ -1330,16 +1340,16 @@ var RelayTransport = class {
1330
1340
  this.perMinuteGiven = options.requestsPerMinute !== void 0;
1331
1341
  this.backgroundPerMinute = this.perMinute === 30 ? 20 : Math.ceil(this.perMinute * 2 / 3);
1332
1342
  this.backgroundWhileSignaling = this.perMinute === 30 ? 5 : Math.ceil(this.perMinute / 6);
1333
- const log = options.log ?? ((line) => console.info(`[ghostly:relay] ${line}`));
1343
+ const log = options.log ?? ((line) => console.info(`ghostly: ${line}`));
1334
1344
  this.breaker = new RelayBreaker({
1335
1345
  ...options.breaker,
1336
1346
  onTrip: (relay, reason, forMs) => {
1337
- log(`${new URL(relay).host} tripped (${reason}); left alone for ${Math.round(forMs / 1e3)} s`);
1347
+ log(`relay ${new URL(relay).host} ${reason === "no answer" ? "did not answer" : reason === "slow" ? "answered too slowly" : `failed (${reason})`}; asked again in ${Math.round(forMs / 1e3)} s`);
1338
1348
  options.breaker?.onTrip?.(relay, reason, forMs);
1339
1349
  this.changed("tripped");
1340
1350
  },
1341
1351
  onRecover: (relay) => {
1342
- log(`${new URL(relay).host} answered again`);
1352
+ log(`relay ${new URL(relay).host} answers again`);
1343
1353
  options.breaker?.onRecover?.(relay);
1344
1354
  this.changed("recovered");
1345
1355
  }
@@ -2023,13 +2033,13 @@ var RelayTransport = class {
2023
2033
  let response;
2024
2034
  try {
2025
2035
  response = await request;
2026
- } catch (error) {
2036
+ } catch {
2027
2037
  this.networkCooldown.set(`PUT ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
2028
2038
  this.answered(relay, {
2029
2039
  kind: "error",
2030
2040
  reason: "no answer"
2031
2041
  });
2032
- throw error;
2042
+ throw new Error(`${relay} did not answer`);
2033
2043
  }
2034
2044
  if (response.status === 429) this.answered(relay, {
2035
2045
  kind: "throttled",
@@ -2083,6 +2093,7 @@ var RelayTransport = class {
2083
2093
  if (departedOver) this.departedOverAdd(key, now);
2084
2094
  this.spent.get(relay).push(now);
2085
2095
  if (who.background) this.spentBackground.get(relay).push(now);
2096
+ if (who.background && who.write) this.spentBackgroundWrites.get(relay).push(now);
2086
2097
  if (isGroupUrgentRead(who)) this.spentGroupUrgent.get(relay).push(now);
2087
2098
  if (isWatch(who)) this.spentWatch.get(relay).push(now);
2088
2099
  if (isChatWatch(who) && !departedOver) this.spentChatWatch.get(relay).push(now);
@@ -2116,6 +2127,8 @@ var RelayTransport = class {
2116
2127
  const recentBackground = (this.spentBackground.get(relay) ?? []).filter((at) => now - at < 6e4);
2117
2128
  this.spent.set(relay, recent);
2118
2129
  this.spentBackground.set(relay, recentBackground);
2130
+ const recentBackgroundWrites = (this.spentBackgroundWrites.get(relay) ?? []).filter((at) => now - at < 6e4);
2131
+ this.spentBackgroundWrites.set(relay, recentBackgroundWrites);
2119
2132
  const over = (list, limit) => list.length >= limit ? list[list.length - limit] + 6e4 - now : 0;
2120
2133
  const limit = this.limitOf(relay);
2121
2134
  const departed = isDepartedRead(who) && key !== void 0 && recent.length >= limit && this.departedReads(key, now) < 6;
@@ -2130,7 +2143,9 @@ var RelayTransport = class {
2130
2143
  this.spentGroupOver.set(relay, groupOver);
2131
2144
  if (isGroupSignal(who) && !who.write && recent.length >= limit && groupOver.length > 0) wait = Math.max(wait, groupOver[groupOver.length - 1] + GROUP_OVER_PACE_MS - now);
2132
2145
  if (who.background && !starved) {
2133
- wait = Math.max(wait, over(recentBackground, Math.min(this.backgroundPerMinute, Math.ceil(limit * 2 / 3))));
2146
+ const backgroundShare = Math.min(this.backgroundPerMinute, Math.ceil(limit * 2 / 3));
2147
+ wait = Math.max(wait, over(recentBackground, backgroundShare));
2148
+ if (who.write) wait = Math.max(wait, over(recentBackgroundWrites, Math.max(1, Math.floor(backgroundShare * BACKGROUND_WRITES_SHARE))));
2134
2149
  const signaling = this.urgentAt + SIGNALING_WINDOW_MS - now;
2135
2150
  if (signaling > 0 && !who.door) wait = Math.max(wait, Math.min(signaling, over(recentBackground, Math.min(this.backgroundWhileSignaling, Math.ceil(limit / 6)))));
2136
2151
  }
@@ -2643,13 +2658,13 @@ function turnName(name) {
2643
2658
  }
2644
2659
  return hasVisible(out) ? out.trimEnd() : "";
2645
2660
  }
2646
- function u32$3(value) {
2661
+ function u32$4(value) {
2647
2662
  return Uint8Array.of(value >>> 24 & 255, value >>> 16 & 255, value >>> 8 & 255, value & 255);
2648
2663
  }
2649
2664
  /** What a release signs: `"ghostly-turn-release" || turnAddress(32) || turn(4) || toKey(32) || H(32)`. */
2650
2665
  function turnReleaseMessage(address, turn, toKey, h) {
2651
2666
  if (address.length !== 32 || toKey.length !== 32 || h.length !== 32) throw new Error("A release names 32-byte values");
2652
- return concatBytes$1(RELEASE_DOMAIN, address, u32$3(turn), toKey, h);
2667
+ return concatBytes$1(RELEASE_DOMAIN, address, u32$4(turn), toKey, h);
2653
2668
  }
2654
2669
  /** What the author signs: `"ghostly-turn" || turnAddress(32) || body[0..310]`. */
2655
2670
  function turnSignedMessage(address, unsigned) {
@@ -2667,8 +2682,8 @@ function encodeTurnFields(fields) {
2667
2682
  if (tombstone ? fields.active !== 255 : !held(fields.active)) throw new Error(tombstone ? "A tombstone names no active device" : "The active device has no slot");
2668
2683
  const body = /* @__PURE__ */ new Uint8Array(310);
2669
2684
  body[OFFSET.version] = 1;
2670
- body.set(u32$3(fields.turn), OFFSET.turn);
2671
- body.set(u32$3(fields.rev).subarray(1), OFFSET.rev);
2685
+ body.set(u32$4(fields.turn), OFFSET.turn);
2686
+ body.set(u32$4(fields.rev).subarray(1), OFFSET.rev);
2672
2687
  body[OFFSET.author] = fields.author;
2673
2688
  body[OFFSET.active] = fields.active;
2674
2689
  body[OFFSET.count] = fields.slots.filter(Boolean).length;
@@ -2920,7 +2935,7 @@ var TURN_PUT_WINDOW_MS = 1e4;
2920
2935
  var TURN_RAISE_READ_TIMEOUT_MS = 5e3;
2921
2936
  /** `T`: how long a device that raised the turn waits, from the end of its put, before the read that may make it active. `T >= P + 2V`. */
2922
2937
  var TURN_SETTLE_MS = 3e4;
2923
- function compareBytes$3(a, b) {
2938
+ function compareBytes$4(a, b) {
2924
2939
  for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return a[i] - b[i];
2925
2940
  return a.length - b.length;
2926
2941
  }
@@ -2931,7 +2946,7 @@ function compareBytes$3(a, b) {
2931
2946
  * reader still agrees.
2932
2947
  */
2933
2948
  function keptAtEqualSequence(a, b) {
2934
- return compareBytes$3(a.record.instance, b.record.instance) || compareBytes$3(a.record.body, b.record.body) || compareBytes$3(a.payload, b.payload);
2949
+ return compareBytes$4(a.record.instance, b.record.instance) || compareBytes$4(a.record.body, b.record.body) || compareBytes$4(a.payload, b.payload);
2935
2950
  }
2936
2951
  var kept = (f) => ({
2937
2952
  record: f.read.record,
@@ -4654,7 +4669,7 @@ function checkAppManifest(value, options = {}) {
4654
4669
  function appDigest(manifestBytes) {
4655
4670
  return toBase64Url(sha256(manifestBytes));
4656
4671
  }
4657
- var u32$2 = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
4672
+ var u32$3 = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
4658
4673
  /**
4659
4674
  * Lets the thread go for one turn: what waits (input, drawing, timers, port messages, IndexedDB answers) runs, then the
4660
4675
  * caller goes on. A message to itself, queued behind the page's other tasks. Never `scheduler.yield()`: in Chromium its
@@ -4730,7 +4745,7 @@ function readAppBundleHead(bytes) {
4730
4745
  ok: false,
4731
4746
  reason: "truncated"
4732
4747
  };
4733
- const manifestLength = u32$2(bytes, at);
4748
+ const manifestLength = u32$3(bytes, at);
4734
4749
  at += 4;
4735
4750
  if (manifestLength > APP_BUNDLE_LIMITS.manifestBytes) return {
4736
4751
  ok: false,
@@ -4742,7 +4757,7 @@ function readAppBundleHead(bytes) {
4742
4757
  };
4743
4758
  const manifestBytes = bytes.subarray(at, at + manifestLength);
4744
4759
  at += manifestLength;
4745
- const statementLength = u32$2(bytes, at);
4760
+ const statementLength = u32$3(bytes, at);
4746
4761
  at += 4;
4747
4762
  if (bytes.length < at + statementLength) return {
4748
4763
  ok: false,
@@ -4888,9 +4903,9 @@ var ContactRequestError = class extends Error {
4888
4903
  this.name = "ContactRequestError";
4889
4904
  }
4890
4905
  };
4891
- var label = (text) => utf8Encode(text);
4906
+ var label$1 = (text) => utf8Encode(text);
4892
4907
  function derive(linkKeyZ32, info) {
4893
- return hkdf(sha256, publicKeyFromZ32(linkKeyZ32), label("ghostly-contact/1"), label(info), 32);
4908
+ return hkdf(sha256, publicKeyFromZ32(linkKeyZ32), label$1("ghostly-contact/1"), label$1(info), 32);
4894
4909
  }
4895
4910
  /** The UTC day number of a time: a stamp is made for one. */
4896
4911
  function contactDay(ms) {
@@ -4898,7 +4913,7 @@ function contactDay(ms) {
4898
4913
  }
4899
4914
  /** The `seen` entry of an asker key on a link: the first 9 bytes of a hash, so the record names nobody. */
4900
4915
  function seenEntry(linkKeyZ32, askerZ32) {
4901
- return toBase64Url(sha256(concatBytes$1(label("ghostly-contact/1 seen"), publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32))).slice(0, 9));
4916
+ return toBase64Url(sha256(concatBytes$1(label$1("ghostly-contact/1 seen"), publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32))).slice(0, 9));
4902
4917
  }
4903
4918
  function linkRecords(record) {
4904
4919
  if (!Number.isInteger(record.bits) || record.bits < 16 || record.bits > 24) throw new Error("A link asks for 16 to 24 bits");
@@ -4936,7 +4951,7 @@ function readLinkRecord(records) {
4936
4951
  function stampPrefix(linkKeyZ32, askerZ32, day) {
4937
4952
  const tail = /* @__PURE__ */ new Uint8Array(4);
4938
4953
  new DataView(tail.buffer).setUint32(0, day);
4939
- return concatBytes$1(label("ghostly-contact/1 stamp"), publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32), tail);
4954
+ return concatBytes$1(label$1("ghostly-contact/1 stamp"), publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32), tail);
4940
4955
  }
4941
4956
  function leadingZeroBits(hash) {
4942
4957
  let bits = 0;
@@ -4992,7 +5007,7 @@ function knockSlotOf(linkKeyZ32, askerZ32) {
4992
5007
  }
4993
5008
  function knockSlotRecords(linkKeyZ32, knocks) {
4994
5009
  const nonce = randomBytes(NONCE_LENGTH$3);
4995
- const body = label(JSON.stringify(knocks.slice(-6).map((k) => [
5010
+ const body = label$1(JSON.stringify(knocks.slice(-6).map((k) => [
4996
5011
  k.key,
4997
5012
  k.day,
4998
5013
  k.stamp
@@ -5027,9 +5042,9 @@ function mergeContactKnocks(existing, mine, now) {
5027
5042
  return [...existing.filter((k) => k.key !== mine.key && k.day >= today - 1 && k.day <= today + 1).slice(-5), mine];
5028
5043
  }
5029
5044
  function requestKey(linkKeyZ32, askerZ32, shared) {
5030
- return hkdf(sha256, shared, label("ghostly-contact/1 request"), concatBytes$1(publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32)), 32);
5045
+ return hkdf(sha256, shared, label$1("ghostly-contact/1 request"), concatBytes$1(publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32)), 32);
5031
5046
  }
5032
- var REQUEST_AAD = label("ghostly-contact/1 request");
5047
+ var REQUEST_AAD = label$1("ghostly-contact/1 request");
5033
5048
  /** The value of a request's record for a plaintext of `length` bytes. */
5034
5049
  var sealedValueLength = (length) => Math.ceil((NONCE_LENGTH$3 + length + TAG_LENGTH) * 4 / 3);
5035
5050
  var plaintextBytes;
@@ -5067,7 +5082,7 @@ function requestRecords(askerSeedB64, linkKeyZ32, request) {
5067
5082
  if (!inviteHolds(request.invite)) throw new ContactRequestError("invite");
5068
5083
  if (!Number.isSafeInteger(request.issued) || !Number.isSafeInteger(request.expires) || request.expires <= request.issued || request.expires - request.issued > 6048e5) throw new ContactRequestError("dates");
5069
5084
  const asker = identityFromSeedB64(askerSeedB64);
5070
- const json = label(JSON.stringify([
5085
+ const json = label$1(JSON.stringify([
5071
5086
  1,
5072
5087
  request.invite,
5073
5088
  request.name,
@@ -7892,6 +7907,13 @@ var AWAITING_PEER_MS = 6e5;
7892
7907
  * to invites nobody may ever open, and a join on one was noticed 90 s later (bug hunt 1013-1642, 2026-10-13).
7893
7908
  */
7894
7909
  var UNUSED_INVITE_WAIT_MAX_MS = 18e4;
7910
+ /**
7911
+ * An invite this side made that nobody used, once no longer awaited, puts its key and its mailbox out this often, not
7912
+ * every `PRESENCE_HEARTBEAT`: 20 of them added about 17 relay writes a minute for as long as the app ran (bug hunt,
7913
+ * 2026-10-30). Not longer: a joiner goes live sooner while it finds both still good, the packet within `PRESENCE_WINDOW`
7914
+ * and the envelope unexpired. At 30 minutes the slowest of 6 joins took 235 s, against 86 s of 9 at the heartbeat's pace.
7915
+ */
7916
+ var UNUSED_INVITE_UPKEEP_MS = 48e4;
7895
7917
  /** The keys and mailboxes of unused invites read slowly over each transport (an app's relays). */
7896
7918
  var unusedInviteReaders = /* @__PURE__ */ new WeakMap();
7897
7919
  /** Counts `reader` (an invite's key or mailbox) among the unused ones read over `transport` while `unused`, or no longer: how many there are. */
@@ -7928,6 +7950,8 @@ var BACKGROUND_RETRY_MAX_MS = 6e4;
7928
7950
  var MIN_POLL_GAP_MS = 250;
7929
7951
  /** Presence is a fresh packet: advertising peers republish this often… */
7930
7952
  var PRESENCE_HEARTBEAT = 24e4;
7953
+ /** …and are considered gone once their packet is older than this. */
7954
+ var PRESENCE_WINDOW = 6e5;
7931
7955
  /** When this device first read the peer's latest packet, by its own clock (`PeerPresence.seenAt`). */
7932
7956
  var presenceSeenAt = (presence) => presence.seenAt ?? presence.lastPacketAt;
7933
7957
  /** With `firstPublish: "after-first-poll"`, the first packet goes out by then whatever happened. */
@@ -7977,6 +8001,8 @@ var LinkSession = class {
7977
8001
  awaitingSince;
7978
8002
  /** This side's invite, nobody used yet (`LinkSessionOptions.invite`). */
7979
8003
  invite;
8004
+ /** This side's own invite, nobody used yet (`LinkSessionOptions.ownInvite`). */
8005
+ ownInvite;
7980
8006
  intervals;
7981
8007
  fastPollUntil = 0;
7982
8008
  /** An offer to a saved contact is out: from then on its fast window looks less often (`OFFER_FAST_MS`); 0 for none. */
@@ -8045,6 +8071,7 @@ var LinkSession = class {
8045
8071
  this.resumeReads = !!options.resumed;
8046
8072
  this.awaitingSince = Math.min(options.awaitingSince ?? this.startedAt, this.startedAt);
8047
8073
  this.invite = options.invite ?? (() => false);
8074
+ this.ownInvite = options.ownInvite ?? (() => false);
8048
8075
  }
8049
8076
  get peerPresence() {
8050
8077
  return this.presence;
@@ -8335,10 +8362,15 @@ var LinkSession = class {
8335
8362
  if (this.heartbeatTimer) clearTimeout(this.heartbeatTimer);
8336
8363
  this.heartbeatTimer = setTimeout(() => {
8337
8364
  if (!this.running) return;
8338
- if (this.getServices() !== void 0) this.publish(true).catch(() => {});
8365
+ if (this.getServices() !== void 0 && !this.upkeepWaits()) this.publish(true).catch(() => {});
8339
8366
  this.scheduleHeartbeat();
8340
8367
  }, PRESENCE_HEARTBEAT);
8341
8368
  }
8369
+ /** An unused invite of this side's, no longer awaited, whose packet went out less than `UNUSED_INVITE_UPKEEP_MS` ago. */
8370
+ upkeepWaits() {
8371
+ const now = Date.now();
8372
+ return this.ownInvite() && !this.presence.online && !this.connected && now - this.awaitingSince >= 6e5 && now - this.lastPublishedAt < 36e4;
8373
+ }
8342
8374
  /**
8343
8375
  * Coalesces publishes: at most one in flight and one queued behind it. `upkeep`: nothing new to say (the heartbeat, a
8344
8376
  * retry of what waits): with nothing else asked for since, the packet goes as upkeep (`publishOnce`).
@@ -9167,6 +9199,460 @@ var DataLink = class {
9167
9199
  }
9168
9200
  };
9169
9201
  //#endregion
9202
+ //#region ../core/src/ratchet.ts
9203
+ /**
9204
+ * The ratchet of a 1:1 chat's stored paths (WISP 4xx-ratchet, reserved number 407): what goes on the DHT floor
9205
+ * (WISP 403) and what is held (WISP 404) is sealed with a key used once, from a double ratchet in the manner of
9206
+ * Signal's (an X25519 step each time the turn passes, a one-way chain per message), so a participation key stolen
9207
+ * later opens none of it once the turn has passed. The live session needs none: its transports agree fresh keys on
9208
+ * every connection.
9209
+ *
9210
+ * Pure: every call takes a state and returns the next one. The caller holds one lock per chat from reading the state
9211
+ * to saving the next (an open's until what it opened is stored), and saves a seal's state before the sealed bytes
9212
+ * leave the device. Nothing here reads a clock or the network but through its options.
9213
+ */
9214
+ var RATCHET_CAPABILITY = "ratchet/1";
9215
+ var LANE = {
9216
+ floor: 1,
9217
+ hold: 2
9218
+ };
9219
+ var VERSION$1 = 1;
9220
+ var SID_BYTES = 8;
9221
+ /**
9222
+ * How far a message may be ahead of the last one opened on its chain. A mailbox shows only its newest envelope, so the
9223
+ * floor's between were replaced unread: their keys are stepped over and never kept. A held item's are kept. A sender
9224
+ * whose chain reaches the bound without the turn passing starts a new session rather than seal past it.
9225
+ */
9226
+ var MAX_SKIP = {
9227
+ floor: 4096,
9228
+ hold: 512
9229
+ };
9230
+ /** A kept key, and a session only received on, is dropped this long after it was last of use: a held item lives 7 days. */
9231
+ var RATCHET_KEEP_MS = 6912e5;
9232
+ var emptyRatchetState = () => ({
9233
+ v: 1,
9234
+ others: [],
9235
+ skipped: [],
9236
+ retired: [],
9237
+ heard: {}
9238
+ });
9239
+ /** Sessions only opened with, at most. */
9240
+ var MAX_OTHERS = 2;
9241
+ var b64 = toBase64Url;
9242
+ var unb64 = fromBase64Url;
9243
+ var label = (text) => utf8Encode(`ghostly-ratchet/1 ${text}`);
9244
+ var mac = (key, text) => hmac(sha256, key, label(text));
9245
+ function u32$2(n) {
9246
+ if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295) throw new Error("Ratchet counter out of range");
9247
+ return new Uint8Array([
9248
+ n >>> 24,
9249
+ n >>> 16 & 255,
9250
+ n >>> 8 & 255,
9251
+ n & 255
9252
+ ]);
9253
+ }
9254
+ var readU32 = (b, at) => (b[at] << 24 >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];
9255
+ function compareBytes$3(a, b) {
9256
+ for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return a[i] - b[i];
9257
+ return a.length - b.length;
9258
+ }
9259
+ /** X25519, or null for a key that gives no secret (a low-order point): such an item does not open. */
9260
+ function agree(secret, pub) {
9261
+ try {
9262
+ return x25519.getSharedSecret(secret, pub);
9263
+ } catch {
9264
+ return null;
9265
+ }
9266
+ }
9267
+ function context(keys) {
9268
+ const secret = ed25519.utils.toMontgomerySecret(keys.seed);
9269
+ return {
9270
+ keys,
9271
+ secret,
9272
+ pub: x25519.getPublicKey(secret),
9273
+ peer: ed25519.utils.toMontgomery(publicKeyFromZ32(keys.peer)),
9274
+ first: compareBytes$3(publicKeyFromZ32(keys.self), publicKeyFromZ32(keys.peer)) < 0
9275
+ };
9276
+ }
9277
+ function root(c, sid) {
9278
+ const { keys } = c;
9279
+ const info = utf8Encode(JSON.stringify([
9280
+ "ghostly-ratchet/1",
9281
+ [...keys.rendezvous].sort(),
9282
+ [keys.self, keys.peer].sort()
9283
+ ]));
9284
+ const salt = hkdf(sha256, keys.secret, info, label("salt"), 32);
9285
+ return hkdf(sha256, x25519.getSharedSecret(c.secret, c.peer), salt, concatBytes$1(label("root"), sid), 32);
9286
+ }
9287
+ /** A ratchet step: the next root key and the chain key it gives, from an X25519 output. */
9288
+ function stepRoot(rk, dh) {
9289
+ const okm = hkdf(sha256, dh, rk, label("step"), 64);
9290
+ return [okm.slice(0, 32), okm.slice(32)];
9291
+ }
9292
+ var lanes = (ck) => ({
9293
+ floor: {
9294
+ k: b64(mac(ck, "lane floor")),
9295
+ n: 0
9296
+ },
9297
+ hold: {
9298
+ k: b64(mac(ck, "lane hold")),
9299
+ n: 0
9300
+ }
9301
+ });
9302
+ /** One message key off a chain, and the chain moved past it. */
9303
+ function advance(chain) {
9304
+ const ck = unb64(chain.k);
9305
+ return [hmac(sha256, ck, new Uint8Array([1])), {
9306
+ k: b64(hmac(sha256, ck, new Uint8Array([2]))),
9307
+ n: chain.n + 1
9308
+ }];
9309
+ }
9310
+ function newSession(c, sid, random, now) {
9311
+ const rk0 = root(c, sid);
9312
+ const initial = lanes(mac(rk0, "initial"));
9313
+ const base = {
9314
+ sid: b64(sid),
9315
+ pnHold: 0,
9316
+ heard: false,
9317
+ fs: false,
9318
+ at: now,
9319
+ made: now
9320
+ };
9321
+ if (!c.first) return {
9322
+ ...base,
9323
+ rk: b64(rk0),
9324
+ dhs: null,
9325
+ dhsPub: b64(c.pub),
9326
+ dhr: null,
9327
+ send: initial,
9328
+ recv: null
9329
+ };
9330
+ const dhs = random(32);
9331
+ const [rk, ck] = stepRoot(rk0, x25519.getSharedSecret(dhs, c.peer));
9332
+ return {
9333
+ ...base,
9334
+ rk: b64(rk),
9335
+ dhs: b64(dhs),
9336
+ dhsPub: b64(x25519.getPublicKey(dhs)),
9337
+ dhr: b64(c.peer),
9338
+ send: lanes(ck),
9339
+ recv: initial
9340
+ };
9341
+ }
9342
+ function messageKeys(mk) {
9343
+ const okm = hkdf(sha256, mk, /* @__PURE__ */ new Uint8Array(32), label("message"), 56);
9344
+ return {
9345
+ key: okm.slice(0, 32),
9346
+ nonce: okm.slice(32)
9347
+ };
9348
+ }
9349
+ function aad(lane, sender, recipient, header) {
9350
+ return concatBytes$1(utf8Encode("ghostly-ratchet/1"), new Uint8Array([LANE[lane]]), publicKeyFromZ32(sender), publicKeyFromZ32(recipient), header);
9351
+ }
9352
+ function header$1(lane, session, n) {
9353
+ return concatBytes$1(new Uint8Array([VERSION$1, LANE[lane]]), unb64(session.sid), unb64(session.dhsPub), u32$2(session.pnHold), u32$2(n));
9354
+ }
9355
+ function parseHeader(sealed) {
9356
+ if (sealed.length < 66 || sealed[0] !== VERSION$1 || sealed[1] !== 1 && sealed[1] !== 2) return null;
9357
+ const at = 42;
9358
+ return {
9359
+ lane: sealed[1] === 1 ? "floor" : "hold",
9360
+ sid: b64(sealed.slice(2, 10)),
9361
+ dh: b64(sealed.slice(10, at)),
9362
+ pnHold: readU32(sealed, at),
9363
+ n: readU32(sealed, 46)
9364
+ };
9365
+ }
9366
+ function prune(state, now) {
9367
+ state.skipped = state.skipped.filter((k) => k.at + RATCHET_KEEP_MS > now).slice(-512);
9368
+ for (const old of state.others.filter((o) => o.at + RATCHET_KEEP_MS <= now)) retire(state, old);
9369
+ state.others = state.others.filter((o) => o.at + RATCHET_KEEP_MS > now);
9370
+ }
9371
+ function retire(state, session) {
9372
+ if (!session) return;
9373
+ if (!state.retired.includes(session.sid)) state.retired = [...state.retired, session.sid].slice(-16);
9374
+ state.skipped = state.skipped.filter((k) => k.s !== session.sid);
9375
+ }
9376
+ /** `session` is only opened with from now on; past `MAX_OTHERS`, the one used least lately is retired. */
9377
+ function demote(state, session) {
9378
+ state.others = [...state.others.filter((o) => o.sid !== session.sid), session].sort((a, b) => a.at - b.at);
9379
+ while (state.others.length > MAX_OTHERS) retire(state, state.others.shift());
9380
+ }
9381
+ /**
9382
+ * Seals one item for the contact on a lane, with the current session (started here when there is none, or when its
9383
+ * chain on this lane reached `MAX_SKIP` without the turn passing: past it the contact could not step over to it). The
9384
+ * state returned MUST be saved before the sealed bytes leave the device: a key is used once, and a crash between the
9385
+ * two that kept the old state would use it again on other bytes.
9386
+ */
9387
+ function ratchetSeal(prev, keys, lane, plaintext, options = {}) {
9388
+ const now = options.now ?? Date.now(), random = options.random ?? randomBytes;
9389
+ const state = structuredClone(prev);
9390
+ prune(state, now);
9391
+ if (state.current && state.current.send[lane].n >= MAX_SKIP[lane]) {
9392
+ demote(state, state.current);
9393
+ delete state.current;
9394
+ }
9395
+ const session = state.current ??= newSession(context(keys), random(SID_BYTES), random, now);
9396
+ const [mk, next] = advance(session.send[lane]);
9397
+ const head = header$1(lane, session, session.send[lane].n);
9398
+ session.send[lane] = next;
9399
+ session.at = now;
9400
+ const { key, nonce } = messageKeys(mk);
9401
+ return {
9402
+ state,
9403
+ sealed: concatBytes$1(head, xchacha20poly1305(key, nonce, aad(lane, keys.self, keys.peer, head)).encrypt(plaintext))
9404
+ };
9405
+ }
9406
+ /**
9407
+ * Opens `sealed` under `session`, changing it and `state` in place (both are a copy the caller throws away on null).
9408
+ * Every bound is checked before any X25519 or chain step.
9409
+ */
9410
+ function openWith(state, session, c, h, sealed, random, now) {
9411
+ const decrypt = (mk) => {
9412
+ const { key, nonce } = messageKeys(mk);
9413
+ try {
9414
+ return xchacha20poly1305(key, nonce, aad(h.lane, c.keys.peer, c.keys.self, sealed.subarray(0, 50))).decrypt(sealed.subarray(50));
9415
+ } catch {
9416
+ return null;
9417
+ }
9418
+ };
9419
+ if (h.lane === "hold") {
9420
+ const i = state.skipped.findIndex((k) => k.s === session.sid && k.d === h.dh && k.n === h.n);
9421
+ if (i >= 0) {
9422
+ const plain = decrypt(unb64(state.skipped[i].k));
9423
+ if (plain) state.skipped.splice(i, 1);
9424
+ return plain;
9425
+ }
9426
+ }
9427
+ const keep = (lane, dh, from, until) => {
9428
+ let chain = from;
9429
+ while (chain.n < until) {
9430
+ const [mk, next] = advance(chain);
9431
+ if (lane === "hold") state.skipped.push({
9432
+ s: session.sid,
9433
+ d: dh,
9434
+ n: chain.n,
9435
+ k: b64(mk),
9436
+ at: now
9437
+ });
9438
+ chain = next;
9439
+ }
9440
+ return chain;
9441
+ };
9442
+ const bound = MAX_SKIP[h.lane];
9443
+ if (h.dh !== session.dhr) {
9444
+ const old = session.recv && session.dhr ? session.recv.hold : null;
9445
+ if (h.n > bound || old && h.pnHold > old.n && h.pnHold - old.n > MAX_SKIP.hold) return null;
9446
+ const received = agree(session.dhs ? unb64(session.dhs) : c.secret, unb64(h.dh));
9447
+ if (!received) return null;
9448
+ if (old && session.dhr) keep("hold", session.dhr, old, h.pnHold);
9449
+ let [rk, ck] = stepRoot(unb64(session.rk), received);
9450
+ const steppedWithOwn = session.dhs !== null;
9451
+ session.recv = lanes(ck);
9452
+ session.dhr = h.dh;
9453
+ session.pnHold = session.send.hold.n;
9454
+ const dhs = random(32);
9455
+ [rk, ck] = stepRoot(rk, x25519.getSharedSecret(dhs, unb64(h.dh)));
9456
+ session.rk = b64(rk);
9457
+ session.dhs = b64(dhs);
9458
+ session.dhsPub = b64(x25519.getPublicKey(dhs));
9459
+ session.send = lanes(ck);
9460
+ if (steppedWithOwn && h.dh !== b64(c.peer)) session.fs = true;
9461
+ }
9462
+ if (!session.recv) return null;
9463
+ const chain = session.recv[h.lane];
9464
+ if (h.n < chain.n || h.n - chain.n > bound) return null;
9465
+ const [mk, next] = advance(keep(h.lane, h.dh, chain, h.n));
9466
+ const plain = decrypt(mk);
9467
+ if (!plain) return null;
9468
+ session.recv[h.lane] = next;
9469
+ session.heard = true;
9470
+ session.at = now;
9471
+ return plain;
9472
+ }
9473
+ /**
9474
+ * Opens an item the contact sealed. Null: not a ratcheted item of this chat on this lane, or one already opened, or
9475
+ * past the bounds. Otherwise the plaintext, and `finish`, which gives the state to save once the item is stored and
9476
+ * passed its path's own checks (a newer DHT sequence, a held item not taken before): those, not the ratchet, are what
9477
+ * refuse a replay. `order`: a floor envelope's sequence, read from the body once opened. `fresh`: it came under a
9478
+ * session this side did not know.
9479
+ */
9480
+ function ratchetOpen(prev, keys, lane, sealed, options = {}) {
9481
+ const now = options.now ?? Date.now(), random = options.random ?? randomBytes;
9482
+ const h = parseHeader(sealed);
9483
+ if (!h || h.lane !== lane) return null;
9484
+ const state = structuredClone(prev);
9485
+ prune(state, now);
9486
+ const c = context(keys);
9487
+ const seen = (session, order) => {
9488
+ if (lane !== "floor" || order === void 0 || !Number.isSafeInteger(order)) return false;
9489
+ const rising = session.floorSeq !== void 0 && order > session.floorSeq;
9490
+ session.floorSeq = Math.max(session.floorSeq ?? 0, order);
9491
+ session.floorAt = now;
9492
+ return rising;
9493
+ };
9494
+ const done = () => {
9495
+ state.heard[lane] = true;
9496
+ prune(state, now);
9497
+ return state;
9498
+ };
9499
+ const known = state.current?.sid === h.sid ? state.current : state.others.find((o) => o.sid === h.sid);
9500
+ if (known) {
9501
+ const plaintext = openWith(state, known, c, h, sealed, random, now);
9502
+ if (!plaintext) return null;
9503
+ return {
9504
+ plaintext,
9505
+ fresh: false,
9506
+ finish: (order) => {
9507
+ const rising = seen(known, order), current = state.current;
9508
+ if (rising && known.lost && current && known !== current && current.floorSeq === void 0 && now - (current.floorAt ?? current.made) > 6e5) {
9509
+ state.others = state.others.filter((o) => o.sid !== known.sid);
9510
+ delete known.lost;
9511
+ demote(state, current);
9512
+ state.current = known;
9513
+ }
9514
+ return done();
9515
+ }
9516
+ };
9517
+ }
9518
+ if (state.retired.includes(h.sid)) return null;
9519
+ if (h.n > MAX_SKIP[lane] || h.pnHold > MAX_SKIP.hold) return null;
9520
+ const fresh = newSession(c, unb64(h.sid), random, now);
9521
+ const plaintext = openWith(state, fresh, c, h, sealed, random, now);
9522
+ if (!plaintext) return null;
9523
+ return {
9524
+ plaintext,
9525
+ fresh: true,
9526
+ finish: (order) => {
9527
+ seen(fresh, order);
9528
+ const current = state.current;
9529
+ if (!current) state.current = fresh;
9530
+ else if (current.floorSeq === void 0) {
9531
+ if (compareBytes$3(unb64(h.sid), unb64(current.sid)) > 0) {
9532
+ current.lost = true;
9533
+ demote(state, current);
9534
+ state.current = fresh;
9535
+ } else {
9536
+ fresh.lost = true;
9537
+ demote(state, fresh);
9538
+ }
9539
+ } else if (lane === "floor" && fresh.floorSeq !== void 0 && fresh.floorSeq > current.floorSeq) {
9540
+ demote(state, current);
9541
+ state.current = fresh;
9542
+ } else if (lane === "floor") {
9543
+ fresh.lost = true;
9544
+ demote(state, fresh);
9545
+ } else state.skipped = state.skipped.filter((k) => k.s !== fresh.sid);
9546
+ return done();
9547
+ }
9548
+ };
9549
+ }
9550
+ /** The session a ratcheted item of this lane names (its `sid`, base64url), as its header says; undefined for anything else. */
9551
+ var ratchetSessionOf = (sealed, lane) => {
9552
+ const h = parseHeader(sealed);
9553
+ return h?.lane === lane ? h.sid : void 0;
9554
+ };
9555
+ /**
9556
+ * Whether `sealed` names a session this side has no state of and did not retire: neither the current one nor one of the
9557
+ * others. What the contact sealed in the session it shares with a device this profile was on before (a Move, a restore:
9558
+ * WISP 4xx § Several devices) is such an item, once the turn passed there; so is anything under a made-up `sid`. It says
9559
+ * nothing of whether the item is genuine: only that this side could not tell, having never had the session.
9560
+ */
9561
+ function ratchetUnknownSession(state, sealed, lane) {
9562
+ const h = parseHeader(sealed);
9563
+ if (!h || h.lane !== lane) return false;
9564
+ const s = state ?? emptyRatchetState();
9565
+ return s.current?.sid !== h.sid && !s.others.some((o) => o.sid === h.sid) && !s.retired.includes(h.sid);
9566
+ }
9567
+ /** Whether forward secrecy is on for this chat: the turn passed both ways in the session this side seals with. */
9568
+ var ratchetOn = (state) => !!state?.current?.fs;
9569
+ /** Whether a lane refuses plain items from the contact: a ratcheted one opened there (WISP 4xx § Downgrade). */
9570
+ var ratchetHeard = (state, lane) => !!state?.heard[lane];
9571
+ /**
9572
+ * One chat's ratchet, shared by its two lanes (the DHT floor and held items): the one lock per chat of WISP 4xx §
9573
+ * Saving state, and the order of saving. Every change goes through `lock`, so a seal and an open never start from the
9574
+ * same state.
9575
+ */
9576
+ var RatchetBox = class {
9577
+ keys;
9578
+ state;
9579
+ save;
9580
+ chain = Promise.resolve();
9581
+ constructor(keys, state, save) {
9582
+ this.keys = keys;
9583
+ this.state = state;
9584
+ this.save = save;
9585
+ }
9586
+ /** Runs `fn` alone among this chat's ratchet changes; `seal` and `open` are called inside it only. */
9587
+ lock(fn) {
9588
+ const run = this.chain.then(() => fn(this.transaction()));
9589
+ this.chain = run.then(() => {}, () => {});
9590
+ return run;
9591
+ }
9592
+ transaction() {
9593
+ return {
9594
+ seal: async (lane, plaintext) => {
9595
+ const { state, sealed } = ratchetSeal(this.state, this.keys(), lane, plaintext);
9596
+ await this.save(state);
9597
+ this.state = state;
9598
+ return sealed;
9599
+ },
9600
+ open: (lane, sealed) => {
9601
+ const opened = ratchetOpen(this.state, this.keys(), lane, sealed);
9602
+ if (!opened) return null;
9603
+ return {
9604
+ plaintext: opened.plaintext,
9605
+ fresh: opened.fresh,
9606
+ commit: async (order) => {
9607
+ const state = opened.finish(order);
9608
+ await this.save(state);
9609
+ this.state = state;
9610
+ }
9611
+ };
9612
+ }
9613
+ };
9614
+ }
9615
+ /**
9616
+ * Opens without keeping anything, and without the lock: a look from another profile, or the first half of a receive
9617
+ * whose content is then stored with no lock held (`commitOpen` keeps it).
9618
+ */
9619
+ peek(lane, sealed) {
9620
+ return ratchetOpen(this.state, this.keys(), lane, sealed)?.plaintext ?? null;
9621
+ }
9622
+ /**
9623
+ * The second half of a receive, once what `peek` gave is stored: opened again under the lock on the state as it is now
9624
+ * (a seal or another open may have moved it meanwhile), and that state saved. False: it no longer opens (taken by a
9625
+ * receive of the same item meanwhile), and nothing moved. So the lock is never held while content is stored, which
9626
+ * may call back into the other lane.
9627
+ */
9628
+ commitOpen(lane, sealed, order) {
9629
+ return this.lock(async (tx) => {
9630
+ const opened = tx.open(lane, sealed);
9631
+ if (!opened) return false;
9632
+ await opened.commit(order);
9633
+ return true;
9634
+ });
9635
+ }
9636
+ heard(lane) {
9637
+ return ratchetHeard(this.state, lane);
9638
+ }
9639
+ /** A ratcheted item from the contact opened on either lane: this side seals with the ratchet whatever the contact's record says. */
9640
+ get heardAny() {
9641
+ return this.heard("floor") || this.heard("hold");
9642
+ }
9643
+ get on() {
9644
+ return ratchetOn(this.state);
9645
+ }
9646
+ /** The session this side seals with now, if any (its `sid`). */
9647
+ get session() {
9648
+ return this.state.current?.sid;
9649
+ }
9650
+ /** `ratchetUnknownSession` on the state as it is: an item under a session this side never had. */
9651
+ unknownSession(lane, sealed) {
9652
+ return ratchetUnknownSession(this.state, sealed, lane);
9653
+ }
9654
+ };
9655
+ //#endregion
9170
9656
  //#region ../core/src/groupCrypto.ts
9171
9657
  /**
9172
9658
  * The cryptography of the `group-mesh/1` profile (WISP 900 / 902 group mesh).
@@ -11302,6 +11788,11 @@ var DhtDelivery = class DhtDelivery {
11302
11788
  live = false;
11303
11789
  active = false;
11304
11790
  startedAt = Date.now();
11791
+ /**
11792
+ * When an envelope of the contact's newer than any before was last read here, in this run. A contact that is there
11793
+ * puts a keep-alive every four minutes: none in `PRESENCE_WINDOW`, it is away (`publish`).
11794
+ */
11795
+ peerNewAt = -Infinity;
11305
11796
  /** The next read was asked for (a refresh, a fresh packet of the contact): it is not a background one. */
11306
11797
  urgent = false;
11307
11798
  /** Reads left that are signaling: the contact is leaving DHT only, and the live link waits on them (`expect`). */
@@ -11375,9 +11866,29 @@ var DhtDelivery = class DhtDelivery {
11375
11866
  maxTextBytes: 256,
11376
11867
  ...this.lastPublished && { lastPublished: this.lastPublished },
11377
11868
  ...this.foreignKeySeenAt && { foreignKeySeenAt: this.foreignKeySeenAt },
11378
- ...this.state.inviteTaken && { inviteTaken: true }
11869
+ ...this.state.inviteTaken && { inviteTaken: true },
11870
+ ...this.forwardSecrecy && { forwardSecrecy: this.forwardSecrecy }
11379
11871
  };
11380
11872
  }
11873
+ get forwardSecrecy() {
11874
+ const ratchet = this.options.ratchet;
11875
+ if (!ratchet || !this.options.credentials.peerKey) return void 0;
11876
+ const supports = ratchet.peerSupports();
11877
+ return ratchet.box.on && supports ? "on" : !supports ? ratchet.box.heardAny ? "stopped" : "unsupported" : "starting";
11878
+ }
11879
+ /**
11880
+ * Whether an envelope to `recipient` is sealed with the ratchet: the contact is pinned and its record lists
11881
+ * `ratchet/1`, or a ratcheted envelope of its was opened here, after which nothing goes plain (WISP 4xx § Downgrade).
11882
+ * And the contact pinned this side too (an envelope of its sealed to this side read, or a live session had): a joiner
11883
+ * pins its inviter from the invite, and its first contact sealed with the ratchet would reach an inviter that has no key
11884
+ * to open it with, and so never pins it.
11885
+ */
11886
+ ratcheted(recipient) {
11887
+ const ratchet = this.options.ratchet, peer = this.options.credentials.peerKey;
11888
+ if (!ratchet || !peer || recipient !== peer) return false;
11889
+ if (ratchet.box.heardAny) return true;
11890
+ return ratchet.peerSupports() && (!!this.state.peerPinned || !!this.state.wasLive);
11891
+ }
11381
11892
  /**
11382
11893
  * This side joined, and its inviter never answered (`DhtDeliveryState.unanswered`): no envelope of its newer than the
11383
11894
  * one that pinned it, none sealed to this side, no text confirmed, never live (as `sealedToAnother` asks too).
@@ -11416,6 +11927,14 @@ var DhtDelivery = class DhtDelivery {
11416
11927
  return this.pinnedBoxes;
11417
11928
  }
11418
11929
  lastPublished;
11930
+ /** The envelope a trace line was last said for, per step: a packet read again says nothing new (a Desktop logs every line). */
11931
+ traced = /* @__PURE__ */ new Map();
11932
+ traceOnce(step, record, detail) {
11933
+ const seen = record.slice(-24);
11934
+ if (this.traced.get(step) === seen) return;
11935
+ this.traced.set(step, seen);
11936
+ traceLink(this.from, step, detail);
11937
+ }
11419
11938
  /** The sealed record's nonce is its first 24 bytes: 32 characters of base64. */
11420
11939
  static facts(body, records, key) {
11421
11940
  return {
@@ -11471,6 +11990,13 @@ var DhtDelivery = class DhtDelivery {
11471
11990
  ]));
11472
11991
  }
11473
11992
  records(body, recipient = this.options.credentials.peerKey) {
11993
+ return this.envelope(body, recipient).records;
11994
+ }
11995
+ /**
11996
+ * The envelope's records. Ratcheted (`ratcheted`), its `_dr` record is the right length but not sealed yet: `seal`
11997
+ * gives its bytes, under the chat's lock, once the publication is sure to go. Measuring a packet takes no key.
11998
+ */
11999
+ envelope(body, recipient = this.options.credentials.peerKey) {
11474
12000
  const signature = toBase64Url(sign(this.signed(body, recipient), this.participation.seed));
11475
12001
  const plaintext = JSON.stringify([body, signature]);
11476
12002
  const hint = recipient ? [{
@@ -11478,20 +12004,46 @@ var DhtDelivery = class DhtDelivery {
11478
12004
  value: encrypt(this.participation.pubKeyZ32, this.key),
11479
12005
  ttl: ENVELOPE_TTL
11480
12006
  }] : [];
12007
+ const ratchet = this.ratcheted(recipient);
12008
+ const sealedBytes = (bytes) => ratchet ? 4 * Math.ceil((66 + bytes) / 3) : sealedLength(bytes);
12009
+ const label = ratchet ? "_dr" : "_dm";
11481
12010
  const fits = (bytes) => bytes <= MAX_ENVELOPE_PLAINTEXT && measureRecords(this.identity.pubKeyZ32, [{
11482
- label: "_dm",
11483
- value: "A".repeat(sealedLength(bytes)),
12011
+ label,
12012
+ value: "A".repeat(sealedBytes(bytes)),
11484
12013
  ttl: ENVELOPE_TTL
11485
12014
  }, ...hint]) <= ENVELOPE_PACKET_BYTES;
11486
12015
  const bytes = utf8Encode(plaintext).length;
11487
12016
  if (!fits(bytes)) throw new Error("Text and authentication exceed the DHT packet budget. Shorten the message.");
11488
12017
  let padded = bytes;
11489
12018
  for (let step = 512; step >= 1; step >>= 1) if (fits(padded + step)) padded += step;
11490
- return [{
11491
- label: "_dm",
11492
- value: encrypt(plaintext + " ".repeat(padded - bytes), recipient ? this.sealedKey(recipient) : this.key),
12019
+ const full = plaintext + " ".repeat(padded - bytes);
12020
+ if (ratchet) return {
12021
+ records: [{
12022
+ label,
12023
+ value: "A".repeat(sealedBytes(padded)),
12024
+ ttl: ENVELOPE_TTL
12025
+ }, ...hint],
12026
+ plaintext: full
12027
+ };
12028
+ return { records: [{
12029
+ label,
12030
+ value: encrypt(full, recipient ? this.sealedKey(recipient) : this.key),
11493
12031
  ttl: ENVELOPE_TTL
11494
- }, ...hint];
12032
+ }, ...hint] };
12033
+ }
12034
+ /**
12035
+ * The records to publish: a ratcheted one sealed now, its state saved first (seal, save, send), from the plaintext
12036
+ * the envelope was measured with.
12037
+ */
12038
+ async sealed(envelope) {
12039
+ const { records, plaintext } = envelope;
12040
+ if (records[0]?.label !== "_dr") return records;
12041
+ if (plaintext === void 0) throw new Error("A ratcheted envelope without its plaintext");
12042
+ const sealed = await this.options.ratchet.box.lock((tx) => tx.seal("floor", utf8Encode(plaintext)));
12043
+ return [{
12044
+ ...records[0],
12045
+ value: toBase64(sealed)
12046
+ }, ...records.slice(1)];
11495
12047
  }
11496
12048
  async start() {
11497
12049
  if (this.running) return;
@@ -11610,6 +12162,7 @@ var DhtDelivery = class DhtDelivery {
11610
12162
  }
11611
12163
  validate(text, timestamp, id, reply, edit) {
11612
12164
  if (this.options.peerAcceptsText?.() === false) return DHT_TEXT_REFUSED;
12165
+ if (this.forwardSecrecy === "stopped") return DHT_RATCHET_STOPPED;
11613
12166
  if (!ID$2.test(id) || !Number.isSafeInteger(timestamp) || timestamp <= 0 || reply !== void 0 && !REPLY_TO.test(reply)) return "Invalid message.";
11614
12167
  if (edit !== void 0 && (reply !== void 0 || !ID$2.test(edit[0]) || !validEditNumber(edit[1]))) return "Invalid message.";
11615
12168
  if (utf8Encode(text).length > 256) return DHT_TEXT_TOO_LONG;
@@ -11884,10 +12437,10 @@ var DhtDelivery = class DhtDelivery {
11884
12437
  for (let count = pending.length; count > 0; count--) {
11885
12438
  const body = this.body(sequence, issued, expires, message, receipt, reply, pending.slice(0, count), edit, forwarded, file);
11886
12439
  try {
11887
- const records = this.records(body);
12440
+ const envelope = this.envelope(body);
11888
12441
  if (utf8Encode(JSON.stringify([body, "x".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT) return {
11889
12442
  body,
11890
- records,
12443
+ ...envelope,
11891
12444
  reactions: count
11892
12445
  };
11893
12446
  } catch {}
@@ -11895,7 +12448,7 @@ var DhtDelivery = class DhtDelivery {
11895
12448
  const body = this.body(sequence, issued, expires, message, receipt, reply, [], edit, forwarded, file);
11896
12449
  return {
11897
12450
  body,
11898
- records: this.records(body),
12451
+ ...this.envelope(body),
11899
12452
  reactions: 0
11900
12453
  };
11901
12454
  }
@@ -11910,10 +12463,21 @@ var DhtDelivery = class DhtDelivery {
11910
12463
  if (keepAlive && (this.controlDue > now || this.state.inviteTaken)) return;
11911
12464
  const expires = pending?.expires ?? now - 12e4 + CONTROL_TTL;
11912
12465
  const issued = Math.min(now, Math.max(now - DHT_ISSUED_BACK_MS, expires - (pending ? DHT_MESSAGE_TTL : CONTROL_TTL), (pending?.message[1] ?? 0) - 3e4));
11913
- const { body, records, reactions } = this.fitted(this.sequence + 1, issued, expires, pending?.message ?? null, receipt?.id ?? null, pending?.reply, pending?.edit, pending?.forwarded, pending?.file);
12466
+ const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
12467
+ const away = !!this.options.credentials.peerKey && now - this.peerNewAt >= 6e5;
12468
+ const options = keepAlive && (this.live || away) ? { background: true } : void 0;
12469
+ const held = this.options.transport.publishHeld?.(identity.pubKeyZ32, options);
12470
+ if (held) {
12471
+ await this.heldBack(held, now, {
12472
+ lastPublish: this.lastPublish,
12473
+ controlDue: this.controlDue
12474
+ }, void 0, void 0);
12475
+ throw held;
12476
+ }
12477
+ const fittedEnvelope = this.fitted(this.sequence + 1, issued, expires, pending?.message ?? null, receipt?.id ?? null, pending?.reply, pending?.edit, pending?.forwarded, pending?.file);
12478
+ const { body, reactions } = fittedEnvelope;
11914
12479
  const reactionsWereDue = this.reactionsDue;
11915
12480
  this.reactionsDue = !reactions && !!this.options.reactions?.().length;
11916
- const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
11917
12481
  const sequence = body[1];
11918
12482
  await this.persist({
11919
12483
  ...this.state,
@@ -11930,20 +12494,23 @@ var DhtDelivery = class DhtDelivery {
11930
12494
  } : this.state.receipt
11931
12495
  });
11932
12496
  this.sequence = sequence;
12497
+ const records = await this.sealed(fittedEnvelope);
11933
12498
  const before = {
11934
12499
  lastPublish: this.lastPublish,
11935
12500
  controlDue: this.controlDue
11936
12501
  };
12502
+ const ownInvite = !this.options.credentials.expectedPeerKey && !this.active && this.unusedInviteAge(now) !== void 0;
11937
12503
  this.lastPublish = now;
11938
- this.controlDue = now + 24e4;
12504
+ this.controlDue = now + (ownInvite ? UNUSED_INVITE_UPKEEP_MS : 24e4);
11939
12505
  traceLink(this.from, "dht-publish", {
11940
12506
  mode: this.mode,
11941
12507
  seq: body[1],
11942
- ...identity !== this.identity && { pinned: true }
12508
+ ...identity !== this.identity && { pinned: true },
12509
+ ...records[0]?.label === "_dr" && { ratchet: true }
11943
12510
  });
11944
12511
  if (pending) this.lastPublished = DhtDelivery.facts(body, records, identity.pubKeyZ32);
11945
12512
  try {
11946
- await this.options.transport.publish(identity, records, keepAlive && this.live ? { background: true } : void 0);
12513
+ await this.options.transport.publish(identity, records, options);
11947
12514
  } catch (error) {
11948
12515
  this.reactionsDue ||= reactionsWereDue;
11949
12516
  if (isDiscoveryBudgetError(error)) await this.heldBack(error, now, before, pending, receipt);
@@ -11969,7 +12536,7 @@ var DhtDelivery = class DhtDelivery {
11969
12536
  this.lastPublish = before.lastPublish;
11970
12537
  this.controlDue = Math.min(before.controlDue, at);
11971
12538
  traceLink(this.from, "dht-publish-waits", { retryInMs: at - now });
11972
- await this.persist({
12539
+ if (pending || receipt) await this.persist({
11973
12540
  ...this.state,
11974
12541
  pending: pending ?? this.state.pending,
11975
12542
  receipt: receipt ?? this.state.receipt
@@ -11980,22 +12547,44 @@ var DhtDelivery = class DhtDelivery {
11980
12547
  * one sealed record, a well-formed body within its times, signed by the key it names. Null: not an envelope of the
11981
12548
  * contact's (the pin rules are the caller's).
11982
12549
  */
11983
- open(packet, box) {
12550
+ open(packet, box, ratchet) {
11984
12551
  const address = box === "pinned" ? this.pinned()?.peerAddress : this.peerAddress;
11985
12552
  if (!address || packet.pubKeyZ32 !== address || measureRecords(packet.pubKeyZ32, packet.records) > 1e3) return null;
11986
- const records = packet.records.filter((r) => r.label === "_dm");
11987
- if (records.length !== 1) return null;
12553
+ const records = packet.records.filter((r) => r.label === "_dm"), ratcheted = packet.records.filter((r) => r.label === "_dr");
12554
+ if (records.length + ratcheted.length !== 1) return null;
11988
12555
  const hints = packet.records.filter((r) => r.label === "_dmk");
11989
12556
  if (hints.length > 1) return null;
11990
12557
  const sender = hints.length ? tryDecrypt(hints[0].value, this.key) : null;
11991
12558
  if (hints.length && !sender) return null;
12559
+ const peer = this.options.credentials.peerKey;
11992
12560
  let plaintext;
11993
- try {
11994
- plaintext = tryDecrypt(records[0].value, sender ? this.sealedKey(sender) : this.key);
11995
- } catch {
11996
- plaintext = null;
12561
+ if (ratcheted.length) {
12562
+ const closed = box === "invite" && sender ? { sealedToAnother: sender } : null;
12563
+ if (!ratchet || !peer || sender !== peer) return closed;
12564
+ let opened;
12565
+ try {
12566
+ opened = ratchet(fromBase64(ratcheted[0].value));
12567
+ } catch {
12568
+ opened = null;
12569
+ }
12570
+ if (!opened) return closed;
12571
+ try {
12572
+ plaintext = utf8Decode(opened);
12573
+ } catch {
12574
+ return null;
12575
+ }
12576
+ } else {
12577
+ if (peer && this.options.ratchet?.box.heard("floor") && (!sender || sender === peer)) {
12578
+ this.traceOnce("dht-plain-refused", records[0].value, { box });
12579
+ return null;
12580
+ }
12581
+ try {
12582
+ plaintext = tryDecrypt(records[0].value, sender ? this.sealedKey(sender) : this.key);
12583
+ } catch {
12584
+ plaintext = null;
12585
+ }
12586
+ if (!plaintext && sender) return { sealedToAnother: sender };
11997
12587
  }
11998
- if (!plaintext && sender) return { sealedToAnother: sender };
11999
12588
  if (!plaintext || utf8Encode(plaintext).length > MAX_ENVELOPE_PLAINTEXT) return null;
12000
12589
  let envelope;
12001
12590
  try {
@@ -12075,7 +12664,41 @@ var DhtDelivery = class DhtDelivery {
12075
12664
  * can write to) or `pinned`. `none`: nothing from the contact in it; `old`: the contact's, already read; `new`: taken.
12076
12665
  */
12077
12666
  async receive(packet, box) {
12078
- const opened = this.open(packet, box);
12667
+ const ratcheted = packet.records.find((r) => r.label === "_dr");
12668
+ if (!ratcheted) return this.take(packet, box, this.open(packet, box));
12669
+ const digest = toBase64Url(sha256(utf8Encode(ratcheted.value)).slice(0, 16));
12670
+ if (digest === this.state.lastDr) return "old";
12671
+ const ratchet = this.options.ratchet;
12672
+ if (!ratchet) return "none";
12673
+ let sealed;
12674
+ const opened = this.open(packet, box, (bytes) => {
12675
+ const plain = ratchet.box.peek("floor", bytes);
12676
+ if (plain) sealed = bytes;
12677
+ return plain;
12678
+ });
12679
+ if (!sealed) this.traceOnce("dht-ratchet-closed", ratcheted.value, {
12680
+ box,
12681
+ pinned: !!this.options.credentials.peerKey
12682
+ });
12683
+ if (!sealed && box === "pinned" && packet.pubKeyZ32 === this.pinned()?.peerAddress && this.state.peerPinned !== "seen") {
12684
+ await this.persist({
12685
+ ...this.state,
12686
+ peerPinned: "seen"
12687
+ });
12688
+ traceLink(this.from, "dht-peer-pinned", {
12689
+ peerPinned: "seen",
12690
+ ratchet: true
12691
+ });
12692
+ }
12693
+ return this.take(packet, box, opened, sealed && {
12694
+ commit: async (order) => {
12695
+ if (!await ratchet.box.commitOpen("floor", sealed, order)) throw new Error("A ratcheted envelope no longer opens");
12696
+ },
12697
+ digest
12698
+ });
12699
+ }
12700
+ /** `ratchet`: the envelope was ratcheted; its state is saved once what it carried is stored, with its digest. */
12701
+ async take(packet, box, opened, ratchet) {
12079
12702
  if (!opened) return "none";
12080
12703
  if ("sealedToAnother" in opened) {
12081
12704
  if (opened.sealedToAnother) await this.sealedToAnother(opened.sealedToAnother);
@@ -12102,6 +12725,7 @@ var DhtDelivery = class DhtDelivery {
12102
12725
  if (message !== null && (!Array.isArray(message) || message.length !== 3 || typeof message[0] !== "string" || !ID$2.test(message[0]) || !Number.isSafeInteger(message[1]) || message[1] <= 0 || message[1] > issued + 3e4 || typeof message[2] !== "string" || utf8Encode(message[2]).length > 256 || expires - issued > 3e5)) return "none";
12103
12726
  if (receipt !== null && (typeof receipt !== "string" || !ID$2.test(receipt))) return "none";
12104
12727
  const unanswered = !this.options.credentials.peerKey && !!this.options.credentials.expectedPeerKey && !sender && !this.live;
12728
+ this.peerNewAt = Date.now();
12105
12729
  await this.options.pin(author);
12106
12730
  this.options.credentials.peerKey = author;
12107
12731
  this.options.credentials.requireSignedSignals = true;
@@ -12145,6 +12769,7 @@ var DhtDelivery = class DhtDelivery {
12145
12769
  if (peerPinned !== this.state.peerPinned) traceLink(this.from, "dht-peer-pinned", { peerPinned });
12146
12770
  if (this.state.inviteTaken) traceLink(this.from, "invite-untaken", {});
12147
12771
  const { inviteTaken: _taken, ...kept } = this.state;
12772
+ if (ratchet) await ratchet.commit(sequence);
12148
12773
  await this.persist({
12149
12774
  ...kept,
12150
12775
  peerSequence: sequence,
@@ -12153,6 +12778,7 @@ var DhtDelivery = class DhtDelivery {
12153
12778
  confirmed,
12154
12779
  ...peerPinned && { peerPinned },
12155
12780
  ...unanswered && { unanswered: sequence },
12781
+ ...ratchet && { lastDr: ratchet.digest },
12156
12782
  pending: confirmed && this.state.pending?.message[0] === confirmed ? void 0 : this.state.pending,
12157
12783
  ...newest > (this.state.reactionsTaken ?? 0) && { reactionsTaken: newest }
12158
12784
  });
@@ -12207,7 +12833,12 @@ var DhtDelivery = class DhtDelivery {
12207
12833
  for (const box of boxes) {
12208
12834
  const packet = await this.options.transport.resolve(box === "pinned" ? pinned.peerAddress : this.peerAddress, options);
12209
12835
  reads++;
12210
- const opened = packet && this.open(packet, box);
12836
+ const dr = packet?.records.find((r) => r.label === "_dr");
12837
+ if (dr && toBase64Url(sha256(utf8Encode(dr.value)).slice(0, 16)) === this.state.lastDr) return {
12838
+ reads,
12839
+ text: null
12840
+ };
12841
+ const opened = packet && this.open(packet, box, (sealed) => this.options.ratchet?.box.peek("floor", sealed) ?? null);
12211
12842
  if (!opened || "sealedToAnother" in opened || opened.author !== expected) continue;
12212
12843
  const { sequence, message } = opened;
12213
12844
  const fresh = Array.isArray(message) && typeof message[0] === "string" && ID$2.test(message[0]) && sequence > this.state.peerSequence && this.state.receipt?.id !== message[0];
@@ -12322,6 +12953,7 @@ var DhtDelivery = class DhtDelivery {
12322
12953
  }
12323
12954
  };
12324
12955
  var DHT_TEXT_REFUSED = "Your contact's app does not accept text over the DHT. It is sent when you are live.";
12956
+ var DHT_RATCHET_STOPPED = "Your contact's app no longer reads protected messages over the DHT. It is sent when you are live.";
12325
12957
  var DHT_FILE_REFUSED = "Your contact's app shows a file only once it comes. It is sent when you are live.";
12326
12958
  var DHT_FILE_TOO_LARGE = "This file's name is too long to say over the DHT. It is sent when you are live.";
12327
12959
  /**
@@ -12332,17 +12964,29 @@ function peekDhtMailbox(options) {
12332
12964
  const refuse = async () => {
12333
12965
  throw new Error("A peek saves nothing");
12334
12966
  };
12967
+ const credentials = { ...options.credentials }, peer = credentials.peerKey;
12968
+ const box = options.ratchet && peer ? new RatchetBox(() => ({
12969
+ seed: fromBase64Url(credentials.seedB64),
12970
+ self: identityFromSeedB64(credentials.seedB64).pubKeyZ32,
12971
+ peer,
12972
+ rendezvous: [identityFromSeedB64(options.params.seedB64).pubKeyZ32, options.params.peerPubKeyZ32],
12973
+ secret: fromBase64Url(options.params.encKeyB64)
12974
+ }), options.ratchet, refuse) : void 0;
12335
12975
  return new DhtDelivery({
12336
12976
  params: options.params,
12337
12977
  mode: "stream",
12338
12978
  state: options.state,
12339
- credentials: { ...options.credentials },
12979
+ credentials,
12340
12980
  transport: options.transport,
12341
12981
  save: refuse,
12342
12982
  pin: refuse,
12343
12983
  message: refuse,
12344
12984
  receipt: refuse,
12345
- changed: () => {}
12985
+ changed: () => {},
12986
+ ...box && { ratchet: {
12987
+ box,
12988
+ peerSupports: () => true
12989
+ } }
12346
12990
  }).peek(options.background ? { background: true } : void 0);
12347
12991
  }
12348
12992
  //#endregion
@@ -14696,17 +15340,23 @@ var CapsExchange = class {
14696
15340
  return;
14697
15341
  }
14698
15342
  if (due) {
15343
+ const options = changed || unpublished ? void 0 : { background: true };
15344
+ const held = this.options.transport.publishHeld?.(this.keys.identity.pubKeyZ32, options);
15345
+ if (held) {
15346
+ this.schedule(budgetRetryMs(held, 1e3, 6e4));
15347
+ throw held;
15348
+ }
14699
15349
  const rev = changed ? this.state.rev + 1 : this.state.rev;
14700
15350
  const { records, dropped } = this.keys.seal(content, rev, peerKey, now);
14701
15351
  this.dropped = dropped;
14702
- await this.persist({
15352
+ if (!(rev === this.state.rev && digest === this.state.digest && peerKey === this.state.sealedFor && this.state.publishedAt === void 0)) await this.persist({
14703
15353
  rev,
14704
15354
  digest,
14705
15355
  sealedFor: peerKey,
14706
15356
  publishedAt: void 0
14707
15357
  });
14708
15358
  try {
14709
- await this.options.transport.publish(this.keys.identity, records, changed || unpublished ? void 0 : { background: true });
15359
+ await this.options.transport.publish(this.keys.identity, records, options);
14710
15360
  } catch (error) {
14711
15361
  this.schedule(isDiscoveryBudgetError(error) ? budgetRetryMs(error, 1e3, 6e4) : 6e4);
14712
15362
  throw error;
@@ -14994,14 +15644,15 @@ function parseDomainTxt(value) {
14994
15644
  var addRecord = (list, r) => {
14995
15645
  if (!list.some((x) => x.key === r.key && x.proof === r.proof)) list.push(r);
14996
15646
  };
14997
- /** All records among the TXT strings of `_ghostly.<domain>`; other strings are skipped. */
15647
+ /** All records among the first 32 TXT strings of `_ghostly.<domain>`; other strings are skipped. A TXT set has
15648
+ * no order, so every record is kept: the one a proof needs may come in any position. */
14998
15649
  function recordsFromTxt(values) {
14999
15650
  const out = [];
15000
15651
  for (const value of values.slice(0, 32)) {
15001
15652
  const r = parseDomainTxt(value);
15002
15653
  if (r) addRecord(out, r);
15003
15654
  }
15004
- return out.slice(0, 8);
15655
+ return out;
15005
15656
  }
15006
15657
  /** The body of `/.well-known/ghostly.json`. */
15007
15658
  function domainWellKnownFile(records) {
@@ -15018,7 +15669,7 @@ function parseJson(text) {
15018
15669
  if (typeof text !== "string" || utf8Encode(text).length > 16384) throw new Error("File too large");
15019
15670
  return JSON.parse(text);
15020
15671
  }
15021
- /** Records from `ghostly.json`. Throws on a malformed file; [] when it names none. */
15672
+ /** Records from the first 32 entries of `ghostly.json`. Throws on a malformed file; [] when it names none. */
15022
15673
  function recordsFromWellKnown(text) {
15023
15674
  const body = parseJson(text);
15024
15675
  if (!body || typeof body !== "object" || Array.isArray(body) || body.ghostly !== 1 || !Array.isArray(body.proofs)) throw new Error("Not a Ghostly domain file");
@@ -15031,7 +15682,7 @@ function recordsFromWellKnown(text) {
15031
15682
  };
15032
15683
  if (validDomainRecord(r)) addRecord(out, r);
15033
15684
  }
15034
- return out.slice(0, 8);
15685
+ return out;
15035
15686
  }
15036
15687
  /** NIP-05: only the root name `_` speaks for the domain itself. Undefined when absent. */
15037
15688
  function nip05RootKey(text) {
@@ -15214,9 +15865,13 @@ var SIG$3 = /^[A-Za-z0-9_-]{86}$/;
15214
15865
  var MAGIC$1 = utf8Encode("GHLD");
15215
15866
  var VERSION = 1;
15216
15867
  var NONCE$2 = 24;
15868
+ /** A bundle sealed by the chat's ratchet (WISP 4xx § Held items). */
15869
+ var RATCHETED = 2;
15217
15870
  /** Why a bundle, manifest or pointer was refused. Never a reason to trust it a little. */
15218
15871
  var HoldRefusedError = class extends Error {
15219
15872
  reason;
15873
+ /** The bytes the chat's ratchet opened, when it opened them before the item was refused: the caller commits them. */
15874
+ ratcheted;
15220
15875
  constructor(reason, message) {
15221
15876
  super(message);
15222
15877
  this.reason = reason;
@@ -15256,6 +15911,19 @@ var HoldKeys = class {
15256
15911
  }
15257
15912
  /** Seals one item for the contact: signed with my participation key, encrypted to our shared key. */
15258
15913
  seal(item, body) {
15914
+ const nonce = randomBytes(NONCE$2);
15915
+ const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(this.inner(item, body));
15916
+ return concatBytes$1(MAGIC$1, new Uint8Array([VERSION]), nonce, box);
15917
+ }
15918
+ /**
15919
+ * The same item as a version-2 bundle (WISP 4xx § Held items): the same plaintext, sealed by the chat's ratchet
15920
+ * (`seal`, which saves the ratchet's state before it returns), so the bundle can be uploaded once this returns.
15921
+ */
15922
+ async sealRatcheted(item, body, seal) {
15923
+ return concatBytes$1(MAGIC$1, new Uint8Array([RATCHETED]), await seal(this.inner(item, body)));
15924
+ }
15925
+ /** What a bundle seals: the header's length, the signed header, the body. */
15926
+ inner(item, body) {
15259
15927
  const fields = [
15260
15928
  VERSION,
15261
15929
  this.from,
@@ -15275,26 +15943,51 @@ var HoldKeys = class {
15275
15943
  const header = utf8Encode(JSON.stringify([fields, signature]));
15276
15944
  const length = /* @__PURE__ */ new Uint8Array(4);
15277
15945
  new DataView(length.buffer).setUint32(0, header.length);
15278
- const nonce = randomBytes(NONCE$2);
15279
- const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(concatBytes$1(length, header, body));
15280
- return concatBytes$1(MAGIC$1, new Uint8Array([VERSION]), nonce, box);
15946
+ return concatBytes$1(length, header, body);
15281
15947
  }
15282
15948
  /**
15283
15949
  * Opens a bundle the contact sealed for me. Everything is checked before anything is returned: the
15284
15950
  * authenticated encryption, the header's shape, that it names this link, this contact and me, the
15285
15951
  * signature, the body digest and the limits of its kind. `loopback`: see `isHoldUrl`.
15286
15952
  */
15953
+ /**
15954
+ * `ratchet`: opens a version-2 bundle's sealed bytes (WISP 4xx), without keeping anything; absent, one is from a newer
15955
+ * Ghostly. `refusePlain`: a ratcheted item from this contact opened here, so a version-1 item other than the manifest is
15956
+ * refused (WISP 4xx § Downgrade). `ratcheted` in the result: the bytes the ratchet opened, for the caller to commit once
15957
+ * the item is stored.
15958
+ */
15287
15959
  open(bytes, expect = {}) {
15288
15960
  const now = expect.now ?? Date.now();
15289
15961
  if (bytes.length > (expect.maxBytes ?? HOLD_LIMITS.maxBundleBytes)) throw new HoldRefusedError("size", "The held item is larger than allowed");
15290
- if (bytes.length < MAGIC$1.length + 1 + NONCE$2 + 16 + 4 || !MAGIC$1.every((b, i) => bytes[i] === b)) throw new HoldRefusedError("format", "Not a held item");
15291
- if (bytes[MAGIC$1.length] !== VERSION) throw new HoldRefusedError("format", "Held item from a newer Ghostly");
15292
- let plain;
15962
+ if (bytes.length < MAGIC$1.length + 1 + 16 + 4 || !MAGIC$1.every((b, i) => bytes[i] === b)) throw new HoldRefusedError("format", "Not a held item");
15963
+ const version = bytes[MAGIC$1.length];
15964
+ if (version !== VERSION && (version !== RATCHETED || !expect.ratchet)) throw new HoldRefusedError("format", "Held item from a newer Ghostly");
15965
+ let plain, ratcheted;
15966
+ if (version === RATCHETED) {
15967
+ ratcheted = bytes.subarray(MAGIC$1.length + 1);
15968
+ try {
15969
+ plain = expect.ratchet(ratcheted);
15970
+ } catch {
15971
+ plain = null;
15972
+ }
15973
+ if (!plain) throw new HoldRefusedError("tampered", "The held item was changed, is not for this chat, or was opened already");
15974
+ } else {
15975
+ if (bytes.length < MAGIC$1.length + 1 + NONCE$2 + 16 + 4) throw new HoldRefusedError("format", "Not a held item");
15976
+ try {
15977
+ plain = xsalsa20poly1305(this.sealKey, bytes.subarray(MAGIC$1.length + 1, MAGIC$1.length + 1 + NONCE$2)).decrypt(bytes.subarray(MAGIC$1.length + 1 + NONCE$2));
15978
+ } catch {
15979
+ throw new HoldRefusedError("tampered", "The held item was changed or is not for this chat");
15980
+ }
15981
+ }
15293
15982
  try {
15294
- plain = xsalsa20poly1305(this.sealKey, bytes.subarray(MAGIC$1.length + 1, MAGIC$1.length + 1 + NONCE$2)).decrypt(bytes.subarray(MAGIC$1.length + 1 + NONCE$2));
15295
- } catch {
15296
- throw new HoldRefusedError("tampered", "The held item was changed or is not for this chat");
15983
+ return this.read(plain, ratcheted, expect, now);
15984
+ } catch (error) {
15985
+ if (error instanceof HoldRefusedError && ratcheted) error.ratcheted = ratcheted;
15986
+ throw error;
15297
15987
  }
15988
+ }
15989
+ /** The checks of `open` once the bundle is decrypted. */
15990
+ read(plain, ratcheted, expect, now) {
15298
15991
  if (plain.length < 4) throw new HoldRefusedError("format", "Not a held item");
15299
15992
  const headerLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0);
15300
15993
  if (headerLength > 131072 || 4 + headerLength > plain.length) throw new HoldRefusedError("format", "Not a held item");
@@ -15336,10 +16029,12 @@ var HoldKeys = class {
15336
16029
  digest,
15337
16030
  expires
15338
16031
  };
16032
+ if (!ratcheted && expect.refusePlain && kind !== "manifest") throw new HoldRefusedError("plain", "The held item was sealed without forward secrecy, which this chat no longer takes");
15339
16033
  checkKind(header, body, expect.loopback);
15340
16034
  return {
15341
16035
  header,
15342
- body
16036
+ body,
16037
+ ...ratcheted && { ratcheted }
15343
16038
  };
15344
16039
  }
15345
16040
  /** My pointer, as records to publish under `identity`. Throws when it cannot fit a packet. */
@@ -17525,6 +18220,15 @@ var FINAL = /* @__PURE__ */ new Set([
17525
18220
  ]);
17526
18221
  var transferEnded = (record) => FINAL.has(record.state);
17527
18222
  /**
18223
+ * Whether a file sent from here arrived whole (the receiver confirmed every byte, and may be checking it): too late
18224
+ * for its person to cancel. The receiver's check comes before a `pf-abort` behind it, so it would keep the file while
18225
+ * the sender said it was cancelled. Not once the receiver asks about it again (`asking`), nor paused here.
18226
+ */
18227
+ function sentWhole(record) {
18228
+ if (record.direction !== "out" || transferEnded(record)) return false;
18229
+ return record.state === "verifying" || record.file.size > 0 && record.confirmed === record.file.size && record.state !== "asking" && record.state !== "paused";
18230
+ }
18231
+ /**
17528
18232
  * Whether an unfinished transfer is stuck, so its person is offered to push it: "Send again" (sending) or "Ask again"
17529
18233
  * (receiving). `movedAt` is when its bytes last moved, `restored` that it has not moved since the app started. What
17530
18234
  * waits for a person (an answer, a pause) is not stuck, and a failed one has its own "Retry".
@@ -17909,6 +18613,11 @@ var ChatFiles = class {
17909
18613
  id: entry.record.id,
17910
18614
  offset: entry.in.written
17911
18615
  });
18616
+ else if (entry.record.state === "asking") this.send({
18617
+ t: "pf-wait",
18618
+ id: entry.record.id,
18619
+ why: "consent"
18620
+ });
17912
18621
  }
17913
18622
  }
17914
18623
  /** The session went: nothing moves until the next one. What was received is made durable. */
@@ -17946,10 +18655,13 @@ var ChatFiles = class {
17946
18655
  ].includes(record.state) || record.since + FILE_LIMITS.offerTtlMs > now) continue;
17947
18656
  if (record.direction === "in" && record.state === "queued" && (entry.in?.starting || this.moved(entry) > 0)) continue;
17948
18657
  this.end(entry, "failed", record.direction === "in" ? "The offer expired" : record.state === "queued" ? "Not delivered in time" : "Not accepted in time");
17949
- if (record.direction === "in") this.send({
18658
+ this.send(record.direction === "in" ? {
17950
18659
  t: "pf-refuse",
17951
18660
  id: record.id,
17952
18661
  why: "expired"
18662
+ } : {
18663
+ t: "pf-abort",
18664
+ id: record.id
17953
18665
  });
17954
18666
  }
17955
18667
  }
@@ -18687,7 +19399,8 @@ var ChatFiles = class {
18687
19399
  return;
18688
19400
  }
18689
19401
  if (!outgoing || transferEnded(outgoing.record)) {
18690
- if (outgoing?.record.state === "cancelled" && frame.t !== "pf-refuse") this.send({
19402
+ const asked = frame.t === "pf-accept" || frame.t === "pf-wait";
19403
+ if (outgoing?.record.state === "cancelled" ? frame.t !== "pf-refuse" : asked && outgoing?.record.state !== "done") this.send({
18691
19404
  t: "pf-abort",
18692
19405
  id
18693
19406
  });
@@ -20062,7 +20775,8 @@ var PairingTracker = class {
20062
20775
  * none of these (a mint's own words, a provider's) stays as it is.
20063
20776
  *
20064
20777
  * `{name}` in a template is a value: a host or domain (no spaces), a network ("Mainnet" or "Testnet"), a chain's name,
20065
- * an ecash unit ("usd"), or an amount (digits, with the separators of whatever locale wrote it).
20778
+ * an ecash unit ("usd"), an amount (digits, with the separators of whatever locale wrote it), or a server's own `{reason}`
20779
+ * (one line, last in its text).
20066
20780
  */
20067
20781
  var ENGINE_ERRORS = {
20068
20782
  mintUnreachable: "Could not reach {host}. Check the address: it should be a Cashu mint.",
@@ -20079,13 +20793,16 @@ var ENGINE_ERRORS = {
20079
20793
  mintNotHttps: "Mints must use https",
20080
20794
  notEnoughSats: "Not enough sats in your wallet",
20081
20795
  notEnoughForFee: "Not enough sats in your wallet: {amount} sats leave room for the fee",
20796
+ mintsNoAnyAmount: "None of your mints can pay an invoice with no amount",
20082
20797
  noSharedMint: "You share no mint with this contact",
20083
20798
  ecashAlreadySpent: "This ecash was already spent somewhere else",
20084
20799
  ecashBeingReceived: "This ecash is already being received",
20800
+ ecashFeeTakesAll: "The mint keeps all {amount} sats of this ecash as its fee to take it in: nothing was redeemed, and its sender can still take it back",
20085
20801
  ecashOtherUnit: "This ecash is in {unit}: only sat ecash can be redeemed here",
20086
20802
  reviewedEcashSpent: "The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.",
20087
20803
  reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.",
20088
20804
  lightningFeeTooHigh: "The Lightning fee ({fee} sats) is too high",
20805
+ lightningRefused: "The mint refused this Lightning payment, and no sats left your wallet: it is safe to try again. The mint said: {reason}",
20089
20806
  invoiceExpired: "That invoice has expired",
20090
20807
  lnurlExactly: "{domain} asks for exactly {amount} sats",
20091
20808
  lnurlRange: "{domain} takes between {min} and {max} sats",
@@ -20820,6 +21537,7 @@ var GhostLink = class {
20820
21537
  peerCapsRev: options.dht.peerCapsRev,
20821
21538
  peerAcceptsText: options.dht.peerAcceptsText,
20822
21539
  peerAcceptsFile: options.dht.peerAcceptsFile,
21540
+ ...options.dht.ratchet && { ratchet: options.dht.ratchet },
20823
21541
  ...options.reactionsSupport && {
20824
21542
  reactions: options.dht.reactions,
20825
21543
  reaction: async (reaction) => {
@@ -20909,6 +21627,7 @@ var GhostLink = class {
20909
21627
  pollIntervals: options.pollIntervals,
20910
21628
  awaitingSince: options.madeAt,
20911
21629
  ...backsOff && { invite: () => !options.pairing.credentials.peerKey || !!this.dht?.unanswered },
21630
+ ...invite && { ownInvite: () => !options.pairing.credentials.peerKey && !options.pairing.credentials.expectedPeerKey },
20912
21631
  getServices: options.getServices,
20913
21632
  firstPublish: options.firstPublish ?? (this.tracker && options.pairingProgress?.role === "joiner" && options.rtcAvailable !== false || this.resuming ? "after-first-poll" : "at-start"),
20914
21633
  resumed: !!this.resuming,
@@ -22754,6 +23473,10 @@ var GhostLink = class {
22754
23473
  get liveAttempt() {
22755
23474
  return this.isDataLinkOpen ? void 0 : this.lastAttempt;
22756
23475
  }
23476
+ /** Automatic dials since the link was last live or its wait started over (`wake`), the one under way included. */
23477
+ get dialAttempts() {
23478
+ return this.autoConnectFailures;
23479
+ }
22757
23480
  /**
22758
23481
  * Which side dials this chat to go live: the lower rendezvous key, or the joiner of a first pairing (WISP 100). The
22759
23482
  * other side answers, so what it can tell of a failed attempt is only what reached it.
@@ -24371,6 +25094,7 @@ var GhostLink = class {
24371
25094
  if (oldChannel) this.retire(oldChannel, () => {
24372
25095
  if (oldRtc && this.activeBinding && this.dataLink.connection === oldRtc) this.dataLink.close();
24373
25096
  }, !oldBinding);
25097
+ if (migration.plan && binding && oldBinding && WEBRTC_ATTEMPT.has(this.dataLink.state)) this.dataLink.close();
24374
25098
  this.session.setDataLinkOpen(true);
24375
25099
  if (migration.plan) switched = {
24376
25100
  from,
@@ -32265,6 +32989,18 @@ var CommunitySession = class {
32265
32989
  get entryKey() {
32266
32990
  return this.state.entry.key;
32267
32991
  }
32992
+ /**
32993
+ * The entry key of the link my admission that lost was let in by (the one its branch named), where I ask again: a
32994
+ * link replaced since keeps me out as it does anyone. `entryKey` once that admission is no longer held.
32995
+ */
32996
+ get lostEntryKey() {
32997
+ const side = this.state.side;
32998
+ for (let i = side.length - 1; i >= 0; i--) if (side[i].k === "add" && side[i].s === this.myKey) {
32999
+ for (const c of this.ancestry(side[i].p)) if (c.x !== void 0) return c.x;
33000
+ return "";
33001
+ }
33002
+ return this.entryKey;
33003
+ }
32268
33004
  role(key) {
32269
33005
  return this.roster.find(([k]) => k === key)?.[1];
32270
33006
  }
@@ -32272,10 +33008,62 @@ var CommunitySession = class {
32272
33008
  get picture() {
32273
33009
  return groupMetaPicture(this.state.meta);
32274
33010
  }
32275
- /** Members of any epoch in the window: whom a frame may come from. */
33011
+ /**
33012
+ * Members of any epoch in the window: whom a frame may come from. A side commit's roster counts only while its branch
33013
+ * could still win (`mayWin`): one let in only on a branch that lost is not in the roster anyone sees, and the main
33014
+ * branch past where they part, a later link among it, is not its business (`lostAt`).
33015
+ */
32276
33016
  isRecentMember(key) {
32277
- for (const roster of this.rosters.values()) if (rosterHas(roster, key)) return true;
32278
- return false;
33017
+ let side = false;
33018
+ for (const [h, roster] of this.rosters) if (rosterHas(roster, key)) {
33019
+ if (this.mainIndex.has(h)) return true;
33020
+ side = true;
33021
+ }
33022
+ return side && [...this.mayWin()].some((h) => rosterHas(this.rosters.get(h) ?? [], key));
33023
+ }
33024
+ /**
33025
+ * The side commits whose branch could still win: it does not drop an admin change the main branch holds (one that
33026
+ * does never wins, see `better`), and it parts within the window. Kept until the tip or the side moves.
33027
+ */
33028
+ mayWin() {
33029
+ const side = this.state.side, at = `${this.topHash}:${side.length}:${side.length ? communityCommitHash(side[side.length - 1]) : ""}`;
33030
+ if (this.winning?.at === at) return this.winning.set;
33031
+ const counts = this.adminCounts(), main = this.branch(this.topHash), set = /* @__PURE__ */ new Set();
33032
+ for (const c of side) {
33033
+ const h = communityCommitHash(c), branch = this.rosters.has(h) ? this.branch(h) : null;
33034
+ if (!branch || !branch.path.length) continue;
33035
+ const { parent, admin } = this.parting(branch, main, counts);
33036
+ if (!(admin[1] && !admin[0]) && parent >= this.epoch - COMMUNITY_LIMITS.window) set.add(h);
33037
+ }
33038
+ this.winning = {
33039
+ at,
33040
+ set
33041
+ };
33042
+ return set;
33043
+ }
33044
+ winning;
33045
+ /**
33046
+ * For a key that is no recent member, let in on a branch that lost: the main-branch index it parts from, and that of
33047
+ * the commit that makes it lose (the latest over its branches). Undefined for anyone else.
33048
+ */
33049
+ lostAt(key) {
33050
+ const side = this.state.side, parents = new Set(side.map((c) => c.p)), counts = this.adminCounts();
33051
+ let lost;
33052
+ for (const c of side) {
33053
+ const h = communityCommitHash(c);
33054
+ if (parents.has(h)) continue;
33055
+ const branch = this.branch(h);
33056
+ if (!branch || !branch.path.some((x) => rosterHas(this.rosters.get(x) ?? [], key))) continue;
33057
+ for (let j = branch.fork + 1; j < this.state.chain.length; j++) {
33058
+ if (this.better(branch, this.branch(communityCommitHash(this.state.chain[j])), counts)) continue;
33059
+ lost = {
33060
+ fork: Math.min(lost?.fork ?? j, branch.fork),
33061
+ end: Math.max(lost?.end ?? j, j)
33062
+ };
33063
+ break;
33064
+ }
33065
+ }
33066
+ return lost;
32279
33067
  }
32280
33068
  /**
32281
33069
  * Whether `key` could read message `messageId` (`<s>:<e>:<h>:<n>`) and still can: a member of the roster it was sealed
@@ -33825,10 +34613,23 @@ var CommunitySession = class {
33825
34613
  for (const { from, frame } of ready) await this.receiveMessage(from, frame);
33826
34614
  }
33827
34615
  async receiveSync(from, frame) {
33828
- if (!this.isRecentMember(from) || !isZ32Key(from) || !Number.isSafeInteger(frame.e) || typeof frame.h !== "string") return;
34616
+ if (!isZ32Key(from) || !Number.isSafeInteger(frame.e) || typeof frame.h !== "string") return;
34617
+ const recent = this.isRecentMember(from), lost = recent ? void 0 : this.lostAt(from);
34618
+ if (!recent && !lost) return;
33829
34619
  let answered = this.syncsAnswered.get(from);
33830
34620
  if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(COMMUNITY_LIMITS.syncAnswers, COMMUNITY_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
33831
34621
  if (!answered.take()) return;
34622
+ if (lost) {
34623
+ const at = this.mainIndex.get(frame.h);
34624
+ const commits = this.state.chain.slice(at !== void 0 ? at + 1 : lost.fork + 1, lost.end + 1);
34625
+ if (commits.length) this.answers.handOut(from, commits.map((commit) => ({
34626
+ t: "group-commit",
34627
+ v: 2,
34628
+ g: this.id,
34629
+ commit
34630
+ })));
34631
+ return;
34632
+ }
33832
34633
  const answer = [];
33833
34634
  const ask = () => {
33834
34635
  const sync = this.question(from);
@@ -34793,6 +35594,6 @@ function readX401SdJwtVc(text) {
34793
35594
  };
34794
35595
  }
34795
35596
  //#endregion
34796
- export { SshSigError as $, RUN_RESULTS as $a, signAppObject as $c, TRANSPORTS as $i, currentRelays as $l, readGroupHave as $n, HANDOFF_ACK as $o, checkPushEndpoint as $r, enrollDigits as $s, SEPOLIA_TEST_USDT as $t, knockIdentity as A, forwardedAgain as Aa, APP_BUNDLE_MAGIC as Ac, recordsName as Ai, TURN_PUT_WINDOW_MS as Al, fedimintRequestPayload as An, WATCH_PEER_MS as Ao, FILE_LIMITS as Ar, newHandoffId as As, didSignedMessages as At, GROUP_REACTED_FRAME as B, readReaction as Ba, readAppBundleAsync as Bc, IdentityCheckUnavailable as Bi, signTurnPacket as Bl, pairedMessageFrame as Bn, RTC_CONFIG as Bo, PIN_LIMITS as Br, SET_ACK as Bs, signingKeys as Bt, communityHasFrame as C, MAX_REMOVAL_NUMBER as Ca, mergeContactKnocks as Cc, domainWellKnownFile as Ci, deviceEchoNonce as Cl, homeserverWebEndpoint as Cn, verifyCommitSignature as Co, pickHubs as Cr, handoffManifestFrames as Cs, DID_FILE_MAX_BYTES as Ct, randomBytes as Cu, decodeGroupEntryLink as D, LINK_TRAILING as Da, requestRecords as Dc, normalizeDomain as Di, newDeviceSetSecret as Dl, decodeBolt11 as Dn, DHT_POLL_INTERVALS as Do, readLobby as Dr, handoffRetryAfter as Ds, checkDidSignature as Dt, utf8Encode as Du, KNOCK_TTL_MS as E, dhtEditId as Ea, readLinkRecord as Ec, nip05RootKey as Ei, devicePingFrame as El, resolveLightningDestination as En, AWAITING_PEER_MS as Eo, readBeaconHead as Er, handoffReleaseFrame as Es, checkDidJws as Et, utf8Decode as Eu, GroupWakeLimiter as F, ReactionWindow as Fa, assembleAppBundle as Fc, capsDescriptors as Fi, TURN_LAST_SEQUENCE as Fl, GhostLink as Fn, webLocalFetch as Fo, TYPING_REFRESH_MS as Fr, readHandoffHello as Fs, didWebHost as Ft, GROUP_EDIT_FRAME as G, replySnippet as Ga, appRef as Gc, identityStatement as Gi, turnStatedVerifier as Gl, GROUP_FILE_LIMITS as Gn, contactRtcConfig as Go, readPin as Gr, signTombstone as Gs, encodeDidDhtDeactivated as Gt, GroupSession as H, wireReaction as Ha, APP_PREFIXES as Hc, boundVerifiedIdentity as Hi, turnInstance as Hl, engineError as Hn, buildSdpFromSignal as Ho, nextPinNumber as Hr, readSetUpdate as Hs, strictBase64Url as Ht, groupWakeFrame as I, nextReactionNumber as Ia, checkAppManifest as Ic, dialDescriptors as Ii, TURN_MAX as Il, INVITE_TAKEN as In, LIMITS as Io, TypingSender as Ir, readHandoffPake as Is, normalizeDid as It, parseCommunityEdit as J, CRON_LINE as Ja, isAppKey as Jc, revokesIdentity as Ji, HEDGE_MISSING_MS as Jl, GROUP_WANT_NO_FRAME as Jn, signalHasVideo as Jo, deviceWakeRequest as Jr, ENROLL_GRANT as Js, signDidDhtPacket as Jt, GROUP_EDIT_TEXT_BYTES as K, BUTTON_ID as Ka, checkAppRevokeStatement as Kc, newIdentityBinding as Ki, turnVerifierMark as Kl, GROUP_HAVE_FRAME as Kn, extractParamsFromSdp as Ko, WAKE_CALL_INTERVAL_MS as Kr, verifySetUpdate as Ks, encodeDidDhtPacket as Kt, groupWakes as L, queueReaction as La, isAppUrl as Lc, IDENTITY_MAX_EVIDENCE as Li, firstDeviceSetSecret as Ll, LIVENESS_PING_MS as Ln, decodeControl as Lo, sanitizeTypingStatus as Lr, readHandoffTurnFrame as Ls, parseDid as Lt, mergeKnocks as M, COMMUNITY_REACTION_FRAME as Ma, APP_PERMISSIONS as Mc, wellKnownUrl as Mi, TURN_SETTLE_MS as Ml, isFederationId as Mn, GhostlyHttpError as Mo, transferEnded as Mr, readHandoffCancel as Ms, didWebFile as Mt, readKnocks as N, GROUP_REACTION_FRAME as Na, appDigest as Nc, CapsExchange as Ni, classifyTurnRead as Nl, parseCashuRequestPayload as Nn, formatLocalTarget as No, transferStalled as Nr, readHandoffDone as Ns, didWebFileNames as Nt, encodeGroupEntryLink as O, linkStop as Oa, seenEntry as Oc, recordsFromTxt as Oi, seedSigner as Ol, ENDPOINT as On, EXPECT_PEER_MS as Oo, shouldBeHub as Or, handoffStreamKey as Os, didGhostlyServiceEntry as Ot, GROUP_WAKE_FRAME as P, REACTION_LIMITS as Pa, appViewOf as Pc, DHT_TEXT_CAPABILITY as Pi, turnPutSummary as Pl, parseFedimintRequestPayload as Pn, parseLocalTarget as Po, TYPING_KINDS as Pr, readHandoffHave as Ps, didWebFileUrl as Pt, SSHSIG_NAMESPACE as Q, ROUTINE_STATES as Qa, setAppSignatureFastPath as Qc, validExternalKey as Qi, SLOW_MS as Ql, readGroupFileMeta as Qn, serviceIdFromName as Qo, wakeRequest as Qr, enrollCancelReason as Qs, PaymentPreflightError as Qt, parseGroupWakeFrame as R, reactionEmoji as Ra, pacer as Rc, IDENTITY_MAX_VALIDITY as Ri, nextTurnPosition as Rl, PAIRED_FRAME_TOO_LARGE as Rn, encodeControl as Ro, typingActivity as Rr, readHandoffVerified as Rs, parseDidDocument as Rt, GROUP_READ_NOTE_COMMUNITY as S, EDIT_RATE_WINDOW_MS as Sa, makeStampPaced as Sc, domainTxtRecord as Si, deviceEchoFrame as Sl, pubkyProofPath as Sn, rosterHas as So, newerHead as Sr, handoffHelloFrame as Ss, DID_DOCUMENT_MAX_BYTES as St, isZ32Key as Su, encodeCommunityLink as T, RateWindow as Ta, readKnockSlot as Tc, isPublicAddress as Ti, deviceLinkPairing as Tl, requestLnurlInvoice as Tn, DirectPathWatch as To, readBeacon as Tr, handoffPakeFrame as Ts, DidError as Tt, toZ32 as Tu, frameBytes as U, pairedReplyAuthor as Ua, APP_STATEMENT_LIMITS as Uc, emptyIdentityLedger as Ui, turnKeys as Ul, engineText as Un, callRtcConfig as Uo, pinIsNewer as Ur, setAckFrame as Us, didDhtDocument as Ut, GROUP_READ_NOTE as V, validReactionNumber as Va, sha256Paced as Vc, IdentityExchange as Vi, signTurnRelease as Vl, EngineError as Vn, answersOffer as Vo, mayPin as Vr, SET_UPDATE as Vs, staticDidDocument as Vt, COMMUNITY_EDIT_FRAME as W, readReply as Wa, appFingerprint as Wc, identityRevocationValue as Wi, turnName as Wl, parseEngineError as Wn, callSignalHeardAt as Wo, pinNumberHolds as Wr, setUpdateFrame as Ws, didDhtFromPublicKey as Wt, groupName as X, PR_CHECKS as Xa, readAppRevocation as Xc, PeerProofs as Xi, RelayTransport as Xl, groupFileFallback as Xn, HTTP_SERVICE_PROTO as Xo, parseWakeFrame as Xr, ENROLL_PROOF as Xs, EVM_TEST_CHAINS as Xt, mentionsMember as Y, ITEM_STATES as Ya, isAppRef as Yc, lastSharedWithMe as Yi, HEDGE_MS as Yl, fetchesByItself as Yn, emptyLinkRecords as Yo, newWakeToken as Yr, ENROLL_HELLO as Ys, ETHEREUM_USDT as Yt, SSHSIG_MAX_ARMOR as Z, PR_STATES as Za, readAppRevocations as Zc, emptyProofLedger as Zi, RelaysFailedError as Zl, isGroupMessageId as Zn, LEGACY_SERVICES as Zo, relayRequest as Zr, enrollCancelFrame as Zs, ONCHAIN_PROVIDER as Zt, groupTypingEpoch as _, parseVoiceMeta as _a, contactDay as _c, newMailbox as _i, inviteOwnership as _l, isPubkyProofFolder as _n, MAX_GROUP_CHAIN as _o, freshHubs as _r, handoffContext as _s, normalizeAtprotoHandle as _t, MAX_AVATAR_LENGTH as _u, appRevocationFor as a, peekDhtMailbox as aa, readEnrollHello as ac, isAppVersion as ai, readCanonicalJson as al, assertTokenUnits as an, cardUrl as ao, SIGNAL_HOLD_MS as ar, HANDOFF_PAKE as as, verifyBitcoinMessage as at, withRequestOptions as au, COMMUNITY_LIMITS as b, parseVideoMeta as ba, knockSlotRecords as bc, decodeDnsResponse as bi, ENROLL_CAPABILITY as bl, pubkyProofCapability as bn, parseGroupCommit as bo, mergeBeacon as br, handoffDigest as bs, AtprotoProofError as bt, bytesEqual as bu, checkAppBeforeRun as c, formatFileSize as ca, endedRequests as cc, EDIT_CAPABILITY as ci, readContactLink as cl, validatePaymentTarget as cn, statusCardBytes as co, readGroupSignal as cr, HANDOFF_TIMINGS as cs, ATPROTO_DECLARED_SCOPE as ct, createRelayPayload as cu, checkAppStoreIndex as d, PLAYABLE_AUDIO as da, planKnocks as dc, HOLD_CAPABILITY as di, readDeviceInvite as dl, SPARK_PROVIDER as dn, claimedTime as do, meshHubs as dr, filePartName as ds, ATPROTO_PROOF_SCOPE as dt, parseRelayPayload as du, automaticTransport as ea, enrollDoneFrame as ec, vapidKeysMatch as ei, signAppRevocation as el, SEPOLIA_TEST_USDT_FAUCET as en, STATUS_CARD_LIMITS as eo, readGroupWant as er, HANDOFF_CANCEL as es, parseSshPublicKey as et, normalizeRelayUrl as eu, readAppStore as f, VOICE_LIMITS as fa, settleRequest as fc, HOLD_DATED_BACK_MS as fi, OwnInviteError as fl, sparkAddressKind as fn, heardTime as fo, pickMeshHubs as fr, handoffAttemptAllowed as fs, atprotoDidMethod as ft, createIdentity as fu, GroupTypingBoard as g, fileMessageText as ga, REQUEST_LIFETIME_MS as gc, isHoldUrl as gi, inviteLink as gl, isPubkyKey as gn, GROUP_MEMBER_CAP as go, doorHubs as gr, handoffCancelFrame as gs, isAtprotoDid as gt, verify as gu, GROUP_TYPING_FRAME as h, downsamplePeaks as ha, ContactRequestError as hc, HoldRefusedError as hi, encodeInviteCode as hl, PUBKY_PROOF_MAX_BYTES as hn, GROUP_ADMIN_OFF_ERROR as ho, beaconRecords as hr, handoffBusyFrame as hs, checkAtprotoProofRecord as ht, publicKeyFromZ32 as hu, addedAppPermissions as i, DHT_MESSAGE_TTL as ia, readEnrollGrant as ic, chatAppId as ii, canonicalJsonBytes as il, arkAddressPrefix as in, cardLine as io, SIGNAL_FRESH_MS as ir, HANDOFF_OFFER as is, verifySshSignature as it, isDiscoveryBudgetError as iu, knockRecords as j, readForwarded as ja, APP_ICON_PATH as jc, txtValue as ji, TURN_RAISE_READ_TIMEOUT_MS as jl, findEndpoint as jn, presenceSeenAt as jo, FileUplink as jr, readHandoffAck as js, didWebDocumentUrl as jt, entryParams as k, parseLinkPreview as ka, APP_BUNDLE_LIMITS as kc, recordsFromWellKnown as ki, webCryptoSigner as kl, cashuRequestPayload as kn, RELAY_POLL_INTERVALS as ko, ChatFiles as kr, handoffVersions as ks, didJwsAlg as kt, planAppUpdate as l, sanitizeFileName as la, inboxRecord as lc, STATUS_CARD_CAPABILITY as li, createDeviceInvite as ll, walletNetworkOf as ln, statusCardText as lo, MESH_HUBS as lr, HANDOFF_VERIFIED as ls, ATPROTO_FULL_SCOPE as lt, newerPacket as lu, signAppStore as m, baseMime as ma, turnOff as mc, HoldKeys as mi, decodeInviteCode as ml, isBitcoinAddress as mn, shownTime as mo, beaconKeys as mr, handoffAttemptSucceeded as ms, atprotoProofRkey as mt, identityFromSeedB64 as mu, readX401SdJwtVc as n, irohRelayUrl as na, enrollHelloFrame as nc, isServeId as ni, readImageMeta as nl, USDT_PUBLIC_RPC as nn, appCardId as no, CarriedTransport as nr, HANDOFF_HAVE as ns, sameSshKey as nt, traceLink as nu, appStoreDecision as o, DHT_FILE_CAPABILITY as oa, verifyEnrollProof as oc, APPS_CAPABILITY as oi, createContactLink as ol, assertWholeSats as on, checkStatusCard as oo, SIGNAL_REPLY_MS as or, HANDOFF_PIECE_BYTES as os, BitcoinAddressError as ot, PacketTooLargeError as ou, readAppStoreSteps as p, VOICE_METER as pa, takeRequest as pc, HOLD_LIMITS as pi, createChatInvite as pl, sparkInvoiceDetails as pn, receivedTimestamp as po, COMMUNITY_TOPOLOGY as pr, handoffAttemptFailed as ps, atprotoProofRecord as pt, identityFromSeed as pu, carryMentions as q, BUTTON_STYLES as qa, isAppHash as qc, receivedIdentityStatus as qi, DEFAULT_RELAYS as ql, GROUP_WANT_FRAME as qn, parseCallSignal as qo, WakeLimiter as qr, ENROLL_DONE as qs, resolveDidDht as qt, sameX401HolderJwk as r, DHT_FILE_TOO_LARGE as ra, enrollProofFrame as rc, APP_DATA_MAX_BYTES as ri, canonicalJson as rl, WALLET_NETWORKS as rn, buttonLabelClash as ro, GROUP_SIGNAL_FRAME as rr, HANDOFF_HELLO as rs, sshSignCommand as rt, budgetRetryMs as ru, appUpdateDecision as s, dhtFileId as sa, clearMissed as sc, BUTTONS_CAPABILITY as si, encodeContactLink as sl, formatPaymentAmount as sn, sameButtonText as so, groupSignalFrame as sr, HANDOFF_REQUEST as ss, decodeAnyBitcoinAddress as st, RELAY_PAYLOAD_MAX_BYTES as su, newX401HolderKey as t, irohDescriptor as ta, enrollGrantFrame as tc, APP_RANGE_LIMITS as ti, parseImageMeta as tl, TEST_USDT_FAUCET_AMOUNT as tn, TASK_STATUSES as to, readGroupWantNo as tr, HANDOFF_DONE as ts, parseSshSignature as tt, setLinkTraceSink as tu, APP_STORE_LIMITS as u, sanitizeMime as ua, newInbox as uc, UPGRADE_CAPABILITY as ui, deviceInviteJoinerParams as ul, SPARK_NETWORKS as un, arrivalKey as uo, mayBeHub as ur, NO_ATTEMPTS as us, ATPROTO_PROOF_COLLECTION as ut, openRelayPayload as uu, openGroupTyping as v, voiceDownloadName as va, knockSlotIdentity as vc, readManifest as vi, ownInviteRefusal as vl, newPubkyProofFolder as vn, MEMBER_KEY as vo, lobbyKeys as vr, handoffContextProof as vs, parseAtprotoDidDocument as vt, sanitizeAvatar as vu, decodeCommunityLink as w, REMOVED_TEXT as wa, openRequest as wc, encodeDnsQuery as wi, deviceKeyZ32 as wl, pubkyHomeserverOf as wn, edgeParams as wo, rankHubs as wr, handoffOfferFrame as ws, DID_JWS_MAX_LENGTH as wt, toBase64Url as wu, CommunitySession as x, EDIT_BUFFER_MS as xa, linkRecords as xc, dnsProofName as xi, HANDOFF_CAPABILITY as xl, pubkyProofFile as xn, rosterAdmin as xo, mergeLobby as xr, handoffEphemeral as xs, verifyAtprotoRecordProof as xt, fromBase64Url as xu, sealGroupTyping as y, voiceLevel as ya, knockSlotOf as yc, DOMAIN_FILE_MAX_BYTES as yi, DEVICES_CAPABILITY as yl, normalizePubkyKey as yn, commitHash as yo, lobbyRecords as yr, handoffDataFrame as ys, shortAtprotoDid as yt, sanitizeDisplayText as yu, GROUP_LIMITS as z, reactionIsNewer as za, readAppBundle as zc, IDENTITY_REVOCATION_LABEL as zi, readTurnPacket as zl, pairedMessageFits as zn, CALL_SIGNAL_MAX_AGE_MS as zo, GROUP_PIN_FRAME as zr, sealHandoffPiece as zs, parseDidSignaturePaste as zt };
35597
+ export { SshSigError as $, ROUTINE_STATES as $a, isAppHash as $c, validExternalKey as $i, DEFAULT_RELAYS as $l, readGroupHave as $n, parseCallSignal as $o, wakeRequest as $r, ENROLL_DONE as $s, SEPOLIA_TEST_USDT as $t, knockIdentity as A, parseLinkPreview as Aa, openRequest as Ac, recordsFromWellKnown as Ai, deviceKeyZ32 as Al, fedimintRequestPayload as An, DirectPathWatch as Ao, FILE_LIMITS as Ar, handoffOfferFrame as As, didSignedMessages as At, toBase64Url as Au, GROUP_REACTED_FRAME as B, reactionIsNewer as Ba, appViewOf as Bc, IDENTITY_REVOCATION_LABEL as Bi, turnPutSummary as Bl, pairedMessageFrame as Bn, parseLocalTarget as Bo, GROUP_PIN_FRAME as Br, readHandoffHave as Bs, signingKeys as Bt, communityHasFrame as C, EDIT_RATE_WINDOW_MS as Ca, contactDay as Cc, domainTxtRecord as Ci, inviteOwnership as Cl, homeserverWebEndpoint as Cn, rosterHas as Co, pickHubs as Cr, handoffContext as Cs, DID_FILE_MAX_BYTES as Ct, MAX_AVATAR_LENGTH as Cu, decodeGroupEntryLink as D, dhtEditId as Da, linkRecords as Dc, nip05RootKey as Di, HANDOFF_CAPABILITY as Dl, decodeBolt11 as Dn, RatchetBox as Do, readLobby as Dr, handoffEphemeral as Ds, checkDidSignature as Dt, fromBase64Url as Du, KNOCK_TTL_MS as E, RateWindow as Ea, knockSlotRecords as Ec, isPublicAddress as Ei, ENROLL_CAPABILITY as El, resolveLightningDestination as En, RATCHET_CAPABILITY as Eo, readBeaconHead as Er, handoffDigest as Es, checkDidJws as Et, bytesEqual as Eu, GroupWakeLimiter as F, REACTION_LIMITS as Fa, APP_BUNDLE_LIMITS as Fc, DHT_TEXT_CAPABILITY as Fi, webCryptoSigner as Fl, GhostLink as Fn, RELAY_POLL_INTERVALS as Fo, TYPING_KINDS as Fr, handoffVersions as Fs, didWebHost as Ft, GROUP_EDIT_FRAME as G, readReply as Ga, readAppBundle as Gc, identityRevocationValue as Gi, readTurnPacket as Gl, GROUP_FILE_LIMITS as Gn, CALL_SIGNAL_MAX_AGE_MS as Go, pinNumberHolds as Gr, sealHandoffPiece as Gs, encodeDidDhtDeactivated as Gt, GroupSession as H, validReactionNumber as Ha, checkAppManifest as Hc, IdentityExchange as Hi, TURN_MAX as Hl, engineError as Hn, LIMITS as Ho, mayPin as Hr, readHandoffPake as Hs, strictBase64Url as Ht, groupWakeFrame as I, ReactionWindow as Ia, APP_BUNDLE_MAGIC as Ic, capsDescriptors as Ii, TURN_PUT_WINDOW_MS as Il, INVITE_TAKEN as In, WATCH_PEER_MS as Io, TYPING_REFRESH_MS as Ir, newHandoffId as Is, normalizeDid as It, parseCommunityEdit as J, BUTTON_STYLES as Ja, APP_PREFIXES as Jc, receivedIdentityStatus as Ji, turnInstance as Jl, GROUP_WANT_NO_FRAME as Jn, buildSdpFromSignal as Jo, WakeLimiter as Jr, readSetUpdate as Js, signDidDhtPacket as Jt, GROUP_EDIT_TEXT_BYTES as K, replySnippet as Ka, readAppBundleAsync as Kc, identityStatement as Ki, signTurnPacket as Kl, GROUP_HAVE_FRAME as Kn, RTC_CONFIG as Ko, readPin as Kr, SET_ACK as Ks, encodeDidDhtPacket as Kt, groupWakes as L, nextReactionNumber as La, APP_ICON_PATH as Lc, dialDescriptors as Li, TURN_RAISE_READ_TIMEOUT_MS as Ll, LIVENESS_PING_MS as Ln, presenceSeenAt as Lo, TypingSender as Lr, readHandoffAck as Ls, parseDid as Lt, mergeKnocks as M, readForwarded as Ma, readLinkRecord as Mc, txtValue as Mi, devicePingFrame as Ml, isFederationId as Mn, DHT_POLL_INTERVALS as Mo, sentWhole as Mr, handoffReleaseFrame as Ms, didWebFile as Mt, utf8Decode as Mu, readKnocks as N, COMMUNITY_REACTION_FRAME as Na, requestRecords as Nc, wellKnownUrl as Ni, newDeviceSetSecret as Nl, parseCashuRequestPayload as Nn, EXPECT_PEER_MS as No, transferEnded as Nr, handoffRetryAfter as Ns, didWebFileNames as Nt, utf8Encode as Nu, encodeGroupEntryLink as O, LINK_TRAILING as Oa, makeStampPaced as Oc, normalizeDomain as Oi, deviceEchoFrame as Ol, ENDPOINT as On, emptyRatchetState as Oo, shouldBeHub as Or, handoffHelloFrame as Os, didGhostlyServiceEntry as Ot, isZ32Key as Ou, GROUP_WAKE_FRAME as P, GROUP_REACTION_FRAME as Pa, seenEntry as Pc, CapsExchange as Pi, seedSigner as Pl, parseFedimintRequestPayload as Pn, PRESENCE_WINDOW as Po, transferStalled as Pr, handoffStreamKey as Ps, didWebFileUrl as Pt, SSHSIG_NAMESPACE as Q, PR_STATES as Qa, checkAppRevokeStatement as Qc, emptyProofLedger as Qi, turnVerifierMark as Ql, readGroupFileMeta as Qn, extractParamsFromSdp as Qo, relayRequest as Qr, verifySetUpdate as Qs, PaymentPreflightError as Qt, parseGroupWakeFrame as R, queueReaction as Ra, APP_PERMISSIONS as Rc, IDENTITY_MAX_EVIDENCE as Ri, TURN_SETTLE_MS as Rl, PAIRED_FRAME_TOO_LARGE as Rn, GhostlyHttpError as Ro, sanitizeTypingStatus as Rr, readHandoffCancel as Rs, parseDidDocument as Rt, GROUP_READ_NOTE_COMMUNITY as S, EDIT_BUFFER_MS as Sa, REQUEST_LIFETIME_MS as Sc, dnsProofName as Si, inviteLink as Sl, pubkyProofPath as Sn, rosterAdmin as So, newerHead as Sr, handoffCancelFrame as Ss, DID_DOCUMENT_MAX_BYTES as St, verify as Su, encodeCommunityLink as T, REMOVED_TEXT as Ta, knockSlotOf as Tc, encodeDnsQuery as Ti, DEVICES_CAPABILITY as Tl, requestLnurlInvoice as Tn, edgeParams as To, readBeacon as Tr, handoffDataFrame as Ts, DidError as Tt, sanitizeDisplayText as Tu, frameBytes as U, wireReaction as Ua, isAppUrl as Uc, boundVerifiedIdentity as Ui, firstDeviceSetSecret as Ul, engineText as Un, decodeControl as Uo, nextPinNumber as Ur, readHandoffTurnFrame as Us, didDhtDocument as Ut, GROUP_READ_NOTE as V, readReaction as Va, assembleAppBundle as Vc, IdentityCheckUnavailable as Vi, TURN_LAST_SEQUENCE as Vl, EngineError as Vn, webLocalFetch as Vo, PIN_LIMITS as Vr, readHandoffHello as Vs, staticDidDocument as Vt, COMMUNITY_EDIT_FRAME as W, pairedReplyAuthor as Wa, pacer as Wc, emptyIdentityLedger as Wi, nextTurnPosition as Wl, parseEngineError as Wn, encodeControl as Wo, pinIsNewer as Wr, readHandoffVerified as Ws, didDhtFromPublicKey as Wt, groupName as X, ITEM_STATES as Xa, appFingerprint as Xc, lastSharedWithMe as Xi, turnName as Xl, groupFileFallback as Xn, callSignalHeardAt as Xo, newWakeToken as Xr, setUpdateFrame as Xs, EVM_TEST_CHAINS as Xt, mentionsMember as Y, CRON_LINE as Ya, APP_STATEMENT_LIMITS as Yc, revokesIdentity as Yi, turnKeys as Yl, fetchesByItself as Yn, callRtcConfig as Yo, deviceWakeRequest as Yr, setAckFrame as Ys, ETHEREUM_USDT as Yt, SSHSIG_MAX_ARMOR as Z, PR_CHECKS as Za, appRef as Zc, PeerProofs as Zi, turnStatedVerifier as Zl, isGroupMessageId as Zn, contactRtcConfig as Zo, parseWakeFrame as Zr, signTombstone as Zs, ONCHAIN_PROVIDER as Zt, groupTypingEpoch as _, fileMessageText as _a, planKnocks as _c, isHoldUrl as _i, readDeviceInvite as _l, isPubkyProofFolder as _n, GROUP_MEMBER_CAP as _o, freshHubs as _r, filePartName as _s, normalizeAtprotoHandle as _t, parseRelayPayload as _u, appRevocationFor as a, DHT_MESSAGE_TTL as aa, enrollDigits as ac, chatAppId as ai, signAppObject as al, assertTokenUnits as an, cardLine as ao, SIGNAL_HOLD_MS as ar, HANDOFF_ACK as as, verifyBitcoinMessage as at, currentRelays as au, COMMUNITY_LIMITS as b, voiceLevel as ba, turnOff as bc, DOMAIN_FILE_MAX_BYTES as bi, decodeInviteCode as bl, pubkyProofCapability as bn, commitHash as bo, mergeBeacon as br, handoffAttemptSucceeded as bs, AtprotoProofError as bt, identityFromSeedB64 as bu, checkAppBeforeRun as c, dhtFileId as ca, enrollHelloFrame as cc, BUTTONS_CAPABILITY as ci, readImageMeta as cl, validatePaymentTarget as cn, sameButtonText as co, readGroupSignal as cr, HANDOFF_HAVE as cs, ATPROTO_DECLARED_SCOPE as ct, traceLink as cu, checkAppStoreIndex as d, sanitizeMime as da, readEnrollHello as dc, UPGRADE_CAPABILITY as di, readCanonicalJson as dl, SPARK_PROVIDER as dn, arrivalKey as do, meshHubs as dr, HANDOFF_PAKE as ds, ATPROTO_PROOF_SCOPE as dt, withRequestOptions as du, TRANSPORTS as ea, ENROLL_GRANT as ec, checkPushEndpoint as ei, isAppKey as el, SEPOLIA_TEST_USDT_FAUCET as en, RUN_RESULTS as eo, readGroupWant as er, signalHasVideo as es, parseSshPublicKey as et, HEDGE_MISSING_MS as eu, readAppStore as f, PLAYABLE_AUDIO as fa, verifyEnrollProof as fc, HOLD_CAPABILITY as fi, createContactLink as fl, sparkAddressKind as fn, claimedTime as fo, pickMeshHubs as fr, HANDOFF_PIECE_BYTES as fs, atprotoDidMethod as ft, PacketTooLargeError as fu, GroupTypingBoard as g, downsamplePeaks as ga, newInbox as gc, HoldRefusedError as gi, deviceInviteJoinerParams as gl, isPubkyKey as gn, GROUP_ADMIN_OFF_ERROR as go, doorHubs as gr, NO_ATTEMPTS as gs, isAtprotoDid as gt, openRelayPayload as gu, GROUP_TYPING_FRAME as h, baseMime as ha, inboxRecord as hc, HoldKeys as hi, createDeviceInvite as hl, PUBKY_PROOF_MAX_BYTES as hn, shownTime as ho, beaconRecords as hr, HANDOFF_VERIFIED as hs, checkAtprotoProofRecord as ht, newerPacket as hu, addedAppPermissions as i, DHT_FILE_TOO_LARGE as ia, enrollCancelReason as ic, APP_DATA_MAX_BYTES as ii, setAppSignatureFastPath as il, arkAddressPrefix as in, buttonLabelClash as io, SIGNAL_FRESH_MS as ir, serviceIdFromName as is, verifySshSignature as it, SLOW_MS as iu, knockRecords as j, forwardedAgain as ja, readKnockSlot as jc, recordsName as ji, deviceLinkPairing as jl, findEndpoint as jn, AWAITING_PEER_MS as jo, FileUplink as jr, handoffPakeFrame as js, didWebDocumentUrl as jt, toZ32 as ju, entryParams as k, linkStop as ka, mergeContactKnocks as kc, recordsFromTxt as ki, deviceEchoNonce as kl, cashuRequestPayload as kn, ratchetSessionOf as ko, ChatFiles as kr, handoffManifestFrames as ks, didJwsAlg as kt, randomBytes as ku, planAppUpdate as l, formatFileSize as la, enrollProofFrame as lc, EDIT_CAPABILITY as li, canonicalJson as ll, walletNetworkOf as ln, statusCardBytes as lo, MESH_HUBS as lr, HANDOFF_HELLO as ls, ATPROTO_FULL_SCOPE as lt, budgetRetryMs as lu, signAppStore as m, VOICE_METER as ma, endedRequests as mc, HOLD_LIMITS as mi, readContactLink as ml, isBitcoinAddress as mn, receivedTimestamp as mo, beaconKeys as mr, HANDOFF_TIMINGS as ms, atprotoProofRkey as mt, createRelayPayload as mu, readX401SdJwtVc as n, irohDescriptor as na, ENROLL_PROOF as nc, APP_RANGE_LIMITS as ni, readAppRevocation as nl, USDT_PUBLIC_RPC as nn, TASK_STATUSES as no, CarriedTransport as nr, HTTP_SERVICE_PROTO as ns, sameSshKey as nt, RelayTransport as nu, appStoreDecision as o, peekDhtMailbox as oa, enrollDoneFrame as oc, isAppVersion as oi, signAppRevocation as ol, assertWholeSats as on, cardUrl as oo, SIGNAL_REPLY_MS as or, HANDOFF_CANCEL as os, BitcoinAddressError as ot, normalizeRelayUrl as ou, readAppStoreSteps as p, VOICE_LIMITS as pa, clearMissed as pc, HOLD_DATED_BACK_MS as pi, encodeContactLink as pl, sparkInvoiceDetails as pn, heardTime as po, COMMUNITY_TOPOLOGY as pr, HANDOFF_REQUEST as ps, atprotoProofRecord as pt, RELAY_PAYLOAD_MAX_BYTES as pu, carryMentions as q, BUTTON_ID as qa, sha256Paced as qc, newIdentityBinding as qi, signTurnRelease as ql, GROUP_WANT_FRAME as qn, answersOffer as qo, WAKE_CALL_INTERVAL_MS as qr, SET_UPDATE as qs, resolveDidDht as qt, sameX401HolderJwk as r, irohRelayUrl as ra, enrollCancelFrame as rc, isServeId as ri, readAppRevocations as rl, WALLET_NETWORKS as rn, appCardId as ro, GROUP_SIGNAL_FRAME as rr, LEGACY_SERVICES as rs, sshSignCommand as rt, RelaysFailedError as ru, appUpdateDecision as s, DHT_FILE_CAPABILITY as sa, enrollGrantFrame as sc, APPS_CAPABILITY as si, parseImageMeta as sl, formatPaymentAmount as sn, checkStatusCard as so, groupSignalFrame as sr, HANDOFF_DONE as ss, decodeAnyBitcoinAddress as st, setLinkTraceSink as su, newX401HolderKey as t, automaticTransport as ta, ENROLL_HELLO as tc, vapidKeysMatch as ti, isAppRef as tl, TEST_USDT_FAUCET_AMOUNT as tn, STATUS_CARD_LIMITS as to, readGroupWantNo as tr, emptyLinkRecords as ts, parseSshSignature as tt, HEDGE_MS as tu, APP_STORE_LIMITS as u, sanitizeFileName as ua, readEnrollGrant as uc, STATUS_CARD_CAPABILITY as ui, canonicalJsonBytes as ul, SPARK_NETWORKS as un, statusCardText as uo, mayBeHub as ur, HANDOFF_OFFER as us, ATPROTO_PROOF_COLLECTION as ut, isDiscoveryBudgetError as uu, openGroupTyping as v, parseVoiceMeta as va, settleRequest as vc, newMailbox as vi, OwnInviteError as vl, newPubkyProofFolder as vn, MAX_GROUP_CHAIN as vo, lobbyKeys as vr, handoffAttemptAllowed as vs, parseAtprotoDidDocument as vt, createIdentity as vu, decodeCommunityLink as w, MAX_REMOVAL_NUMBER as wa, knockSlotIdentity as wc, domainWellKnownFile as wi, ownInviteRefusal as wl, pubkyHomeserverOf as wn, verifyCommitSignature as wo, rankHubs as wr, handoffContextProof as ws, DID_JWS_MAX_LENGTH as wt, sanitizeAvatar as wu, CommunitySession as x, parseVideoMeta as xa, ContactRequestError as xc, decodeDnsResponse as xi, encodeInviteCode as xl, pubkyProofFile as xn, parseGroupCommit as xo, mergeLobby as xr, handoffBusyFrame as xs, verifyAtprotoRecordProof as xt, publicKeyFromZ32 as xu, sealGroupTyping as y, voiceDownloadName as ya, takeRequest as yc, readManifest as yi, createChatInvite as yl, normalizePubkyKey as yn, MEMBER_KEY as yo, lobbyRecords as yr, handoffAttemptFailed as ys, shortAtprotoDid as yt, identityFromSeed as yu, GROUP_LIMITS as z, reactionEmoji as za, appDigest as zc, IDENTITY_MAX_VALIDITY as zi, classifyTurnRead as zl, pairedMessageFits as zn, formatLocalTarget as zo, typingActivity as zr, readHandoffDone as zs, parseDidSignaturePaste as zt };
34797
35598
 
34798
- //# sourceMappingURL=src-BB5-5P3s.js.map
35599
+ //# sourceMappingURL=src-1RU4TilT.js.map