@ghostlytools/cli 1.7.4 → 1.8.1

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 (99) hide show
  1. package/README.md +16 -10
  2. package/SKILL.md +1 -1
  3. package/dist/assets/{api-D3i2hwy0.js → api-BpQC8dAw.js} +121 -40
  4. package/dist/assets/api-BpQC8dAw.js.map +1 -0
  5. package/dist/assets/{api-Chhvpwok.js → api-CttDF-S5.js} +2 -2
  6. package/dist/assets/{apiKit-BtsHrnoo.js → apiKit-CSMeHKgo.js} +17 -5
  7. package/dist/assets/{apiKit-BtsHrnoo.js.map → apiKit-CSMeHKgo.js.map} +1 -1
  8. package/dist/assets/{apps-BHl97rHs.js → apps-DqTyZ40T.js} +8 -7
  9. package/dist/assets/apps-DqTyZ40T.js.map +1 -0
  10. package/dist/assets/{apps-BFJTqvAt.js → apps-DzFMdVt6.js} +1 -1
  11. package/dist/assets/{arkade-BFE8KkEE.js → arkade-Cu3TbPxC.js} +2 -2
  12. package/dist/assets/{arkade-BFE8KkEE.js.map → arkade-Cu3TbPxC.js.map} +1 -1
  13. package/dist/assets/{backup-Bbsr6nDi.js → backup-CLZOORFC.js} +1 -1
  14. package/dist/assets/{backup-CxACdtQX.js → backup-CyTZhu28.js} +6 -6
  15. package/dist/assets/{backup-CxACdtQX.js.map → backup-CyTZhu28.js.map} +1 -1
  16. package/dist/assets/{buttons-CieBtXEO.js → buttons-Bd9fR31r.js} +177 -23
  17. package/dist/assets/buttons-Bd9fR31r.js.map +1 -0
  18. package/dist/assets/buttons-c4CJnL6i.js +2 -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-CGfUsR1m.js} +2 -2
  22. package/dist/assets/{envelope-DYiGwzq_.js.map → envelope-CGfUsR1m.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/fixedHosts-BiukTsd9.js +24 -0
  26. package/dist/assets/fixedHosts-BiukTsd9.js.map +1 -0
  27. package/dist/assets/{ghostly_iroh_web-CO0onry8.js → ghostly_iroh_web-BzAXJUYH.js} +10 -10
  28. package/dist/assets/{ghostly_iroh_web-CO0onry8.js.map → ghostly_iroh_web-BzAXJUYH.js.map} +1 -1
  29. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  30. package/dist/assets/{groupFiles-CBJIEvCE.js → groupFiles-CeF9nPv9.js} +759 -29
  31. package/dist/assets/groupFiles-CeF9nPv9.js.map +1 -0
  32. package/dist/assets/{host-Va-r_KJz.js → host-CKAehWP6.js} +65 -29
  33. package/dist/assets/host-CKAehWP6.js.map +1 -0
  34. package/dist/assets/hyperdhtRelay-1wzya_0L.js +25 -0
  35. package/dist/assets/hyperdhtRelay-1wzya_0L.js.map +1 -0
  36. package/dist/assets/{hyperdhtRelay-B2uK9tJv.js → hyperdhtRelay-B8Pdykhg.js} +15 -3
  37. package/dist/assets/hyperdhtRelay-B8Pdykhg.js.map +1 -0
  38. package/dist/assets/{irohWeb-DxeEgQ-W.js → irohWeb-D6tAPHZa.js} +11 -7
  39. package/dist/assets/{irohWeb-DxeEgQ-W.js.map → irohWeb-D6tAPHZa.js.map} +1 -1
  40. package/dist/assets/{main-BX4oPWCJ.js → main-BDY-pfpz.js} +121 -37
  41. package/dist/assets/main-BDY-pfpz.js.map +1 -0
  42. package/dist/assets/{mainline-IfWQOB-J.js → mainline-3ueXpFQL.js} +2 -2
  43. package/dist/assets/{mainline-IfWQOB-J.js.map → mainline-3ueXpFQL.js.map} +1 -1
  44. package/dist/assets/mints-BaOmx517.js +2 -0
  45. package/dist/assets/{mints-BrlY773j.js → mints-j5XAOk4f.js} +15 -3
  46. package/dist/assets/mints-j5XAOk4f.js.map +1 -0
  47. package/dist/assets/{networkReason-N2vAaoth.js → networkReason-DhJYOomu.js} +2 -2
  48. package/dist/assets/{networkReason-N2vAaoth.js.map → networkReason-DhJYOomu.js.map} +1 -1
  49. package/dist/assets/{nwc-CzyCtNK2.js → nwc-B1Quqda-.js} +3 -3
  50. package/dist/assets/{nwc-CzyCtNK2.js.map → nwc-B1Quqda-.js.map} +1 -1
  51. package/dist/assets/{nwcProvider-DjWmEn3j.js → nwcProvider-DUB6xO-b.js} +2 -2
  52. package/dist/assets/{nwcProvider-DjWmEn3j.js.map → nwcProvider-DUB6xO-b.js.map} +1 -1
  53. package/dist/assets/ownDid-BfqHJdA6.js +281 -0
  54. package/dist/assets/ownDid-BfqHJdA6.js.map +1 -0
  55. package/dist/assets/{profiles-DcCeOi7J.js → profiles-MFtCmJwK.js} +3 -3
  56. package/dist/assets/{profiles-DcCeOi7J.js.map → profiles-MFtCmJwK.js.map} +1 -1
  57. package/dist/assets/{registry-BmS02J5h.js → registry-CZTmtSws.js} +1 -1
  58. package/dist/assets/{registry-CeW8XEQc.js → registry-DwlTNQjr.js} +5 -246
  59. package/dist/assets/registry-DwlTNQjr.js.map +1 -0
  60. package/dist/assets/{resolve-BvHkAhDH.js → resolve-BVwhiYjj.js} +3 -268
  61. package/dist/assets/resolve-BVwhiYjj.js.map +1 -0
  62. package/dist/assets/{restoredRows-mTTp3XNs.js → restoredRows-BCRCjhdF.js} +26 -2
  63. package/dist/assets/{restoredRows-mTTp3XNs.js.map → restoredRows-BCRCjhdF.js.map} +1 -1
  64. package/dist/assets/{server-BUcJo4vz.js → server-Br3XPwFG.js} +1001 -243
  65. package/dist/assets/server-Br3XPwFG.js.map +1 -0
  66. package/dist/assets/{src-BB5-5P3s.js → src-C4sOH4zH.js} +1109 -181
  67. package/dist/assets/src-C4sOH4zH.js.map +1 -0
  68. package/dist/assets/sshForges-CQQomStK.js +253 -0
  69. package/dist/assets/sshForges-CQQomStK.js.map +1 -0
  70. package/dist/assets/{translate-2WyaRVCr.js → translate-C2aNyUkR.js} +20 -10
  71. package/dist/assets/translate-C2aNyUkR.js.map +1 -0
  72. package/dist/assets/{usdt-BLazHiaP.js → usdt-CMwatDnQ.js} +3 -3
  73. package/dist/assets/{usdt-BLazHiaP.js.map → usdt-CMwatDnQ.js.map} +1 -1
  74. package/dist/assets/waitNotice-Ck3el3_Z.js +45 -0
  75. package/dist/assets/waitNotice-Ck3el3_Z.js.map +1 -0
  76. package/dist/assets/{words-BaumxjXe.js → words-CqN2KG1r.js} +6 -3
  77. package/dist/assets/words-CqN2KG1r.js.map +1 -0
  78. package/dist/ghostly.mjs +1 -1
  79. package/examples/claude-code-agent.sh +1 -1
  80. package/package.json +1 -1
  81. package/dist/assets/api-D3i2hwy0.js.map +0 -1
  82. package/dist/assets/apps-BHl97rHs.js.map +0 -1
  83. package/dist/assets/buttons-CieBtXEO.js.map +0 -1
  84. package/dist/assets/buttons-YtAj3R_E.js +0 -2
  85. package/dist/assets/errors-QUGP-jIF.js.map +0 -1
  86. package/dist/assets/groupFiles-CBJIEvCE.js.map +0 -1
  87. package/dist/assets/host-Va-r_KJz.js.map +0 -1
  88. package/dist/assets/hyperdhtRelay-B2uK9tJv.js.map +0 -1
  89. package/dist/assets/hyperdhtRelay-BT_wRxab.js +0 -21
  90. package/dist/assets/hyperdhtRelay-BT_wRxab.js.map +0 -1
  91. package/dist/assets/main-BX4oPWCJ.js.map +0 -1
  92. package/dist/assets/mints-BrlY773j.js.map +0 -1
  93. package/dist/assets/mints-CqTdA4Gk.js +0 -2
  94. package/dist/assets/registry-CeW8XEQc.js.map +0 -1
  95. package/dist/assets/resolve-BvHkAhDH.js.map +0 -1
  96. package/dist/assets/server-BUcJo4vz.js.map +0 -1
  97. package/dist/assets/src-BB5-5P3s.js.map +0 -1
  98. package/dist/assets/translate-2WyaRVCr.js.map +0 -1
  99. 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).
@@ -9660,6 +10146,18 @@ function cardUrl(value) {
9660
10146
  if (url.protocol !== "https:" || !url.hostname || url.username || url.password) return void 0;
9661
10147
  return url.href.length <= STATUS_CARD_LIMITS.url ? url.href : void 0;
9662
10148
  }
10149
+ /**
10150
+ * The link an app card names, sent or read (WISP 405 § An app): a card's link without its query or fragment. A
10151
+ * private file's read token rides in a query, and a card goes to a contact; a bundle is pinned by its digest, not its link.
10152
+ */
10153
+ function appCardUrl(value) {
10154
+ const href = cardUrl(value);
10155
+ if (!href) return void 0;
10156
+ const url = new URL(href);
10157
+ url.search = "";
10158
+ url.hash = "";
10159
+ return url.href;
10160
+ }
9663
10161
  var count = (value, min = 0) => typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= STATUS_CARD_LIMITS.count ? value : void 0;
9664
10162
  /** A time on a card as a reader keeps it: a positive whole number, never later than `latest`. */
9665
10163
  var time = (value, latest) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? Math.min(value, latest) : void 0;
@@ -9769,7 +10267,7 @@ function readStatusCard(raw, now = Date.now()) {
9769
10267
  if (!isAppRef(raw.ref) || id !== appCardId(raw.ref) || !isAppHash(raw.digest) || !appSequence(raw.sequence)) return void 0;
9770
10268
  const title = cardLine(raw.title, STATUS_CARD_LIMITS.appTitle);
9771
10269
  if (!title) return void 0;
9772
- const version = cardLine(raw.version, STATUS_CARD_LIMITS.appVersion), url = cardUrl(raw.url);
10270
+ const version = cardLine(raw.version, STATUS_CARD_LIMITS.appVersion), url = appCardUrl(raw.url);
9773
10271
  return {
9774
10272
  kind: "app",
9775
10273
  id,
@@ -10107,8 +10605,8 @@ function removedCardText(of, title) {
10107
10605
  function statusCardText(card) {
10108
10606
  if (card.kind === "removed") return removedCardText(card.of);
10109
10607
  if (card.kind === "app") {
10110
- const named = `${card.title}${card.version ? ` ${card.version}` : ""}`;
10111
- return [card.opened ? `🧩 Opened ${named} in this chat (Ghostly app)` : `🧩 ${named} (Ghostly app)`, ...card.url ? [card.url] : []].join("\n");
10608
+ const named = `${card.title}${card.version ? ` ${card.version}` : ""}`, url = appCardUrl(card.url);
10609
+ return [card.opened ? `🧩 Opened ${named} in this chat (Ghostly app)` : `🧩 ${named} (Ghostly app)`, ...url ? [url] : []].join("\n");
10112
10610
  }
10113
10611
  if (card.kind === "usage") {
10114
10612
  const left = `${usageLeft(card)}% left${card.window ? ` (${card.window})` : ""}`;
@@ -11302,6 +11800,11 @@ var DhtDelivery = class DhtDelivery {
11302
11800
  live = false;
11303
11801
  active = false;
11304
11802
  startedAt = Date.now();
11803
+ /**
11804
+ * When an envelope of the contact's newer than any before was last read here, in this run. A contact that is there
11805
+ * puts a keep-alive every four minutes: none in `PRESENCE_WINDOW`, it is away (`publish`).
11806
+ */
11807
+ peerNewAt = -Infinity;
11305
11808
  /** The next read was asked for (a refresh, a fresh packet of the contact): it is not a background one. */
11306
11809
  urgent = false;
11307
11810
  /** Reads left that are signaling: the contact is leaving DHT only, and the live link waits on them (`expect`). */
@@ -11375,9 +11878,29 @@ var DhtDelivery = class DhtDelivery {
11375
11878
  maxTextBytes: 256,
11376
11879
  ...this.lastPublished && { lastPublished: this.lastPublished },
11377
11880
  ...this.foreignKeySeenAt && { foreignKeySeenAt: this.foreignKeySeenAt },
11378
- ...this.state.inviteTaken && { inviteTaken: true }
11881
+ ...this.state.inviteTaken && { inviteTaken: true },
11882
+ ...this.forwardSecrecy && { forwardSecrecy: this.forwardSecrecy }
11379
11883
  };
11380
11884
  }
11885
+ get forwardSecrecy() {
11886
+ const ratchet = this.options.ratchet;
11887
+ if (!ratchet || !this.options.credentials.peerKey) return void 0;
11888
+ const supports = ratchet.peerSupports();
11889
+ return ratchet.box.on && supports ? "on" : !supports ? ratchet.box.heardAny ? "stopped" : "unsupported" : "starting";
11890
+ }
11891
+ /**
11892
+ * Whether an envelope to `recipient` is sealed with the ratchet: the contact is pinned and its record lists
11893
+ * `ratchet/1`, or a ratcheted envelope of its was opened here, after which nothing goes plain (WISP 4xx § Downgrade).
11894
+ * And the contact pinned this side too (an envelope of its sealed to this side read, or a live session had): a joiner
11895
+ * pins its inviter from the invite, and its first contact sealed with the ratchet would reach an inviter that has no key
11896
+ * to open it with, and so never pins it.
11897
+ */
11898
+ ratcheted(recipient) {
11899
+ const ratchet = this.options.ratchet, peer = this.options.credentials.peerKey;
11900
+ if (!ratchet || !peer || recipient !== peer) return false;
11901
+ if (ratchet.box.heardAny) return true;
11902
+ return ratchet.peerSupports() && (!!this.state.peerPinned || !!this.state.wasLive);
11903
+ }
11381
11904
  /**
11382
11905
  * This side joined, and its inviter never answered (`DhtDeliveryState.unanswered`): no envelope of its newer than the
11383
11906
  * one that pinned it, none sealed to this side, no text confirmed, never live (as `sealedToAnother` asks too).
@@ -11416,6 +11939,14 @@ var DhtDelivery = class DhtDelivery {
11416
11939
  return this.pinnedBoxes;
11417
11940
  }
11418
11941
  lastPublished;
11942
+ /** The envelope a trace line was last said for, per step: a packet read again says nothing new (a Desktop logs every line). */
11943
+ traced = /* @__PURE__ */ new Map();
11944
+ traceOnce(step, record, detail) {
11945
+ const seen = record.slice(-24);
11946
+ if (this.traced.get(step) === seen) return;
11947
+ this.traced.set(step, seen);
11948
+ traceLink(this.from, step, detail);
11949
+ }
11419
11950
  /** The sealed record's nonce is its first 24 bytes: 32 characters of base64. */
11420
11951
  static facts(body, records, key) {
11421
11952
  return {
@@ -11471,6 +12002,13 @@ var DhtDelivery = class DhtDelivery {
11471
12002
  ]));
11472
12003
  }
11473
12004
  records(body, recipient = this.options.credentials.peerKey) {
12005
+ return this.envelope(body, recipient).records;
12006
+ }
12007
+ /**
12008
+ * The envelope's records. Ratcheted (`ratcheted`), its `_dr` record is the right length but not sealed yet: `seal`
12009
+ * gives its bytes, under the chat's lock, once the publication is sure to go. Measuring a packet takes no key.
12010
+ */
12011
+ envelope(body, recipient = this.options.credentials.peerKey) {
11474
12012
  const signature = toBase64Url(sign(this.signed(body, recipient), this.participation.seed));
11475
12013
  const plaintext = JSON.stringify([body, signature]);
11476
12014
  const hint = recipient ? [{
@@ -11478,20 +12016,46 @@ var DhtDelivery = class DhtDelivery {
11478
12016
  value: encrypt(this.participation.pubKeyZ32, this.key),
11479
12017
  ttl: ENVELOPE_TTL
11480
12018
  }] : [];
12019
+ const ratchet = this.ratcheted(recipient);
12020
+ const sealedBytes = (bytes) => ratchet ? 4 * Math.ceil((66 + bytes) / 3) : sealedLength(bytes);
12021
+ const label = ratchet ? "_dr" : "_dm";
11481
12022
  const fits = (bytes) => bytes <= MAX_ENVELOPE_PLAINTEXT && measureRecords(this.identity.pubKeyZ32, [{
11482
- label: "_dm",
11483
- value: "A".repeat(sealedLength(bytes)),
12023
+ label,
12024
+ value: "A".repeat(sealedBytes(bytes)),
11484
12025
  ttl: ENVELOPE_TTL
11485
12026
  }, ...hint]) <= ENVELOPE_PACKET_BYTES;
11486
12027
  const bytes = utf8Encode(plaintext).length;
11487
12028
  if (!fits(bytes)) throw new Error("Text and authentication exceed the DHT packet budget. Shorten the message.");
11488
12029
  let padded = bytes;
11489
12030
  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),
12031
+ const full = plaintext + " ".repeat(padded - bytes);
12032
+ if (ratchet) return {
12033
+ records: [{
12034
+ label,
12035
+ value: "A".repeat(sealedBytes(padded)),
12036
+ ttl: ENVELOPE_TTL
12037
+ }, ...hint],
12038
+ plaintext: full
12039
+ };
12040
+ return { records: [{
12041
+ label,
12042
+ value: encrypt(full, recipient ? this.sealedKey(recipient) : this.key),
11493
12043
  ttl: ENVELOPE_TTL
11494
- }, ...hint];
12044
+ }, ...hint] };
12045
+ }
12046
+ /**
12047
+ * The records to publish: a ratcheted one sealed now, its state saved first (seal, save, send), from the plaintext
12048
+ * the envelope was measured with.
12049
+ */
12050
+ async sealed(envelope) {
12051
+ const { records, plaintext } = envelope;
12052
+ if (records[0]?.label !== "_dr") return records;
12053
+ if (plaintext === void 0) throw new Error("A ratcheted envelope without its plaintext");
12054
+ const sealed = await this.options.ratchet.box.lock((tx) => tx.seal("floor", utf8Encode(plaintext)));
12055
+ return [{
12056
+ ...records[0],
12057
+ value: toBase64(sealed)
12058
+ }, ...records.slice(1)];
11495
12059
  }
11496
12060
  async start() {
11497
12061
  if (this.running) return;
@@ -11610,6 +12174,7 @@ var DhtDelivery = class DhtDelivery {
11610
12174
  }
11611
12175
  validate(text, timestamp, id, reply, edit) {
11612
12176
  if (this.options.peerAcceptsText?.() === false) return DHT_TEXT_REFUSED;
12177
+ if (this.forwardSecrecy === "stopped") return DHT_RATCHET_STOPPED;
11613
12178
  if (!ID$2.test(id) || !Number.isSafeInteger(timestamp) || timestamp <= 0 || reply !== void 0 && !REPLY_TO.test(reply)) return "Invalid message.";
11614
12179
  if (edit !== void 0 && (reply !== void 0 || !ID$2.test(edit[0]) || !validEditNumber(edit[1]))) return "Invalid message.";
11615
12180
  if (utf8Encode(text).length > 256) return DHT_TEXT_TOO_LONG;
@@ -11884,10 +12449,10 @@ var DhtDelivery = class DhtDelivery {
11884
12449
  for (let count = pending.length; count > 0; count--) {
11885
12450
  const body = this.body(sequence, issued, expires, message, receipt, reply, pending.slice(0, count), edit, forwarded, file);
11886
12451
  try {
11887
- const records = this.records(body);
12452
+ const envelope = this.envelope(body);
11888
12453
  if (utf8Encode(JSON.stringify([body, "x".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT) return {
11889
12454
  body,
11890
- records,
12455
+ ...envelope,
11891
12456
  reactions: count
11892
12457
  };
11893
12458
  } catch {}
@@ -11895,7 +12460,7 @@ var DhtDelivery = class DhtDelivery {
11895
12460
  const body = this.body(sequence, issued, expires, message, receipt, reply, [], edit, forwarded, file);
11896
12461
  return {
11897
12462
  body,
11898
- records: this.records(body),
12463
+ ...this.envelope(body),
11899
12464
  reactions: 0
11900
12465
  };
11901
12466
  }
@@ -11910,10 +12475,21 @@ var DhtDelivery = class DhtDelivery {
11910
12475
  if (keepAlive && (this.controlDue > now || this.state.inviteTaken)) return;
11911
12476
  const expires = pending?.expires ?? now - 12e4 + CONTROL_TTL;
11912
12477
  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);
12478
+ const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
12479
+ const away = !!this.options.credentials.peerKey && now - this.peerNewAt >= 6e5;
12480
+ const options = keepAlive && (this.live || away) ? { background: true } : void 0;
12481
+ const held = this.options.transport.publishHeld?.(identity.pubKeyZ32, options);
12482
+ if (held) {
12483
+ await this.heldBack(held, now, {
12484
+ lastPublish: this.lastPublish,
12485
+ controlDue: this.controlDue
12486
+ }, void 0, void 0);
12487
+ throw held;
12488
+ }
12489
+ const fittedEnvelope = this.fitted(this.sequence + 1, issued, expires, pending?.message ?? null, receipt?.id ?? null, pending?.reply, pending?.edit, pending?.forwarded, pending?.file);
12490
+ const { body, reactions } = fittedEnvelope;
11914
12491
  const reactionsWereDue = this.reactionsDue;
11915
12492
  this.reactionsDue = !reactions && !!this.options.reactions?.().length;
11916
- const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
11917
12493
  const sequence = body[1];
11918
12494
  await this.persist({
11919
12495
  ...this.state,
@@ -11930,20 +12506,23 @@ var DhtDelivery = class DhtDelivery {
11930
12506
  } : this.state.receipt
11931
12507
  });
11932
12508
  this.sequence = sequence;
12509
+ const records = await this.sealed(fittedEnvelope);
11933
12510
  const before = {
11934
12511
  lastPublish: this.lastPublish,
11935
12512
  controlDue: this.controlDue
11936
12513
  };
12514
+ const ownInvite = !this.options.credentials.expectedPeerKey && !this.active && this.unusedInviteAge(now) !== void 0;
11937
12515
  this.lastPublish = now;
11938
- this.controlDue = now + 24e4;
12516
+ this.controlDue = now + (ownInvite ? UNUSED_INVITE_UPKEEP_MS : 24e4);
11939
12517
  traceLink(this.from, "dht-publish", {
11940
12518
  mode: this.mode,
11941
12519
  seq: body[1],
11942
- ...identity !== this.identity && { pinned: true }
12520
+ ...identity !== this.identity && { pinned: true },
12521
+ ...records[0]?.label === "_dr" && { ratchet: true }
11943
12522
  });
11944
12523
  if (pending) this.lastPublished = DhtDelivery.facts(body, records, identity.pubKeyZ32);
11945
12524
  try {
11946
- await this.options.transport.publish(identity, records, keepAlive && this.live ? { background: true } : void 0);
12525
+ await this.options.transport.publish(identity, records, options);
11947
12526
  } catch (error) {
11948
12527
  this.reactionsDue ||= reactionsWereDue;
11949
12528
  if (isDiscoveryBudgetError(error)) await this.heldBack(error, now, before, pending, receipt);
@@ -11969,7 +12548,7 @@ var DhtDelivery = class DhtDelivery {
11969
12548
  this.lastPublish = before.lastPublish;
11970
12549
  this.controlDue = Math.min(before.controlDue, at);
11971
12550
  traceLink(this.from, "dht-publish-waits", { retryInMs: at - now });
11972
- await this.persist({
12551
+ if (pending || receipt) await this.persist({
11973
12552
  ...this.state,
11974
12553
  pending: pending ?? this.state.pending,
11975
12554
  receipt: receipt ?? this.state.receipt
@@ -11980,22 +12559,44 @@ var DhtDelivery = class DhtDelivery {
11980
12559
  * one sealed record, a well-formed body within its times, signed by the key it names. Null: not an envelope of the
11981
12560
  * contact's (the pin rules are the caller's).
11982
12561
  */
11983
- open(packet, box) {
12562
+ open(packet, box, ratchet) {
11984
12563
  const address = box === "pinned" ? this.pinned()?.peerAddress : this.peerAddress;
11985
12564
  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;
12565
+ const records = packet.records.filter((r) => r.label === "_dm"), ratcheted = packet.records.filter((r) => r.label === "_dr");
12566
+ if (records.length + ratcheted.length !== 1) return null;
11988
12567
  const hints = packet.records.filter((r) => r.label === "_dmk");
11989
12568
  if (hints.length > 1) return null;
11990
12569
  const sender = hints.length ? tryDecrypt(hints[0].value, this.key) : null;
11991
12570
  if (hints.length && !sender) return null;
12571
+ const peer = this.options.credentials.peerKey;
11992
12572
  let plaintext;
11993
- try {
11994
- plaintext = tryDecrypt(records[0].value, sender ? this.sealedKey(sender) : this.key);
11995
- } catch {
11996
- plaintext = null;
12573
+ if (ratcheted.length) {
12574
+ const closed = box === "invite" && sender ? { sealedToAnother: sender } : null;
12575
+ if (!ratchet || !peer || sender !== peer) return closed;
12576
+ let opened;
12577
+ try {
12578
+ opened = ratchet(fromBase64(ratcheted[0].value));
12579
+ } catch {
12580
+ opened = null;
12581
+ }
12582
+ if (!opened) return closed;
12583
+ try {
12584
+ plaintext = utf8Decode(opened);
12585
+ } catch {
12586
+ return null;
12587
+ }
12588
+ } else {
12589
+ if (peer && this.options.ratchet?.box.heard("floor") && (!sender || sender === peer)) {
12590
+ this.traceOnce("dht-plain-refused", records[0].value, { box });
12591
+ return null;
12592
+ }
12593
+ try {
12594
+ plaintext = tryDecrypt(records[0].value, sender ? this.sealedKey(sender) : this.key);
12595
+ } catch {
12596
+ plaintext = null;
12597
+ }
12598
+ if (!plaintext && sender) return { sealedToAnother: sender };
11997
12599
  }
11998
- if (!plaintext && sender) return { sealedToAnother: sender };
11999
12600
  if (!plaintext || utf8Encode(plaintext).length > MAX_ENVELOPE_PLAINTEXT) return null;
12000
12601
  let envelope;
12001
12602
  try {
@@ -12075,7 +12676,41 @@ var DhtDelivery = class DhtDelivery {
12075
12676
  * can write to) or `pinned`. `none`: nothing from the contact in it; `old`: the contact's, already read; `new`: taken.
12076
12677
  */
12077
12678
  async receive(packet, box) {
12078
- const opened = this.open(packet, box);
12679
+ const ratcheted = packet.records.find((r) => r.label === "_dr");
12680
+ if (!ratcheted) return this.take(packet, box, this.open(packet, box));
12681
+ const digest = toBase64Url(sha256(utf8Encode(ratcheted.value)).slice(0, 16));
12682
+ if (digest === this.state.lastDr) return "old";
12683
+ const ratchet = this.options.ratchet;
12684
+ if (!ratchet) return "none";
12685
+ let sealed;
12686
+ const opened = this.open(packet, box, (bytes) => {
12687
+ const plain = ratchet.box.peek("floor", bytes);
12688
+ if (plain) sealed = bytes;
12689
+ return plain;
12690
+ });
12691
+ if (!sealed) this.traceOnce("dht-ratchet-closed", ratcheted.value, {
12692
+ box,
12693
+ pinned: !!this.options.credentials.peerKey
12694
+ });
12695
+ if (!sealed && box === "pinned" && packet.pubKeyZ32 === this.pinned()?.peerAddress && this.state.peerPinned !== "seen") {
12696
+ await this.persist({
12697
+ ...this.state,
12698
+ peerPinned: "seen"
12699
+ });
12700
+ traceLink(this.from, "dht-peer-pinned", {
12701
+ peerPinned: "seen",
12702
+ ratchet: true
12703
+ });
12704
+ }
12705
+ return this.take(packet, box, opened, sealed && {
12706
+ commit: async (order) => {
12707
+ if (!await ratchet.box.commitOpen("floor", sealed, order)) throw new Error("A ratcheted envelope no longer opens");
12708
+ },
12709
+ digest
12710
+ });
12711
+ }
12712
+ /** `ratchet`: the envelope was ratcheted; its state is saved once what it carried is stored, with its digest. */
12713
+ async take(packet, box, opened, ratchet) {
12079
12714
  if (!opened) return "none";
12080
12715
  if ("sealedToAnother" in opened) {
12081
12716
  if (opened.sealedToAnother) await this.sealedToAnother(opened.sealedToAnother);
@@ -12102,6 +12737,7 @@ var DhtDelivery = class DhtDelivery {
12102
12737
  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
12738
  if (receipt !== null && (typeof receipt !== "string" || !ID$2.test(receipt))) return "none";
12104
12739
  const unanswered = !this.options.credentials.peerKey && !!this.options.credentials.expectedPeerKey && !sender && !this.live;
12740
+ this.peerNewAt = Date.now();
12105
12741
  await this.options.pin(author);
12106
12742
  this.options.credentials.peerKey = author;
12107
12743
  this.options.credentials.requireSignedSignals = true;
@@ -12145,6 +12781,7 @@ var DhtDelivery = class DhtDelivery {
12145
12781
  if (peerPinned !== this.state.peerPinned) traceLink(this.from, "dht-peer-pinned", { peerPinned });
12146
12782
  if (this.state.inviteTaken) traceLink(this.from, "invite-untaken", {});
12147
12783
  const { inviteTaken: _taken, ...kept } = this.state;
12784
+ if (ratchet) await ratchet.commit(sequence);
12148
12785
  await this.persist({
12149
12786
  ...kept,
12150
12787
  peerSequence: sequence,
@@ -12153,6 +12790,7 @@ var DhtDelivery = class DhtDelivery {
12153
12790
  confirmed,
12154
12791
  ...peerPinned && { peerPinned },
12155
12792
  ...unanswered && { unanswered: sequence },
12793
+ ...ratchet && { lastDr: ratchet.digest },
12156
12794
  pending: confirmed && this.state.pending?.message[0] === confirmed ? void 0 : this.state.pending,
12157
12795
  ...newest > (this.state.reactionsTaken ?? 0) && { reactionsTaken: newest }
12158
12796
  });
@@ -12207,7 +12845,12 @@ var DhtDelivery = class DhtDelivery {
12207
12845
  for (const box of boxes) {
12208
12846
  const packet = await this.options.transport.resolve(box === "pinned" ? pinned.peerAddress : this.peerAddress, options);
12209
12847
  reads++;
12210
- const opened = packet && this.open(packet, box);
12848
+ const dr = packet?.records.find((r) => r.label === "_dr");
12849
+ if (dr && toBase64Url(sha256(utf8Encode(dr.value)).slice(0, 16)) === this.state.lastDr) return {
12850
+ reads,
12851
+ text: null
12852
+ };
12853
+ const opened = packet && this.open(packet, box, (sealed) => this.options.ratchet?.box.peek("floor", sealed) ?? null);
12211
12854
  if (!opened || "sealedToAnother" in opened || opened.author !== expected) continue;
12212
12855
  const { sequence, message } = opened;
12213
12856
  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 +12965,7 @@ var DhtDelivery = class DhtDelivery {
12322
12965
  }
12323
12966
  };
12324
12967
  var DHT_TEXT_REFUSED = "Your contact's app does not accept text over the DHT. It is sent when you are live.";
12968
+ var DHT_RATCHET_STOPPED = "Your contact's app no longer reads protected messages over the DHT. It is sent when you are live.";
12325
12969
  var DHT_FILE_REFUSED = "Your contact's app shows a file only once it comes. It is sent when you are live.";
12326
12970
  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
12971
  /**
@@ -12332,17 +12976,29 @@ function peekDhtMailbox(options) {
12332
12976
  const refuse = async () => {
12333
12977
  throw new Error("A peek saves nothing");
12334
12978
  };
12979
+ const credentials = { ...options.credentials }, peer = credentials.peerKey;
12980
+ const box = options.ratchet && peer ? new RatchetBox(() => ({
12981
+ seed: fromBase64Url(credentials.seedB64),
12982
+ self: identityFromSeedB64(credentials.seedB64).pubKeyZ32,
12983
+ peer,
12984
+ rendezvous: [identityFromSeedB64(options.params.seedB64).pubKeyZ32, options.params.peerPubKeyZ32],
12985
+ secret: fromBase64Url(options.params.encKeyB64)
12986
+ }), options.ratchet, refuse) : void 0;
12335
12987
  return new DhtDelivery({
12336
12988
  params: options.params,
12337
12989
  mode: "stream",
12338
12990
  state: options.state,
12339
- credentials: { ...options.credentials },
12991
+ credentials,
12340
12992
  transport: options.transport,
12341
12993
  save: refuse,
12342
12994
  pin: refuse,
12343
12995
  message: refuse,
12344
12996
  receipt: refuse,
12345
- changed: () => {}
12997
+ changed: () => {},
12998
+ ...box && { ratchet: {
12999
+ box,
13000
+ peerSupports: () => true
13001
+ } }
12346
13002
  }).peek(options.background ? { background: true } : void 0);
12347
13003
  }
12348
13004
  //#endregion
@@ -12637,7 +13293,7 @@ function irohRelayUrl(value, spelling = "dotted") {
12637
13293
  const host = url.hostname, name = host.replace(/\.$/, "");
12638
13294
  if (!name.includes(".") && name !== "localhost") return value;
12639
13295
  if (name.startsWith("[") || /^\d+(\.\d+){3}$/.test(name)) return value;
12640
- const wanted = spelling === "plain" || name === "localhost" ? name : `${name}.`;
13296
+ const wanted = spelling === "dotted" && /(^|\.)iroh\.link$/.test(name) ? `${name}.` : name;
12641
13297
  if (wanted === host) return value;
12642
13298
  url.hostname = wanted;
12643
13299
  return url.href;
@@ -12657,6 +13313,14 @@ function irohDescriptor(descriptor, spelling = "dotted") {
12657
13313
  * as a test relay is (the same rule as the relay settings).
12658
13314
  */
12659
13315
  var RELAY_URL = /^((https|wss):\/\/[^\s]{1,120}|(http|ws):\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d{1,5})?(\/[^\s]{0,100})?)$/;
13316
+ /**
13317
+ * A relay URL with more than its server's address in it: a login, a query or a fragment, which no relay setting takes
13318
+ * (irohWeb.ts `irohRelayProblem`, hyperdhtRelay.ts `hyperdhtRelayProblem`). An older app named its HyperDHT relay as
13319
+ * set, with them; such a descriptor is not dialed or kept, and the rest of what the contact told still is.
13320
+ */
13321
+ var RELAY_WITH_SECRETS = /^[a-z]+:\/\/[^/?#]*@|[?#]/i;
13322
+ /** A relay URL a descriptor may name: `RELAY_URL`, with nothing but the server's address in it. */
13323
+ var relayUrl = (value) => typeof value === "string" && RELAY_URL.test(value) && !RELAY_WITH_SECRETS.test(value);
12660
13324
  var HEX_KEY = /^[0-9a-f]{64}$/;
12661
13325
  /** An Iroh direct address as the adapters parse it: an IPv4 or bracketed IPv6 address and its port. */
12662
13326
  var SOCKET_ADDRESS = /^(\d{1,3}(\.\d{1,3}){3}|\[[0-9A-Fa-f:.]{2,45}(%[A-Za-z0-9._-]{1,16})?\]):\d{1,5}$/;
@@ -12664,7 +13328,7 @@ var MAX_ADDRESSES = 8;
12664
13328
  /**
12665
13329
  * A contact's native descriptors as it tells them on a session (`paired-policy`, `paired-adapters`) or as this app
12666
13330
  * kept them: only what the adapters dial, each field in the shape its adapter makes. The keys are 64 hex characters,
12667
- * a relay passes `RELAY_URL` (the rule its capability record is read by), an Iroh descriptor lists at most eight
13331
+ * a relay passes `relayUrl` (the rule its capability record is read by), an Iroh descriptor lists at most eight
12668
13332
  * socket addresses. A descriptor that is anything else is left out, as one the contact never told; a field this app
12669
13333
  * does not know is not kept.
12670
13334
  */
@@ -12672,17 +13336,16 @@ function checkedDescriptors(value) {
12672
13336
  const out = {};
12673
13337
  if (!value || typeof value !== "object" || Array.isArray(value)) return out;
12674
13338
  const raw = value;
12675
- const relay = (v) => typeof v === "string" && RELAY_URL.test(v);
12676
13339
  const relayed = (v) => v === void 0 || typeof v === "boolean";
12677
13340
  const iroh = raw["iroh/1"];
12678
- if (iroh && typeof iroh === "object" && typeof iroh.id === "string" && HEX_KEY.test(iroh.id) && (iroh.relay === void 0 || iroh.relay === null || relay(iroh.relay)) && relayed(iroh.relayed) && Array.isArray(iroh.addresses) && iroh.addresses.length <= MAX_ADDRESSES && iroh.addresses.every((a) => typeof a === "string" && SOCKET_ADDRESS.test(a))) out["iroh/1"] = {
13341
+ if (iroh && typeof iroh === "object" && typeof iroh.id === "string" && HEX_KEY.test(iroh.id) && (iroh.relay === void 0 || iroh.relay === null || relayUrl(iroh.relay)) && relayed(iroh.relayed) && Array.isArray(iroh.addresses) && iroh.addresses.length <= MAX_ADDRESSES && iroh.addresses.every((a) => typeof a === "string" && SOCKET_ADDRESS.test(a))) out["iroh/1"] = {
12679
13342
  id: iroh.id,
12680
13343
  relay: iroh.relay ?? null,
12681
13344
  addresses: [...iroh.addresses],
12682
13345
  ...iroh.relayed !== void 0 ? { relayed: iroh.relayed } : {}
12683
13346
  };
12684
13347
  const hyper = raw["hyperdht/1"];
12685
- if (hyper && typeof hyper === "object" && typeof hyper.publicKey === "string" && HEX_KEY.test(hyper.publicKey) && (hyper.relay === void 0 || relay(hyper.relay)) && relayed(hyper.relayed)) out["hyperdht/1"] = {
13348
+ if (hyper && typeof hyper === "object" && typeof hyper.publicKey === "string" && HEX_KEY.test(hyper.publicKey) && (hyper.relay === void 0 || relayUrl(hyper.relay)) && relayed(hyper.relayed)) out["hyperdht/1"] = {
12686
13349
  publicKey: hyper.publicKey,
12687
13350
  ...hyper.relay !== void 0 ? { relay: hyper.relay } : {},
12688
13351
  ...hyper.relayed !== void 0 ? { relayed: hyper.relayed } : {}
@@ -14376,12 +15039,12 @@ function capsDescriptors(descriptors) {
14376
15039
  const iroh = descriptors?.["iroh/1"];
14377
15040
  if (iroh && typeof iroh.id === "string" && HEX64$1.test(iroh.id)) out["iroh/1"] = {
14378
15041
  id: hexToKey(iroh.id),
14379
- ...typeof iroh.relay === "string" && RELAY_URL.test(iroh.relay) ? { relay: iroh.relay } : {}
15042
+ ...relayUrl(iroh.relay) ? { relay: iroh.relay } : {}
14380
15043
  };
14381
15044
  const hyper = descriptors?.["hyperdht/1"];
14382
15045
  if (hyper && typeof hyper.publicKey === "string" && HEX64$1.test(hyper.publicKey)) out["hyperdht/1"] = {
14383
15046
  publicKey: hexToKey(hyper.publicKey),
14384
- ...typeof hyper.relay === "string" && RELAY_URL.test(hyper.relay) ? { relay: hyper.relay } : {}
15047
+ ...relayUrl(hyper.relay) ? { relay: hyper.relay } : {}
14385
15048
  };
14386
15049
  return out;
14387
15050
  }
@@ -14415,16 +15078,17 @@ function parseDescriptors(value) {
14415
15078
  const raw = value;
14416
15079
  const out = {};
14417
15080
  const iroh = raw["iroh/1"], hyper = raw["hyperdht/1"];
15081
+ const withSecrets = (relay) => typeof relay === "string" && RELAY_WITH_SECRETS.test(relay);
14418
15082
  if (iroh !== void 0) {
14419
15083
  if (!iroh || typeof iroh.id !== "string" || !KEY.test(iroh.id) || iroh.relay !== void 0 && (typeof iroh.relay !== "string" || !RELAY_URL.test(iroh.relay))) return null;
14420
- out["iroh/1"] = {
15084
+ if (!withSecrets(iroh.relay)) out["iroh/1"] = {
14421
15085
  id: iroh.id,
14422
15086
  ...iroh.relay !== void 0 ? { relay: iroh.relay } : {}
14423
15087
  };
14424
15088
  }
14425
15089
  if (hyper !== void 0) {
14426
15090
  if (!hyper || typeof hyper.publicKey !== "string" || !KEY.test(hyper.publicKey) || hyper.relay !== void 0 && (typeof hyper.relay !== "string" || !RELAY_URL.test(hyper.relay))) return null;
14427
- out["hyperdht/1"] = {
15091
+ if (!withSecrets(hyper.relay)) out["hyperdht/1"] = {
14428
15092
  publicKey: hyper.publicKey,
14429
15093
  ...hyper.relay !== void 0 ? { relay: hyper.relay } : {}
14430
15094
  };
@@ -14696,17 +15360,23 @@ var CapsExchange = class {
14696
15360
  return;
14697
15361
  }
14698
15362
  if (due) {
15363
+ const options = changed || unpublished ? void 0 : { background: true };
15364
+ const held = this.options.transport.publishHeld?.(this.keys.identity.pubKeyZ32, options);
15365
+ if (held) {
15366
+ this.schedule(budgetRetryMs(held, 1e3, 6e4));
15367
+ throw held;
15368
+ }
14699
15369
  const rev = changed ? this.state.rev + 1 : this.state.rev;
14700
15370
  const { records, dropped } = this.keys.seal(content, rev, peerKey, now);
14701
15371
  this.dropped = dropped;
14702
- await this.persist({
15372
+ if (!(rev === this.state.rev && digest === this.state.digest && peerKey === this.state.sealedFor && this.state.publishedAt === void 0)) await this.persist({
14703
15373
  rev,
14704
15374
  digest,
14705
15375
  sealedFor: peerKey,
14706
15376
  publishedAt: void 0
14707
15377
  });
14708
15378
  try {
14709
- await this.options.transport.publish(this.keys.identity, records, changed || unpublished ? void 0 : { background: true });
15379
+ await this.options.transport.publish(this.keys.identity, records, options);
14710
15380
  } catch (error) {
14711
15381
  this.schedule(isDiscoveryBudgetError(error) ? budgetRetryMs(error, 1e3, 6e4) : 6e4);
14712
15382
  throw error;
@@ -14994,14 +15664,15 @@ function parseDomainTxt(value) {
14994
15664
  var addRecord = (list, r) => {
14995
15665
  if (!list.some((x) => x.key === r.key && x.proof === r.proof)) list.push(r);
14996
15666
  };
14997
- /** All records among the TXT strings of `_ghostly.<domain>`; other strings are skipped. */
15667
+ /** All records among the first 32 TXT strings of `_ghostly.<domain>`; other strings are skipped. A TXT set has
15668
+ * no order, so every record is kept: the one a proof needs may come in any position. */
14998
15669
  function recordsFromTxt(values) {
14999
15670
  const out = [];
15000
15671
  for (const value of values.slice(0, 32)) {
15001
15672
  const r = parseDomainTxt(value);
15002
15673
  if (r) addRecord(out, r);
15003
15674
  }
15004
- return out.slice(0, 8);
15675
+ return out;
15005
15676
  }
15006
15677
  /** The body of `/.well-known/ghostly.json`. */
15007
15678
  function domainWellKnownFile(records) {
@@ -15018,7 +15689,7 @@ function parseJson(text) {
15018
15689
  if (typeof text !== "string" || utf8Encode(text).length > 16384) throw new Error("File too large");
15019
15690
  return JSON.parse(text);
15020
15691
  }
15021
- /** Records from `ghostly.json`. Throws on a malformed file; [] when it names none. */
15692
+ /** Records from the first 32 entries of `ghostly.json`. Throws on a malformed file; [] when it names none. */
15022
15693
  function recordsFromWellKnown(text) {
15023
15694
  const body = parseJson(text);
15024
15695
  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 +15702,7 @@ function recordsFromWellKnown(text) {
15031
15702
  };
15032
15703
  if (validDomainRecord(r)) addRecord(out, r);
15033
15704
  }
15034
- return out.slice(0, 8);
15705
+ return out;
15035
15706
  }
15036
15707
  /** NIP-05: only the root name `_` speaks for the domain itself. Undefined when absent. */
15037
15708
  function nip05RootKey(text) {
@@ -15214,9 +15885,13 @@ var SIG$3 = /^[A-Za-z0-9_-]{86}$/;
15214
15885
  var MAGIC$1 = utf8Encode("GHLD");
15215
15886
  var VERSION = 1;
15216
15887
  var NONCE$2 = 24;
15888
+ /** A bundle sealed by the chat's ratchet (WISP 4xx § Held items). */
15889
+ var RATCHETED = 2;
15217
15890
  /** Why a bundle, manifest or pointer was refused. Never a reason to trust it a little. */
15218
15891
  var HoldRefusedError = class extends Error {
15219
15892
  reason;
15893
+ /** The bytes the chat's ratchet opened, when it opened them before the item was refused: the caller commits them. */
15894
+ ratcheted;
15220
15895
  constructor(reason, message) {
15221
15896
  super(message);
15222
15897
  this.reason = reason;
@@ -15256,6 +15931,19 @@ var HoldKeys = class {
15256
15931
  }
15257
15932
  /** Seals one item for the contact: signed with my participation key, encrypted to our shared key. */
15258
15933
  seal(item, body) {
15934
+ const nonce = randomBytes(NONCE$2);
15935
+ const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(this.inner(item, body));
15936
+ return concatBytes$1(MAGIC$1, new Uint8Array([VERSION]), nonce, box);
15937
+ }
15938
+ /**
15939
+ * The same item as a version-2 bundle (WISP 4xx § Held items): the same plaintext, sealed by the chat's ratchet
15940
+ * (`seal`, which saves the ratchet's state before it returns), so the bundle can be uploaded once this returns.
15941
+ */
15942
+ async sealRatcheted(item, body, seal) {
15943
+ return concatBytes$1(MAGIC$1, new Uint8Array([RATCHETED]), await seal(this.inner(item, body)));
15944
+ }
15945
+ /** What a bundle seals: the header's length, the signed header, the body. */
15946
+ inner(item, body) {
15259
15947
  const fields = [
15260
15948
  VERSION,
15261
15949
  this.from,
@@ -15275,26 +15963,51 @@ var HoldKeys = class {
15275
15963
  const header = utf8Encode(JSON.stringify([fields, signature]));
15276
15964
  const length = /* @__PURE__ */ new Uint8Array(4);
15277
15965
  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);
15966
+ return concatBytes$1(length, header, body);
15281
15967
  }
15282
15968
  /**
15283
15969
  * Opens a bundle the contact sealed for me. Everything is checked before anything is returned: the
15284
15970
  * authenticated encryption, the header's shape, that it names this link, this contact and me, the
15285
15971
  * signature, the body digest and the limits of its kind. `loopback`: see `isHoldUrl`.
15286
15972
  */
15973
+ /**
15974
+ * `ratchet`: opens a version-2 bundle's sealed bytes (WISP 4xx), without keeping anything; absent, one is from a newer
15975
+ * Ghostly. `refusePlain`: a ratcheted item from this contact opened here, so a version-1 item other than the manifest is
15976
+ * refused (WISP 4xx § Downgrade). `ratcheted` in the result: the bytes the ratchet opened, for the caller to commit once
15977
+ * the item is stored.
15978
+ */
15287
15979
  open(bytes, expect = {}) {
15288
15980
  const now = expect.now ?? Date.now();
15289
15981
  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;
15982
+ 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");
15983
+ const version = bytes[MAGIC$1.length];
15984
+ if (version !== VERSION && (version !== RATCHETED || !expect.ratchet)) throw new HoldRefusedError("format", "Held item from a newer Ghostly");
15985
+ let plain, ratcheted;
15986
+ if (version === RATCHETED) {
15987
+ ratcheted = bytes.subarray(MAGIC$1.length + 1);
15988
+ try {
15989
+ plain = expect.ratchet(ratcheted);
15990
+ } catch {
15991
+ plain = null;
15992
+ }
15993
+ if (!plain) throw new HoldRefusedError("tampered", "The held item was changed, is not for this chat, or was opened already");
15994
+ } else {
15995
+ if (bytes.length < MAGIC$1.length + 1 + NONCE$2 + 16 + 4) throw new HoldRefusedError("format", "Not a held item");
15996
+ try {
15997
+ 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));
15998
+ } catch {
15999
+ throw new HoldRefusedError("tampered", "The held item was changed or is not for this chat");
16000
+ }
16001
+ }
15293
16002
  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");
16003
+ return this.read(plain, ratcheted, expect, now);
16004
+ } catch (error) {
16005
+ if (error instanceof HoldRefusedError && ratcheted) error.ratcheted = ratcheted;
16006
+ throw error;
15297
16007
  }
16008
+ }
16009
+ /** The checks of `open` once the bundle is decrypted. */
16010
+ read(plain, ratcheted, expect, now) {
15298
16011
  if (plain.length < 4) throw new HoldRefusedError("format", "Not a held item");
15299
16012
  const headerLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0);
15300
16013
  if (headerLength > 131072 || 4 + headerLength > plain.length) throw new HoldRefusedError("format", "Not a held item");
@@ -15336,10 +16049,12 @@ var HoldKeys = class {
15336
16049
  digest,
15337
16050
  expires
15338
16051
  };
16052
+ 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
16053
  checkKind(header, body, expect.loopback);
15340
16054
  return {
15341
16055
  header,
15342
- body
16056
+ body,
16057
+ ...ratcheted && { ratcheted }
15343
16058
  };
15344
16059
  }
15345
16060
  /** My pointer, as records to publish under `identity`. Throws when it cannot fit a packet. */
@@ -17490,8 +18205,20 @@ var FILE_LIMITS = {
17490
18205
  stallMs: 6e4,
17491
18206
  /** A receiver makes what it stored durable, and records the point to resume from, this often. */
17492
18207
  checkpointBytes: 8388608,
17493
- /** A receiver confirms at least this often while writing. */
18208
+ /**
18209
+ * A receiver confirms at least this often while writing, and the file's last bytes at once. Its writes are buffered
18210
+ * and done at once, so confirming whenever they were all done too was confirming nearly every chunk: 6,400 confirms for
18211
+ * 100 MiB, each a native call and a progress update on both sides. A host that batches them (`batchConfirms`) does not.
18212
+ */
17494
18213
  ackEveryBytes: 131072,
18214
+ /**
18215
+ * Batched (`ChatFilesHost.batchConfirms`), bytes stored and not confirmed are confirmed this long after the first of
18216
+ * them was stored, at most. What a sender has in flight may be no more than `ackEveryBytes` (a window at its floor, one
18217
+ * chunk while the path is measured), and bytes waiting here for a confirm are bytes it cannot send: on a slow or
18218
+ * wavering path a confirm comes about every this long, as fast as the window needs. A round trip it measures is up to
18219
+ * this much longer, well inside the queue it allows (`queueMs`).
18220
+ */
18221
+ ackWaitMs: 10,
17495
18222
  /** A sender reads its file this much at a time. */
17496
18223
  readBytes: 1048576,
17497
18224
  /** The session refused a data frame (its send budget was full): the sender looks again after this long. */
@@ -17525,6 +18252,15 @@ var FINAL = /* @__PURE__ */ new Set([
17525
18252
  ]);
17526
18253
  var transferEnded = (record) => FINAL.has(record.state);
17527
18254
  /**
18255
+ * Whether a file sent from here arrived whole (the receiver confirmed every byte, and may be checking it): too late
18256
+ * for its person to cancel. The receiver's check comes before a `pf-abort` behind it, so it would keep the file while
18257
+ * the sender said it was cancelled. Not once the receiver asks about it again (`asking`), nor paused here.
18258
+ */
18259
+ function sentWhole(record) {
18260
+ if (record.direction !== "out" || transferEnded(record)) return false;
18261
+ return record.state === "verifying" || record.file.size > 0 && record.confirmed === record.file.size && record.state !== "asking" && record.state !== "paused";
18262
+ }
18263
+ /**
17528
18264
  * Whether an unfinished transfer is stuck, so its person is offered to push it: "Send again" (sending) or "Ask again"
17529
18265
  * (receiving). `movedAt` is when its bytes last moved, `restored` that it has not moved since the app started. What
17530
18266
  * waits for a person (an answer, a pause) is not stuck, and a failed one has its own "Retry".
@@ -17812,6 +18548,13 @@ var ChatFiles = class {
17812
18548
  peerRoomValue = null;
17813
18549
  /** What the chat's files may have in flight, sized by the path. */
17814
18550
  pace = new FilePace();
18551
+ /**
18552
+ * What the chat's files had in flight just before the last confirm. A receiver confirms many chunks at once
18553
+ * (`ackEveryBytes`), and the chunks sent for them go with that much in flight, the window: counted one by one, the
18554
+ * first went with the window less a confirm, and read as a path carrying that little, it shrank the window and ended
18555
+ * every trial of a larger one (a fifth of the rate on a wavering path). Confirmed chunk by chunk, it is what each sends with.
18556
+ */
18557
+ refill = 0;
17815
18558
  constructor(host) {
17816
18559
  this.host = host;
17817
18560
  }
@@ -17896,6 +18639,7 @@ var ChatFiles = class {
17896
18639
  this.attached = true;
17897
18640
  this.peerRoomValue = null;
17898
18641
  this.pace.reset();
18642
+ this.refill = 0;
17899
18643
  this.host.uplink?.join(this);
17900
18644
  this.sayRoom();
17901
18645
  this.sweep();
@@ -17909,6 +18653,11 @@ var ChatFiles = class {
17909
18653
  id: entry.record.id,
17910
18654
  offset: entry.in.written
17911
18655
  });
18656
+ else if (entry.record.state === "asking") this.send({
18657
+ t: "pf-wait",
18658
+ id: entry.record.id,
18659
+ why: "consent"
18660
+ });
17912
18661
  }
17913
18662
  }
17914
18663
  /** The session went: nothing moves until the next one. What was received is made durable. */
@@ -17926,7 +18675,11 @@ var ChatFiles = class {
17926
18675
  clearTimeout(entry.out.wake);
17927
18676
  entry.out.next = entry.record.confirmed;
17928
18677
  }
17929
- if (entry.in) clearTimeout(entry.in.timer);
18678
+ if (entry.in) {
18679
+ clearTimeout(entry.in.timer);
18680
+ clearTimeout(entry.in.ackTimer);
18681
+ entry.in.ackTimer = void 0;
18682
+ }
17930
18683
  if (entry.in && !transferEnded(entry.record)) this.checkpoint(entry);
17931
18684
  }
17932
18685
  }
@@ -17946,10 +18699,13 @@ var ChatFiles = class {
17946
18699
  ].includes(record.state) || record.since + FILE_LIMITS.offerTtlMs > now) continue;
17947
18700
  if (record.direction === "in" && record.state === "queued" && (entry.in?.starting || this.moved(entry) > 0)) continue;
17948
18701
  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({
18702
+ this.send(record.direction === "in" ? {
17950
18703
  t: "pf-refuse",
17951
18704
  id: record.id,
17952
18705
  why: "expired"
18706
+ } : {
18707
+ t: "pf-abort",
18708
+ id: record.id
17953
18709
  });
17954
18710
  }
17955
18711
  }
@@ -18117,7 +18873,7 @@ var ChatFiles = class {
18117
18873
  out.sends.push({
18118
18874
  end: out.next,
18119
18875
  at: this.now(),
18120
- flight: this.inFlight(),
18876
+ flight: Math.max(this.inFlight(), Math.min(this.refill, this.pace.limit(this.floor()))),
18121
18877
  generation
18122
18878
  });
18123
18879
  }
@@ -18466,6 +19222,7 @@ var ChatFiles = class {
18466
19222
  /** An agreed file that ended here, offered again: taken again from the start. */
18467
19223
  async retake(entry) {
18468
19224
  await entry.in?.target?.then((t) => t.discard()).catch(() => {});
19225
+ clearTimeout(entry.in?.ackTimer);
18469
19226
  entry.in = {
18470
19227
  written: 0,
18471
19228
  stored: 0,
@@ -18518,15 +19275,8 @@ var ChatFiles = class {
18518
19275
  if (transferEnded(record) || incoming.dropped) return;
18519
19276
  await (await target).append(bytes);
18520
19277
  incoming.stored = offset + bytes.length;
18521
- if (incoming.stored === incoming.written || incoming.stored - incoming.acked >= FILE_LIMITS.ackEveryBytes) {
18522
- incoming.acked = incoming.stored;
18523
- this.send({
18524
- t: "pf-got",
18525
- id: record.id,
18526
- offset: incoming.stored
18527
- });
18528
- this.changed(entry, true);
18529
- }
19278
+ if (incoming.stored - incoming.acked >= FILE_LIMITS.ackEveryBytes || incoming.stored === record.file.size || !this.host.batchConfirms && incoming.stored === incoming.written) this.confirm(entry);
19279
+ else if (this.host.batchConfirms) incoming.ackTimer ??= setTimeout(() => this.confirm(entry), FILE_LIMITS.ackWaitMs);
18530
19280
  if (incoming.stored - incoming.checkpointed >= FILE_LIMITS.checkpointBytes) await this.checkpointNow(entry);
18531
19281
  }).catch((error) => {
18532
19282
  if (transferEnded(record)) return;
@@ -18540,6 +19290,20 @@ var ChatFiles = class {
18540
19290
  this.startNext();
18541
19291
  });
18542
19292
  }
19293
+ /** `pf-got` for what is stored and not confirmed yet. */
19294
+ confirm(entry) {
19295
+ const { record } = entry, incoming = entry.in;
19296
+ clearTimeout(incoming.ackTimer);
19297
+ incoming.ackTimer = void 0;
19298
+ if (transferEnded(record) || incoming.stored <= incoming.acked) return;
19299
+ incoming.acked = incoming.stored;
19300
+ this.send({
19301
+ t: "pf-got",
19302
+ id: record.id,
19303
+ offset: incoming.stored
19304
+ });
19305
+ this.changed(entry, true);
19306
+ }
18543
19307
  /** What was stored is durable, and a restart resumes from there. */
18544
19308
  async checkpoint(entry) {
18545
19309
  if (!entry.in?.target) return;
@@ -18687,7 +19451,8 @@ var ChatFiles = class {
18687
19451
  return;
18688
19452
  }
18689
19453
  if (!outgoing || transferEnded(outgoing.record)) {
18690
- if (outgoing?.record.state === "cancelled" && frame.t !== "pf-refuse") this.send({
19454
+ const asked = frame.t === "pf-accept" || frame.t === "pf-wait";
19455
+ if (outgoing?.record.state === "cancelled" ? frame.t !== "pf-refuse" : asked && outgoing?.record.state !== "done") this.send({
18691
19456
  t: "pf-abort",
18692
19457
  id
18693
19458
  });
@@ -18704,6 +19469,7 @@ var ChatFiles = class {
18704
19469
  out.generation++;
18705
19470
  record.confirmed = frame.offset;
18706
19471
  out.next = frame.offset;
19472
+ this.refill = 0;
18707
19473
  record.state = "active";
18708
19474
  record.pausedBy = record.waitingFor = void 0;
18709
19475
  this.changed(outgoing);
@@ -18731,6 +19497,7 @@ var ChatFiles = class {
18731
19497
  return;
18732
19498
  case "pf-got": {
18733
19499
  if (!isInt$1(frame.offset) || frame.offset <= record.confirmed || frame.offset > out.next) return;
19500
+ this.refill = this.inFlight();
18734
19501
  this.pace.delivered += frame.offset - record.confirmed;
18735
19502
  record.confirmed = frame.offset;
18736
19503
  let sample;
@@ -18775,6 +19542,8 @@ var ChatFiles = class {
18775
19542
  if (entry.in) {
18776
19543
  const incoming = entry.in;
18777
19544
  clearTimeout(incoming.timer);
19545
+ clearTimeout(incoming.ackTimer);
19546
+ incoming.ackTimer = void 0;
18778
19547
  incoming.writing.finally(() => {
18779
19548
  if (transferEnded(record)) incoming.target = void 0;
18780
19549
  });
@@ -19499,6 +20268,8 @@ var CarriedTransport = class {
19499
20268
  seen = -1n;
19500
20269
  /** A read under way: resolved when a carried packet comes meanwhile. */
19501
20270
  waiting = null;
20271
+ /** The records of a publish refused before they were signed, while nobody could carry them: signed when one can (`latest`). */
20272
+ unsigned = null;
19502
20273
  /** The packet the relays have not got yet. */
19503
20274
  pending = null;
19504
20275
  /** How many carried packets of the member's came: a deferral that ends with none more says no member reaches it. */
@@ -19531,6 +20302,7 @@ var CarriedTransport = class {
19531
20302
  async publish(identity, records, options) {
19532
20303
  if (this.stopped || identity.pubKeyZ32 !== this.myKey) return this.inner.publish(identity, records, options);
19533
20304
  this.drop();
20305
+ this.unsigned = null;
19534
20306
  if (this.hooks.open()) {
19535
20307
  const relayOptions = options?.signal ? options : {
19536
20308
  ...options,
@@ -19544,6 +20316,16 @@ var CarriedTransport = class {
19544
20316
  if (this.hooks.direct && this.inner.publishPayload) published.then(() => this.handDirect(payload), () => {});
19545
20317
  return published;
19546
20318
  }
20319
+ if (this.hooks.canCarry && !this.hooks.canCarry()) {
20320
+ const held = this.inner.publishHeld?.(identity.pubKeyZ32, options);
20321
+ if (held) {
20322
+ this.unsigned = {
20323
+ identity,
20324
+ records
20325
+ };
20326
+ throw held;
20327
+ }
20328
+ }
19547
20329
  const payload = this.newest = this.stamp(identity, records);
19548
20330
  this.mine = payload;
19549
20331
  let carried = {
@@ -19710,13 +20492,20 @@ var CarriedTransport = class {
19710
20492
  }
19711
20493
  /** My newest packet for this edge while it is down, for a member that can pass it on now; null once it is up. */
19712
20494
  latest() {
19713
- return this.stopped || this.hooks.open() ? null : this.mine;
20495
+ if (this.stopped || this.hooks.open()) return null;
20496
+ if (this.unsigned) {
20497
+ const { identity, records } = this.unsigned;
20498
+ this.unsigned = null;
20499
+ this.mine = this.newest = this.stamp(identity, records);
20500
+ }
20501
+ return this.mine;
19714
20502
  }
19715
20503
  /** The edge is going: nothing more is deferred or carried, and a last packet goes straight to the relays. */
19716
20504
  stop() {
19717
20505
  this.stopped = true;
19718
20506
  this.drop();
19719
20507
  this.mine = null;
20508
+ this.unsigned = null;
19720
20509
  const waiting = this.waiting;
19721
20510
  this.waiting = null;
19722
20511
  waiting?.();
@@ -20062,7 +20851,8 @@ var PairingTracker = class {
20062
20851
  * none of these (a mint's own words, a provider's) stays as it is.
20063
20852
  *
20064
20853
  * `{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).
20854
+ * an ecash unit ("usd"), an amount (digits, with the separators of whatever locale wrote it), or a server's own `{reason}`
20855
+ * (one line, last in its text).
20066
20856
  */
20067
20857
  var ENGINE_ERRORS = {
20068
20858
  mintUnreachable: "Could not reach {host}. Check the address: it should be a Cashu mint.",
@@ -20079,13 +20869,16 @@ var ENGINE_ERRORS = {
20079
20869
  mintNotHttps: "Mints must use https",
20080
20870
  notEnoughSats: "Not enough sats in your wallet",
20081
20871
  notEnoughForFee: "Not enough sats in your wallet: {amount} sats leave room for the fee",
20872
+ mintsNoAnyAmount: "None of your mints can pay an invoice with no amount",
20082
20873
  noSharedMint: "You share no mint with this contact",
20083
20874
  ecashAlreadySpent: "This ecash was already spent somewhere else",
20084
20875
  ecashBeingReceived: "This ecash is already being received",
20876
+ 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
20877
  ecashOtherUnit: "This ecash is in {unit}: only sat ecash can be redeemed here",
20086
20878
  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
20879
  reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.",
20088
20880
  lightningFeeTooHigh: "The Lightning fee ({fee} sats) is too high",
20881
+ lightningRefused: "The mint refused this Lightning payment, and no sats left your wallet: it is safe to try again. The mint said: {reason}",
20089
20882
  invoiceExpired: "That invoice has expired",
20090
20883
  lnurlExactly: "{domain} asks for exactly {amount} sats",
20091
20884
  lnurlRange: "{domain} takes between {min} and {max} sats",
@@ -20820,6 +21613,7 @@ var GhostLink = class {
20820
21613
  peerCapsRev: options.dht.peerCapsRev,
20821
21614
  peerAcceptsText: options.dht.peerAcceptsText,
20822
21615
  peerAcceptsFile: options.dht.peerAcceptsFile,
21616
+ ...options.dht.ratchet && { ratchet: options.dht.ratchet },
20823
21617
  ...options.reactionsSupport && {
20824
21618
  reactions: options.dht.reactions,
20825
21619
  reaction: async (reaction) => {
@@ -20909,6 +21703,7 @@ var GhostLink = class {
20909
21703
  pollIntervals: options.pollIntervals,
20910
21704
  awaitingSince: options.madeAt,
20911
21705
  ...backsOff && { invite: () => !options.pairing.credentials.peerKey || !!this.dht?.unanswered },
21706
+ ...invite && { ownInvite: () => !options.pairing.credentials.peerKey && !options.pairing.credentials.expectedPeerKey },
20912
21707
  getServices: options.getServices,
20913
21708
  firstPublish: options.firstPublish ?? (this.tracker && options.pairingProgress?.role === "joiner" && options.rtcAvailable !== false || this.resuming ? "after-first-poll" : "at-start"),
20914
21709
  resumed: !!this.resuming,
@@ -21921,6 +22716,9 @@ var GhostLink = class {
21921
22716
  this.advertiseTransports();
21922
22717
  this.options.events?.onTransportsChanged?.();
21923
22718
  };
22719
+ endpoint.onRelayBack = () => {
22720
+ if (this.endpoints.get(endpoint.transport) === endpoint) this.knockAgain(endpoint.transport);
22721
+ };
21924
22722
  this.advertiseTransports();
21925
22723
  if (this.resuming === endpoint.transport) this.knock(endpoint.transport);
21926
22724
  else this.joinRace(endpoint.transport);
@@ -22098,6 +22896,11 @@ var GhostLink = class {
22098
22896
  if (!this.transportOffer().includes(transport)) return;
22099
22897
  const epoch = this.connectionEpoch;
22100
22898
  this.dialing = true;
22899
+ const knocking = this.knocking = {
22900
+ transport,
22901
+ epoch,
22902
+ again: false
22903
+ };
22101
22904
  traceLink(this.myPubKeyZ32, "knock", { transport });
22102
22905
  try {
22103
22906
  const { channel, binding } = await endpoint.connect(descriptor);
@@ -22112,6 +22915,7 @@ var GhostLink = class {
22112
22915
  error: error instanceof Error ? error.message : String(error)
22113
22916
  });
22114
22917
  } finally {
22918
+ if (this.knocking === knocking) this.knocking = null;
22115
22919
  if (epoch === this.connectionEpoch) {
22116
22920
  this.dialing = false;
22117
22921
  this.settleCrossed();
@@ -22119,6 +22923,36 @@ var GhostLink = class {
22119
22923
  }
22120
22924
  if (!this.channel) this.maybeAutoConnect(this.presence);
22121
22925
  }
22926
+ /** The knock under way (`knock`): its transport, its attempt, and whether it was knocked again (`knockAgain`). */
22927
+ knocking = null;
22928
+ /**
22929
+ * The endpoint of a knock still under way is back on its relay (`NativeEndpoint.onRelayBack`): it is knocked again, once,
22930
+ * beside the first, and the first live wins. An Android phone back from Doze knocked at once through an Iroh whose relay
22931
+ * was gone; Iroh found it again only seconds later (its reconnect backoff, up to 16 s), and what the knock sent meanwhile
22932
+ * went nowhere: QUIC sends it again seconds on, and the dial is given 20 s. Live again 4.4 s and 9.8 s after the
22933
+ * return (away 5 and 15 minutes), and once not over Iroh at all (the emulator with a CLI bot, 2026-11-01).
22934
+ */
22935
+ async knockAgain(transport) {
22936
+ const knocking = this.knocking;
22937
+ if (!knocking || knocking.transport !== transport || knocking.again || knocking.epoch !== this.connectionEpoch) return;
22938
+ const endpoint = this.endpoints.get(transport), descriptor = this.peerDescriptors[transport];
22939
+ if (!endpoint || !descriptor || this.channel || this.stopped || this.streamBlocked || this.keyStopped) return;
22940
+ knocking.again = true;
22941
+ traceLink(this.myPubKeyZ32, "knock-again", { transport });
22942
+ try {
22943
+ const { channel, binding } = await endpoint.connect(descriptor);
22944
+ if (this.stopped || knocking.epoch !== this.connectionEpoch || this.channel) {
22945
+ channel.close();
22946
+ return;
22947
+ }
22948
+ this.attach(channel, binding);
22949
+ } catch (error) {
22950
+ traceLink(this.myPubKeyZ32, "knock-again-failed", {
22951
+ transport,
22952
+ error: error instanceof Error ? error.message : String(error)
22953
+ });
22954
+ }
22955
+ }
22122
22956
  canReleaseEndpoint(transport) {
22123
22957
  return this.activeBinding?.transport !== transport && this.candidate?.binding?.transport !== transport && !this.dialing && !this.switcher.pending && !this.transitionTarget;
22124
22958
  }
@@ -22754,6 +23588,10 @@ var GhostLink = class {
22754
23588
  get liveAttempt() {
22755
23589
  return this.isDataLinkOpen ? void 0 : this.lastAttempt;
22756
23590
  }
23591
+ /** Automatic dials since the link was last live or its wait started over (`wake`), the one under way included. */
23592
+ get dialAttempts() {
23593
+ return this.autoConnectFailures;
23594
+ }
22757
23595
  /**
22758
23596
  * Which side dials this chat to go live: the lower rendezvous key, or the joiner of a first pairing (WISP 100). The
22759
23597
  * other side answers, so what it can tell of a failed attempt is only what reached it.
@@ -24371,6 +25209,7 @@ var GhostLink = class {
24371
25209
  if (oldChannel) this.retire(oldChannel, () => {
24372
25210
  if (oldRtc && this.activeBinding && this.dataLink.connection === oldRtc) this.dataLink.close();
24373
25211
  }, !oldBinding);
25212
+ if (migration.plan && binding && oldBinding && WEBRTC_ATTEMPT.has(this.dataLink.state)) this.dataLink.close();
24374
25213
  this.session.setDataLinkOpen(true);
24375
25214
  if (migration.plan) switched = {
24376
25215
  from,
@@ -29606,16 +30445,10 @@ var GroupSession = class {
29606
30445
  /** Set while a save of what received messages changed is due (`persistSoon`). */
29607
30446
  saveTimer;
29608
30447
  /**
29609
- * The frames of members who left that each member was handed (`frameKey`), so an app that does not take them (from
29610
- * before revision 2026-10-13, and never marks them seen) is not handed them again at every sync. In memory only.
30448
+ * The removals of authors out of the roster that each member was handed (`editKey`), so an app that does not take
30449
+ * them is not handed them again at every sync. In memory only.
29611
30450
  */
29612
30451
  leaversHanded = /* @__PURE__ */ new Map();
29613
- /**
29614
- * The frames a commit took out of the logs (`pruneRelay`), newest last, and whether the app holds them with its
29615
- * messages: a removal's `left` mark can come after its commit, and what the leaver wrote is then kept again
29616
- * (`unprune`). In memory only: started again, the app's rows bring theirs back.
29617
- */
29618
- pruned = [];
29619
30452
  /** Syncs answered per member, a few a minute (`GROUP_LIMITS.syncAnswers`). In memory only. */
29620
30453
  syncsAnswered = /* @__PURE__ */ new Map();
29621
30454
  /**
@@ -29629,6 +30462,8 @@ var GroupSession = class {
29629
30462
  * message written just now. Each frame of the answer keeps it open: it goes a slice at a time. In memory only.
29630
30463
  */
29631
30464
  answering = /* @__PURE__ */ new Map();
30465
+ /** Per member ahead of me: the epoch its last sync said, up to which its answer to mine brings the chain. In memory only. */
30466
+ syncedEpoch = /* @__PURE__ */ new Map();
29632
30467
  /** Catch-up answers still going out, a slice at a time (`handOut`). */
29633
30468
  answers;
29634
30469
  /**
@@ -29651,20 +30486,20 @@ var GroupSession = class {
29651
30486
  if (onRows) {
29652
30487
  const held = new Set(onRows.map(frameKey$1));
29653
30488
  if (state.relay?.length) state.relay = state.relay.filter((f) => !held.has(frameKey$1(f)));
29654
- this.onRows = state.status === "active" ? onRows.filter((f) => this.handsOn(f.s, f.e)) : [];
30489
+ this.onRows = state.status === "active" ? onRows.filter((f) => this.handsOn(f.s)) : [];
29655
30490
  this.trimRelay();
29656
30491
  }
29657
30492
  this.answers = new CatchUpAnswers({
29658
30493
  send: (to, frame) => {
29659
- if ((frame.t === "group-msg" || frame.t === "group-edit") && !rosterHas(this.roster, frame.s)) {
30494
+ if (frame.t === "group-edit" && !rosterHas(this.roster, frame.s)) {
29660
30495
  const handed = this.leaversHanded.get(to) ?? /* @__PURE__ */ new Set();
29661
- this.leaversHanded.set(to, handed.add(frame.t === "group-edit" ? editKey(frame) : frameKey$1(frame)));
30496
+ this.leaversHanded.set(to, handed.add(editKey(frame)));
29662
30497
  }
29663
30498
  return hooks.send(to, frame);
29664
30499
  },
29665
30500
  ...hooks.handled && { handled: (to) => hooks.handled(to) },
29666
30501
  active: () => this.state.status === "active",
29667
- key: (frame) => frame.t === "group-msg" ? frameKey$1(frame) : void 0
30502
+ key: (frame) => frame.t === "group-msg" ? frameKey$1(frame) : frame.t === "group-commit" ? `commit:${frame.commit.e}` : void 0
29668
30503
  });
29669
30504
  this.provisional = new Set((state.provisional ?? []).slice(-GROUP_LIMITS.provisional));
29670
30505
  this.chainMovedAt = this.clock();
@@ -29953,8 +30788,9 @@ var GroupSession = class {
29953
30788
  return this.hooks.save(structuredClone(this.state));
29954
30789
  }
29955
30790
  /**
29956
- * A save within `GROUP_LIMITS.saveWithinMs`, for what a received message changes (what was seen, what is kept to hand
29957
- * on): the state holds the whole hand-on log, and a member back in a busy group wrote all of it once per message.
30791
+ * A save within `GROUP_LIMITS.saveWithinMs`, for what a received message, commit or secret changes (what was seen,
30792
+ * what is kept to hand on, the chain): the state holds the whole hand-on log and chain, and a member back in a busy
30793
+ * group wrote all of it once per message, and once per commit.
29958
30794
  * The message itself is stored before (`hooks.message`). An app killed before the save takes those frames again when
29959
30795
  * it syncs: its store has the messages already, and the state then catches up.
29960
30796
  */
@@ -30062,7 +30898,7 @@ var GroupSession = class {
30062
30898
  }
30063
30899
  transferAdmin(memberKey, now = Date.now()) {
30064
30900
  return this.serialize(async () => {
30065
- this.requireAdmin();
30901
+ this.requireAdmin("Only the admin can hand the admin role over");
30066
30902
  if (!rosterHas(this.roster, memberKey) || memberKey === this.myKey) throw new Error("Not a member");
30067
30903
  await this.commit("role", memberKey, now);
30068
30904
  });
@@ -30123,18 +30959,10 @@ var GroupSession = class {
30123
30959
  this.hooks.changed();
30124
30960
  return { secret };
30125
30961
  }
30126
- /**
30127
- * Someone removed is not handed on any more, whatever they sent while in the roster; one who left still is, for the
30128
- * epochs before its leave (WISP 902 § Catch-up).
30129
- */
30962
+ /** Someone removed or gone is not handed on any more, whatever they sent while in the roster (WISP 902 § Catch-up). */
30130
30963
  pruneRelay() {
30131
- const prune = (log, row) => log.filter((f) => this.handsOn(f.s, f.e) || (this.pruned.push({
30132
- frame: f,
30133
- row
30134
- }), false));
30135
- if (this.state.relay?.length) this.state.relay = prune(this.state.relay, false);
30136
- if (this.onRows?.length) this.onRows = prune(this.onRows, true);
30137
- this.pruned.splice(0, this.pruned.length - GROUP_LIMITS.relay);
30964
+ if (this.state.relay?.length) this.state.relay = this.state.relay.filter((f) => this.handsOn(f.s));
30965
+ if (this.onRows?.length) this.onRows = this.onRows.filter((f) => this.handsOn(f.s));
30138
30966
  if (this.state.relayEdits?.length) this.state.relayEdits = this.state.relayEdits.filter((f) => rosterHas(this.roster, f.s) || this.isRemovalEdit(f));
30139
30967
  }
30140
30968
  /** Whether a kept edit is a removal (WISP 400 § Delete for everyone): its box, under its epoch's key, says `rm`. */
@@ -30148,18 +30976,6 @@ var GroupSession = class {
30148
30976
  return false;
30149
30977
  }
30150
30978
  }
30151
- /** The frames `pruneRelay` dropped that are handed on again now (a removal's `left` mark came after it), back in their logs. */
30152
- unprune() {
30153
- const back = this.pruned.filter((p) => this.handsOn(p.frame.s, p.frame.e));
30154
- if (!back.length) return;
30155
- this.pruned = this.pruned.filter((p) => !back.includes(p));
30156
- for (const { frame, row } of back) {
30157
- const log = row && this.onRows ? this.onRows : this.state.relay ??= [];
30158
- const at = log.findIndex((f) => f.ts > frame.ts);
30159
- log.splice(at < 0 ? log.length : at, 0, frame);
30160
- }
30161
- this.trimRelay();
30162
- }
30163
30979
  /** Another member's edit, kept to hand on: the latest per message; the oldest go once the log is full. False: one as new was kept. */
30164
30980
  keepEdit(frame) {
30165
30981
  const same = (f) => f.s === frame.s && f.e === frame.e && f.n === frame.n;
@@ -30224,7 +31040,6 @@ var GroupSession = class {
30224
31040
  this.state.sent = [];
30225
31041
  this.state.relay = [];
30226
31042
  if (this.onRows) this.onRows = [];
30227
- this.pruned = [];
30228
31043
  this.state.relayEdits = [];
30229
31044
  this.state.alone = [];
30230
31045
  this.waiting = [];
@@ -30727,8 +31542,8 @@ var GroupSession = class {
30727
31542
  }
30728
31543
  /**
30729
31544
  * A message, from its author's edge or handed on by another member. Handed on, it is taken only while both are in
30730
- * the roster (someone removed is neither heard from nor handed on, #300), or from a member in it when its author left
30731
- * after it (`handsOn`), and its boxes only with the author's `xs`.
31545
+ * the roster (someone removed or gone is neither heard from nor handed on, #300, `handsOn`), and its boxes only with
31546
+ * the author's `xs`.
30732
31547
  */
30733
31548
  async receiveMessage(from, raw, waited = false) {
30734
31549
  if (!isMessageFrame$1(raw)) return;
@@ -30739,7 +31554,7 @@ var GroupSession = class {
30739
31554
  const relayed = raw.s !== from;
30740
31555
  const now = this.now(), answer = (this.answering.get(from) ?? 0) > now;
30741
31556
  if (answer) this.answering.set(from, now + ANSWER_WINDOW_MS);
30742
- if (relayed && (!rosterHas(this.roster, from) || !this.handsOn(raw.s, raw.e))) return;
31557
+ if (relayed && (!rosterHas(this.roster, from) || !this.handsOn(raw.s))) return;
30743
31558
  if (this.isDuplicate(raw)) return;
30744
31559
  const signedWhole = relayed && this.wholeSigned(raw);
30745
31560
  if (!signedWhole && !verify(fromBase64Url(raw.sig), messageSigned$1(raw), publicKeyFromZ32(raw.s))) return;
@@ -30790,7 +31605,7 @@ var GroupSession = class {
30790
31605
  this.markSeen(raw);
30791
31606
  this.keep(clean(raw));
30792
31607
  this.persistSoon();
30793
- if (this.handsOn(raw.s, raw.e)) this.took(clean(raw));
31608
+ if (this.handsOn(raw.s)) this.took(clean(raw));
30794
31609
  return;
30795
31610
  }
30796
31611
  const id = first && !this.provisional.has(own) ? groupMessageId(raw.s, first.e, first.n) : own;
@@ -30828,7 +31643,7 @@ var GroupSession = class {
30828
31643
  if (firstFrame && rosterHas(this.state.chain[firstFrame.e]?.m ?? [], this.myKey)) this.markSeen(firstFrame);
30829
31644
  this.keep(clean(raw));
30830
31645
  this.persistSoon();
30831
- if (this.handsOn(raw.s, raw.e)) this.took(clean(raw));
31646
+ if (this.handsOn(raw.s)) this.took(clean(raw));
30832
31647
  }
30833
31648
  /**
30834
31649
  * An edit of a member's own message, from its author's edge or handed on by another member: believed only while its
@@ -31008,6 +31823,14 @@ var GroupSession = class {
31008
31823
  this.asked.set(from, now);
31009
31824
  this.hooks.send(from, this.syncFrame([], from));
31010
31825
  }
31826
+ /**
31827
+ * Whether my sync to `from` (the one my edge opened with) still waits for its answer, which has the chain from the
31828
+ * epoch it said: asking again on reading its newer sync, or a commit of that answer, had each commit I missed sent
31829
+ * twice, each with a secret sealed again (200 missed went as 400 frames, 1,456 when answers go a slice at a time).
31830
+ */
31831
+ awaitsAnswer(from) {
31832
+ return (this.answering.get(from) ?? 0) > this.now();
31833
+ }
31011
31834
  async replayWaiting() {
31012
31835
  await this.metaFollowsChain();
31013
31836
  const ready = this.waiting.filter((w) => w.frame.e <= this.epoch && !!this.state.secrets[w.frame.e]);
@@ -31022,15 +31845,13 @@ var GroupSession = class {
31022
31845
  const raw = frame.commit;
31023
31846
  if (!raw || typeof raw !== "object" || !Number.isSafeInteger(raw.e)) return;
31024
31847
  const e = raw.e;
31848
+ if (this.awaitsAnswer(from)) this.answering.set(from, this.now() + ANSWER_WINDOW_MS);
31025
31849
  if (e <= this.epoch) {
31026
31850
  const known = this.state.chain[e];
31027
31851
  const result = verifyCommit(raw, this.state.chain[e - 1] ?? null, this.id);
31028
31852
  if ("error" in result || result.commit.by !== known.by || result.commit.by !== this.admin) return;
31029
31853
  if (commitHash(result.commit) !== commitHash(known)) await this.fork(`Member ${from.slice(0, 8)} holds a different membership history for epoch ${e}`);
31030
- else if (this.takeLeftMark(known, frame.left)) {
31031
- this.unprune();
31032
- await this.persist();
31033
- }
31854
+ else if (this.takeLeftMark(known, frame.left)) await this.persist();
31034
31855
  return;
31035
31856
  }
31036
31857
  if (e > this.epoch + 1) {
@@ -31052,7 +31873,7 @@ var GroupSession = class {
31052
31873
  commit: result.commit,
31053
31874
  ...mark ? { left: mark } : {}
31054
31875
  });
31055
- if (this.state.status === "active" && !this.state.secrets[this.epoch]) this.ask(from);
31876
+ if (this.state.status === "active" && !this.state.secrets[this.epoch] && !(this.awaitsAnswer(from) && this.epoch < (this.syncedEpoch.get(from) ?? 0))) this.ask(from);
31056
31877
  const next = this.pendingCommits.get(this.epoch + 1);
31057
31878
  if (next) {
31058
31879
  this.pendingCommits.delete(this.epoch + 1);
@@ -31060,21 +31881,12 @@ var GroupSession = class {
31060
31881
  }
31061
31882
  }
31062
31883
  /**
31063
- * Whether a frame of `author` under `epoch` is taken from another member, kept and handed on: while its author is in
31064
- * the roster, or when it left (its removal marked `left`, and it is not back in) and the frame is from before that,
31065
- * and from after any removal of it before that was not a leave: let back in, it is not handed on for those epochs.
31884
+ * Whether a frame of `author` is taken from another member, kept and handed on: only while its author is in the
31885
+ * roster. One who left, as one removed, keeps its seed and the secrets of its epochs, and a copy of its state signs
31886
+ * frames for them after the leave, dated as it likes: whether the admin marked its removal `left` changes nothing.
31066
31887
  */
31067
- handsOn(author, epoch) {
31068
- if (rosterHas(this.roster, author)) return true;
31069
- const chain = this.state.chain;
31070
- let left = false;
31071
- for (let e = chain.length - 1; e > 0; e--) {
31072
- if (chain[e].k !== "remove" || chain[e].s !== author) continue;
31073
- if (left && epoch >= e) return true;
31074
- if (!this.state.leftMarks?.[e] || epoch >= e) return false;
31075
- left = true;
31076
- }
31077
- return left;
31888
+ handsOn(author) {
31889
+ return rosterHas(this.roster, author);
31078
31890
  }
31079
31891
  /** Keeps the admin's mark on a commit that took out a member who left (`GroupCommitFrame.left`) when it holds; true when new. */
31080
31892
  takeLeftMark(commit, mark) {
@@ -31101,7 +31913,7 @@ var GroupSession = class {
31101
31913
  if (sealed) this.takeSecret(commit.e, sealed);
31102
31914
  this.pruneSecrets();
31103
31915
  this.pruneRelay();
31104
- await this.persist();
31916
+ this.persistSoon();
31105
31917
  this.hooks.changed();
31106
31918
  await this.replayWaiting();
31107
31919
  }
@@ -31123,7 +31935,7 @@ var GroupSession = class {
31123
31935
  taken = this.takeSecret(entry.e, entry.s) || taken;
31124
31936
  }
31125
31937
  if (!taken) return;
31126
- await this.persist();
31938
+ this.persistSoon();
31127
31939
  this.hooks.changed();
31128
31940
  await this.replayWaiting();
31129
31941
  }
@@ -31134,7 +31946,8 @@ var GroupSession = class {
31134
31946
  if (!answered.take()) return;
31135
31947
  this.hear(frame);
31136
31948
  if (frame.e > this.epoch) {
31137
- this.ask(from);
31949
+ this.syncedEpoch.set(from, frame.e);
31950
+ if (!this.awaitsAnswer(from)) this.ask(from);
31138
31951
  this.offerMeta(from, frame.mt);
31139
31952
  this.handOwn(from, frame);
31140
31953
  return;
@@ -31171,12 +31984,7 @@ var GroupSession = class {
31171
31984
  });
31172
31985
  const lacks = missingIn(frame, from);
31173
31986
  const asked = new Set(Array.isArray(frame.ask) ? frame.ask.filter((k) => typeof k === "string" && k !== from && k !== this.myKey && rosterHas(this.roster, k)) : []);
31174
- const handed = this.leaversHanded.get(from);
31175
- const kept = !asked.size && !this.state.leftMarks ? [] : this.kept().filter((f) => {
31176
- if (!this.state.chain[f.e] || !rosterHas(this.state.chain[f.e].m, from) || !lacks(f) || this.isRemoved(f)) return false;
31177
- if (asked.has(f.s)) return true;
31178
- return !rosterHas(this.roster, f.s) && !handed?.has(frameKey$1(f)) && this.handsOn(f.s, f.e);
31179
- });
31987
+ const kept = !asked.size ? [] : this.kept().filter((f) => asked.has(f.s) && !!this.state.chain[f.e] && rosterHas(this.state.chain[f.e].m, from) && lacks(f) && !this.isRemoved(f));
31180
31988
  const written = asWritten(this.ownLacked(from, frame), kept);
31181
31989
  const metas = this.metaFor(from, frame.mt);
31182
31990
  for (const f of written) {
@@ -31188,6 +31996,7 @@ var GroupSession = class {
31188
31996
  const edits = (this.state.relayEdits ?? []).filter((f) => f.s === author && readable(f));
31189
31997
  answer.push(...edits.slice(-GROUP_LIMITS.handOnEdits));
31190
31998
  }
31999
+ const handed = this.leaversHanded.get(from);
31191
32000
  const gone = (this.state.relayEdits ?? []).filter((f) => !rosterHas(this.roster, f.s) && readable(f) && !handed?.has(editKey(f)));
31192
32001
  answer.push(...gone.slice(-GROUP_LIMITS.handOnEdits));
31193
32002
  answer.push(...metas.map((m) => m.frame));
@@ -31865,6 +32674,29 @@ function verifyCommunityCommit(raw, parent, parentRoster, groupId, before) {
31865
32674
  * member's second leave under the one statement there was, and no newcomer could enter that group again.
31866
32675
  */
31867
32676
  function verifyCommunityChain(raw, groupId) {
32677
+ const check = checkChain(raw, groupId);
32678
+ for (;;) {
32679
+ const step = check.next();
32680
+ if (step.done) return step.value;
32681
+ }
32682
+ }
32683
+ /**
32684
+ * `verifyCommunityChain` for a client whose engine shares its page's thread: the same checks, letting the thread go every
32685
+ * `CHAIN_SLICE_MS` of them. One commit's signature takes ~2.6 ms in JavaScript on a desktop CPU, several times that on a
32686
+ * phone, so a history near `COMMUNITY_LIMITS.chain` checked at once was an app that drew nothing for 5 s and more.
32687
+ */
32688
+ async function verifyCommunityChainPaced(raw, groupId) {
32689
+ const check = checkChain(raw, groupId), pause = pacer(CHAIN_SLICE_MS);
32690
+ for (;;) {
32691
+ const step = check.next();
32692
+ if (step.done) return step.value;
32693
+ await pause();
32694
+ }
32695
+ }
32696
+ /** `verifyCommunityChainPaced` checks commits for this long at most before it lets the thread go. */
32697
+ var CHAIN_SLICE_MS = 5;
32698
+ /** The chain's checks, one commit per step. */
32699
+ function* checkChain(raw, groupId) {
31868
32700
  if (!Array.isArray(raw) || raw.length === 0 || raw.length > COMMUNITY_LIMITS.chain) return { error: "Malformed membership chain" };
31869
32701
  const chain = [], rosters = [];
31870
32702
  let entry = "";
@@ -31874,6 +32706,7 @@ function verifyCommunityChain(raw, groupId) {
31874
32706
  chain.push(result.commit);
31875
32707
  rosters.push(result.roster);
31876
32708
  if (result.commit.x !== void 0) entry = result.commit.x;
32709
+ yield;
31877
32710
  }
31878
32711
  return {
31879
32712
  chain,
@@ -32025,6 +32858,18 @@ function isSealed(v) {
32025
32858
  "c"
32026
32859
  ].every((k) => typeof v[k] === "string" && B64.test(v[k]) && v[k].length <= 128);
32027
32860
  }
32861
+ /** A welcome's shape and the whole chain it and the pieces before it carry, not yet checked (`CommunitySession.join`). */
32862
+ function readWelcome(link, pieces, welcome) {
32863
+ if (!welcome || typeof welcome !== "object") return { error: "Malformed welcome" };
32864
+ const w = welcome;
32865
+ if (w.t !== "group-welcome" || w.v !== 2 || w.g !== link.g || !Array.isArray(w.commits) || !Array.isArray(w.secrets) || !isSealed(w.rv) || !isSealed(w.entry)) return { error: "Malformed welcome" };
32866
+ const commits = [...pieces.flatMap((p) => p && typeof p === "object" && Array.isArray(p.commits) ? p.commits : []), ...w.commits];
32867
+ if (commits.length > COMMUNITY_LIMITS.chain) return { error: "Membership chain too long" };
32868
+ return {
32869
+ welcome: w,
32870
+ commits
32871
+ };
32872
+ }
32028
32873
  /** A pair payload's box: an ephemeral key, a nonce and a ciphertext of at most `appBytes` sealed. */
32029
32874
  var MAX_PAIR_BOX = Math.ceil((COMMUNITY_LIMITS.appBytes + 16) * 4 / 3) + 4;
32030
32875
  function isPairBox(v) {
@@ -32039,7 +32884,7 @@ function isMessageFrame(v) {
32039
32884
  * One member's view of a community group: the branch it follows and the ones it knows, the
32040
32885
  * secrets it holds, what it has seen, and the recent frames it keeps for others.
32041
32886
  */
32042
- var CommunitySession = class {
32887
+ var CommunitySession = class CommunitySession {
32043
32888
  hooks;
32044
32889
  state;
32045
32890
  identity;
@@ -32152,12 +32997,17 @@ var CommunitySession = class {
32152
32997
  * add was made by another member (the first one to answer me went away) is as good.
32153
32998
  */
32154
32999
  static join(link, pieces, welcome, seedB64, now = Date.now()) {
32155
- if (!welcome || typeof welcome !== "object") return { error: "Malformed welcome" };
32156
- const w = welcome;
32157
- if (w.t !== "group-welcome" || w.v !== 2 || w.g !== link.g || !Array.isArray(w.commits) || !Array.isArray(w.secrets) || !isSealed(w.rv) || !isSealed(w.entry)) return { error: "Malformed welcome" };
32158
- const commits = [...pieces.flatMap((p) => p && typeof p === "object" && Array.isArray(p.commits) ? p.commits : []), ...w.commits];
32159
- if (commits.length > COMMUNITY_LIMITS.chain) return { error: "Membership chain too long" };
32160
- const verified = verifyCommunityChain(commits, link.g);
33000
+ const read = readWelcome(link, pieces, welcome);
33001
+ if ("error" in read) return read;
33002
+ return CommunitySession.joinVerified(link, read.welcome, verifyCommunityChain(read.commits, link.g), seedB64, now);
33003
+ }
33004
+ /** `join`, its chain checked a slice at a time (`verifyCommunityChainPaced`): what an app sharing its page's thread calls. */
33005
+ static async joinPaced(link, pieces, welcome, seedB64, now = Date.now()) {
33006
+ const read = readWelcome(link, pieces, welcome);
33007
+ if ("error" in read) return read;
33008
+ return CommunitySession.joinVerified(link, read.welcome, await verifyCommunityChainPaced(read.commits, link.g), seedB64, now);
33009
+ }
33010
+ static joinVerified(link, w, verified, seedB64, now) {
32161
33011
  if ("error" in verified) return verified;
32162
33012
  const { chain, roster, entry } = verified;
32163
33013
  const me = identityFromSeedB64(seedB64);
@@ -32265,6 +33115,18 @@ var CommunitySession = class {
32265
33115
  get entryKey() {
32266
33116
  return this.state.entry.key;
32267
33117
  }
33118
+ /**
33119
+ * The entry key of the link my admission that lost was let in by (the one its branch named), where I ask again: a
33120
+ * link replaced since keeps me out as it does anyone. `entryKey` once that admission is no longer held.
33121
+ */
33122
+ get lostEntryKey() {
33123
+ const side = this.state.side;
33124
+ for (let i = side.length - 1; i >= 0; i--) if (side[i].k === "add" && side[i].s === this.myKey) {
33125
+ for (const c of this.ancestry(side[i].p)) if (c.x !== void 0) return c.x;
33126
+ return "";
33127
+ }
33128
+ return this.entryKey;
33129
+ }
32268
33130
  role(key) {
32269
33131
  return this.roster.find(([k]) => k === key)?.[1];
32270
33132
  }
@@ -32272,10 +33134,62 @@ var CommunitySession = class {
32272
33134
  get picture() {
32273
33135
  return groupMetaPicture(this.state.meta);
32274
33136
  }
32275
- /** Members of any epoch in the window: whom a frame may come from. */
33137
+ /**
33138
+ * Members of any epoch in the window: whom a frame may come from. A side commit's roster counts only while its branch
33139
+ * could still win (`mayWin`): one let in only on a branch that lost is not in the roster anyone sees, and the main
33140
+ * branch past where they part, a later link among it, is not its business (`lostAt`).
33141
+ */
32276
33142
  isRecentMember(key) {
32277
- for (const roster of this.rosters.values()) if (rosterHas(roster, key)) return true;
32278
- return false;
33143
+ let side = false;
33144
+ for (const [h, roster] of this.rosters) if (rosterHas(roster, key)) {
33145
+ if (this.mainIndex.has(h)) return true;
33146
+ side = true;
33147
+ }
33148
+ return side && [...this.mayWin()].some((h) => rosterHas(this.rosters.get(h) ?? [], key));
33149
+ }
33150
+ /**
33151
+ * The side commits whose branch could still win: it does not drop an admin change the main branch holds (one that
33152
+ * does never wins, see `better`), and it parts within the window. Kept until the tip or the side moves.
33153
+ */
33154
+ mayWin() {
33155
+ const side = this.state.side, at = `${this.topHash}:${side.length}:${side.length ? communityCommitHash(side[side.length - 1]) : ""}`;
33156
+ if (this.winning?.at === at) return this.winning.set;
33157
+ const counts = this.adminCounts(), main = this.branch(this.topHash), set = /* @__PURE__ */ new Set();
33158
+ for (const c of side) {
33159
+ const h = communityCommitHash(c), branch = this.rosters.has(h) ? this.branch(h) : null;
33160
+ if (!branch || !branch.path.length) continue;
33161
+ const { parent, admin } = this.parting(branch, main, counts);
33162
+ if (!(admin[1] && !admin[0]) && parent >= this.epoch - COMMUNITY_LIMITS.window) set.add(h);
33163
+ }
33164
+ this.winning = {
33165
+ at,
33166
+ set
33167
+ };
33168
+ return set;
33169
+ }
33170
+ winning;
33171
+ /**
33172
+ * 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
33173
+ * the commit that makes it lose (the latest over its branches). Undefined for anyone else.
33174
+ */
33175
+ lostAt(key) {
33176
+ const side = this.state.side, parents = new Set(side.map((c) => c.p)), counts = this.adminCounts();
33177
+ let lost;
33178
+ for (const c of side) {
33179
+ const h = communityCommitHash(c);
33180
+ if (parents.has(h)) continue;
33181
+ const branch = this.branch(h);
33182
+ if (!branch || !branch.path.some((x) => rosterHas(this.rosters.get(x) ?? [], key))) continue;
33183
+ for (let j = branch.fork + 1; j < this.state.chain.length; j++) {
33184
+ if (this.better(branch, this.branch(communityCommitHash(this.state.chain[j])), counts)) continue;
33185
+ lost = {
33186
+ fork: Math.min(lost?.fork ?? j, branch.fork),
33187
+ end: Math.max(lost?.end ?? j, j)
33188
+ };
33189
+ break;
33190
+ }
33191
+ }
33192
+ return lost;
32279
33193
  }
32280
33194
  /**
32281
33195
  * Whether `key` could read message `messageId` (`<s>:<e>:<h>:<n>`) and still can: a member of the roster it was sealed
@@ -33574,6 +34488,7 @@ var CommunitySession = class {
33574
34488
  case "group-left": return this.receiveLeft(frame);
33575
34489
  case "group-entry": {
33576
34490
  if (frame.to !== this.myKey || !isSealed(frame.s) || frame.x !== this.currentEntryKey()) return false;
34491
+ if (this.state.entry.key === frame.x && this.state.entry.seedB64) return false;
33577
34492
  const seed = openSecret(this.identity.seed, this.myKey, frame.s, entryAad(this.id, this.myKey));
33578
34493
  return !!seed && this.takeEntrySeed(toBase64Url(seed));
33579
34494
  }
@@ -33825,10 +34740,23 @@ var CommunitySession = class {
33825
34740
  for (const { from, frame } of ready) await this.receiveMessage(from, frame);
33826
34741
  }
33827
34742
  async receiveSync(from, frame) {
33828
- if (!this.isRecentMember(from) || !isZ32Key(from) || !Number.isSafeInteger(frame.e) || typeof frame.h !== "string") return;
34743
+ if (!isZ32Key(from) || !Number.isSafeInteger(frame.e) || typeof frame.h !== "string") return;
34744
+ const recent = this.isRecentMember(from), lost = recent ? void 0 : this.lostAt(from);
34745
+ if (!recent && !lost) return;
33829
34746
  let answered = this.syncsAnswered.get(from);
33830
34747
  if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(COMMUNITY_LIMITS.syncAnswers, COMMUNITY_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
33831
34748
  if (!answered.take()) return;
34749
+ if (lost) {
34750
+ const at = this.mainIndex.get(frame.h);
34751
+ const commits = this.state.chain.slice(at !== void 0 ? at + 1 : lost.fork + 1, lost.end + 1);
34752
+ if (commits.length) this.answers.handOut(from, commits.map((commit) => ({
34753
+ t: "group-commit",
34754
+ v: 2,
34755
+ g: this.id,
34756
+ commit
34757
+ })));
34758
+ return;
34759
+ }
33832
34760
  const answer = [];
33833
34761
  const ask = () => {
33834
34762
  const sync = this.question(from);
@@ -34793,6 +35721,6 @@ function readX401SdJwtVc(text) {
34793
35721
  };
34794
35722
  }
34795
35723
  //#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 };
35724
+ export { SshSigError as $, ROUTINE_STATES as $a, checkAppRevokeStatement as $c, validExternalKey as $i, turnStatedVerifier as $l, readGroupHave as $n, extractParamsFromSdp as $o, wakeRequest as $r, verifySetUpdate as $s, SEPOLIA_TEST_USDT as $t, knockIdentity as A, parseLinkPreview as Aa, mergeContactKnocks as Ac, recordsFromWellKnown as Ai, deviceEchoFrame as Al, fedimintRequestPayload as An, ratchetSessionOf as Ao, FILE_LIMITS as Ar, handoffManifestFrames as As, didSignedMessages as At, isZ32Key as Au, GROUP_REACTED_FRAME as B, reactionIsNewer as Ba, appDigest as Bc, IDENTITY_REVOCATION_LABEL as Bi, TURN_SETTLE_MS as Bl, pairedMessageFrame as Bn, formatLocalTarget as Bo, GROUP_PIN_FRAME as Br, readHandoffDone as Bs, signingKeys as Bt, communityHasFrame as C, EDIT_RATE_WINDOW_MS as Ca, REQUEST_LIFETIME_MS as Cc, domainTxtRecord as Ci, encodeInviteCode as Cl, homeserverWebEndpoint as Cn, rosterAdmin as Co, pickHubs as Cr, handoffCancelFrame as Cs, DID_FILE_MAX_BYTES as Ct, publicKeyFromZ32 as Cu, decodeGroupEntryLink as D, dhtEditId as Da, knockSlotRecords as Dc, nip05RootKey as Di, DEVICES_CAPABILITY as Dl, decodeBolt11 as Dn, RATCHET_CAPABILITY as Do, readLobby as Dr, handoffDigest as Ds, checkDidSignature as Dt, sanitizeDisplayText as Du, KNOCK_TTL_MS as E, RateWindow as Ea, knockSlotOf as Ec, isPublicAddress as Ei, ownInviteRefusal as El, resolveLightningDestination as En, edgeParams as Eo, readBeaconHead as Er, handoffDataFrame as Es, checkDidJws as Et, sanitizeAvatar as Eu, GroupWakeLimiter as F, REACTION_LIMITS as Fa, seenEntry as Fc, DHT_TEXT_CAPABILITY as Fi, newDeviceSetSecret as Fl, GhostLink as Fn, PRESENCE_WINDOW as Fo, TYPING_KINDS as Fr, handoffStreamKey as Fs, didWebHost as Ft, utf8Encode as Fu, GROUP_EDIT_FRAME as G, readReply as Ga, pacer as Gc, identityRevocationValue as Gi, firstDeviceSetSecret as Gl, GROUP_FILE_LIMITS as Gn, encodeControl as Go, pinNumberHolds as Gr, readHandoffVerified as Gs, encodeDidDhtDeactivated as Gt, GroupSession as H, validReactionNumber as Ha, assembleAppBundle as Hc, IdentityExchange as Hi, turnPutSummary as Hl, engineError as Hn, webLocalFetch as Ho, mayPin as Hr, readHandoffHello as Hs, strictBase64Url as Ht, groupWakeFrame as I, ReactionWindow as Ia, APP_BUNDLE_LIMITS as Ic, capsDescriptors as Ii, seedSigner as Il, INVITE_TAKEN as In, RELAY_POLL_INTERVALS as Io, TYPING_REFRESH_MS as Ir, handoffVersions as Is, normalizeDid as It, parseCommunityEdit as J, BUTTON_STYLES as Ja, sha256Paced as Jc, receivedIdentityStatus as Ji, signTurnPacket as Jl, GROUP_WANT_NO_FRAME as Jn, answersOffer as Jo, WakeLimiter as Jr, SET_UPDATE as Js, signDidDhtPacket as Jt, GROUP_EDIT_TEXT_BYTES as K, replySnippet as Ka, readAppBundle as Kc, identityStatement as Ki, nextTurnPosition as Kl, GROUP_HAVE_FRAME as Kn, CALL_SIGNAL_MAX_AGE_MS as Ko, readPin as Kr, sealHandoffPiece as Ks, encodeDidDhtPacket as Kt, groupWakes as L, nextReactionNumber as La, APP_BUNDLE_MAGIC as Lc, dialDescriptors as Li, webCryptoSigner as Ll, LIVENESS_PING_MS as Ln, WATCH_PEER_MS as Lo, TypingSender as Lr, newHandoffId as Ls, parseDid as Lt, mergeKnocks as M, readForwarded as Ma, readKnockSlot as Mc, txtValue as Mi, deviceKeyZ32 as Ml, isFederationId as Mn, AWAITING_PEER_MS as Mo, sentWhole as Mr, handoffPakeFrame as Ms, didWebFile as Mt, toBase64Url as Mu, readKnocks as N, COMMUNITY_REACTION_FRAME as Na, readLinkRecord as Nc, wellKnownUrl as Ni, deviceLinkPairing as Nl, parseCashuRequestPayload as Nn, DHT_POLL_INTERVALS as No, transferEnded as Nr, handoffReleaseFrame as Ns, didWebFileNames as Nt, toZ32 as Nu, encodeGroupEntryLink as O, LINK_TRAILING as Oa, linkRecords as Oc, normalizeDomain as Oi, ENROLL_CAPABILITY as Ol, ENDPOINT as On, RatchetBox as Oo, shouldBeHub as Or, handoffEphemeral as Os, didGhostlyServiceEntry as Ot, bytesEqual as Ou, GROUP_WAKE_FRAME as P, GROUP_REACTION_FRAME as Pa, requestRecords as Pc, CapsExchange as Pi, devicePingFrame as Pl, parseFedimintRequestPayload as Pn, EXPECT_PEER_MS as Po, transferStalled as Pr, handoffRetryAfter as Ps, didWebFileUrl as Pt, utf8Decode as Pu, SSHSIG_NAMESPACE as Q, PR_STATES as Qa, appRef as Qc, emptyProofLedger as Qi, turnName as Ql, readGroupFileMeta as Qn, contactRtcConfig as Qo, relayRequest as Qr, signTombstone as Qs, PaymentPreflightError as Qt, parseGroupWakeFrame as R, queueReaction as Ra, APP_ICON_PATH as Rc, IDENTITY_MAX_EVIDENCE as Ri, TURN_PUT_WINDOW_MS as Rl, PAIRED_FRAME_TOO_LARGE as Rn, presenceSeenAt as Ro, sanitizeTypingStatus as Rr, readHandoffAck as Rs, parseDidDocument as Rt, GROUP_READ_NOTE_COMMUNITY as S, EDIT_BUFFER_MS as Sa, ContactRequestError as Sc, dnsProofName as Si, decodeInviteCode as Sl, pubkyProofPath as Sn, parseGroupCommit as So, newerHead as Sr, handoffBusyFrame as Ss, DID_DOCUMENT_MAX_BYTES as St, identityFromSeedB64 as Su, encodeCommunityLink as T, REMOVED_TEXT as Ta, knockSlotIdentity as Tc, encodeDnsQuery as Ti, inviteOwnership as Tl, requestLnurlInvoice as Tn, verifyCommitSignature as To, readBeacon as Tr, handoffContextProof as Ts, DidError as Tt, MAX_AVATAR_LENGTH as Tu, frameBytes as U, wireReaction as Ua, checkAppManifest as Uc, boundVerifiedIdentity as Ui, TURN_LAST_SEQUENCE as Ul, engineText as Un, LIMITS as Uo, nextPinNumber as Ur, readHandoffPake as Us, didDhtDocument as Ut, GROUP_READ_NOTE as V, readReaction as Va, appViewOf as Vc, IdentityCheckUnavailable as Vi, classifyTurnRead as Vl, EngineError as Vn, parseLocalTarget as Vo, PIN_LIMITS as Vr, readHandoffHave as Vs, staticDidDocument as Vt, COMMUNITY_EDIT_FRAME as W, pairedReplyAuthor as Wa, isAppUrl as Wc, emptyIdentityLedger as Wi, TURN_MAX as Wl, parseEngineError as Wn, decodeControl as Wo, pinIsNewer as Wr, readHandoffTurnFrame as Ws, didDhtFromPublicKey as Wt, groupName as X, ITEM_STATES as Xa, APP_STATEMENT_LIMITS as Xc, lastSharedWithMe as Xi, turnInstance as Xl, groupFileFallback as Xn, callRtcConfig as Xo, newWakeToken as Xr, setAckFrame as Xs, EVM_TEST_CHAINS as Xt, mentionsMember as Y, CRON_LINE as Ya, APP_PREFIXES as Yc, revokesIdentity as Yi, signTurnRelease as Yl, fetchesByItself as Yn, buildSdpFromSignal as Yo, deviceWakeRequest as Yr, readSetUpdate as Ys, ETHEREUM_USDT as Yt, SSHSIG_MAX_ARMOR as Z, PR_CHECKS as Za, appFingerprint as Zc, PeerProofs as Zi, turnKeys as Zl, isGroupMessageId as Zn, callSignalHeardAt as Zo, parseWakeFrame as Zr, setUpdateFrame as Zs, ONCHAIN_PROVIDER as Zt, groupTypingEpoch as _, fileMessageText as _a, newInbox as _c, isHoldUrl as _i, createDeviceInvite as _l, isPubkyProofFolder as _n, GROUP_ADMIN_OFF_ERROR as _o, freshHubs as _r, NO_ATTEMPTS as _s, normalizeAtprotoHandle as _t, newerPacket as _u, appRevocationFor as a, DHT_MESSAGE_TTL as aa, enrollCancelReason as ac, chatAppId as ai, setAppSignatureFastPath as al, assertTokenUnits as an, buttonLabelClash as ao, SIGNAL_HOLD_MS as ar, serviceIdFromName as as, verifyBitcoinMessage as at, RelaysFailedError as au, COMMUNITY_LIMITS as b, voiceLevel as ba, takeRequest as bc, DOMAIN_FILE_MAX_BYTES as bi, OwnInviteError as bl, pubkyProofCapability as bn, MEMBER_KEY as bo, mergeBeacon as br, handoffAttemptFailed as bs, AtprotoProofError as bt, createIdentity as bu, checkAppBeforeRun as c, dhtFileId as ca, enrollGrantFrame as cc, BUTTONS_CAPABILITY as ci, exifOrientation as cl, validatePaymentTarget as cn, checkStatusCard as co, readGroupSignal as cr, HANDOFF_DONE as cs, ATPROTO_DECLARED_SCOPE as ct, normalizeRelayUrl as cu, checkAppStoreIndex as d, sanitizeMime as da, readEnrollGrant as dc, UPGRADE_CAPABILITY as di, canonicalJson as dl, SPARK_PROVIDER as dn, statusCardText as do, meshHubs as dr, HANDOFF_OFFER as ds, ATPROTO_PROOF_SCOPE as dt, budgetRetryMs as du, TRANSPORTS as ea, ENROLL_DONE as ec, checkPushEndpoint as ei, isAppHash as el, SEPOLIA_TEST_USDT_FAUCET as en, RUN_RESULTS as eo, readGroupWant as er, parseCallSignal as es, parseSshPublicKey as et, turnVerifierMark as eu, readAppStore as f, PLAYABLE_AUDIO as fa, readEnrollHello as fc, HOLD_CAPABILITY as fi, canonicalJsonBytes as fl, sparkAddressKind as fn, arrivalKey as fo, pickMeshHubs as fr, HANDOFF_PAKE as fs, atprotoDidMethod as ft, isDiscoveryBudgetError as fu, GroupTypingBoard as g, downsamplePeaks as ga, inboxRecord as gc, HoldRefusedError as gi, readContactLink as gl, isPubkyKey as gn, shownTime as go, doorHubs as gr, HANDOFF_VERIFIED as gs, isAtprotoDid as gt, createRelayPayload as gu, GROUP_TYPING_FRAME as h, baseMime as ha, endedRequests as hc, HoldKeys as hi, encodeContactLink as hl, PUBKY_PROOF_MAX_BYTES as hn, receivedTimestamp as ho, beaconRecords as hr, HANDOFF_TIMINGS as hs, checkAtprotoProofRecord as ht, RELAY_PAYLOAD_MAX_BYTES as hu, addedAppPermissions as i, DHT_FILE_TOO_LARGE as ia, enrollCancelFrame as ic, APP_DATA_MAX_BYTES as ii, readAppRevocations as il, arkAddressPrefix as in, appCardUrl as io, SIGNAL_FRESH_MS as ir, LEGACY_SERVICES as is, verifySshSignature as it, RelayTransport as iu, knockRecords as j, forwardedAgain as ja, openRequest as jc, recordsName as ji, deviceEchoNonce as jl, findEndpoint as jn, DirectPathWatch as jo, FileUplink as jr, handoffOfferFrame as js, didWebDocumentUrl as jt, randomBytes as ju, entryParams as k, linkStop as ka, makeStampPaced as kc, recordsFromTxt as ki, HANDOFF_CAPABILITY as kl, cashuRequestPayload as kn, emptyRatchetState as ko, ChatFiles as kr, handoffHelloFrame as ks, didJwsAlg as kt, fromBase64Url as ku, planAppUpdate as l, formatFileSize as la, enrollHelloFrame as lc, EDIT_CAPABILITY as li, parseImageMeta as ll, walletNetworkOf as ln, sameButtonText as lo, MESH_HUBS as lr, HANDOFF_HAVE as ls, ATPROTO_FULL_SCOPE as lt, setLinkTraceSink as lu, signAppStore as m, VOICE_METER as ma, clearMissed as mc, HOLD_LIMITS as mi, createContactLink as ml, isBitcoinAddress as mn, heardTime as mo, beaconKeys as mr, HANDOFF_REQUEST as ms, atprotoProofRkey as mt, PacketTooLargeError as mu, readX401SdJwtVc as n, irohDescriptor as na, ENROLL_HELLO as nc, APP_RANGE_LIMITS as ni, isAppRef as nl, USDT_PUBLIC_RPC as nn, TASK_STATUSES as no, CarriedTransport as nr, emptyLinkRecords as ns, sameSshKey as nt, HEDGE_MISSING_MS as nu, appStoreDecision as o, peekDhtMailbox as oa, enrollDigits as oc, isAppVersion as oi, signAppObject as ol, assertWholeSats as on, cardLine as oo, SIGNAL_REPLY_MS as or, HANDOFF_ACK as os, BitcoinAddressError as ot, SLOW_MS as ou, readAppStoreSteps as p, VOICE_LIMITS as pa, verifyEnrollProof as pc, HOLD_DATED_BACK_MS as pi, readCanonicalJson as pl, sparkInvoiceDetails as pn, claimedTime as po, COMMUNITY_TOPOLOGY as pr, HANDOFF_PIECE_BYTES as ps, atprotoProofRecord as pt, withRequestOptions as pu, carryMentions as q, BUTTON_ID as qa, readAppBundleAsync as qc, newIdentityBinding as qi, readTurnPacket as ql, GROUP_WANT_FRAME as qn, RTC_CONFIG as qo, WAKE_CALL_INTERVAL_MS as qr, SET_ACK as qs, resolveDidDht as qt, sameX401HolderJwk as r, irohRelayUrl as ra, ENROLL_PROOF as rc, isServeId as ri, readAppRevocation as rl, WALLET_NETWORKS as rn, appCardId as ro, GROUP_SIGNAL_FRAME as rr, HTTP_SERVICE_PROTO as rs, sshSignCommand as rt, HEDGE_MS as ru, appUpdateDecision as s, DHT_FILE_CAPABILITY as sa, enrollDoneFrame as sc, APPS_CAPABILITY as si, signAppRevocation as sl, formatPaymentAmount as sn, cardUrl as so, groupSignalFrame as sr, HANDOFF_CANCEL as ss, decodeAnyBitcoinAddress as st, currentRelays as su, newX401HolderKey as t, automaticTransport as ta, ENROLL_GRANT as tc, vapidKeysMatch as ti, isAppKey as tl, TEST_USDT_FAUCET_AMOUNT as tn, STATUS_CARD_LIMITS as to, readGroupWantNo as tr, signalHasVideo as ts, parseSshSignature as tt, DEFAULT_RELAYS as tu, APP_STORE_LIMITS as u, sanitizeFileName as ua, enrollProofFrame as uc, STATUS_CARD_CAPABILITY as ui, readImageMeta as ul, SPARK_NETWORKS as un, statusCardBytes as uo, mayBeHub as ur, HANDOFF_HELLO as us, ATPROTO_PROOF_COLLECTION as ut, traceLink as uu, openGroupTyping as v, parseVoiceMeta as va, planKnocks as vc, newMailbox as vi, deviceInviteJoinerParams as vl, newPubkyProofFolder as vn, GROUP_MEMBER_CAP as vo, lobbyKeys as vr, filePartName as vs, parseAtprotoDidDocument as vt, openRelayPayload as vu, decodeCommunityLink as w, MAX_REMOVAL_NUMBER as wa, contactDay as wc, domainWellKnownFile as wi, inviteLink as wl, pubkyHomeserverOf as wn, rosterHas as wo, rankHubs as wr, handoffContext as ws, DID_JWS_MAX_LENGTH as wt, verify as wu, CommunitySession as x, parseVideoMeta as xa, turnOff as xc, decodeDnsResponse as xi, createChatInvite as xl, pubkyProofFile as xn, commitHash as xo, mergeLobby as xr, handoffAttemptSucceeded as xs, verifyAtprotoRecordProof as xt, identityFromSeed as xu, sealGroupTyping as y, voiceDownloadName as ya, settleRequest as yc, readManifest as yi, readDeviceInvite as yl, normalizePubkyKey as yn, MAX_GROUP_CHAIN as yo, lobbyRecords as yr, handoffAttemptAllowed as ys, shortAtprotoDid as yt, parseRelayPayload as yu, GROUP_LIMITS as z, reactionEmoji as za, APP_PERMISSIONS as zc, IDENTITY_MAX_VALIDITY as zi, TURN_RAISE_READ_TIMEOUT_MS as zl, pairedMessageFits as zn, GhostlyHttpError as zo, typingActivity as zr, readHandoffCancel as zs, parseDidSignaturePaste as zt };
34797
35725
 
34798
- //# sourceMappingURL=src-BB5-5P3s.js.map
35726
+ //# sourceMappingURL=src-C4sOH4zH.js.map