@ghostlytools/cli 1.7.3 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +30 -19
  2. package/SKILL.md +6 -4
  3. package/dist/assets/{api-B42F9ytB.js → api-Dj1yn0px.js} +2 -2
  4. package/dist/assets/{api-tf-wAAnB.js → api-I_KbuXHa.js} +192 -88
  5. package/dist/assets/api-I_KbuXHa.js.map +1 -0
  6. package/dist/assets/{apiKit-DJb9hulp.js → apiKit-C-_PWZvy.js} +44 -9
  7. package/dist/assets/apiKit-C-_PWZvy.js.map +1 -0
  8. package/dist/assets/{apps-DIrWmLgL.js → apps-DKIe8VjF.js} +11 -8
  9. package/dist/assets/apps-DKIe8VjF.js.map +1 -0
  10. package/dist/assets/{apps-BfoDISRg.js → apps-DbEfL_3b.js} +1 -1
  11. package/dist/assets/{arkade-CJAhhgPQ.js → arkade-k1bdSm70.js} +2 -2
  12. package/dist/assets/{arkade-CJAhhgPQ.js.map → arkade-k1bdSm70.js.map} +1 -1
  13. package/dist/assets/{backup-BkUeeduy.js → backup-Cdd6-HNu.js} +1 -1
  14. package/dist/assets/{backup-Bko-AAm0.js → backup-beKfbfNk.js} +7 -7
  15. package/dist/assets/{backup-Bko-AAm0.js.map → backup-beKfbfNk.js.map} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{blobFiles-Bckz9fjp.js → blobFiles-DOQDRdDI.js} +3 -3
  19. package/dist/assets/{blobFiles-Bckz9fjp.js.map → blobFiles-DOQDRdDI.js.map} +1 -1
  20. package/dist/assets/buttons-BO1_7V4L.js +2 -0
  21. package/dist/assets/{buttons-DeA6Yddq.js → buttons-ClI13rdv.js} +7 -6
  22. package/dist/assets/buttons-ClI13rdv.js.map +1 -0
  23. package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-DtrL5lE5.js} +2 -2
  24. package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-DtrL5lE5.js.map} +1 -1
  25. package/dist/assets/{envelope-Cz5fc7BM.js → envelope-B88yiCQj.js} +2 -2
  26. package/dist/assets/{envelope-Cz5fc7BM.js.map → envelope-B88yiCQj.js.map} +1 -1
  27. package/dist/assets/{errors-mnjSQlbX.js → errors-R4S2SAEM.js} +8 -3
  28. package/dist/assets/errors-R4S2SAEM.js.map +1 -0
  29. package/dist/assets/{fileBytes-OolN5cSY.js → fileBytes-BPDKufla.js} +1 -1
  30. package/dist/assets/{fileBytes-BD0v3rRG.js → fileBytes-DNgrRL0R.js} +3 -3
  31. package/dist/assets/{fileBytes-BD0v3rRG.js.map → fileBytes-DNgrRL0R.js.map} +1 -1
  32. package/dist/assets/{fileBytes-_fd-2JRY.js → fileBytes-Q3ehcEr8.js} +2 -2
  33. package/dist/assets/{fileBytes-_fd-2JRY.js.map → fileBytes-Q3ehcEr8.js.map} +1 -1
  34. package/dist/assets/fileBytesIdb-DZcESfTt.js +2 -0
  35. package/dist/assets/{fileBytesIdb-NtA8r9EM.js → fileBytesIdb-Dm1EyEbT.js} +3 -3
  36. package/dist/assets/{fileBytesIdb-NtA8r9EM.js.map → fileBytesIdb-Dm1EyEbT.js.map} +1 -1
  37. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js → fileBytesOpfs-ZGD21c4Q.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-B8fJwkwM.js.map → fileBytesOpfs-ZGD21c4Q.js.map} +1 -1
  39. package/dist/assets/{groupFiles-BlZRBWpt.js → groupFiles-DjQc5XXv.js} +151 -28
  40. package/dist/assets/groupFiles-DjQc5XXv.js.map +1 -0
  41. package/dist/assets/{host-BX0DmKW6.js → host-CNWGB3-j.js} +86 -24
  42. package/dist/assets/host-CNWGB3-j.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-DitYDnXx.js → hyperdhtRelay-g7eXzf5h.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-DitYDnXx.js.map → hyperdhtRelay-g7eXzf5h.js.map} +1 -1
  45. package/dist/assets/{idb-BlH8-O3R.js → idb-BkOJES5_.js} +5 -3
  46. package/dist/assets/idb-BkOJES5_.js.map +1 -0
  47. package/dist/assets/{irohWeb-R3bcd34h.js → irohWeb-Bx8dI4be.js} +2 -2
  48. package/dist/assets/{irohWeb-R3bcd34h.js.map → irohWeb-Bx8dI4be.js.map} +1 -1
  49. package/dist/assets/{main-6QOSvQ8b.js → main-BRxhBctJ.js} +462 -126
  50. package/dist/assets/main-BRxhBctJ.js.map +1 -0
  51. package/dist/assets/{mainline-BfwezHWi.js → mainline-CwuS6ngj.js} +39 -12
  52. package/dist/assets/mainline-CwuS6ngj.js.map +1 -0
  53. package/dist/assets/mints-BaOmx517.js +2 -0
  54. package/dist/assets/{mints-BrlY773j.js → mints-j5XAOk4f.js} +15 -3
  55. package/dist/assets/mints-j5XAOk4f.js.map +1 -0
  56. package/dist/assets/{networkReason-Ba9415nn.js → networkReason-CIAMieQm.js} +3 -3
  57. package/dist/assets/{networkReason-Ba9415nn.js.map → networkReason-CIAMieQm.js.map} +1 -1
  58. package/dist/assets/{nwc-ovXSN2M2.js → nwc-C9JLJJkL.js} +3 -3
  59. package/dist/assets/{nwc-ovXSN2M2.js.map → nwc-C9JLJJkL.js.map} +1 -1
  60. package/dist/assets/{nwcProvider-BzZbfFP3.js → nwcProvider-pFMrsUJh.js} +2 -2
  61. package/dist/assets/{nwcProvider-BzZbfFP3.js.map → nwcProvider-pFMrsUJh.js.map} +1 -1
  62. package/dist/assets/{profiles-C6XWqre5.js → profiles-MFtCmJwK.js} +104 -10
  63. package/dist/assets/profiles-MFtCmJwK.js.map +1 -0
  64. package/dist/assets/{registry-B0Uv9yL6.js → registry-Cks7FA_o.js} +45 -14
  65. package/dist/assets/registry-Cks7FA_o.js.map +1 -0
  66. package/dist/assets/{registry-CFtlhWCI.js → registry-DY2ixQfU.js} +1 -1
  67. package/dist/assets/{resolve-BzFG4WDU.js → resolve-C4Y2HPqQ.js} +79 -30
  68. package/dist/assets/resolve-C4Y2HPqQ.js.map +1 -0
  69. package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-BCRCjhdF.js} +27 -3
  70. package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-BCRCjhdF.js.map} +1 -1
  71. package/dist/assets/{server-BGCuHbmQ.js → server-D9RAmGdm.js} +1398 -358
  72. package/dist/assets/server-D9RAmGdm.js.map +1 -0
  73. package/dist/assets/{src-DWw2hUE5.js → src-1RU4TilT.js} +1416 -234
  74. package/dist/assets/src-1RU4TilT.js.map +1 -0
  75. package/dist/assets/{translate-DObb-1tq.js → translate-od5GbpvR.js} +19 -13
  76. package/dist/assets/translate-od5GbpvR.js.map +1 -0
  77. package/dist/assets/{usdt-Bkva90Vo.js → usdt-DldXV0MR.js} +3 -3
  78. package/dist/assets/{usdt-Bkva90Vo.js.map → usdt-DldXV0MR.js.map} +1 -1
  79. package/dist/assets/waitNotice-Ck3el3_Z.js +45 -0
  80. package/dist/assets/waitNotice-Ck3el3_Z.js.map +1 -0
  81. package/dist/assets/{words-odSAoasK.js → words-BS2qq_vV.js} +7 -4
  82. package/dist/assets/words-BS2qq_vV.js.map +1 -0
  83. package/dist/ghostly.mjs +1 -1
  84. package/examples/claude-code-agent.sh +1 -1
  85. package/package.json +1 -1
  86. package/dist/assets/api-tf-wAAnB.js.map +0 -1
  87. package/dist/assets/apiKit-DJb9hulp.js.map +0 -1
  88. package/dist/assets/apps-DIrWmLgL.js.map +0 -1
  89. package/dist/assets/buttons-Be7u0V5g.js +0 -2
  90. package/dist/assets/buttons-DeA6Yddq.js.map +0 -1
  91. package/dist/assets/errors-mnjSQlbX.js.map +0 -1
  92. package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
  93. package/dist/assets/groupFiles-BlZRBWpt.js.map +0 -1
  94. package/dist/assets/host-BX0DmKW6.js.map +0 -1
  95. package/dist/assets/idb-BlH8-O3R.js.map +0 -1
  96. package/dist/assets/main-6QOSvQ8b.js.map +0 -1
  97. package/dist/assets/mainline-BfwezHWi.js.map +0 -1
  98. package/dist/assets/mints-BrlY773j.js.map +0 -1
  99. package/dist/assets/mints-CqTdA4Gk.js +0 -2
  100. package/dist/assets/profiles-C6XWqre5.js.map +0 -1
  101. package/dist/assets/registry-B0Uv9yL6.js.map +0 -1
  102. package/dist/assets/resolve-BzFG4WDU.js.map +0 -1
  103. package/dist/assets/server-BGCuHbmQ.js.map +0 -1
  104. package/dist/assets/src-DWw2hUE5.js.map +0 -1
  105. package/dist/assets/translate-DObb-1tq.js.map +0 -1
  106. package/dist/assets/words-odSAoasK.js.map +0 -1
@@ -905,6 +905,64 @@ var firstWriter = (who) => !who.write || who.background ? null : who.group ? "gr
905
905
  /** A key's turn neither asked nor read in the last minute: it is dropped, and asking again starts a new one (`TURNS_PRUNE_MS`). */
906
906
  var staleTurn = (turn, now) => now - Math.max(turn.askedAt, turn.servedAt) >= 6e4;
907
907
  /**
908
+ * Keys and when each was last set, those of the last minute: how many and the latest, without walking them all (the
909
+ * chats that need a relay, `chatNeeds`). Each is set at the time it is set, so the sets come oldest first; a clock
910
+ * gone back makes the later ones as of now.
911
+ */
912
+ var RecentKeys = class {
913
+ at = /* @__PURE__ */ new Map();
914
+ /** Every set, oldest first, from `head`; one a later set or a delete replaced is skipped. */
915
+ order = [];
916
+ head = 0;
917
+ set(key, now) {
918
+ this.prune(now);
919
+ this.at.set(key, now);
920
+ this.order.push([key, now]);
921
+ }
922
+ delete(key) {
923
+ this.at.delete(key);
924
+ }
925
+ size(now) {
926
+ this.prune(now);
927
+ return this.at.size;
928
+ }
929
+ /** When the key set last was, -Infinity with none in the last minute. */
930
+ latest(now) {
931
+ this.prune(now);
932
+ while (this.order.length > this.head) {
933
+ const [key, at] = this.order[this.order.length - 1];
934
+ if (this.at.get(key) === at) return at;
935
+ this.order.pop();
936
+ }
937
+ return -Infinity;
938
+ }
939
+ /** The keys set in the last minute, oldest first. */
940
+ *entries(now) {
941
+ this.prune(now);
942
+ for (let i = this.head; i < this.order.length; i++) if (this.at.get(this.order[i][0]) === this.order[i][1]) yield this.order[i];
943
+ }
944
+ /** Drops the keys set a minute ago or more. */
945
+ prune(now) {
946
+ if (this.order.length > this.head && now < this.order[this.order.length - 1][1]) {
947
+ for (const [key, at] of this.at) this.at.set(key, Math.min(at, now));
948
+ this.order = [...this.at].sort((a, b) => a[1] - b[1]);
949
+ this.head = 0;
950
+ }
951
+ while (this.head < this.order.length) {
952
+ const [key, at] = this.order[this.head];
953
+ if (this.at.get(key) === at) {
954
+ if (now - at < 6e4) break;
955
+ this.at.delete(key);
956
+ }
957
+ this.head++;
958
+ }
959
+ if (this.head > 64 && this.head * 2 > this.order.length) {
960
+ this.order = this.order.slice(this.head);
961
+ this.head = 0;
962
+ }
963
+ }
964
+ };
965
+ /**
908
966
  * Public Pkarr relays. They are generic Pkarr infrastructure (an HTTP bridge to
909
967
  * the Mainline DHT), not a Ghostly backend: they only ever see signed,
910
968
  * encrypted packets. Every client uses this list: the browser clients read and
@@ -928,6 +986,14 @@ function currentRelays(relays) {
928
986
  return PREVIOUS_DEFAULT_RELAYS.some((old) => same(old, relays)) ? [...DEFAULT_RELAYS] : relays;
929
987
  }
930
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
+ /**
931
997
  * A link's write the budget refused (its presence, its offer, its answer) goes first when the minute
932
998
  * frees a request: reads on that relay wait this long after the refusal. A link that polls fast for a
933
999
  * peer while its offer waits would otherwise take every request the minute frees, and the offer (the
@@ -1194,6 +1260,8 @@ var RelayTransport = class {
1194
1260
  lastReadFrom = /* @__PURE__ */ new Map();
1195
1261
  spent = /* @__PURE__ */ new Map();
1196
1262
  spentBackground = /* @__PURE__ */ new Map();
1263
+ /** Background writes on each relay in the last minute (`BACKGROUND_WRITES_SHARE`). */
1264
+ spentBackgroundWrites = /* @__PURE__ */ new Map();
1197
1265
  /** Groups' urgent reads on each relay in the last `GROUP_BURST_MS`. */
1198
1266
  spentGroupUrgent = /* @__PURE__ */ new Map();
1199
1267
  /** Watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`WATCH_SHARE`). */
@@ -1227,9 +1295,11 @@ var RelayTransport = class {
1227
1295
  /**
1228
1296
  * Per key a 1:1 chat asks for: when it last read urgently (for the next minute, groups leave it `CHAT_RESERVE` on
1229
1297
  * every relay) and when the budget last refused it on each relay (the same, on that relay). A read of the key at a
1230
- * slow pace (the chat is live, or back in the background) drops it: `CHAT_RESERVE`.
1298
+ * slow pace (the chat is live, or back in the background) drops it: `CHAT_RESERVE`. Per relay, the later of the two
1299
+ * for each key (`chatNeed`); `chatUrgentAt` keeps the urgent ones for a relay not asked yet.
1231
1300
  */
1232
1301
  chatNeeds = /* @__PURE__ */ new Map();
1302
+ chatUrgentAt = new RecentKeys();
1233
1303
  /** When a link (a chat's or a group's) last asked urgently: background requests yield for `SIGNALING_WINDOW_MS`. */
1234
1304
  urgentAt = -Infinity;
1235
1305
  /** Timestamp of the last packet sent to each relay, per key: the compare-and-swap value for the next one. */
@@ -1270,16 +1340,16 @@ var RelayTransport = class {
1270
1340
  this.perMinuteGiven = options.requestsPerMinute !== void 0;
1271
1341
  this.backgroundPerMinute = this.perMinute === 30 ? 20 : Math.ceil(this.perMinute * 2 / 3);
1272
1342
  this.backgroundWhileSignaling = this.perMinute === 30 ? 5 : Math.ceil(this.perMinute / 6);
1273
- const log = options.log ?? ((line) => console.info(`[ghostly:relay] ${line}`));
1343
+ const log = options.log ?? ((line) => console.info(`ghostly: ${line}`));
1274
1344
  this.breaker = new RelayBreaker({
1275
1345
  ...options.breaker,
1276
1346
  onTrip: (relay, reason, forMs) => {
1277
- 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`);
1278
1348
  options.breaker?.onTrip?.(relay, reason, forMs);
1279
1349
  this.changed("tripped");
1280
1350
  },
1281
1351
  onRecover: (relay) => {
1282
- log(`${new URL(relay).host} answered again`);
1352
+ log(`relay ${new URL(relay).host} answers again`);
1283
1353
  options.breaker?.onRecover?.(relay);
1284
1354
  this.changed("recovered");
1285
1355
  }
@@ -1636,7 +1706,7 @@ var RelayTransport = class {
1636
1706
  */
1637
1707
  async resolve(pubKeyZ32, options = {}, keptOnFailure = true) {
1638
1708
  if (this.relays.length === 0) throw new Error("No Pkarr relays configured");
1639
- if (options.background && !options.urgent && !options.group) this.chatNeeds.delete(pubKeyZ32);
1709
+ if (options.background && !options.urgent && !options.group) this.chatNeedLapsed(pubKeyZ32);
1640
1710
  const readAt = this.readAt.get(pubKeyZ32);
1641
1711
  if (readAt !== void 0 && Date.now() - readAt < this.freshReadMs) return this.newest.get(pubKeyZ32) ?? null;
1642
1712
  const order = this.readOrder(pubKeyZ32);
@@ -1963,13 +2033,13 @@ var RelayTransport = class {
1963
2033
  let response;
1964
2034
  try {
1965
2035
  response = await request;
1966
- } catch (error) {
2036
+ } catch {
1967
2037
  this.networkCooldown.set(`PUT ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
1968
2038
  this.answered(relay, {
1969
2039
  kind: "error",
1970
2040
  reason: "no answer"
1971
2041
  });
1972
- throw error;
2042
+ throw new Error(`${relay} did not answer`);
1973
2043
  }
1974
2044
  if (response.status === 429) this.answered(relay, {
1975
2045
  kind: "throttled",
@@ -1992,13 +2062,13 @@ var RelayTransport = class {
1992
2062
  const writer = firstWriter(who);
1993
2063
  if (who.urgent && !who.background) {
1994
2064
  this.urgentAt = now;
1995
- if (isChat(who)) this.chatNeed(key).urgentAt = now;
2065
+ if (isChat(who)) this.chatNeed(key, now);
1996
2066
  }
1997
2067
  if (isGroupRead(who) || isChatWatch(who)) this.readAsked(key, who, now);
1998
2068
  if (isTurnRead(who)) this.turnAsked(key, who, now);
1999
2069
  if (this.heldFor(relay, who, now, key) > 0) {
2000
2070
  if (isGroupRead(who) && (this.spent.get(relay)?.length ?? 0) >= this.limitOf(relay)) this.groupsFullAt.set(relay, now);
2001
- if (isChat(who)) this.chatNeed(key).refused.set(relay, now);
2071
+ if (isChat(who)) this.chatNeed(key, now, relay);
2002
2072
  if (writer) this.writeWaiting.set(`${writer} ${relay}`, now);
2003
2073
  return false;
2004
2074
  }
@@ -2023,6 +2093,7 @@ var RelayTransport = class {
2023
2093
  if (departedOver) this.departedOverAdd(key, now);
2024
2094
  this.spent.get(relay).push(now);
2025
2095
  if (who.background) this.spentBackground.get(relay).push(now);
2096
+ if (who.background && who.write) this.spentBackgroundWrites.get(relay).push(now);
2026
2097
  if (isGroupUrgentRead(who)) this.spentGroupUrgent.get(relay).push(now);
2027
2098
  if (isWatch(who)) this.spentWatch.get(relay).push(now);
2028
2099
  if (isChatWatch(who) && !departedOver) this.spentChatWatch.get(relay).push(now);
@@ -2056,6 +2127,8 @@ var RelayTransport = class {
2056
2127
  const recentBackground = (this.spentBackground.get(relay) ?? []).filter((at) => now - at < 6e4);
2057
2128
  this.spent.set(relay, recent);
2058
2129
  this.spentBackground.set(relay, recentBackground);
2130
+ const recentBackgroundWrites = (this.spentBackgroundWrites.get(relay) ?? []).filter((at) => now - at < 6e4);
2131
+ this.spentBackgroundWrites.set(relay, recentBackgroundWrites);
2059
2132
  const over = (list, limit) => list.length >= limit ? list[list.length - limit] + 6e4 - now : 0;
2060
2133
  const limit = this.limitOf(relay);
2061
2134
  const departed = isDepartedRead(who) && key !== void 0 && recent.length >= limit && this.departedReads(key, now) < 6;
@@ -2070,7 +2143,9 @@ var RelayTransport = class {
2070
2143
  this.spentGroupOver.set(relay, groupOver);
2071
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);
2072
2145
  if (who.background && !starved) {
2073
- 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))));
2074
2149
  const signaling = this.urgentAt + SIGNALING_WINDOW_MS - now;
2075
2150
  if (signaling > 0 && !who.door) wait = Math.max(wait, Math.min(signaling, over(recentBackground, Math.min(this.backgroundWhileSignaling, Math.ceil(limit / 6)))));
2076
2151
  }
@@ -2203,25 +2278,36 @@ var RelayTransport = class {
2203
2278
  for (const [other, reads] of this.departedOver) if (now - reads[reads.length - 1] >= 6e4) this.departedOver.delete(other);
2204
2279
  this.departedOver.set(key, [...this.departedOver.get(key) ?? [], now]);
2205
2280
  }
2206
- chatNeed(key) {
2207
- let need = this.chatNeeds.get(key);
2208
- if (!need) this.chatNeeds.set(key, need = {
2209
- urgentAt: -Infinity,
2210
- refused: /* @__PURE__ */ new Map()
2211
- });
2212
- return need;
2281
+ /** A chat's request of `key` asked urgently (it needs every relay), or the budget refused it on `relay` (it needs that one). */
2282
+ chatNeed(key, now, relay) {
2283
+ if (relay !== void 0) {
2284
+ this.chatNeedsOn(relay, now).set(key, now);
2285
+ return;
2286
+ }
2287
+ this.chatUrgentAt.set(key, now);
2288
+ for (const needs of this.chatNeeds.values()) needs.set(key, now);
2213
2289
  }
2214
- /** How long groups still leave a chat its reserve on this relay (`CHAT_RESERVE`); a chat's need a minute old goes. */
2215
- chatReservedFor(relay, now) {
2216
- let until = -Infinity;
2217
- for (const [key, need] of this.chatNeeds) {
2218
- if (now - Math.max(need.urgentAt, ...need.refused.values()) >= 6e4) {
2219
- this.chatNeeds.delete(key);
2220
- continue;
2221
- }
2222
- until = Math.max(until, need.urgentAt, need.refused.get(relay) ?? -Infinity);
2290
+ /** The chats that need this relay: those a request of was refused there, and the urgent ones. */
2291
+ chatNeedsOn(relay, now) {
2292
+ let needs = this.chatNeeds.get(relay);
2293
+ if (!needs) {
2294
+ this.chatNeeds.set(relay, needs = new RecentKeys());
2295
+ for (const [key, at] of this.chatUrgentAt.entries(now)) needs.set(key, at);
2223
2296
  }
2224
- return until + 6e4 - now;
2297
+ return needs;
2298
+ }
2299
+ /** The chat reading `key` has nothing due: it needs no relay any more. */
2300
+ chatNeedLapsed(key) {
2301
+ this.chatUrgentAt.delete(key);
2302
+ for (const needs of this.chatNeeds.values()) needs.delete(key);
2303
+ }
2304
+ /**
2305
+ * How long groups still leave a chat its reserve on this relay (`CHAT_RESERVE`); a chat's need a minute old goes.
2306
+ * Kept up to date as needs come and go (`RecentKeys`): walking them all for each request cost a daemon with 500
2307
+ * contacts away 2.7 s of CPU per 10 idle minutes (bug hunt, 2026-11-01).
2308
+ */
2309
+ chatReservedFor(relay, now) {
2310
+ return this.chatNeedsOn(relay, now).latest(now) + 6e4 - now;
2225
2311
  }
2226
2312
  /**
2227
2313
  * How long a chat's packet another relay already took waits for this one: while chats need the relays, a copy takes
@@ -2242,8 +2328,7 @@ var RelayTransport = class {
2242
2328
  }
2243
2329
  /** What the chats that need the relays keep on this relay (`CHAT_RESERVE_PER_CHAT`), never less than `reserveOf`. */
2244
2330
  chatReserveOf(relay, now) {
2245
- let needing = 0;
2246
- for (const need of this.chatNeeds.values()) if (now - Math.max(need.urgentAt, need.refused.get(relay) ?? -Infinity) < 6e4) needing++;
2331
+ const needing = this.chatNeedsOn(relay, now).size(now);
2247
2332
  return Math.max(this.reserveOf(relay), Math.min(needing * 3, Math.floor(this.limitOf(relay) * CHAT_RESERVE_MOST_SHARE)));
2248
2333
  }
2249
2334
  /** What groups leave a chat on this relay: `CHAT_RESERVE`, or a third of a smaller budget. */
@@ -2573,13 +2658,13 @@ function turnName(name) {
2573
2658
  }
2574
2659
  return hasVisible(out) ? out.trimEnd() : "";
2575
2660
  }
2576
- function u32$3(value) {
2661
+ function u32$4(value) {
2577
2662
  return Uint8Array.of(value >>> 24 & 255, value >>> 16 & 255, value >>> 8 & 255, value & 255);
2578
2663
  }
2579
2664
  /** What a release signs: `"ghostly-turn-release" || turnAddress(32) || turn(4) || toKey(32) || H(32)`. */
2580
2665
  function turnReleaseMessage(address, turn, toKey, h) {
2581
2666
  if (address.length !== 32 || toKey.length !== 32 || h.length !== 32) throw new Error("A release names 32-byte values");
2582
- return concatBytes$1(RELEASE_DOMAIN, address, u32$3(turn), toKey, h);
2667
+ return concatBytes$1(RELEASE_DOMAIN, address, u32$4(turn), toKey, h);
2583
2668
  }
2584
2669
  /** What the author signs: `"ghostly-turn" || turnAddress(32) || body[0..310]`. */
2585
2670
  function turnSignedMessage(address, unsigned) {
@@ -2597,8 +2682,8 @@ function encodeTurnFields(fields) {
2597
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");
2598
2683
  const body = /* @__PURE__ */ new Uint8Array(310);
2599
2684
  body[OFFSET.version] = 1;
2600
- body.set(u32$3(fields.turn), OFFSET.turn);
2601
- 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);
2602
2687
  body[OFFSET.author] = fields.author;
2603
2688
  body[OFFSET.active] = fields.active;
2604
2689
  body[OFFSET.count] = fields.slots.filter(Boolean).length;
@@ -2850,7 +2935,7 @@ var TURN_PUT_WINDOW_MS = 1e4;
2850
2935
  var TURN_RAISE_READ_TIMEOUT_MS = 5e3;
2851
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`. */
2852
2937
  var TURN_SETTLE_MS = 3e4;
2853
- function compareBytes$3(a, b) {
2938
+ function compareBytes$4(a, b) {
2854
2939
  for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return a[i] - b[i];
2855
2940
  return a.length - b.length;
2856
2941
  }
@@ -2861,7 +2946,7 @@ function compareBytes$3(a, b) {
2861
2946
  * reader still agrees.
2862
2947
  */
2863
2948
  function keptAtEqualSequence(a, b) {
2864
- 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);
2865
2950
  }
2866
2951
  var kept = (f) => ({
2867
2952
  record: f.read.record,
@@ -3899,14 +3984,38 @@ function webpSize(b) {
3899
3984
  if (ascii(b, 12, "VP8X")) return sized(u24le(b, 24) + 1, u24le(b, 27) + 1);
3900
3985
  }
3901
3986
  /**
3987
+ * A GIF's size as it is decoded: its logical screen, or as far as its first frame reaches past it (a browser decodes
3988
+ * the first frame whole, at its own size, however small the screen says it is). Undefined when its first frame is not
3989
+ * in these bytes: what it would be drawn at is not known.
3990
+ */
3991
+ function gifSize(b) {
3992
+ if (b.length < 13) return void 0;
3993
+ const screenWidth = u16le(b, 6), screenHeight = u16le(b, 8);
3994
+ let at = 13 + (b[10] & 128 ? 3 * (2 << (b[10] & 7)) : 0);
3995
+ while (at < b.length) {
3996
+ const block = b[at];
3997
+ if (block === 44) {
3998
+ if (at + 9 > b.length) return void 0;
3999
+ const left = u16le(b, at + 1), top = u16le(b, at + 3), width = u16le(b, at + 5), height = u16le(b, at + 7);
4000
+ return sized(Math.max(screenWidth, left + width), Math.max(screenHeight, top + height));
4001
+ }
4002
+ if (block === 59) return sized(screenWidth, screenHeight);
4003
+ if (block !== 33 || at + 2 > b.length) return void 0;
4004
+ at += 2;
4005
+ while (at < b.length && b[at] !== 0) at += 1 + b[at];
4006
+ at++;
4007
+ }
4008
+ }
4009
+ /**
3902
4010
  * A picture's size as it is shown, read from its first bytes (PNG, JPEG, GIF, WebP), or undefined when they do not
3903
- * say. Only the header is read: a JPEG whose frame header sits past `IMAGE_LIMITS.headBytes` goes without.
4011
+ * say. Only the header is read: a JPEG whose frame header, or a GIF whose first frame, sits past
4012
+ * `IMAGE_LIMITS.headBytes` goes without.
3904
4013
  */
3905
4014
  function imageSize(head) {
3906
4015
  const b = head;
3907
4016
  try {
3908
4017
  if (b.length >= 24 && b[0] === 137 && ascii(b, 1, "PNG\r\n\n") && ascii(b, 12, "IHDR")) return sized(u32be(b, 16), u32be(b, 20));
3909
- if (b.length >= 10 && (ascii(b, 0, "GIF87a") || ascii(b, 0, "GIF89a"))) return sized(u16le(b, 6), u16le(b, 8));
4018
+ if (b.length >= 10 && (ascii(b, 0, "GIF87a") || ascii(b, 0, "GIF89a"))) return gifSize(b);
3910
4019
  if (b.length >= 4 && b[0] === 255 && b[1] === 216 && b[2] === 255) return jpegSize(b);
3911
4020
  if (b.length >= 16 && ascii(b, 0, "RIFF") && ascii(b, 8, "WEBP")) return webpSize(b);
3912
4021
  } catch {}
@@ -4368,7 +4477,7 @@ function isAppUrl(value) {
4368
4477
  return false;
4369
4478
  }
4370
4479
  if (url.protocol !== "https:" || url.username || url.password || !url.hostname) return false;
4371
- const host = url.hostname.toLowerCase();
4480
+ const host = url.hostname.toLowerCase().replace(/\.+$/, "");
4372
4481
  if (host === "jsdelivr.net" || host.endsWith(".jsdelivr.net")) return host === "cdn.jsdelivr.net" && /^\/gh\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}\/./.test(url.pathname);
4373
4482
  return true;
4374
4483
  }
@@ -4560,7 +4669,7 @@ function checkAppManifest(value, options = {}) {
4560
4669
  function appDigest(manifestBytes) {
4561
4670
  return toBase64Url(sha256(manifestBytes));
4562
4671
  }
4563
- 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];
4564
4673
  /**
4565
4674
  * Lets the thread go for one turn: what waits (input, drawing, timers, port messages, IndexedDB answers) runs, then the
4566
4675
  * caller goes on. A message to itself, queued behind the page's other tasks. Never `scheduler.yield()`: in Chromium its
@@ -4636,7 +4745,7 @@ function readAppBundleHead(bytes) {
4636
4745
  ok: false,
4637
4746
  reason: "truncated"
4638
4747
  };
4639
- const manifestLength = u32$2(bytes, at);
4748
+ const manifestLength = u32$3(bytes, at);
4640
4749
  at += 4;
4641
4750
  if (manifestLength > APP_BUNDLE_LIMITS.manifestBytes) return {
4642
4751
  ok: false,
@@ -4648,7 +4757,7 @@ function readAppBundleHead(bytes) {
4648
4757
  };
4649
4758
  const manifestBytes = bytes.subarray(at, at + manifestLength);
4650
4759
  at += manifestLength;
4651
- const statementLength = u32$2(bytes, at);
4760
+ const statementLength = u32$3(bytes, at);
4652
4761
  at += 4;
4653
4762
  if (bytes.length < at + statementLength) return {
4654
4763
  ok: false,
@@ -4794,9 +4903,9 @@ var ContactRequestError = class extends Error {
4794
4903
  this.name = "ContactRequestError";
4795
4904
  }
4796
4905
  };
4797
- var label = (text) => utf8Encode(text);
4906
+ var label$1 = (text) => utf8Encode(text);
4798
4907
  function derive(linkKeyZ32, info) {
4799
- 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);
4800
4909
  }
4801
4910
  /** The UTC day number of a time: a stamp is made for one. */
4802
4911
  function contactDay(ms) {
@@ -4804,7 +4913,7 @@ function contactDay(ms) {
4804
4913
  }
4805
4914
  /** The `seen` entry of an asker key on a link: the first 9 bytes of a hash, so the record names nobody. */
4806
4915
  function seenEntry(linkKeyZ32, askerZ32) {
4807
- 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));
4808
4917
  }
4809
4918
  function linkRecords(record) {
4810
4919
  if (!Number.isInteger(record.bits) || record.bits < 16 || record.bits > 24) throw new Error("A link asks for 16 to 24 bits");
@@ -4842,7 +4951,7 @@ function readLinkRecord(records) {
4842
4951
  function stampPrefix(linkKeyZ32, askerZ32, day) {
4843
4952
  const tail = /* @__PURE__ */ new Uint8Array(4);
4844
4953
  new DataView(tail.buffer).setUint32(0, day);
4845
- 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);
4846
4955
  }
4847
4956
  function leadingZeroBits(hash) {
4848
4957
  let bits = 0;
@@ -4898,7 +5007,7 @@ function knockSlotOf(linkKeyZ32, askerZ32) {
4898
5007
  }
4899
5008
  function knockSlotRecords(linkKeyZ32, knocks) {
4900
5009
  const nonce = randomBytes(NONCE_LENGTH$3);
4901
- const body = label(JSON.stringify(knocks.slice(-6).map((k) => [
5010
+ const body = label$1(JSON.stringify(knocks.slice(-6).map((k) => [
4902
5011
  k.key,
4903
5012
  k.day,
4904
5013
  k.stamp
@@ -4933,9 +5042,9 @@ function mergeContactKnocks(existing, mine, now) {
4933
5042
  return [...existing.filter((k) => k.key !== mine.key && k.day >= today - 1 && k.day <= today + 1).slice(-5), mine];
4934
5043
  }
4935
5044
  function requestKey(linkKeyZ32, askerZ32, shared) {
4936
- 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);
4937
5046
  }
4938
- var REQUEST_AAD = label("ghostly-contact/1 request");
5047
+ var REQUEST_AAD = label$1("ghostly-contact/1 request");
4939
5048
  /** The value of a request's record for a plaintext of `length` bytes. */
4940
5049
  var sealedValueLength = (length) => Math.ceil((NONCE_LENGTH$3 + length + TAG_LENGTH) * 4 / 3);
4941
5050
  var plaintextBytes;
@@ -4973,7 +5082,7 @@ function requestRecords(askerSeedB64, linkKeyZ32, request) {
4973
5082
  if (!inviteHolds(request.invite)) throw new ContactRequestError("invite");
4974
5083
  if (!Number.isSafeInteger(request.issued) || !Number.isSafeInteger(request.expires) || request.expires <= request.issued || request.expires - request.issued > 6048e5) throw new ContactRequestError("dates");
4975
5084
  const asker = identityFromSeedB64(askerSeedB64);
4976
- const json = label(JSON.stringify([
5085
+ const json = label$1(JSON.stringify([
4977
5086
  1,
4978
5087
  request.invite,
4979
5088
  request.name,
@@ -7798,6 +7907,13 @@ var AWAITING_PEER_MS = 6e5;
7798
7907
  * to invites nobody may ever open, and a join on one was noticed 90 s later (bug hunt 1013-1642, 2026-10-13).
7799
7908
  */
7800
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;
7801
7917
  /** The keys and mailboxes of unused invites read slowly over each transport (an app's relays). */
7802
7918
  var unusedInviteReaders = /* @__PURE__ */ new WeakMap();
7803
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. */
@@ -7834,6 +7950,8 @@ var BACKGROUND_RETRY_MAX_MS = 6e4;
7834
7950
  var MIN_POLL_GAP_MS = 250;
7835
7951
  /** Presence is a fresh packet: advertising peers republish this often… */
7836
7952
  var PRESENCE_HEARTBEAT = 24e4;
7953
+ /** …and are considered gone once their packet is older than this. */
7954
+ var PRESENCE_WINDOW = 6e5;
7837
7955
  /** When this device first read the peer's latest packet, by its own clock (`PeerPresence.seenAt`). */
7838
7956
  var presenceSeenAt = (presence) => presence.seenAt ?? presence.lastPacketAt;
7839
7957
  /** With `firstPublish: "after-first-poll"`, the first packet goes out by then whatever happened. */
@@ -7883,6 +8001,8 @@ var LinkSession = class {
7883
8001
  awaitingSince;
7884
8002
  /** This side's invite, nobody used yet (`LinkSessionOptions.invite`). */
7885
8003
  invite;
8004
+ /** This side's own invite, nobody used yet (`LinkSessionOptions.ownInvite`). */
8005
+ ownInvite;
7886
8006
  intervals;
7887
8007
  fastPollUntil = 0;
7888
8008
  /** An offer to a saved contact is out: from then on its fast window looks less often (`OFFER_FAST_MS`); 0 for none. */
@@ -7951,6 +8071,7 @@ var LinkSession = class {
7951
8071
  this.resumeReads = !!options.resumed;
7952
8072
  this.awaitingSince = Math.min(options.awaitingSince ?? this.startedAt, this.startedAt);
7953
8073
  this.invite = options.invite ?? (() => false);
8074
+ this.ownInvite = options.ownInvite ?? (() => false);
7954
8075
  }
7955
8076
  get peerPresence() {
7956
8077
  return this.presence;
@@ -8241,10 +8362,15 @@ var LinkSession = class {
8241
8362
  if (this.heartbeatTimer) clearTimeout(this.heartbeatTimer);
8242
8363
  this.heartbeatTimer = setTimeout(() => {
8243
8364
  if (!this.running) return;
8244
- if (this.getServices() !== void 0) this.publish(true).catch(() => {});
8365
+ if (this.getServices() !== void 0 && !this.upkeepWaits()) this.publish(true).catch(() => {});
8245
8366
  this.scheduleHeartbeat();
8246
8367
  }, PRESENCE_HEARTBEAT);
8247
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
+ }
8248
8374
  /**
8249
8375
  * Coalesces publishes: at most one in flight and one queued behind it. `upkeep`: nothing new to say (the heartbeat, a
8250
8376
  * retry of what waits): with nothing else asked for since, the packet goes as upkeep (`publishOnce`).
@@ -9073,6 +9199,460 @@ var DataLink = class {
9073
9199
  }
9074
9200
  };
9075
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
9076
9656
  //#region ../core/src/groupCrypto.ts
9077
9657
  /**
9078
9658
  * The cryptography of the `group-mesh/1` profile (WISP 900 / 902 group mesh).
@@ -10381,11 +10961,25 @@ var LINK_CLOSERS = {
10381
10961
  "}": "{"
10382
10962
  };
10383
10963
  /**
10384
- * A link ends where the sentence around it takes over: trailing punctuation ("see https://x.example/a.") and a
10385
- * closing bracket or quote the link did not open ("(https://x.example/a)") are left as text. The same rule as the
10386
- * message bubble's links.
10964
+ * Punctuation a sentence in Chinese, Japanese or Arabic puts right after a link, with no space: the ideographic comma
10965
+ * and full stop, the full-width ! , : ; ? and brackets, the corner quotes, the Arabic comma, semicolon and question
10966
+ * mark, the Urdu full stop. No address holds one as typed, so a link stops at the first.
10387
10967
  */
10388
- function linkEnd(url) {
10968
+ var LINK_STOP = /[、。〈-】!(),:;?،؛؟۔]/;
10969
+ /** What a link leaves out at its end: a sentence's punctuation ("…", "»", "”" too), never a path's "/". */
10970
+ var LINK_TRAILING = /[.,;:!?'"*_>…»’”]/;
10971
+ /** A link up to the first `LINK_STOP`: "https://x.example/a。" opens /a, not /a%E3%80%82. */
10972
+ function linkStop(url) {
10973
+ const at = url.search(LINK_STOP);
10974
+ return at < 0 ? url : url.slice(0, at);
10975
+ }
10976
+ /**
10977
+ * A link ends where the sentence around it takes over: trailing punctuation ("see https://x.example/a.", in any of
10978
+ * the app's languages) and a closing bracket or quote the link did not open ("(https://x.example/a)") are left as
10979
+ * text. The same rule as the message bubble's links.
10980
+ */
10981
+ function linkEnd(whole) {
10982
+ const url = linkStop(whole);
10389
10983
  const count = {
10390
10984
  "(": 0,
10391
10985
  ")": 0,
@@ -10399,7 +10993,7 @@ function linkEnd(url) {
10399
10993
  while (end > 0) {
10400
10994
  const last = url[end - 1];
10401
10995
  const opener = LINK_CLOSERS[last];
10402
- if (!/[.,;:!?'"*_>]/.test(last) && !(opener && count[last] > count[opener])) break;
10996
+ if (!LINK_TRAILING.test(last) && !(opener && count[last] > count[opener])) break;
10403
10997
  if (opener) count[last]--;
10404
10998
  end--;
10405
10999
  }
@@ -10409,7 +11003,7 @@ function linkEnd(url) {
10409
11003
  var LINK_MAX_CHARS = 4096;
10410
11004
  /** The http(s) links of a text, in order, each ending as the bubble ends it. */
10411
11005
  function linksIn(text) {
10412
- return [...text.matchAll(/https?:\/\/\S+/g)].filter((match) => match[0].length <= LINK_MAX_CHARS).map((match) => linkEnd(match[0])).filter((url) => url.length > 8);
11006
+ return [...text.matchAll(/https?:\/\/\S+/gi)].filter((match) => match[0].length <= LINK_MAX_CHARS).map((match) => linkEnd(match[0])).filter((url) => url.length > 8);
10413
11007
  }
10414
11008
  /**
10415
11009
  * The link as a preview names it: parsed, http(s) only, without tracking parameters (`utm_*`, `fbclid`, …). The
@@ -10836,6 +11430,17 @@ var BLANK = /[\u034F\u115F\u1160\u2800\u3164\uFFA0]/gu;
10836
11430
  */
10837
11431
  var SPACE_RUN = /(?:\s\p{M}*)+/gu;
10838
11432
  /**
11433
+ * A run of characters meant to draw nothing (variation selectors, the Khmer inherent vowels, the Mongolian free
11434
+ * variation selectors). WebKit draws some of them as wide blanks after a letter, so "Invoice.pdf" + 150 of one +
11435
+ * ".exe" reads as a PDF there. A letter keeps one variation selector (its variant form); the rest go.
11436
+ */
11437
+ var IGNORABLE_RUN = /\p{Default_Ignorable_Code_Point}+/gu;
11438
+ var VARIATION_SELECTOR = /^\p{Variation_Selector}/u;
11439
+ function dropIgnorable(run, offset, text) {
11440
+ const kept = VARIATION_SELECTOR.exec(run)?.[0];
11441
+ return kept && offset > 0 && !/\s/u.test(text[offset - 1]) ? kept : "";
11442
+ }
11443
+ /**
10839
11444
  * Names Windows keeps for devices, whatever the case, with any extension, and with spaces before the dot:
10840
11445
  * "CON", "nul.txt", "COM1 .log" open a device there, not a file.
10841
11446
  */
@@ -10852,7 +11457,7 @@ function shorten(name) {
10852
11457
  }
10853
11458
  /** A file name is display text and a download suggestion, never a path. */
10854
11459
  function sanitizeFileName(name) {
10855
- const clean = shorten(name.replace(INVISIBLE, "").replace(BLANK, "").replace(/[/\\:]/g, "").replace(SPACE_RUN, " ").replace(/^[\s.]+/, "").trim());
11460
+ const clean = shorten(name.replace(INVISIBLE, "").replace(BLANK, "").replace(/[/\\:]/g, "").replace(IGNORABLE_RUN, dropIgnorable).replace(SPACE_RUN, " ").replace(/^[\s.]+/, "").trim());
10856
11461
  if (WINDOWS_DEVICE.test(clean)) return shorten("_" + clean);
10857
11462
  return clean || "file";
10858
11463
  }
@@ -11183,6 +11788,11 @@ var DhtDelivery = class DhtDelivery {
11183
11788
  live = false;
11184
11789
  active = false;
11185
11790
  startedAt = Date.now();
11791
+ /**
11792
+ * When an envelope of the contact's newer than any before was last read here, in this run. A contact that is there
11793
+ * puts a keep-alive every four minutes: none in `PRESENCE_WINDOW`, it is away (`publish`).
11794
+ */
11795
+ peerNewAt = -Infinity;
11186
11796
  /** The next read was asked for (a refresh, a fresh packet of the contact): it is not a background one. */
11187
11797
  urgent = false;
11188
11798
  /** Reads left that are signaling: the contact is leaving DHT only, and the live link waits on them (`expect`). */
@@ -11256,9 +11866,29 @@ var DhtDelivery = class DhtDelivery {
11256
11866
  maxTextBytes: 256,
11257
11867
  ...this.lastPublished && { lastPublished: this.lastPublished },
11258
11868
  ...this.foreignKeySeenAt && { foreignKeySeenAt: this.foreignKeySeenAt },
11259
- ...this.state.inviteTaken && { inviteTaken: true }
11869
+ ...this.state.inviteTaken && { inviteTaken: true },
11870
+ ...this.forwardSecrecy && { forwardSecrecy: this.forwardSecrecy }
11260
11871
  };
11261
11872
  }
11873
+ get forwardSecrecy() {
11874
+ const ratchet = this.options.ratchet;
11875
+ if (!ratchet || !this.options.credentials.peerKey) return void 0;
11876
+ const supports = ratchet.peerSupports();
11877
+ return ratchet.box.on && supports ? "on" : !supports ? ratchet.box.heardAny ? "stopped" : "unsupported" : "starting";
11878
+ }
11879
+ /**
11880
+ * Whether an envelope to `recipient` is sealed with the ratchet: the contact is pinned and its record lists
11881
+ * `ratchet/1`, or a ratcheted envelope of its was opened here, after which nothing goes plain (WISP 4xx § Downgrade).
11882
+ * And the contact pinned this side too (an envelope of its sealed to this side read, or a live session had): a joiner
11883
+ * pins its inviter from the invite, and its first contact sealed with the ratchet would reach an inviter that has no key
11884
+ * to open it with, and so never pins it.
11885
+ */
11886
+ ratcheted(recipient) {
11887
+ const ratchet = this.options.ratchet, peer = this.options.credentials.peerKey;
11888
+ if (!ratchet || !peer || recipient !== peer) return false;
11889
+ if (ratchet.box.heardAny) return true;
11890
+ return ratchet.peerSupports() && (!!this.state.peerPinned || !!this.state.wasLive);
11891
+ }
11262
11892
  /**
11263
11893
  * This side joined, and its inviter never answered (`DhtDeliveryState.unanswered`): no envelope of its newer than the
11264
11894
  * one that pinned it, none sealed to this side, no text confirmed, never live (as `sealedToAnother` asks too).
@@ -11297,6 +11927,14 @@ var DhtDelivery = class DhtDelivery {
11297
11927
  return this.pinnedBoxes;
11298
11928
  }
11299
11929
  lastPublished;
11930
+ /** The envelope a trace line was last said for, per step: a packet read again says nothing new (a Desktop logs every line). */
11931
+ traced = /* @__PURE__ */ new Map();
11932
+ traceOnce(step, record, detail) {
11933
+ const seen = record.slice(-24);
11934
+ if (this.traced.get(step) === seen) return;
11935
+ this.traced.set(step, seen);
11936
+ traceLink(this.from, step, detail);
11937
+ }
11300
11938
  /** The sealed record's nonce is its first 24 bytes: 32 characters of base64. */
11301
11939
  static facts(body, records, key) {
11302
11940
  return {
@@ -11352,6 +11990,13 @@ var DhtDelivery = class DhtDelivery {
11352
11990
  ]));
11353
11991
  }
11354
11992
  records(body, recipient = this.options.credentials.peerKey) {
11993
+ return this.envelope(body, recipient).records;
11994
+ }
11995
+ /**
11996
+ * The envelope's records. Ratcheted (`ratcheted`), its `_dr` record is the right length but not sealed yet: `seal`
11997
+ * gives its bytes, under the chat's lock, once the publication is sure to go. Measuring a packet takes no key.
11998
+ */
11999
+ envelope(body, recipient = this.options.credentials.peerKey) {
11355
12000
  const signature = toBase64Url(sign(this.signed(body, recipient), this.participation.seed));
11356
12001
  const plaintext = JSON.stringify([body, signature]);
11357
12002
  const hint = recipient ? [{
@@ -11359,20 +12004,46 @@ var DhtDelivery = class DhtDelivery {
11359
12004
  value: encrypt(this.participation.pubKeyZ32, this.key),
11360
12005
  ttl: ENVELOPE_TTL
11361
12006
  }] : [];
12007
+ const ratchet = this.ratcheted(recipient);
12008
+ const sealedBytes = (bytes) => ratchet ? 4 * Math.ceil((66 + bytes) / 3) : sealedLength(bytes);
12009
+ const label = ratchet ? "_dr" : "_dm";
11362
12010
  const fits = (bytes) => bytes <= MAX_ENVELOPE_PLAINTEXT && measureRecords(this.identity.pubKeyZ32, [{
11363
- label: "_dm",
11364
- value: "A".repeat(sealedLength(bytes)),
12011
+ label,
12012
+ value: "A".repeat(sealedBytes(bytes)),
11365
12013
  ttl: ENVELOPE_TTL
11366
12014
  }, ...hint]) <= ENVELOPE_PACKET_BYTES;
11367
12015
  const bytes = utf8Encode(plaintext).length;
11368
12016
  if (!fits(bytes)) throw new Error("Text and authentication exceed the DHT packet budget. Shorten the message.");
11369
12017
  let padded = bytes;
11370
12018
  for (let step = 512; step >= 1; step >>= 1) if (fits(padded + step)) padded += step;
11371
- return [{
11372
- label: "_dm",
11373
- value: encrypt(plaintext + " ".repeat(padded - bytes), recipient ? this.sealedKey(recipient) : this.key),
12019
+ const full = plaintext + " ".repeat(padded - bytes);
12020
+ if (ratchet) return {
12021
+ records: [{
12022
+ label,
12023
+ value: "A".repeat(sealedBytes(padded)),
12024
+ ttl: ENVELOPE_TTL
12025
+ }, ...hint],
12026
+ plaintext: full
12027
+ };
12028
+ return { records: [{
12029
+ label,
12030
+ value: encrypt(full, recipient ? this.sealedKey(recipient) : this.key),
11374
12031
  ttl: ENVELOPE_TTL
11375
- }, ...hint];
12032
+ }, ...hint] };
12033
+ }
12034
+ /**
12035
+ * The records to publish: a ratcheted one sealed now, its state saved first (seal, save, send), from the plaintext
12036
+ * the envelope was measured with.
12037
+ */
12038
+ async sealed(envelope) {
12039
+ const { records, plaintext } = envelope;
12040
+ if (records[0]?.label !== "_dr") return records;
12041
+ if (plaintext === void 0) throw new Error("A ratcheted envelope without its plaintext");
12042
+ const sealed = await this.options.ratchet.box.lock((tx) => tx.seal("floor", utf8Encode(plaintext)));
12043
+ return [{
12044
+ ...records[0],
12045
+ value: toBase64(sealed)
12046
+ }, ...records.slice(1)];
11376
12047
  }
11377
12048
  async start() {
11378
12049
  if (this.running) return;
@@ -11491,6 +12162,7 @@ var DhtDelivery = class DhtDelivery {
11491
12162
  }
11492
12163
  validate(text, timestamp, id, reply, edit) {
11493
12164
  if (this.options.peerAcceptsText?.() === false) return DHT_TEXT_REFUSED;
12165
+ if (this.forwardSecrecy === "stopped") return DHT_RATCHET_STOPPED;
11494
12166
  if (!ID$2.test(id) || !Number.isSafeInteger(timestamp) || timestamp <= 0 || reply !== void 0 && !REPLY_TO.test(reply)) return "Invalid message.";
11495
12167
  if (edit !== void 0 && (reply !== void 0 || !ID$2.test(edit[0]) || !validEditNumber(edit[1]))) return "Invalid message.";
11496
12168
  if (utf8Encode(text).length > 256) return DHT_TEXT_TOO_LONG;
@@ -11765,10 +12437,10 @@ var DhtDelivery = class DhtDelivery {
11765
12437
  for (let count = pending.length; count > 0; count--) {
11766
12438
  const body = this.body(sequence, issued, expires, message, receipt, reply, pending.slice(0, count), edit, forwarded, file);
11767
12439
  try {
11768
- const records = this.records(body);
12440
+ const envelope = this.envelope(body);
11769
12441
  if (utf8Encode(JSON.stringify([body, "x".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT) return {
11770
12442
  body,
11771
- records,
12443
+ ...envelope,
11772
12444
  reactions: count
11773
12445
  };
11774
12446
  } catch {}
@@ -11776,7 +12448,7 @@ var DhtDelivery = class DhtDelivery {
11776
12448
  const body = this.body(sequence, issued, expires, message, receipt, reply, [], edit, forwarded, file);
11777
12449
  return {
11778
12450
  body,
11779
- records: this.records(body),
12451
+ ...this.envelope(body),
11780
12452
  reactions: 0
11781
12453
  };
11782
12454
  }
@@ -11791,10 +12463,21 @@ var DhtDelivery = class DhtDelivery {
11791
12463
  if (keepAlive && (this.controlDue > now || this.state.inviteTaken)) return;
11792
12464
  const expires = pending?.expires ?? now - 12e4 + CONTROL_TTL;
11793
12465
  const issued = Math.min(now, Math.max(now - DHT_ISSUED_BACK_MS, expires - (pending ? DHT_MESSAGE_TTL : CONTROL_TTL), (pending?.message[1] ?? 0) - 3e4));
11794
- const { body, records, reactions } = this.fitted(this.sequence + 1, issued, expires, pending?.message ?? null, receipt?.id ?? null, pending?.reply, pending?.edit, pending?.forwarded, pending?.file);
12466
+ const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
12467
+ const away = !!this.options.credentials.peerKey && now - this.peerNewAt >= 6e5;
12468
+ const options = keepAlive && (this.live || away) ? { background: true } : void 0;
12469
+ const held = this.options.transport.publishHeld?.(identity.pubKeyZ32, options);
12470
+ if (held) {
12471
+ await this.heldBack(held, now, {
12472
+ lastPublish: this.lastPublish,
12473
+ controlDue: this.controlDue
12474
+ }, void 0, void 0);
12475
+ throw held;
12476
+ }
12477
+ const fittedEnvelope = this.fitted(this.sequence + 1, issued, expires, pending?.message ?? null, receipt?.id ?? null, pending?.reply, pending?.edit, pending?.forwarded, pending?.file);
12478
+ const { body, reactions } = fittedEnvelope;
11795
12479
  const reactionsWereDue = this.reactionsDue;
11796
12480
  this.reactionsDue = !reactions && !!this.options.reactions?.().length;
11797
- const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
11798
12481
  const sequence = body[1];
11799
12482
  await this.persist({
11800
12483
  ...this.state,
@@ -11811,20 +12494,23 @@ var DhtDelivery = class DhtDelivery {
11811
12494
  } : this.state.receipt
11812
12495
  });
11813
12496
  this.sequence = sequence;
12497
+ const records = await this.sealed(fittedEnvelope);
11814
12498
  const before = {
11815
12499
  lastPublish: this.lastPublish,
11816
12500
  controlDue: this.controlDue
11817
12501
  };
12502
+ const ownInvite = !this.options.credentials.expectedPeerKey && !this.active && this.unusedInviteAge(now) !== void 0;
11818
12503
  this.lastPublish = now;
11819
- this.controlDue = now + 24e4;
12504
+ this.controlDue = now + (ownInvite ? UNUSED_INVITE_UPKEEP_MS : 24e4);
11820
12505
  traceLink(this.from, "dht-publish", {
11821
12506
  mode: this.mode,
11822
12507
  seq: body[1],
11823
- ...identity !== this.identity && { pinned: true }
12508
+ ...identity !== this.identity && { pinned: true },
12509
+ ...records[0]?.label === "_dr" && { ratchet: true }
11824
12510
  });
11825
12511
  if (pending) this.lastPublished = DhtDelivery.facts(body, records, identity.pubKeyZ32);
11826
12512
  try {
11827
- await this.options.transport.publish(identity, records, keepAlive && this.live ? { background: true } : void 0);
12513
+ await this.options.transport.publish(identity, records, options);
11828
12514
  } catch (error) {
11829
12515
  this.reactionsDue ||= reactionsWereDue;
11830
12516
  if (isDiscoveryBudgetError(error)) await this.heldBack(error, now, before, pending, receipt);
@@ -11850,7 +12536,7 @@ var DhtDelivery = class DhtDelivery {
11850
12536
  this.lastPublish = before.lastPublish;
11851
12537
  this.controlDue = Math.min(before.controlDue, at);
11852
12538
  traceLink(this.from, "dht-publish-waits", { retryInMs: at - now });
11853
- await this.persist({
12539
+ if (pending || receipt) await this.persist({
11854
12540
  ...this.state,
11855
12541
  pending: pending ?? this.state.pending,
11856
12542
  receipt: receipt ?? this.state.receipt
@@ -11861,22 +12547,44 @@ var DhtDelivery = class DhtDelivery {
11861
12547
  * one sealed record, a well-formed body within its times, signed by the key it names. Null: not an envelope of the
11862
12548
  * contact's (the pin rules are the caller's).
11863
12549
  */
11864
- open(packet, box) {
12550
+ open(packet, box, ratchet) {
11865
12551
  const address = box === "pinned" ? this.pinned()?.peerAddress : this.peerAddress;
11866
12552
  if (!address || packet.pubKeyZ32 !== address || measureRecords(packet.pubKeyZ32, packet.records) > 1e3) return null;
11867
- const records = packet.records.filter((r) => r.label === "_dm");
11868
- if (records.length !== 1) return null;
12553
+ const records = packet.records.filter((r) => r.label === "_dm"), ratcheted = packet.records.filter((r) => r.label === "_dr");
12554
+ if (records.length + ratcheted.length !== 1) return null;
11869
12555
  const hints = packet.records.filter((r) => r.label === "_dmk");
11870
12556
  if (hints.length > 1) return null;
11871
12557
  const sender = hints.length ? tryDecrypt(hints[0].value, this.key) : null;
11872
12558
  if (hints.length && !sender) return null;
12559
+ const peer = this.options.credentials.peerKey;
11873
12560
  let plaintext;
11874
- try {
11875
- plaintext = tryDecrypt(records[0].value, sender ? this.sealedKey(sender) : this.key);
11876
- } catch {
11877
- plaintext = null;
12561
+ if (ratcheted.length) {
12562
+ const closed = box === "invite" && sender ? { sealedToAnother: sender } : null;
12563
+ if (!ratchet || !peer || sender !== peer) return closed;
12564
+ let opened;
12565
+ try {
12566
+ opened = ratchet(fromBase64(ratcheted[0].value));
12567
+ } catch {
12568
+ opened = null;
12569
+ }
12570
+ if (!opened) return closed;
12571
+ try {
12572
+ plaintext = utf8Decode(opened);
12573
+ } catch {
12574
+ return null;
12575
+ }
12576
+ } else {
12577
+ if (peer && this.options.ratchet?.box.heard("floor") && (!sender || sender === peer)) {
12578
+ this.traceOnce("dht-plain-refused", records[0].value, { box });
12579
+ return null;
12580
+ }
12581
+ try {
12582
+ plaintext = tryDecrypt(records[0].value, sender ? this.sealedKey(sender) : this.key);
12583
+ } catch {
12584
+ plaintext = null;
12585
+ }
12586
+ if (!plaintext && sender) return { sealedToAnother: sender };
11878
12587
  }
11879
- if (!plaintext && sender) return { sealedToAnother: sender };
11880
12588
  if (!plaintext || utf8Encode(plaintext).length > MAX_ENVELOPE_PLAINTEXT) return null;
11881
12589
  let envelope;
11882
12590
  try {
@@ -11956,7 +12664,41 @@ var DhtDelivery = class DhtDelivery {
11956
12664
  * can write to) or `pinned`. `none`: nothing from the contact in it; `old`: the contact's, already read; `new`: taken.
11957
12665
  */
11958
12666
  async receive(packet, box) {
11959
- const opened = this.open(packet, box);
12667
+ const ratcheted = packet.records.find((r) => r.label === "_dr");
12668
+ if (!ratcheted) return this.take(packet, box, this.open(packet, box));
12669
+ const digest = toBase64Url(sha256(utf8Encode(ratcheted.value)).slice(0, 16));
12670
+ if (digest === this.state.lastDr) return "old";
12671
+ const ratchet = this.options.ratchet;
12672
+ if (!ratchet) return "none";
12673
+ let sealed;
12674
+ const opened = this.open(packet, box, (bytes) => {
12675
+ const plain = ratchet.box.peek("floor", bytes);
12676
+ if (plain) sealed = bytes;
12677
+ return plain;
12678
+ });
12679
+ if (!sealed) this.traceOnce("dht-ratchet-closed", ratcheted.value, {
12680
+ box,
12681
+ pinned: !!this.options.credentials.peerKey
12682
+ });
12683
+ if (!sealed && box === "pinned" && packet.pubKeyZ32 === this.pinned()?.peerAddress && this.state.peerPinned !== "seen") {
12684
+ await this.persist({
12685
+ ...this.state,
12686
+ peerPinned: "seen"
12687
+ });
12688
+ traceLink(this.from, "dht-peer-pinned", {
12689
+ peerPinned: "seen",
12690
+ ratchet: true
12691
+ });
12692
+ }
12693
+ return this.take(packet, box, opened, sealed && {
12694
+ commit: async (order) => {
12695
+ if (!await ratchet.box.commitOpen("floor", sealed, order)) throw new Error("A ratcheted envelope no longer opens");
12696
+ },
12697
+ digest
12698
+ });
12699
+ }
12700
+ /** `ratchet`: the envelope was ratcheted; its state is saved once what it carried is stored, with its digest. */
12701
+ async take(packet, box, opened, ratchet) {
11960
12702
  if (!opened) return "none";
11961
12703
  if ("sealedToAnother" in opened) {
11962
12704
  if (opened.sealedToAnother) await this.sealedToAnother(opened.sealedToAnother);
@@ -11983,6 +12725,7 @@ var DhtDelivery = class DhtDelivery {
11983
12725
  if (message !== null && (!Array.isArray(message) || message.length !== 3 || typeof message[0] !== "string" || !ID$2.test(message[0]) || !Number.isSafeInteger(message[1]) || message[1] <= 0 || message[1] > issued + 3e4 || typeof message[2] !== "string" || utf8Encode(message[2]).length > 256 || expires - issued > 3e5)) return "none";
11984
12726
  if (receipt !== null && (typeof receipt !== "string" || !ID$2.test(receipt))) return "none";
11985
12727
  const unanswered = !this.options.credentials.peerKey && !!this.options.credentials.expectedPeerKey && !sender && !this.live;
12728
+ this.peerNewAt = Date.now();
11986
12729
  await this.options.pin(author);
11987
12730
  this.options.credentials.peerKey = author;
11988
12731
  this.options.credentials.requireSignedSignals = true;
@@ -12026,6 +12769,7 @@ var DhtDelivery = class DhtDelivery {
12026
12769
  if (peerPinned !== this.state.peerPinned) traceLink(this.from, "dht-peer-pinned", { peerPinned });
12027
12770
  if (this.state.inviteTaken) traceLink(this.from, "invite-untaken", {});
12028
12771
  const { inviteTaken: _taken, ...kept } = this.state;
12772
+ if (ratchet) await ratchet.commit(sequence);
12029
12773
  await this.persist({
12030
12774
  ...kept,
12031
12775
  peerSequence: sequence,
@@ -12034,6 +12778,7 @@ var DhtDelivery = class DhtDelivery {
12034
12778
  confirmed,
12035
12779
  ...peerPinned && { peerPinned },
12036
12780
  ...unanswered && { unanswered: sequence },
12781
+ ...ratchet && { lastDr: ratchet.digest },
12037
12782
  pending: confirmed && this.state.pending?.message[0] === confirmed ? void 0 : this.state.pending,
12038
12783
  ...newest > (this.state.reactionsTaken ?? 0) && { reactionsTaken: newest }
12039
12784
  });
@@ -12088,7 +12833,12 @@ var DhtDelivery = class DhtDelivery {
12088
12833
  for (const box of boxes) {
12089
12834
  const packet = await this.options.transport.resolve(box === "pinned" ? pinned.peerAddress : this.peerAddress, options);
12090
12835
  reads++;
12091
- const opened = packet && this.open(packet, box);
12836
+ const dr = packet?.records.find((r) => r.label === "_dr");
12837
+ if (dr && toBase64Url(sha256(utf8Encode(dr.value)).slice(0, 16)) === this.state.lastDr) return {
12838
+ reads,
12839
+ text: null
12840
+ };
12841
+ const opened = packet && this.open(packet, box, (sealed) => this.options.ratchet?.box.peek("floor", sealed) ?? null);
12092
12842
  if (!opened || "sealedToAnother" in opened || opened.author !== expected) continue;
12093
12843
  const { sequence, message } = opened;
12094
12844
  const fresh = Array.isArray(message) && typeof message[0] === "string" && ID$2.test(message[0]) && sequence > this.state.peerSequence && this.state.receipt?.id !== message[0];
@@ -12203,6 +12953,7 @@ var DhtDelivery = class DhtDelivery {
12203
12953
  }
12204
12954
  };
12205
12955
  var DHT_TEXT_REFUSED = "Your contact's app does not accept text over the DHT. It is sent when you are live.";
12956
+ var DHT_RATCHET_STOPPED = "Your contact's app no longer reads protected messages over the DHT. It is sent when you are live.";
12206
12957
  var DHT_FILE_REFUSED = "Your contact's app shows a file only once it comes. It is sent when you are live.";
12207
12958
  var DHT_FILE_TOO_LARGE = "This file's name is too long to say over the DHT. It is sent when you are live.";
12208
12959
  /**
@@ -12213,17 +12964,29 @@ function peekDhtMailbox(options) {
12213
12964
  const refuse = async () => {
12214
12965
  throw new Error("A peek saves nothing");
12215
12966
  };
12967
+ const credentials = { ...options.credentials }, peer = credentials.peerKey;
12968
+ const box = options.ratchet && peer ? new RatchetBox(() => ({
12969
+ seed: fromBase64Url(credentials.seedB64),
12970
+ self: identityFromSeedB64(credentials.seedB64).pubKeyZ32,
12971
+ peer,
12972
+ rendezvous: [identityFromSeedB64(options.params.seedB64).pubKeyZ32, options.params.peerPubKeyZ32],
12973
+ secret: fromBase64Url(options.params.encKeyB64)
12974
+ }), options.ratchet, refuse) : void 0;
12216
12975
  return new DhtDelivery({
12217
12976
  params: options.params,
12218
12977
  mode: "stream",
12219
12978
  state: options.state,
12220
- credentials: { ...options.credentials },
12979
+ credentials,
12221
12980
  transport: options.transport,
12222
12981
  save: refuse,
12223
12982
  pin: refuse,
12224
12983
  message: refuse,
12225
12984
  receipt: refuse,
12226
- changed: () => {}
12985
+ changed: () => {},
12986
+ ...box && { ratchet: {
12987
+ box,
12988
+ peerSupports: () => true
12989
+ } }
12227
12990
  }).peek(options.background ? { background: true } : void 0);
12228
12991
  }
12229
12992
  //#endregion
@@ -13048,6 +13811,14 @@ var TransportSwitch = class {
13048
13811
  };
13049
13812
  var enc = base64urlnopad.encode;
13050
13813
  var dec = base64urlnopad.decode;
13814
+ /** No bytes for text that is not base64url: the checks then refuse it with their own message. */
13815
+ var decOrEmpty = (s) => {
13816
+ try {
13817
+ return dec(s);
13818
+ } catch {
13819
+ return /* @__PURE__ */ new Uint8Array(0);
13820
+ }
13821
+ };
13051
13822
  var hash = (s) => enc(sha256(utf8Encode(s)));
13052
13823
  var header = enc(utf8Encode(JSON.stringify({
13053
13824
  alg: "EdDSA",
@@ -13067,8 +13838,14 @@ function verifyRingAuthorization(authorization, statement, issuer, issuedAt, exp
13067
13838
  if (typeof authorization !== "string" || authorization.length > 2400) throw new Error("Invalid Ring authorization");
13068
13839
  const [h, p, s, ...extra] = authorization.split(".");
13069
13840
  if (extra.length || h !== header || !p || !s) throw new Error("Unsupported Ring authorization");
13070
- const claims = JSON.parse(utf8Decode(dec(p)));
13071
- if (typeof claims?.cnf !== "string" || !validRingKey(claims.cnf) || expiresAt !== issuedAt + 600 || p !== enc(utf8Encode(JSON.stringify(ringClaims(statement, issuer, claims.cnf, issuedAt, expiresAt)))) || !validRingKey(issuer) || dec(s).length !== 64 || enc(dec(s)) !== s || !ed25519.verify(dec(s), utf8Encode(h + "." + p), fromZ32(issuer), { zip215: false })) throw new Error("Ring did not authorize this exact conversation");
13841
+ let claims;
13842
+ try {
13843
+ claims = JSON.parse(utf8Decode(dec(p)));
13844
+ } catch {
13845
+ throw new Error("Unsupported Ring authorization");
13846
+ }
13847
+ const sig = decOrEmpty(s);
13848
+ if (typeof claims?.cnf !== "string" || !validRingKey(claims.cnf) || expiresAt !== issuedAt + 600 || p !== enc(utf8Encode(JSON.stringify(ringClaims(statement, issuer, claims.cnf, issuedAt, expiresAt)))) || !validRingKey(issuer) || sig.length !== 64 || enc(sig) !== s || !ed25519.verify(sig, utf8Encode(h + "." + p), fromZ32(issuer), { zip215: false })) throw new Error("Ring did not authorize this exact conversation");
13072
13849
  return claims;
13073
13850
  }
13074
13851
  function validRingKey(key) {
@@ -13094,7 +13871,7 @@ function evidenceId(authorization, signature) {
13094
13871
  function verifyRingEvidence(e, statement, issuer, issuedAt, expiresAt) {
13095
13872
  if (!e || e.scheme !== "pubky-ring/1" || typeof e.signature !== "string" || e.signature.length !== 86) throw new Error("Invalid Ring proof");
13096
13873
  const claims = verifyRingAuthorization(e.authorization, statement, issuer, issuedAt, expiresAt);
13097
- const sig = dec(e.signature);
13874
+ const sig = decOrEmpty(e.signature);
13098
13875
  if (enc(sig) !== e.signature || e.id !== evidenceId(e.authorization, e.signature) || !ed25519.verify(sig, possession(e.authorization, statement), fromZ32(claims.cnf), { zip215: false })) throw new Error("Invalid delegated proof of possession");
13099
13876
  }
13100
13877
  //#endregion
@@ -13447,10 +14224,12 @@ function applyIdentityEvent(timeline, event, at) {
13447
14224
  const i = lastOf(out, event.side, event.type === "result" ? [event.proof, event.requested] : [event.proof]);
13448
14225
  const last = i >= 0 ? out[i] : void 0;
13449
14226
  const add = (entry) => {
13450
- const n = out.filter((e) => e.side === entry.side && e.proof === entry.proof).length;
14227
+ const prefix = `${entry.side}:${entry.proof}:`;
14228
+ let n = 0;
14229
+ for (const e of out) if (e.id.startsWith(prefix)) n = Math.max(n, Number(e.id.slice(prefix.length)) + 1 || 0);
13451
14230
  out.push({
13452
14231
  ...entry,
13453
- id: `${entry.side}:${entry.proof}:${n}`,
14232
+ id: `${prefix}${n}`,
13454
14233
  at
13455
14234
  });
13456
14235
  };
@@ -13641,13 +14420,19 @@ function verifyIdentityPresentation(key, sig, proofId, scope, nonce, issuedAt) {
13641
14420
  }
13642
14421
  var clean$1 = (value, max) => {
13643
14422
  if (typeof value !== "string") return void 0;
13644
- const text = value.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, "").trim();
13645
- return text ? text.slice(0, max) : void 0;
14423
+ const text = stripHidden(value).trim();
14424
+ return text && hasVisible(text) ? text.slice(0, max) : void 0;
13646
14425
  };
14426
+ /**
14427
+ * Room for a line that names a domain (up to 253 characters) once or twice: a How line or a reason cut inside the name
14428
+ * names a record that does not exist, and the app no longer knows the reason to say it in the person's language.
14429
+ */
14430
+ var SOURCE_MAX = 640;
14431
+ var ERROR_MAX = 512;
13647
14432
  /** Bounds a provider's result so a buggy provider cannot store or show arbitrary data. */
13648
14433
  function boundVerifiedIdentity(v) {
13649
14434
  if (!v || typeof v.subject !== "string" || !IDENTITY_SUBJECT.test(v.subject)) throw new Error("Provider returned an invalid subject");
13650
- const source = clean$1(v.source, 120);
14435
+ const source = clean$1(v.source, SOURCE_MAX);
13651
14436
  if (!source) throw new Error("Provider did not say how it verified");
13652
14437
  const out = {
13653
14438
  subject: v.subject,
@@ -13701,7 +14486,10 @@ function receivedWithRoom(received, id, replaced, now) {
13701
14486
  const out = kept.filter((r) => !drop.has(r));
13702
14487
  return out.length < 16 ? out : void 0;
13703
14488
  }
13704
- var shortError = (e) => clean$1(e instanceof Error ? e.message : String(e), 160) ?? "Invalid proof";
14489
+ var REVOKED = "Its owner revoked this proof";
14490
+ /** Revoked is final: a later lookup that fails or finds nothing (the relays forgot it) does not undo it. */
14491
+ var revokedHere = (received, id) => received.some((r) => r.id === id && r.status === "revoked");
14492
+ var shortError = (e) => clean$1(e instanceof Error ? e.message : String(e), ERROR_MAX) ?? "Invalid proof";
13705
14493
  /**
13706
14494
  * A check this side could not finish because of what its own network did: a host it refused to contact, a server
13707
14495
  * that did not answer or answered an error. The message is for this side only. The contact is told the proof could
@@ -13862,54 +14650,60 @@ var IdentityExchange = class {
13862
14650
  const r = this.options.storage.read().received.find((x) => x.id === id);
13863
14651
  if (!r) throw new Error("Unknown identity");
13864
14652
  if (r.status === "revoked") return r;
13865
- let next;
13866
- const settled = r.status === "withdrawn";
13867
- if (await this.options.revoked?.(identityStatement(r.binding)).catch(() => false)) {
13868
- next = {
13869
- ...r,
13870
- status: "revoked",
13871
- checkedAt: this.now(),
13872
- error: void 0
13873
- };
13874
- await this.options.storage.update((l) => this.log({
13875
- ...l,
13876
- received: l.received.map((x) => x.id === id ? next : x)
13877
- }, {
13878
- type: "stopped",
13879
- side: "theirs",
13880
- proof: id,
13881
- provider: r.binding.provider,
13882
- subject: r.verified.subject,
13883
- reason: "revoked"
13884
- }));
13885
- return next;
13886
- }
14653
+ if (await this.options.revoked?.(identityStatement(r.binding)).catch(() => false)) return await this.settleRecheck(id, (x) => x.status === "revoked" ? x : {
14654
+ ...x,
14655
+ status: "revoked",
14656
+ checkedAt: this.now(),
14657
+ error: void 0
14658
+ }, {
14659
+ type: "stopped",
14660
+ side: "theirs",
14661
+ proof: id,
14662
+ provider: r.binding.provider,
14663
+ subject: r.verified.subject,
14664
+ reason: "revoked"
14665
+ }) ?? r;
13887
14666
  if (revocationOnly) return r;
14667
+ let outcome;
13888
14668
  try {
13889
14669
  const verified = boundVerifiedIdentity(await this.options.verify(identityStatement(r.binding), r.evidence));
13890
14670
  if (verified.subject !== r.verified.subject) throw new Error("The identity changed");
13891
- next = {
13892
- ...r,
14671
+ outcome = (x) => ({
14672
+ ...x,
13893
14673
  verified: {
13894
14674
  ...verified,
13895
- display: verified.display ?? r.verified.display
14675
+ display: verified.display ?? x.verified.display
13896
14676
  },
13897
14677
  checkedAt: this.now(),
13898
- status: settled ? "withdrawn" : "verified",
14678
+ status: "verified",
13899
14679
  error: void 0
13900
- };
14680
+ });
13901
14681
  } catch (e) {
13902
- next = {
13903
- ...r,
14682
+ const error = shortError(e);
14683
+ outcome = (x) => ({
14684
+ ...x,
13904
14685
  checkedAt: this.now(),
13905
- status: settled ? "withdrawn" : "unconfirmed",
13906
- error: shortError(e)
13907
- };
14686
+ status: "unconfirmed",
14687
+ error
14688
+ });
13908
14689
  }
13909
- await this.options.storage.update((l) => ({
13910
- ...l,
13911
- received: l.received.map((x) => x.id === id ? next : x)
13912
- }));
14690
+ return await this.settleRecheck(id, (x) => x.status === "revoked" ? x : x.status === "withdrawn" ? {
14691
+ ...outcome(x),
14692
+ status: "withdrawn"
14693
+ } : outcome(x)) ?? r;
14694
+ }
14695
+ async settleRecheck(id, outcome, event) {
14696
+ let next;
14697
+ await this.options.storage.update((l) => {
14698
+ const x = l.received.find((y) => y.id === id);
14699
+ if (!x) return l;
14700
+ next = outcome(x);
14701
+ const out = {
14702
+ ...l,
14703
+ received: l.received.map((y) => y.id === id ? next : y)
14704
+ };
14705
+ return event && x.status !== "revoked" ? this.log(out, event) : out;
14706
+ });
13913
14707
  return next;
13914
14708
  }
13915
14709
  async receive(frame) {
@@ -13926,7 +14720,7 @@ var IdentityExchange = class {
13926
14720
  case "idp-result": {
13927
14721
  const s = id ? this.shared(id) : void 0;
13928
14722
  if (!s || s.status !== "pending") return;
13929
- const error = frame.ok === true ? void 0 : clean$1(frame.error, 160) ?? "Your contact could not verify it";
14723
+ const error = frame.ok === true ? void 0 : clean$1(frame.error, ERROR_MAX) ?? "Your contact could not verify it";
13930
14724
  await this.setShared({
13931
14725
  ...s,
13932
14726
  status: frame.ok === true ? "accepted" : "rejected",
@@ -13944,7 +14738,7 @@ var IdentityExchange = class {
13944
14738
  case "idp-withdraw": {
13945
14739
  if (!id) return;
13946
14740
  const r = this.options.storage.read().received.find((x) => x.id === id);
13947
- if (r && r.status !== "withdrawn") await this.options.storage.update((l) => this.log({
14741
+ if (r && r.status !== "withdrawn" && r.status !== "revoked") await this.options.storage.update((l) => this.log({
13948
14742
  ...l,
13949
14743
  received: l.received.map((x) => x.id === id ? {
13950
14744
  ...x,
@@ -14072,13 +14866,14 @@ var IdentityExchange = class {
14072
14866
  let reason;
14073
14867
  try {
14074
14868
  const mayReplace = (r) => r.binding.provider === binding.provider && (r.binding.subject === binding.subject || r.verified.subject === binding.subject);
14869
+ if (revokedHere(this.options.storage.read().received, id)) throw new Error(REVOKED);
14075
14870
  if (!receivedWithRoom(this.options.storage.read().received, id, mayReplace, now)) throw new Error(TOO_MANY_RECEIVED);
14076
14871
  if (JSON.stringify(evidence ?? null).length > 16384) throw new Error("Evidence too large");
14077
14872
  if (!verifyIdentityPresentation(binding.key, sig, id, scope, nonce, issuedAt)) throw new Error("The proof key did not sign this conversation's challenge");
14078
14873
  if (binding.issuedAt > now + 300) throw new Error("The proof is dated in the future");
14079
14874
  const result = boundVerifiedIdentity(await this.options.verify(statement, evidence));
14080
14875
  if (Math.min(binding.expiresAt, result.expiresAt ?? Infinity) <= now) throw new Error("The proof has expired");
14081
- if (await this.options.revoked?.(statement).catch(() => false)) throw new Error("Its owner revoked this proof");
14876
+ if (await this.options.revoked?.(statement).catch(() => false)) throw new Error(REVOKED);
14082
14877
  verified = result;
14083
14878
  } catch (e) {
14084
14879
  error = peerError(e);
@@ -14089,6 +14884,10 @@ var IdentityExchange = class {
14089
14884
  if (!challenge) throw new Error("Unknown or reused identity challenge");
14090
14885
  const challenges = l.challenges.filter((c) => c.nonce !== nonce);
14091
14886
  const subject = verified?.subject;
14887
+ if (verified && revokedHere(l.received, id)) {
14888
+ verified = void 0;
14889
+ error = reason = REVOKED;
14890
+ }
14092
14891
  const received = verified && receivedWithRoom(l.received, id, (r) => r.binding.provider === binding.provider && r.verified.subject === subject, now);
14093
14892
  if (verified && !received) {
14094
14893
  verified = void 0;
@@ -14541,17 +15340,23 @@ var CapsExchange = class {
14541
15340
  return;
14542
15341
  }
14543
15342
  if (due) {
15343
+ const options = changed || unpublished ? void 0 : { background: true };
15344
+ const held = this.options.transport.publishHeld?.(this.keys.identity.pubKeyZ32, options);
15345
+ if (held) {
15346
+ this.schedule(budgetRetryMs(held, 1e3, 6e4));
15347
+ throw held;
15348
+ }
14544
15349
  const rev = changed ? this.state.rev + 1 : this.state.rev;
14545
15350
  const { records, dropped } = this.keys.seal(content, rev, peerKey, now);
14546
15351
  this.dropped = dropped;
14547
- await this.persist({
15352
+ if (!(rev === this.state.rev && digest === this.state.digest && peerKey === this.state.sealedFor && this.state.publishedAt === void 0)) await this.persist({
14548
15353
  rev,
14549
15354
  digest,
14550
15355
  sealedFor: peerKey,
14551
15356
  publishedAt: void 0
14552
15357
  });
14553
15358
  try {
14554
- await this.options.transport.publish(this.keys.identity, records, changed || unpublished ? void 0 : { background: true });
15359
+ await this.options.transport.publish(this.keys.identity, records, options);
14555
15360
  } catch (error) {
14556
15361
  this.schedule(isDiscoveryBudgetError(error) ? budgetRetryMs(error, 1e3, 6e4) : 6e4);
14557
15362
  throw error;
@@ -14839,14 +15644,15 @@ function parseDomainTxt(value) {
14839
15644
  var addRecord = (list, r) => {
14840
15645
  if (!list.some((x) => x.key === r.key && x.proof === r.proof)) list.push(r);
14841
15646
  };
14842
- /** All records among the TXT strings of `_ghostly.<domain>`; other strings are skipped. */
15647
+ /** All records among the first 32 TXT strings of `_ghostly.<domain>`; other strings are skipped. A TXT set has
15648
+ * no order, so every record is kept: the one a proof needs may come in any position. */
14843
15649
  function recordsFromTxt(values) {
14844
15650
  const out = [];
14845
15651
  for (const value of values.slice(0, 32)) {
14846
15652
  const r = parseDomainTxt(value);
14847
15653
  if (r) addRecord(out, r);
14848
15654
  }
14849
- return out.slice(0, 8);
15655
+ return out;
14850
15656
  }
14851
15657
  /** The body of `/.well-known/ghostly.json`. */
14852
15658
  function domainWellKnownFile(records) {
@@ -14863,7 +15669,7 @@ function parseJson(text) {
14863
15669
  if (typeof text !== "string" || utf8Encode(text).length > 16384) throw new Error("File too large");
14864
15670
  return JSON.parse(text);
14865
15671
  }
14866
- /** Records from `ghostly.json`. Throws on a malformed file; [] when it names none. */
15672
+ /** Records from the first 32 entries of `ghostly.json`. Throws on a malformed file; [] when it names none. */
14867
15673
  function recordsFromWellKnown(text) {
14868
15674
  const body = parseJson(text);
14869
15675
  if (!body || typeof body !== "object" || Array.isArray(body) || body.ghostly !== 1 || !Array.isArray(body.proofs)) throw new Error("Not a Ghostly domain file");
@@ -14876,7 +15682,7 @@ function recordsFromWellKnown(text) {
14876
15682
  };
14877
15683
  if (validDomainRecord(r)) addRecord(out, r);
14878
15684
  }
14879
- return out.slice(0, 8);
15685
+ return out;
14880
15686
  }
14881
15687
  /** NIP-05: only the root name `_` speaks for the domain itself. Undefined when absent. */
14882
15688
  function nip05RootKey(text) {
@@ -15059,9 +15865,13 @@ var SIG$3 = /^[A-Za-z0-9_-]{86}$/;
15059
15865
  var MAGIC$1 = utf8Encode("GHLD");
15060
15866
  var VERSION = 1;
15061
15867
  var NONCE$2 = 24;
15868
+ /** A bundle sealed by the chat's ratchet (WISP 4xx § Held items). */
15869
+ var RATCHETED = 2;
15062
15870
  /** Why a bundle, manifest or pointer was refused. Never a reason to trust it a little. */
15063
15871
  var HoldRefusedError = class extends Error {
15064
15872
  reason;
15873
+ /** The bytes the chat's ratchet opened, when it opened them before the item was refused: the caller commits them. */
15874
+ ratcheted;
15065
15875
  constructor(reason, message) {
15066
15876
  super(message);
15067
15877
  this.reason = reason;
@@ -15101,6 +15911,19 @@ var HoldKeys = class {
15101
15911
  }
15102
15912
  /** Seals one item for the contact: signed with my participation key, encrypted to our shared key. */
15103
15913
  seal(item, body) {
15914
+ const nonce = randomBytes(NONCE$2);
15915
+ const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(this.inner(item, body));
15916
+ return concatBytes$1(MAGIC$1, new Uint8Array([VERSION]), nonce, box);
15917
+ }
15918
+ /**
15919
+ * The same item as a version-2 bundle (WISP 4xx § Held items): the same plaintext, sealed by the chat's ratchet
15920
+ * (`seal`, which saves the ratchet's state before it returns), so the bundle can be uploaded once this returns.
15921
+ */
15922
+ async sealRatcheted(item, body, seal) {
15923
+ return concatBytes$1(MAGIC$1, new Uint8Array([RATCHETED]), await seal(this.inner(item, body)));
15924
+ }
15925
+ /** What a bundle seals: the header's length, the signed header, the body. */
15926
+ inner(item, body) {
15104
15927
  const fields = [
15105
15928
  VERSION,
15106
15929
  this.from,
@@ -15120,26 +15943,51 @@ var HoldKeys = class {
15120
15943
  const header = utf8Encode(JSON.stringify([fields, signature]));
15121
15944
  const length = /* @__PURE__ */ new Uint8Array(4);
15122
15945
  new DataView(length.buffer).setUint32(0, header.length);
15123
- const nonce = randomBytes(NONCE$2);
15124
- const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(concatBytes$1(length, header, body));
15125
- return concatBytes$1(MAGIC$1, new Uint8Array([VERSION]), nonce, box);
15946
+ return concatBytes$1(length, header, body);
15126
15947
  }
15127
15948
  /**
15128
15949
  * Opens a bundle the contact sealed for me. Everything is checked before anything is returned: the
15129
15950
  * authenticated encryption, the header's shape, that it names this link, this contact and me, the
15130
15951
  * signature, the body digest and the limits of its kind. `loopback`: see `isHoldUrl`.
15131
15952
  */
15953
+ /**
15954
+ * `ratchet`: opens a version-2 bundle's sealed bytes (WISP 4xx), without keeping anything; absent, one is from a newer
15955
+ * Ghostly. `refusePlain`: a ratcheted item from this contact opened here, so a version-1 item other than the manifest is
15956
+ * refused (WISP 4xx § Downgrade). `ratcheted` in the result: the bytes the ratchet opened, for the caller to commit once
15957
+ * the item is stored.
15958
+ */
15132
15959
  open(bytes, expect = {}) {
15133
15960
  const now = expect.now ?? Date.now();
15134
15961
  if (bytes.length > (expect.maxBytes ?? HOLD_LIMITS.maxBundleBytes)) throw new HoldRefusedError("size", "The held item is larger than allowed");
15135
- 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");
15136
- if (bytes[MAGIC$1.length] !== VERSION) throw new HoldRefusedError("format", "Held item from a newer Ghostly");
15137
- let plain;
15962
+ if (bytes.length < MAGIC$1.length + 1 + 16 + 4 || !MAGIC$1.every((b, i) => bytes[i] === b)) throw new HoldRefusedError("format", "Not a held item");
15963
+ const version = bytes[MAGIC$1.length];
15964
+ if (version !== VERSION && (version !== RATCHETED || !expect.ratchet)) throw new HoldRefusedError("format", "Held item from a newer Ghostly");
15965
+ let plain, ratcheted;
15966
+ if (version === RATCHETED) {
15967
+ ratcheted = bytes.subarray(MAGIC$1.length + 1);
15968
+ try {
15969
+ plain = expect.ratchet(ratcheted);
15970
+ } catch {
15971
+ plain = null;
15972
+ }
15973
+ if (!plain) throw new HoldRefusedError("tampered", "The held item was changed, is not for this chat, or was opened already");
15974
+ } else {
15975
+ if (bytes.length < MAGIC$1.length + 1 + NONCE$2 + 16 + 4) throw new HoldRefusedError("format", "Not a held item");
15976
+ try {
15977
+ plain = xsalsa20poly1305(this.sealKey, bytes.subarray(MAGIC$1.length + 1, MAGIC$1.length + 1 + NONCE$2)).decrypt(bytes.subarray(MAGIC$1.length + 1 + NONCE$2));
15978
+ } catch {
15979
+ throw new HoldRefusedError("tampered", "The held item was changed or is not for this chat");
15980
+ }
15981
+ }
15138
15982
  try {
15139
- 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));
15140
- } catch {
15141
- throw new HoldRefusedError("tampered", "The held item was changed or is not for this chat");
15983
+ return this.read(plain, ratcheted, expect, now);
15984
+ } catch (error) {
15985
+ if (error instanceof HoldRefusedError && ratcheted) error.ratcheted = ratcheted;
15986
+ throw error;
15142
15987
  }
15988
+ }
15989
+ /** The checks of `open` once the bundle is decrypted. */
15990
+ read(plain, ratcheted, expect, now) {
15143
15991
  if (plain.length < 4) throw new HoldRefusedError("format", "Not a held item");
15144
15992
  const headerLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0);
15145
15993
  if (headerLength > 131072 || 4 + headerLength > plain.length) throw new HoldRefusedError("format", "Not a held item");
@@ -15181,10 +16029,12 @@ var HoldKeys = class {
15181
16029
  digest,
15182
16030
  expires
15183
16031
  };
16032
+ if (!ratcheted && expect.refusePlain && kind !== "manifest") throw new HoldRefusedError("plain", "The held item was sealed without forward secrecy, which this chat no longer takes");
15184
16033
  checkKind(header, body, expect.loopback);
15185
16034
  return {
15186
16035
  header,
15187
- body
16036
+ body,
16037
+ ...ratcheted && { ratcheted }
15188
16038
  };
15189
16039
  }
15190
16040
  /** My pointer, as records to publish under `identity`. Throws when it cannot fit a packet. */
@@ -15933,6 +16783,12 @@ var SessionCapabilities = class {
15933
16783
  var APP_FRAME = "paired-app";
15934
16784
  /** The largest `d`, as compact UTF-8 JSON. The session's 60 KiB cap on any frame still holds above it. */
15935
16785
  var APP_DATA_MAX_BYTES = 32768;
16786
+ /**
16787
+ * How long the peer's open apps are held when its session ends or is replaced (a transport switch, a resume, a
16788
+ * re-dial), before they are taken as closed. A new session within it says `open` again for each: the app hears that
16789
+ * open (and catches up), never a `close` in between. Past it, each still held is closed with `offline`.
16790
+ */
16791
+ var APP_RESUME_GRACE_MS = 1e4;
15936
16792
  var DOMAIN = "ghostly-apps/1";
15937
16793
  var APP_ID = /^[A-Za-z0-9_-]{22}$/;
15938
16794
  /** Semantic versioning 2.0.0, as a manifest's `version` is. */
@@ -16082,7 +16938,10 @@ var AppSessions = class {
16082
16938
  open;
16083
16939
  now;
16084
16940
  peer = /* @__PURE__ */ new Map();
16085
- /** What the peer had open on a session that ended, held for `APP_RESUME_GRACE_MS` until it says so again. */
16941
+ /**
16942
+ * What the peer had open on a session that ended, until it says so again: each with its version and the time its
16943
+ * grace ends, counted from the suspension that took it from the peer.
16944
+ */
16086
16945
  held = /* @__PURE__ */ new Map();
16087
16946
  received = new RateWindows(50, 64);
16088
16947
  sent = new RateWindows(48, 64);
@@ -16116,7 +16975,7 @@ var AppSessions = class {
16116
16975
  app,
16117
16976
  o: "close"
16118
16977
  } : null;
16119
- if (!this.peer.has(app) && this.peer.size >= 16) return null;
16978
+ if (!this.peer.has(app) && !this.held.has(app) && this.peer.size + this.held.size >= 16) return null;
16120
16979
  this.held.delete(app);
16121
16980
  this.peer.set(app, parsed.v);
16122
16981
  return {
@@ -16151,10 +17010,14 @@ var AppSessions = class {
16151
17010
  /**
16152
17011
  * The session ended or was replaced, and another may follow at once: what the peer had open is held, not closed (no
16153
17012
  * event now). Nothing is sent to a held app; an `open` on the next session takes it back, a `close` closes it, and
16154
- * `heldExpired` closes the rest once `APP_RESUME_GRACE_MS` has passed.
17013
+ * `heldExpired` closes the rest once `graceMs` has passed since the suspension that held each.
16155
17014
  */
16156
- sessionSuspended() {
16157
- for (const [app, version] of this.peer) this.held.set(app, version);
17015
+ sessionSuspended(graceMs = APP_RESUME_GRACE_MS) {
17016
+ const until = this.now() + graceMs;
17017
+ for (const [app, version] of this.peer) this.held.set(app, {
17018
+ version,
17019
+ until
17020
+ });
16158
17021
  this.peer.clear();
16159
17022
  this.received.clear();
16160
17023
  this.sent.clear();
@@ -16163,14 +17026,23 @@ var AppSessions = class {
16163
17026
  get holding() {
16164
17027
  return this.held.size > 0;
16165
17028
  }
16166
- /** The grace is over: each app still held is closed, with `offline`. */
17029
+ /** When the next held app's grace ends; undefined when none is held. */
17030
+ get heldUntil() {
17031
+ let first;
17032
+ for (const { until } of this.held.values()) if (first === void 0 || until < first) first = until;
17033
+ return first;
17034
+ }
17035
+ /** Each app held whose grace is over is closed, with `offline`; the ones held later keep theirs. */
16167
17036
  heldExpired() {
16168
- const closed = [...this.held.keys()].map((app) => ({
16169
- app,
16170
- o: "close",
16171
- offline: true
16172
- }));
16173
- this.held.clear();
17037
+ const now = this.now(), closed = [];
17038
+ for (const [app, { until }] of this.held) if (until <= now) {
17039
+ this.held.delete(app);
17040
+ closed.push({
17041
+ app,
17042
+ o: "close",
17043
+ offline: true
17044
+ });
17045
+ }
16174
17046
  return closed;
16175
17047
  }
16176
17048
  };
@@ -17291,6 +18163,12 @@ var FILE_LIMITS = {
17291
18163
  autoAcceptBytesPerPeer: 524288e3,
17292
18164
  /** Offers from one contact waiting for an answer here. */
17293
18165
  maxWaitingOffers: 16,
18166
+ /**
18167
+ * Files from one contact not finished here, whatever their state (asked about, taken and waiting their turn, paused,
18168
+ * arriving). Only bytes were counted before: offers of 0 bytes were each taken, and 2,500 of them were 2,500
18169
+ * messages and records waiting for good.
18170
+ */
18171
+ maxUnfinishedIncoming: 256,
17294
18172
  /** Files one contact sends at once; accepted ones beyond wait their turn. */
17295
18173
  maxActiveIncoming: 3,
17296
18174
  /** An offer nobody answered ends after this long. */
@@ -17342,6 +18220,15 @@ var FINAL = /* @__PURE__ */ new Set([
17342
18220
  ]);
17343
18221
  var transferEnded = (record) => FINAL.has(record.state);
17344
18222
  /**
18223
+ * Whether a file sent from here arrived whole (the receiver confirmed every byte, and may be checking it): too late
18224
+ * for its person to cancel. The receiver's check comes before a `pf-abort` behind it, so it would keep the file while
18225
+ * the sender said it was cancelled. Not once the receiver asks about it again (`asking`), nor paused here.
18226
+ */
18227
+ function sentWhole(record) {
18228
+ if (record.direction !== "out" || transferEnded(record)) return false;
18229
+ return record.state === "verifying" || record.file.size > 0 && record.confirmed === record.file.size && record.state !== "asking" && record.state !== "paused";
18230
+ }
18231
+ /**
17345
18232
  * Whether an unfinished transfer is stuck, so its person is offered to push it: "Send again" (sending) or "Ask again"
17346
18233
  * (receiving). `movedAt` is when its bytes last moved, `restored` that it has not moved since the app started. What
17347
18234
  * waits for a person (an answer, a pause) is not stuck, and a failed one has its own "Retry".
@@ -17721,6 +18608,16 @@ var ChatFiles = class {
17721
18608
  if (entry.record.direction === "out") this.announce(entry);
17722
18609
  else if (entry.record.state === "queued") this.startIncoming(entry);
17723
18610
  else if (entry.record.state === "active") this.armNudge(entry);
18611
+ else if (entry.record.state === "paused" && entry.record.pausedBy === "peer") this.send({
18612
+ t: "pf-accept",
18613
+ id: entry.record.id,
18614
+ offset: entry.in.written
18615
+ });
18616
+ else if (entry.record.state === "asking") this.send({
18617
+ t: "pf-wait",
18618
+ id: entry.record.id,
18619
+ why: "consent"
18620
+ });
17724
18621
  }
17725
18622
  }
17726
18623
  /** The session went: nothing moves until the next one. What was received is made durable. */
@@ -17742,7 +18639,11 @@ var ChatFiles = class {
17742
18639
  if (entry.in && !transferEnded(entry.record)) this.checkpoint(entry);
17743
18640
  }
17744
18641
  }
17745
- /** Offers ended by their time to live. The host calls it now and then; `attach` does too. */
18642
+ /**
18643
+ * Offers ended by their time to live. The host calls it now and then; `attach` does too. A file taken here and waiting
18644
+ * its turn ends too once nothing of it arrived in that time: its sender never sent it. Offered again, it is taken
18645
+ * again (`retakeAgreed`).
18646
+ */
17746
18647
  sweep() {
17747
18648
  const now = this.now();
17748
18649
  for (const entry of this.entries.values()) {
@@ -17752,12 +18653,15 @@ var ChatFiles = class {
17752
18653
  "offered",
17753
18654
  "asking"
17754
18655
  ].includes(record.state) || record.since + FILE_LIMITS.offerTtlMs > now) continue;
17755
- if (record.direction === "in" && record.state === "queued") continue;
18656
+ if (record.direction === "in" && record.state === "queued" && (entry.in?.starting || this.moved(entry) > 0)) continue;
17756
18657
  this.end(entry, "failed", record.direction === "in" ? "The offer expired" : record.state === "queued" ? "Not delivered in time" : "Not accepted in time");
17757
- if (record.direction === "in") this.send({
18658
+ this.send(record.direction === "in" ? {
17758
18659
  t: "pf-refuse",
17759
18660
  id: record.id,
17760
18661
  why: "expired"
18662
+ } : {
18663
+ t: "pf-abort",
18664
+ id: record.id
17761
18665
  });
17762
18666
  }
17763
18667
  }
@@ -17973,6 +18877,9 @@ var ChatFiles = class {
17973
18877
  waitingOffers() {
17974
18878
  return [...this.entries.values()].filter((e) => e.record.direction === "in" && e.record.state === "asking").length;
17975
18879
  }
18880
+ unfinishedIncoming() {
18881
+ return [...this.entries.values()].filter((e) => e.record.direction === "in" && !transferEnded(e.record)).length;
18882
+ }
17976
18883
  activeIncoming(except) {
17977
18884
  return [...this.entries.values()].filter((e) => e !== except && e.record.direction === "in" && (e.record.state === "active" || e.record.state === "verifying" || e.in?.starting)).length;
17978
18885
  }
@@ -18161,7 +19068,7 @@ var ChatFiles = class {
18161
19068
  this.startIncoming(existing);
18162
19069
  return;
18163
19070
  }
18164
- if (this.waitingOffers() >= FILE_LIMITS.maxWaitingOffers) {
19071
+ if (this.waitingOffers() >= FILE_LIMITS.maxWaitingOffers || this.unfinishedIncoming() >= FILE_LIMITS.maxUnfinishedIncoming) {
18165
19072
  this.send({
18166
19073
  t: "pf-refuse",
18167
19074
  id,
@@ -18220,6 +19127,14 @@ var ChatFiles = class {
18220
19127
  */
18221
19128
  async retakeAgreed(entry) {
18222
19129
  const { record } = entry;
19130
+ if (this.unfinishedIncoming() >= FILE_LIMITS.maxUnfinishedIncoming) {
19131
+ this.send({
19132
+ t: "pf-refuse",
19133
+ id: record.id,
19134
+ why: "too-many"
19135
+ });
19136
+ return false;
19137
+ }
18223
19138
  if (!record.consented) {
18224
19139
  let decision;
18225
19140
  try {
@@ -18484,7 +19399,8 @@ var ChatFiles = class {
18484
19399
  return;
18485
19400
  }
18486
19401
  if (!outgoing || transferEnded(outgoing.record)) {
18487
- if (outgoing?.record.state === "cancelled" && frame.t !== "pf-refuse") this.send({
19402
+ const asked = frame.t === "pf-accept" || frame.t === "pf-wait";
19403
+ if (outgoing?.record.state === "cancelled" ? frame.t !== "pf-refuse" : asked && outgoing?.record.state !== "done") this.send({
18488
19404
  t: "pf-abort",
18489
19405
  id
18490
19406
  });
@@ -18590,6 +19506,7 @@ var ChatFiles = class {
18590
19506
  if (entry.record.state !== "asking") return;
18591
19507
  entry.record.state = "queued";
18592
19508
  entry.record.consented = entry.record.agreed = true;
19509
+ entry.record.since = this.now();
18593
19510
  this.changed(entry);
18594
19511
  this.startIncoming(entry);
18595
19512
  }
@@ -18633,6 +19550,7 @@ var ChatFiles = class {
18633
19550
  if (record.state !== "paused" || record.pausedBy !== "me") return;
18634
19551
  record.pausedBy = void 0;
18635
19552
  record.state = "queued";
19553
+ if (direction === "in") record.since = this.now();
18636
19554
  this.changed(entry);
18637
19555
  if (direction === "out") {
18638
19556
  if (this.attached) this.announce(entry);
@@ -19857,7 +20775,8 @@ var PairingTracker = class {
19857
20775
  * none of these (a mint's own words, a provider's) stays as it is.
19858
20776
  *
19859
20777
  * `{name}` in a template is a value: a host or domain (no spaces), a network ("Mainnet" or "Testnet"), a chain's name,
19860
- * an ecash unit ("usd"), or an amount (digits, with the separators of whatever locale wrote it).
20778
+ * an ecash unit ("usd"), an amount (digits, with the separators of whatever locale wrote it), or a server's own `{reason}`
20779
+ * (one line, last in its text).
19861
20780
  */
19862
20781
  var ENGINE_ERRORS = {
19863
20782
  mintUnreachable: "Could not reach {host}. Check the address: it should be a Cashu mint.",
@@ -19874,13 +20793,16 @@ var ENGINE_ERRORS = {
19874
20793
  mintNotHttps: "Mints must use https",
19875
20794
  notEnoughSats: "Not enough sats in your wallet",
19876
20795
  notEnoughForFee: "Not enough sats in your wallet: {amount} sats leave room for the fee",
20796
+ mintsNoAnyAmount: "None of your mints can pay an invoice with no amount",
19877
20797
  noSharedMint: "You share no mint with this contact",
19878
20798
  ecashAlreadySpent: "This ecash was already spent somewhere else",
19879
20799
  ecashBeingReceived: "This ecash is already being received",
20800
+ ecashFeeTakesAll: "The mint keeps all {amount} sats of this ecash as its fee to take it in: nothing was redeemed, and its sender can still take it back",
19880
20801
  ecashOtherUnit: "This ecash is in {unit}: only sat ecash can be redeemed here",
19881
20802
  reviewedEcashSpent: "The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.",
19882
20803
  reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.",
19883
20804
  lightningFeeTooHigh: "The Lightning fee ({fee} sats) is too high",
20805
+ lightningRefused: "The mint refused this Lightning payment, and no sats left your wallet: it is safe to try again. The mint said: {reason}",
19884
20806
  invoiceExpired: "That invoice has expired",
19885
20807
  lnurlExactly: "{domain} asks for exactly {amount} sats",
19886
20808
  lnurlRange: "{domain} takes between {min} and {max} sats",
@@ -20149,6 +21071,13 @@ var WAKE_LOST_MS = 1e4;
20149
21071
  * then did the resume dial: a chat opened on return went live 21 s after the tap (Android emulator, 2026-10-29).
20150
21072
  */
20151
21073
  var WAKE_ANSWER_GRACE_MS = 3e3;
21074
+ function peerSaidWindow() {
21075
+ return {
21076
+ window: new RateWindow(6, 6e4),
21077
+ read: null,
21078
+ timer: null
21079
+ };
21080
+ }
20152
21081
  /**
20153
21082
  * What files/3 may hold on a session's channel (WISP 501, Backpressure): a quarter of its send budget (native and iroh
20154
21083
  * channels throw past 120 KiB), or the high water mark of a WebRTC channel, which has none.
@@ -20354,6 +21283,11 @@ var GhostLink = class {
20354
21283
  peerNickOverride = null;
20355
21284
  /** Group protocol versions the peer announced on this session; null until it does. */
20356
21285
  peerGroupVersions = null;
21286
+ /**
21287
+ * Groups were on on this session. Off again, they stay off until the next session: each "on" runs a group edge's
21288
+ * whole opening, and the peer says its versions once a session.
21289
+ */
21290
+ peerGroupsWereOn = false;
20357
21291
  /** What each side announced after the handshake (`paired-capabilities`): calls, services. */
20358
21292
  sessionCapabilities = new SessionCapabilities(() => this.offeredCapabilities());
20359
21293
  pairedCalls = new PairedCalls();
@@ -20378,20 +21312,16 @@ var GhostLink = class {
20378
21312
  editsReceived = new RateWindow(30, EDIT_RATE_WINDOW_MS);
20379
21313
  wakeReceived = new RateWindow(6, 6e4);
20380
21314
  /**
20381
- * The contact's name and picture, each saved when it changes: said once a session and when changed, so a handful a
20382
- * minute each. Past that only the newest waits, read once the window has room again.
21315
+ * The contact's name and picture, its word on held items, its ways of paying and its transport descriptors, each saved
21316
+ * on this side when it changes: said once a session and when changed, so a handful a minute each. Past that only the
21317
+ * newest waits, read once the window has room again.
20383
21318
  */
20384
21319
  peerSaid = {
20385
- "paired-nick": {
20386
- window: new RateWindow(6, 6e4),
20387
- read: null,
20388
- timer: null
20389
- },
20390
- "paired-avatar": {
20391
- window: new RateWindow(6, 6e4),
20392
- read: null,
20393
- timer: null
20394
- }
21320
+ "paired-nick": peerSaidWindow(),
21321
+ "paired-avatar": peerSaidWindow(),
21322
+ "paired-hold": peerSaidWindow(),
21323
+ "paired-payments": peerSaidWindow(),
21324
+ "paired-adapters": peerSaidWindow()
20395
21325
  };
20396
21326
  /** Identity-proof frames the contact may send per window; the rest are dropped before they are read. */
20397
21327
  identityReceived = new RateWindow(40, IDENTITY_FRAME_WINDOW_MS);
@@ -20607,6 +21537,7 @@ var GhostLink = class {
20607
21537
  peerCapsRev: options.dht.peerCapsRev,
20608
21538
  peerAcceptsText: options.dht.peerAcceptsText,
20609
21539
  peerAcceptsFile: options.dht.peerAcceptsFile,
21540
+ ...options.dht.ratchet && { ratchet: options.dht.ratchet },
20610
21541
  ...options.reactionsSupport && {
20611
21542
  reactions: options.dht.reactions,
20612
21543
  reaction: async (reaction) => {
@@ -20696,6 +21627,7 @@ var GhostLink = class {
20696
21627
  pollIntervals: options.pollIntervals,
20697
21628
  awaitingSince: options.madeAt,
20698
21629
  ...backsOff && { invite: () => !options.pairing.credentials.peerKey || !!this.dht?.unanswered },
21630
+ ...invite && { ownInvite: () => !options.pairing.credentials.peerKey && !options.pairing.credentials.expectedPeerKey },
20699
21631
  getServices: options.getServices,
20700
21632
  firstPublish: options.firstPublish ?? (this.tracker && options.pairingProgress?.role === "joiner" && options.rtcAvailable !== false || this.resuming ? "after-first-poll" : "at-start"),
20701
21633
  resumed: !!this.resuming,
@@ -22541,6 +23473,10 @@ var GhostLink = class {
22541
23473
  get liveAttempt() {
22542
23474
  return this.isDataLinkOpen ? void 0 : this.lastAttempt;
22543
23475
  }
23476
+ /** Automatic dials since the link was last live or its wait started over (`wake`), the one under way included. */
23477
+ get dialAttempts() {
23478
+ return this.autoConnectFailures;
23479
+ }
22544
23480
  /**
22545
23481
  * Which side dials this chat to go live: the lower rendezvous key, or the joiner of a first pairing (WISP 100). The
22546
23482
  * other side answers, so what it can tell of a failed attempt is only what reached it.
@@ -23499,16 +24435,27 @@ var GhostLink = class {
23499
24435
  /**
23500
24436
  * The session ended or a new one took its place (a transport switch, a resume, a re-dial): what the contact had open
23501
24437
  * is held for `APP_RESUME_GRACE_MS` (WISP 1200 § In a chat). The next session's `open` takes each back, and the app
23502
- * hears only that open, not a close first; one not said again by then is closed with `offline`.
24438
+ * hears only that open, not a close first; one not said again by then is closed with `offline`. Each suspension
24439
+ * gives what it held its own grace: a later one's apps do not close at an earlier one's time.
23503
24440
  */
23504
24441
  appsSuspended() {
23505
24442
  this.appRanges.reset();
23506
- this.apps.sessionSuspended();
23507
- if (!this.apps.holding || this.appsGrace) return;
24443
+ this.apps.sessionSuspended(this.options.appResumeGraceMs ?? 1e4);
24444
+ this.armAppsGrace();
24445
+ }
24446
+ /** A timer for the next held app's grace, as long as any is held. */
24447
+ armAppsGrace() {
24448
+ if (this.appsGrace) {
24449
+ clearTimeout(this.appsGrace);
24450
+ this.appsGrace = null;
24451
+ }
24452
+ const until = this.apps.heldUntil;
24453
+ if (until === void 0) return;
23508
24454
  this.appsGrace = setTimeout(() => {
23509
24455
  this.appsGrace = null;
23510
24456
  for (const event of this.apps.heldExpired()) this.options.events?.onAppFrame?.(event);
23511
- }, this.options.appResumeGraceMs ?? 1e4);
24457
+ this.armAppsGrace();
24458
+ }, Math.max(0, until - Date.now()));
23512
24459
  }
23513
24460
  /** Whether files/3 was agreed on the session open now; kept to say when that changes. */
23514
24461
  filesOpen = false;
@@ -24147,6 +25094,7 @@ var GhostLink = class {
24147
25094
  if (oldChannel) this.retire(oldChannel, () => {
24148
25095
  if (oldRtc && this.activeBinding && this.dataLink.connection === oldRtc) this.dataLink.close();
24149
25096
  }, !oldBinding);
25097
+ if (migration.plan && binding && oldBinding && WEBRTC_ATTEMPT.has(this.dataLink.state)) this.dataLink.close();
24150
25098
  this.session.setDataLinkOpen(true);
24151
25099
  if (migration.plan) switched = {
24152
25100
  from,
@@ -24181,6 +25129,7 @@ var GhostLink = class {
24181
25129
  this.peerNetworks = null;
24182
25130
  this.peerHoldOverride = null;
24183
25131
  this.sessionCapabilities.reset();
25132
+ this.peerGroupsWereOn = false;
24184
25133
  this.leaveHangUp();
24185
25134
  this.typingSender.reset();
24186
25135
  this.typingReceiver.clear();
@@ -24359,7 +25308,7 @@ var GhostLink = class {
24359
25308
  return;
24360
25309
  }
24361
25310
  if (frame?.t === "paired-avatar" || frame?.t === "paired-nick") {
24362
- this.peerSays(channel, frame.t, frame);
25311
+ this.peerSaysOfItself(channel, frame.t, frame);
24363
25312
  return;
24364
25313
  }
24365
25314
  if (frame?.t === "paired-capabilities") {
@@ -24451,15 +25400,21 @@ var GhostLink = class {
24451
25400
  }
24452
25401
  if (frame?.t === "paired-payments") {
24453
25402
  if (!Array.isArray(frame.m) || frame.m.length > 16 || !frame.m.every((m) => typeof m === "string")) return;
24454
- this.peerPaymentMethods = new Set(frame.m.filter((m) => PAYMENT_METHODS.includes(m)));
24455
- this.peerNetworks = frame.n === void 0 ? null : parsePaymentNetworks(frame.n) ?? this.peerNetworks;
24456
- this.emitPairingState();
25403
+ const methods = new Set(frame.m.filter((m) => PAYMENT_METHODS.includes(m)));
25404
+ const networks = frame.n === void 0 ? null : parsePaymentNetworks(frame.n);
25405
+ this.peerSays(channel, "paired-payments", () => {
25406
+ this.peerPaymentMethods = methods;
25407
+ this.peerNetworks = frame.n === void 0 ? null : networks ?? this.peerNetworks;
25408
+ this.emitPairingState();
25409
+ });
24457
25410
  return;
24458
25411
  }
24459
25412
  if (frame?.t === "paired-groups") {
24460
25413
  if (!Array.isArray(frame.v) || frame.v.length > 8 || !frame.v.every((v) => Number.isSafeInteger(v) && v > 0)) return;
24461
25414
  const before = this.groupsSupport;
25415
+ if (!before && this.peerGroupsWereOn && frame.v.includes(1)) return;
24462
25416
  this.peerGroupVersions = frame.v;
25417
+ if (this.groupsSupport) this.peerGroupsWereOn = true;
24463
25418
  if (this.groupsSupport !== before) this.options.events?.onGroupsSupport?.(this.groupsSupport);
24464
25419
  return;
24465
25420
  }
@@ -24476,12 +25431,15 @@ var GhostLink = class {
24476
25431
  }
24477
25432
  if (frame?.t === "paired-hold") {
24478
25433
  if (typeof frame.on !== "boolean" || frame.top !== void 0 && !(Number.isSafeInteger(frame.top) && frame.top >= 0)) return;
24479
- this.peerHoldOverride = frame.on;
24480
- Promise.resolve(this.options.events?.onHold?.({
24481
- peerAllows: frame.on,
24482
- peerTop: frame.top
24483
- })).catch(() => {});
24484
- this.emitPairingState();
25434
+ const on = frame.on, top = frame.top;
25435
+ this.peerSays(channel, "paired-hold", () => {
25436
+ this.peerHoldOverride = on;
25437
+ Promise.resolve(this.options.events?.onHold?.({
25438
+ peerAllows: on,
25439
+ peerTop: top
25440
+ })).catch(() => {});
25441
+ this.emitPairingState();
25442
+ });
24485
25443
  return;
24486
25444
  }
24487
25445
  if (frame?.t === "paired-reconnect") {
@@ -24496,12 +25454,14 @@ var GhostLink = class {
24496
25454
  if (frame?.t === "paired-adapters") {
24497
25455
  if (!frame.descriptors || typeof frame.descriptors !== "object" || JSON.stringify(frame.descriptors).length > 4096) return;
24498
25456
  const descriptors = checkedDescriptors(frame.descriptors);
24499
- const transports = [...this.paired?.peerTransports ?? []];
24500
- const fallback = this.paired?.peerAllowsFallback ?? false;
24501
- await this.options.events?.onTransportDiscovery?.(descriptors, transports, fallback);
24502
- this.peerDescriptors = descriptors;
24503
- this.peerTransports = transports;
24504
- this.peerFallback = fallback;
25457
+ await this.peerSays(channel, "paired-adapters", async () => {
25458
+ const transports = [...this.paired?.peerTransports ?? []];
25459
+ const fallback = this.paired?.peerAllowsFallback ?? false;
25460
+ await this.options.events?.onTransportDiscovery?.(descriptors, transports, fallback);
25461
+ this.peerDescriptors = descriptors;
25462
+ this.peerTransports = transports;
25463
+ this.peerFallback = fallback;
25464
+ });
24505
25465
  return;
24506
25466
  }
24507
25467
  if (!frame || typeof frame.id !== "string" || !/^[A-Za-z0-9_-]{22}$/.test(frame.id)) return;
@@ -24860,11 +25820,8 @@ var GhostLink = class {
24860
25820
  traceLink(this.myPubKeyZ32, "wake-answer-dropped", {});
24861
25821
  this.dataLink.abandon();
24862
25822
  }
24863
- /**
24864
- * A name or picture the contact said, once it is one (reading it costs little; saving it is what counts): past the
24865
- * window the newest waits for room on this session, so the last word still counts.
24866
- */
24867
- peerSays(channel, kind, frame) {
25823
+ /** A name or picture the contact said, once it is one (reading it costs little; saving it is what counts). */
25824
+ peerSaysOfItself(channel, kind, frame) {
24868
25825
  let read;
24869
25826
  if (kind === "paired-avatar") {
24870
25827
  const avatar = sanitizeAvatar(frame.a);
@@ -24880,11 +25837,15 @@ var GhostLink = class {
24880
25837
  }
24881
25838
  };
24882
25839
  }
25840
+ this.peerSays(channel, kind, read);
25841
+ }
25842
+ /**
25843
+ * Something the contact said that this side saves, read within its window: past it the newest waits for room on this
25844
+ * session (handed on unawaited then), so the last word still counts. What `read` returns when read at once is returned.
25845
+ */
25846
+ peerSays(channel, kind, read) {
24883
25847
  const held = this.peerSaid[kind];
24884
- if (!held.timer && held.window.take()) {
24885
- read();
24886
- return;
24887
- }
25848
+ if (!held.timer && held.window.take()) return read();
24888
25849
  held.read = read;
24889
25850
  if (held.timer) return;
24890
25851
  const due = () => {
@@ -24899,7 +25860,7 @@ var GhostLink = class {
24899
25860
  }
24900
25861
  const next = held.read;
24901
25862
  held.read = null;
24902
- next();
25863
+ Promise.resolve(next()).catch(() => {});
24903
25864
  };
24904
25865
  held.timer = setTimeout(due, held.window.wait());
24905
25866
  }
@@ -24960,6 +25921,7 @@ var GhostLink = class {
24960
25921
  this.typingReceiver.clear();
24961
25922
  this.appsSuspended();
24962
25923
  this.emitFilesSession();
25924
+ this.peerGroupsWereOn = false;
24963
25925
  if (this.peerGroupVersions) {
24964
25926
  this.peerGroupVersions = null;
24965
25927
  this.options.events?.onGroupsSupport?.(false);
@@ -26319,7 +27281,7 @@ function decodeDidDhtPacket(did, dnsPacket) {
26319
27281
  const alg = props.get("a") ?? KEY_TYPES[type].alg;
26320
27282
  if (!ALG.test(alg)) throw malformed(`the key ${alias} has an unusable algorithm`);
26321
27283
  const k = props.get("k") ?? "";
26322
- const bytes = /^[A-Za-z0-9_-]+$/.test(k) ? fromBase64Url(k) : /* @__PURE__ */ new Uint8Array();
27284
+ const bytes = /^[A-Za-z0-9_-]+$/.test(k) && k.length % 4 !== 1 ? fromBase64Url(k) : /* @__PURE__ */ new Uint8Array();
26323
27285
  if (bytes.length === 0 || toBase64Url(bytes) !== k) throw malformed(`the key ${alias} is not unpadded base64url`);
26324
27286
  const controller = props.get("c") ?? did;
26325
27287
  if (!DID.test(controller)) throw malformed(`the key ${alias} has a controller that is not a DID`);
@@ -26592,6 +27554,11 @@ function parseWeb(id) {
26592
27554
  path
26593
27555
  };
26594
27556
  }
27557
+ /**
27558
+ * A did:web (or one of its URLs) with the port's `%3a` written `%3A`, as `parseDid` writes it: percent-encoding is
27559
+ * case-insensitive (RFC 3986), so a document may write either. The fragment is left as it is.
27560
+ */
27561
+ var webPortForm = (value) => value.startsWith("did:web:") ? value.replace(/^[^#]*/, (part) => part.replace(/%3a/g, "%3A")) : value;
26595
27562
  var web = (did) => {
26596
27563
  const parsed = parseDid(did);
26597
27564
  if (parsed.method !== "web") throw new DidError("Not a did:web");
@@ -26628,7 +27595,7 @@ function didWebFileNames(text, did, statement) {
26628
27595
  } catch {
26629
27596
  return false;
26630
27597
  }
26631
- return isObject$3(body) && body.ghostly === 1 && body.did === did && body.statement === statement;
27598
+ return isObject$3(body) && body.ghostly === 1 && typeof body.did === "string" && webPortForm(body.did) === did && body.statement === statement;
26632
27599
  }
26633
27600
  /** The service entry a did.json can carry instead of the file. */
26634
27601
  function didGhostlyServiceEntry(did, key, proofId) {
@@ -26780,7 +27747,7 @@ function staticDidDocument(did) {
26780
27747
  /** An id as absolute `<did>#<fragment>`, from `#frag` or the absolute form; undefined for another DID's. */
26781
27748
  function methodId(did, id) {
26782
27749
  if (typeof id !== "string" || id.length > 640) return void 0;
26783
- const absolute = id.startsWith("#") ? `${did}${id}` : id;
27750
+ const absolute = id.startsWith("#") ? `${did}${id}` : webPortForm(id);
26784
27751
  return absolute.startsWith(`${did}#`) && absolute.length > did.length + 1 && /^[\x21-\x7e]+$/.test(absolute) ? absolute : void 0;
26785
27752
  }
26786
27753
  /** Key material of one verification method: `publicKeyJwk`, `publicKeyMultibase` or (Ed25519 2018) `publicKeyBase58`. */
@@ -26819,7 +27786,7 @@ var list = (value, name) => {
26819
27786
  */
26820
27787
  function parseDidDocument(did, raw) {
26821
27788
  if (!isObject$3(raw)) throw new DidError("The DID document is not a JSON object");
26822
- if (raw.id !== did) throw new DidError(typeof raw.id === "string" ? `The DID document is for another DID (${raw.id.slice(0, 80)})` : "The DID document has no id");
27789
+ if (typeof raw.id !== "string" || webPortForm(raw.id) !== did) throw new DidError(typeof raw.id === "string" ? `The DID document is for another DID (${raw.id.slice(0, 80)})` : "The DID document has no id");
26823
27790
  const keys = /* @__PURE__ */ new Map();
26824
27791
  const unusable = /* @__PURE__ */ new Set();
26825
27792
  let skipped = 0;
@@ -26973,14 +27940,19 @@ function checkDidJws(input, messages, doc) {
26973
27940
  inputs = [];
26974
27941
  }
26975
27942
  if (!inputs.length) throw new DidError("The JWS carries another text: sign exactly the statement shown");
27943
+ let refused;
26976
27944
  for (const key of candidates) {
26977
27945
  if (!inputs.some((m) => verifyWith(key, jws.signature, m))) continue;
26978
- if (!key.relationships.length) throw refusedKey(key);
27946
+ if (!key.relationships.length) {
27947
+ refused ??= key;
27948
+ continue;
27949
+ }
26979
27950
  return {
26980
27951
  key,
26981
27952
  alg: jws.alg
26982
27953
  };
26983
27954
  }
27955
+ if (refused) throw refusedKey(refused);
26984
27956
  throw new DidError("The JWS signature does not match: sign exactly the statement shown, with a key of this DID");
26985
27957
  }
26986
27958
  /**
@@ -26998,10 +27970,14 @@ function checkDidSignature(signature, messages, doc, vm) {
26998
27970
  }
26999
27971
  const der = signature.length !== 64 && signature[0] === 48;
27000
27972
  if (signature.length !== 64 && !der) throw new DidError("A signature is 64 bytes (or DER, for ECDSA)");
27973
+ let refused;
27001
27974
  for (const key of candidates) {
27002
27975
  if (der && key.curve === "Ed25519") continue;
27003
27976
  if (!messages.some((m) => verifyWith(key, signature, m, der ? "der" : "compact"))) continue;
27004
- if (!key.relationships.length) throw refusedKey(key);
27977
+ if (!key.relationships.length) {
27978
+ refused ??= key;
27979
+ continue;
27980
+ }
27005
27981
  const canonical = der ? (key.curve === "secp256k1" ? secp256k1 : p256).Signature.fromBytes(signature, "der").toBytes("compact") : signature;
27006
27982
  return {
27007
27983
  key,
@@ -27009,6 +27985,7 @@ function checkDidSignature(signature, messages, doc, vm) {
27009
27985
  signature: canonical
27010
27986
  };
27011
27987
  }
27988
+ if (refused) throw refusedKey(refused);
27012
27989
  throw new DidError("The signature does not match: sign exactly the statement shown, with a key of this DID");
27013
27990
  }
27014
27991
  function parseDidSignaturePaste(pasted) {
@@ -29217,6 +30194,8 @@ function readFirstPlace(o, epoch) {
29217
30194
  var ownKey = (f) => `${f.e}:${f.n}`;
29218
30195
  /** What a frame weighs in a log, roughly: its boxes plus the fixed fields around them. */
29219
30196
  var frameKey$1 = (f) => `${f.s}:${f.e}:${f.n}`;
30197
+ /** One edit of a message, by its number: an edit handed already, apart from the message's own `frameKey`. */
30198
+ var editKey = (f) => `${f.s}:${f.e}:${f.n}:v${f.v}`;
29220
30199
  /** What a kept frame counts for against `GROUP_LIMITS.relayBytes`. */
29221
30200
  var frameBytes = (f) => f.c.length + (f.m?.c.length ?? 0) + (f.r?.c.length ?? 0) + (f.sc?.c.length ?? 0) + (f.fl?.c.length ?? 0) + (f.nk?.c.length ?? 0) + 400;
29222
30201
  /** Only the fields an edit frame has, as `clean` does for a message. */
@@ -29401,9 +30380,9 @@ var GroupSession = class {
29401
30380
  }
29402
30381
  this.answers = new CatchUpAnswers({
29403
30382
  send: (to, frame) => {
29404
- if (frame.t === "group-msg" && !rosterHas(this.roster, frame.s)) {
30383
+ if ((frame.t === "group-msg" || frame.t === "group-edit") && !rosterHas(this.roster, frame.s)) {
29405
30384
  const handed = this.leaversHanded.get(to) ?? /* @__PURE__ */ new Set();
29406
- this.leaversHanded.set(to, handed.add(frameKey$1(frame)));
30385
+ this.leaversHanded.set(to, handed.add(frame.t === "group-edit" ? editKey(frame) : frameKey$1(frame)));
29407
30386
  }
29408
30387
  return hooks.send(to, frame);
29409
30388
  },
@@ -29880,7 +30859,18 @@ var GroupSession = class {
29880
30859
  if (this.state.relay?.length) this.state.relay = prune(this.state.relay, false);
29881
30860
  if (this.onRows?.length) this.onRows = prune(this.onRows, true);
29882
30861
  this.pruned.splice(0, this.pruned.length - GROUP_LIMITS.relay);
29883
- if (this.state.relayEdits?.length) this.state.relayEdits = this.state.relayEdits.filter((f) => rosterHas(this.roster, f.s));
30862
+ if (this.state.relayEdits?.length) this.state.relayEdits = this.state.relayEdits.filter((f) => rosterHas(this.roster, f.s) || this.isRemovalEdit(f));
30863
+ }
30864
+ /** Whether a kept edit is a removal (WISP 400 § Delete for everyone): its box, under its epoch's key, says `rm`. */
30865
+ isRemovalEdit(frame) {
30866
+ const secret = this.secret(frame.e);
30867
+ const plain = secret && decryptText(epochKeys(secret, this.id, frame.e).message, editAad(frame), frame.nn, frame.c);
30868
+ if (!plain) return false;
30869
+ try {
30870
+ return JSON.parse(plain)?.rm === true;
30871
+ } catch {
30872
+ return false;
30873
+ }
29884
30874
  }
29885
30875
  /** The frames `pruneRelay` dropped that are handed on again now (a removal's `left` mark came after it), back in their logs. */
29886
30876
  unprune() {
@@ -30567,11 +31557,14 @@ var GroupSession = class {
30567
31557
  /**
30568
31558
  * An edit of a member's own message, from its author's edge or handed on by another member: believed only while its
30569
31559
  * author is still in the roster (someone removed edits nothing), and the member handing it on too; for an epoch the
30570
- * author and I were both members of, with the author's signature over the whole frame and a box that opens. One for
30571
- * an epoch or a secret not here yet waits, as a message does. Taken, it is kept to hand on in turn.
31560
+ * author and I were both members of, with the author's signature over the whole frame and a box that opens. A removal
31561
+ * of an author out of the roster still stands, handed on by a member: it only takes away what the author wrote while
31562
+ * in, and a member away when it was said would keep the message for good. One for an epoch or a secret not here yet
31563
+ * waits, as a message does. Taken, it is kept to hand on in turn.
30572
31564
  */
30573
31565
  async receiveEdit(from, raw) {
30574
- if (!isEditFrame(raw) || raw.s === this.myKey || !rosterHas(this.roster, raw.s) || !rosterHas(this.roster, from)) return;
31566
+ if (!isEditFrame(raw) || raw.s === this.myKey || !rosterHas(this.roster, from)) return;
31567
+ const member = rosterHas(this.roster, raw.s);
30575
31568
  if (!verify(fromBase64Url(raw.sig), editSigned(raw), publicKeyFromZ32(raw.s))) return;
30576
31569
  if (raw.e > this.epoch) {
30577
31570
  this.parkEdit(from, raw);
@@ -30595,6 +31588,7 @@ var GroupSession = class {
30595
31588
  if (!body || typeof body !== "object" || !validEditText(body.text)) return;
30596
31589
  if (body.rm !== void 0 && body.rm !== true) return;
30597
31590
  const rm = body.rm === true;
31591
+ if (!member && !rm) return;
30598
31592
  if (!rm && !cardEditNumber(raw.v)) return;
30599
31593
  const k = rm ? [] : validMentions(body.m, body.text, rosterAdmin(commit.m) === raw.s && this.admin === raw.s);
30600
31594
  const sc = rm || body.sc === void 0 ? void 0 : readStatusCard(body.sc);
@@ -30755,7 +31749,7 @@ var GroupSession = class {
30755
31749
  if (e <= this.epoch) {
30756
31750
  const known = this.state.chain[e];
30757
31751
  const result = verifyCommit(raw, this.state.chain[e - 1] ?? null, this.id);
30758
- if ("error" in result || result.commit.by !== known.by) return;
31752
+ if ("error" in result || result.commit.by !== known.by || result.commit.by !== this.admin) return;
30759
31753
  if (commitHash(result.commit) !== commitHash(known)) await this.fork(`Member ${from.slice(0, 8)} holds a different membership history for epoch ${e}`);
30760
31754
  else if (this.takeLeftMark(known, frame.left)) {
30761
31755
  this.unprune();
@@ -30913,10 +31907,13 @@ var GroupSession = class {
30913
31907
  while (metas.length && metas[0].ts < f.ts) answer.push(metas.shift().frame);
30914
31908
  answer.push(f);
30915
31909
  }
31910
+ const readable = (f) => !!this.state.chain[f.e] && rosterHas(this.state.chain[f.e].m, from);
30916
31911
  for (const author of asked) {
30917
- const edits = (this.state.relayEdits ?? []).filter((f) => f.s === author && this.state.chain[f.e] && rosterHas(this.state.chain[f.e].m, from));
31912
+ const edits = (this.state.relayEdits ?? []).filter((f) => f.s === author && readable(f));
30918
31913
  answer.push(...edits.slice(-GROUP_LIMITS.handOnEdits));
30919
31914
  }
31915
+ const gone = (this.state.relayEdits ?? []).filter((f) => !rosterHas(this.roster, f.s) && readable(f) && !handed?.has(editKey(f)));
31916
+ answer.push(...gone.slice(-GROUP_LIMITS.handOnEdits));
30920
31917
  answer.push(...metas.map((m) => m.frame));
30921
31918
  this.handOut(from, answer);
30922
31919
  }
@@ -31286,8 +32283,9 @@ function entryParams(link, mySeed, myZ32, peerZ32) {
31286
32283
  * only a newcomer is sent it; `leave`, `remove` and `rotate` get a fresh secret sealed to everyone;
31287
32284
  * - concurrent commits are a race with a deterministic winner, not a fork: the branch that keeps the
31288
32285
  * admin's changes (remove, role, rotate, link) since the common parent, then the longest, then the
31289
- * lowest hash of the first commit after the common parent. The admin signing changes on two
31290
- * branches (after the same commit or not) is still a fork and halts the group;
32286
+ * lowest hash of the first commit after the common parent. The admin of the tip signing changes on
32287
+ * two branches (after the same commit or not) is still a fork and halts the group; a former admin
32288
+ * doing so on a branch from before its hand-over is refused, as a stale branch;
31291
32289
  * - messages name the commit of their epoch, so messages under a commit that lost stay readable;
31292
32290
  * every member keeps recent frames from everyone and re-sends them to whoever was away.
31293
32291
  *
@@ -31342,6 +32340,15 @@ var COMMUNITY_LIMITS = {
31342
32340
  syncAnswers: 16,
31343
32341
  syncWindowMs: 6e4,
31344
32342
  /**
32343
+ * Messages of one member taken per `messageWindowMs`, and the bytes of their sealed bodies, past what one catch-up
32344
+ * answer holds (a whole store, and the lasting frames): anyone with the link is a member, and each message taken is a
32345
+ * row in every member's app and a frame each hub passes on. The rest are not taken now and come again in a catch-up
32346
+ * (`MessagePace`).
32347
+ */
32348
+ messagesPerAuthor: 30,
32349
+ messageBytesPerAuthor: 131072,
32350
+ messageWindowMs: 1e4,
32351
+ /**
31345
32352
  * Frames of one catch-up answer in a slice (`CommunitySessionHooks.handled`), two slices at most not handled yet by
31346
32353
  * the member's app: a member back after the store filled was handed 258 at once, and an app holds 64 waiting at most
31347
32354
  * before 2026-10-07 (more ends the session). As a private group's (`GROUP_LIMITS.catchUpSlice`).
@@ -31547,7 +32554,7 @@ function communityRoster(previous, c, trusted = false) {
31547
32554
  /**
31548
32555
  * One commit against its parent (null for a genesis) and the parent's roster: shape, id, link,
31549
32556
  * authority, roster arithmetic, roster hash and signature. The confirmation tag is checked once
31550
- * the secret is known. `before`: the commits before it on its branch, newest first; given, a `leave` is held to the
32557
+ * the secret is known (a derived kind's on arrival, by a member holding the parent's: `receiveCommit`). `before`: the commits before it on its branch, newest first; given, a `leave` is held to the
31551
32558
  * admission it ends (`leaveStands`). A member gives it for every commit it takes in after its own admission; the chain
31552
32559
  * of a welcome is not held to it (`verifyCommunityChain`).
31553
32560
  */
@@ -31649,6 +32656,56 @@ var messageSigned = (f) => utf8Encode(JSON.stringify([
31649
32656
  ]));
31650
32657
  var communityMessageId = (sender, epoch, h, seq) => `${sender}:${epoch}:${h}:${seq}`;
31651
32658
  var seenKey = (e, h) => `${e}:${h}`;
32659
+ /**
32660
+ * One member's messages taken: a whole catch-up answer at once (`MESSAGE_BURST`), then
32661
+ * `COMMUNITY_LIMITS.messagesPerAuthor` and `messageBytesPerAuthor` per `messageWindowMs`. One not taken is not marked
32662
+ * seen, so a catch-up hands it again; until it is taken, those after it under the same commit (`seenKey`) are not taken
32663
+ * either: a later one taken would say I have everything up to it (`syncFrame`'s `have`) and the one before would never
32664
+ * be handed again. A place that moves no more for `COMMUNITY_LIMITS.pendingMs` (no catch-up holds it any longer) is let go.
32665
+ */
32666
+ var MESSAGE_BURST = {
32667
+ frames: COMMUNITY_LIMITS.store + COMMUNITY_LIMITS.lasting,
32668
+ bytes: COMMUNITY_LIMITS.storeBytes + COMMUNITY_LIMITS.lasting * COMMUNITY_LIMITS.textBytes * 2
32669
+ };
32670
+ var MessagePace = class {
32671
+ frames = MESSAGE_BURST.frames;
32672
+ bytes = MESSAGE_BURST.bytes;
32673
+ at;
32674
+ held = /* @__PURE__ */ new Map();
32675
+ take(key, n, bytes, now) {
32676
+ let held = this.held.get(key);
32677
+ if (held && now - held.at >= COMMUNITY_LIMITS.pendingMs) {
32678
+ this.held.delete(key);
32679
+ held = void 0;
32680
+ }
32681
+ if (held && n > held.low) {
32682
+ held.top = Math.max(held.top, n);
32683
+ return false;
32684
+ }
32685
+ const elapsed = Math.max(0, now - (this.at ?? now)) / COMMUNITY_LIMITS.messageWindowMs;
32686
+ this.at = now;
32687
+ this.frames = Math.min(MESSAGE_BURST.frames, this.frames + elapsed * COMMUNITY_LIMITS.messagesPerAuthor);
32688
+ this.bytes = Math.min(MESSAGE_BURST.bytes, this.bytes + elapsed * COMMUNITY_LIMITS.messageBytesPerAuthor);
32689
+ if (this.frames < 1 || this.bytes < bytes) {
32690
+ if (held) held.low = n;
32691
+ else this.held.set(key, {
32692
+ low: n,
32693
+ top: n,
32694
+ at: now
32695
+ });
32696
+ return false;
32697
+ }
32698
+ this.frames -= 1;
32699
+ this.bytes -= bytes;
32700
+ if (held && n === held.low) {
32701
+ if (held.top > n) {
32702
+ held.low = n + 1;
32703
+ held.at = now;
32704
+ } else this.held.delete(key);
32705
+ }
32706
+ return true;
32707
+ }
32708
+ };
31652
32709
  /** One of a member's frames, among its own. */
31653
32710
  var frameKey = (f) => `${f.e}:${f.h}:${f.n}`;
31654
32711
  /** A frame among everyone's: each member counts its own `n`, so `frameKey` alone tells only one member's frames apart. */
@@ -31732,6 +32789,8 @@ var CommunitySession = class {
31732
32789
  asked = /* @__PURE__ */ new Map();
31733
32790
  /** Syncs answered per member, a few a minute (`COMMUNITY_LIMITS.syncAnswers`). In memory only. */
31734
32791
  syncsAnswered = /* @__PURE__ */ new Map();
32792
+ /** Messages taken per author, a few a second (`MessagePace`). In memory only. */
32793
+ messagePace = /* @__PURE__ */ new Map();
31735
32794
  /** The entry seed sealed to each member, for the seed it seals (`entryFrame`): every sync answer carries it. In memory only. */
31736
32795
  sealedEntries = /* @__PURE__ */ new Map();
31737
32796
  /** Catch-up answers still going out, a slice at a time (`receiveSync`). */
@@ -31930,6 +32989,18 @@ var CommunitySession = class {
31930
32989
  get entryKey() {
31931
32990
  return this.state.entry.key;
31932
32991
  }
32992
+ /**
32993
+ * The entry key of the link my admission that lost was let in by (the one its branch named), where I ask again: a
32994
+ * link replaced since keeps me out as it does anyone. `entryKey` once that admission is no longer held.
32995
+ */
32996
+ get lostEntryKey() {
32997
+ const side = this.state.side;
32998
+ for (let i = side.length - 1; i >= 0; i--) if (side[i].k === "add" && side[i].s === this.myKey) {
32999
+ for (const c of this.ancestry(side[i].p)) if (c.x !== void 0) return c.x;
33000
+ return "";
33001
+ }
33002
+ return this.entryKey;
33003
+ }
31933
33004
  role(key) {
31934
33005
  return this.roster.find(([k]) => k === key)?.[1];
31935
33006
  }
@@ -31937,10 +33008,62 @@ var CommunitySession = class {
31937
33008
  get picture() {
31938
33009
  return groupMetaPicture(this.state.meta);
31939
33010
  }
31940
- /** Members of any epoch in the window: whom a frame may come from. */
33011
+ /**
33012
+ * Members of any epoch in the window: whom a frame may come from. A side commit's roster counts only while its branch
33013
+ * could still win (`mayWin`): one let in only on a branch that lost is not in the roster anyone sees, and the main
33014
+ * branch past where they part, a later link among it, is not its business (`lostAt`).
33015
+ */
31941
33016
  isRecentMember(key) {
31942
- for (const roster of this.rosters.values()) if (rosterHas(roster, key)) return true;
31943
- return false;
33017
+ let side = false;
33018
+ for (const [h, roster] of this.rosters) if (rosterHas(roster, key)) {
33019
+ if (this.mainIndex.has(h)) return true;
33020
+ side = true;
33021
+ }
33022
+ return side && [...this.mayWin()].some((h) => rosterHas(this.rosters.get(h) ?? [], key));
33023
+ }
33024
+ /**
33025
+ * The side commits whose branch could still win: it does not drop an admin change the main branch holds (one that
33026
+ * does never wins, see `better`), and it parts within the window. Kept until the tip or the side moves.
33027
+ */
33028
+ mayWin() {
33029
+ const side = this.state.side, at = `${this.topHash}:${side.length}:${side.length ? communityCommitHash(side[side.length - 1]) : ""}`;
33030
+ if (this.winning?.at === at) return this.winning.set;
33031
+ const counts = this.adminCounts(), main = this.branch(this.topHash), set = /* @__PURE__ */ new Set();
33032
+ for (const c of side) {
33033
+ const h = communityCommitHash(c), branch = this.rosters.has(h) ? this.branch(h) : null;
33034
+ if (!branch || !branch.path.length) continue;
33035
+ const { parent, admin } = this.parting(branch, main, counts);
33036
+ if (!(admin[1] && !admin[0]) && parent >= this.epoch - COMMUNITY_LIMITS.window) set.add(h);
33037
+ }
33038
+ this.winning = {
33039
+ at,
33040
+ set
33041
+ };
33042
+ return set;
33043
+ }
33044
+ winning;
33045
+ /**
33046
+ * For a key that is no recent member, let in on a branch that lost: the main-branch index it parts from, and that of
33047
+ * the commit that makes it lose (the latest over its branches). Undefined for anyone else.
33048
+ */
33049
+ lostAt(key) {
33050
+ const side = this.state.side, parents = new Set(side.map((c) => c.p)), counts = this.adminCounts();
33051
+ let lost;
33052
+ for (const c of side) {
33053
+ const h = communityCommitHash(c);
33054
+ if (parents.has(h)) continue;
33055
+ const branch = this.branch(h);
33056
+ if (!branch || !branch.path.some((x) => rosterHas(this.rosters.get(x) ?? [], key))) continue;
33057
+ for (let j = branch.fork + 1; j < this.state.chain.length; j++) {
33058
+ if (this.better(branch, this.branch(communityCommitHash(this.state.chain[j])), counts)) continue;
33059
+ lost = {
33060
+ fork: Math.min(lost?.fork ?? j, branch.fork),
33061
+ end: Math.max(lost?.end ?? j, j)
33062
+ };
33063
+ break;
33064
+ }
33065
+ }
33066
+ return lost;
31944
33067
  }
31945
33068
  /**
31946
33069
  * Whether `key` could read message `messageId` (`<s>:<e>:<h>:<n>`) and still can: a member of the roster it was sealed
@@ -32245,11 +33368,17 @@ var CommunitySession = class {
32245
33368
  if (!parsed || this.known.has(communityCommitHash(parsed))) return false;
32246
33369
  const result = verifyCommunityCommit(raw, parent, parentRoster, this.id, this.ancestry(p));
32247
33370
  if ("error" in result) return false;
33371
+ const previous = this.state.secrets[p];
33372
+ if (previous && !FRESH.has(result.commit.k)) {
33373
+ const untagged = communityUntaggedHash(result.commit);
33374
+ if (!confirmationMatches(epochKeys(derivedSecret(fromBase64Url(previous), untagged), this.id, result.commit.e).confirm, untagged, result.commit.c)) return false;
33375
+ }
32248
33376
  if (GROWS.has(result.commit.k) && !keepsRoom(result.commit.e, result.roster)) return false;
32249
33377
  const commit = result.commit, h = communityCommitHash(commit);
32250
33378
  const admin = rosterAdmin(parentRoster);
32251
33379
  if (commit.by === admin) {
32252
33380
  for (const [other, c] of this.known) if (other !== h && c.p === commit.p && c.by === admin) {
33381
+ if (admin !== this.admin) return false;
32253
33382
  this.known.set(h, commit);
32254
33383
  this.rosters.set(h, result.roster);
32255
33384
  await this.fork(`The admin signed two different changes after epoch ${parent.e}`);
@@ -32262,6 +33391,11 @@ var CommunitySession = class {
32262
33391
  if (branch && branch.path.length) {
32263
33392
  const { admin } = this.parting(branch, this.branch(this.topHash), this.adminCounts());
32264
33393
  if (ADMIN_ONLY.has(commit.k) && admin[1]) {
33394
+ if (commit.by !== this.admin) {
33395
+ this.known.delete(h);
33396
+ this.rosters.delete(h);
33397
+ return false;
33398
+ }
32265
33399
  await this.fork(`The admin signed changes on two branches after epoch ${this.state.chain[branch.fork].e}`);
32266
33400
  return true;
32267
33401
  }
@@ -32353,6 +33487,7 @@ var CommunitySession = class {
32353
33487
  this.state.chain.push(c);
32354
33488
  this.takeDerived(h);
32355
33489
  }
33490
+ this.holdDroppedLeaves(dropped);
32356
33491
  if (!rosterHas(this.roster, this.myKey) && this.state.status === "active") {
32357
33492
  const out = [...path].reverse().map((h) => this.known.get(h)).find((c) => (c.k === "remove" || c.k === "leave") && c.s === this.myKey);
32358
33493
  if (out) this.out(out.k === "remove" ? "removed" : "left", out.k === "remove" ? "You were removed from this group" : "You left this group");
@@ -32362,6 +33497,33 @@ var CommunitySession = class {
32362
33497
  }
32363
33498
  }
32364
33499
  }
33500
+ /**
33501
+ * A leave the branch I left behind had committed, whose member the main branch still lists (an admin-only commit
33502
+ * signed on a stale view won the fork): its request is held again, so the next hub commits it on top. The hub that
33503
+ * committed it kept no copy and the leaver's app forgot the group, so nobody would say it again (agents#2285).
33504
+ */
33505
+ holdDroppedLeaves(dropped) {
33506
+ let held = this.state.pendingLeaves;
33507
+ for (const c of dropped) {
33508
+ if (c.k !== "leave" || !c.s || !c.ls || c.s === this.myKey || !rosterHas(this.roster, c.s)) continue;
33509
+ const request = {
33510
+ s: c.s,
33511
+ ls: c.ls,
33512
+ ...c.ls3 ? { ls3: c.ls3 } : {}
33513
+ };
33514
+ if (!leaveStands({
33515
+ g: this.id,
33516
+ ...request
33517
+ }, this.ancestry(this.topHash))) continue;
33518
+ const other = held.find((r) => r.s === c.s && leaveStands({
33519
+ g: this.id,
33520
+ ...r
33521
+ }, this.ancestry(this.topHash)));
33522
+ if (other && (other.ls3 || !request.ls3)) continue;
33523
+ held = [...held.filter((r) => r.s !== c.s), request].slice(-COMMUNITY_LIMITS.pendingLeaves);
33524
+ }
33525
+ this.state.pendingLeaves = held;
33526
+ }
32365
33527
  /** The entry key is the one the main branch names; its seed comes with a `group-entry` from whoever holds it. */
32366
33528
  followEntry() {
32367
33529
  const key = this.currentEntryKey();
@@ -32616,6 +33778,10 @@ var CommunitySession = class {
32616
33778
  return this.serialize(async () => {
32617
33779
  this.requireAdmin();
32618
33780
  if (!rosterHas(this.roster, memberKey) || memberKey === this.myKey) throw new Error("Not a member");
33781
+ if (this.state.pendingLeaves.some((r) => r.s === memberKey && leaveStands({
33782
+ g: this.id,
33783
+ ...r
33784
+ }, this.ancestry(this.topHash)))) throw new Error("This member has left the group. Make someone else the admin.");
32619
33785
  await this.commit("role", { s: memberKey }, now);
32620
33786
  });
32621
33787
  }
@@ -33247,6 +34413,9 @@ var CommunitySession = class {
33247
34413
  }
33248
34414
  const roster = this.rosterOf(found.hash);
33249
34415
  if (!rosterHas(roster, raw.s)) return false;
34416
+ let pace = this.messagePace.get(raw.s);
34417
+ if (!pace) this.messagePace.set(raw.s, pace = new MessagePace());
34418
+ if (!pace.take(seenKey(raw.e, raw.h), raw.n, raw.c.length, this.hooks.clock?.() ?? Date.now())) return false;
33250
34419
  if (!rosterHas(roster, this.myKey)) {
33251
34420
  this.markSeen(raw);
33252
34421
  this.keep(raw);
@@ -33444,10 +34613,23 @@ var CommunitySession = class {
33444
34613
  for (const { from, frame } of ready) await this.receiveMessage(from, frame);
33445
34614
  }
33446
34615
  async receiveSync(from, frame) {
33447
- if (!this.isRecentMember(from) || !isZ32Key(from) || !Number.isSafeInteger(frame.e) || typeof frame.h !== "string") return;
34616
+ if (!isZ32Key(from) || !Number.isSafeInteger(frame.e) || typeof frame.h !== "string") return;
34617
+ const recent = this.isRecentMember(from), lost = recent ? void 0 : this.lostAt(from);
34618
+ if (!recent && !lost) return;
33448
34619
  let answered = this.syncsAnswered.get(from);
33449
34620
  if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(COMMUNITY_LIMITS.syncAnswers, COMMUNITY_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
33450
34621
  if (!answered.take()) return;
34622
+ if (lost) {
34623
+ const at = this.mainIndex.get(frame.h);
34624
+ const commits = this.state.chain.slice(at !== void 0 ? at + 1 : lost.fork + 1, lost.end + 1);
34625
+ if (commits.length) this.answers.handOut(from, commits.map((commit) => ({
34626
+ t: "group-commit",
34627
+ v: 2,
34628
+ g: this.id,
34629
+ commit
34630
+ })));
34631
+ return;
34632
+ }
33451
34633
  const answer = [];
33452
34634
  const ask = () => {
33453
34635
  const sync = this.question(from);
@@ -33498,8 +34680,8 @@ var CommunitySession = class {
33498
34680
  const unheard = new Set(this.state.unheard ?? []);
33499
34681
  const marked = /* @__PURE__ */ new Set();
33500
34682
  const metas = this.metaFor(from, frame.mt);
33501
- const inStore = new Set(this.state.store.map(frameKey));
33502
- const lasting = Object.values(this.state.lasting ?? {}).filter((f) => !inStore.has(frameKey(f))).sort((a, b) => a.ts - b.ts);
34683
+ const inStore = new Set(this.state.store.map(storeKey));
34684
+ const lasting = Object.values(this.state.lasting ?? {}).filter((f) => !inStore.has(storeKey(f))).sort((a, b) => a.ts - b.ts);
33503
34685
  for (const stored of [...lasting, ...this.state.store]) {
33504
34686
  if (stored.s === from) continue;
33505
34687
  const high = have[stored.s]?.[seenKey(stored.e, stored.h)];
@@ -34412,6 +35594,6 @@ function readX401SdJwtVc(text) {
34412
35594
  };
34413
35595
  }
34414
35596
  //#endregion
34415
- export { parseSshPublicKey as $, appCardId as $a, readImageMeta as $c, automaticTransport as $i, traceLink as $l, readGroupWant as $n, HANDOFF_HAVE as $o, vapidKeysMatch as $r, enrollHelloFrame as $s, SEPOLIA_TEST_USDT_FAUCET as $t, knockRecords as A, GROUP_REACTION_FRAME as Aa, appDigest as Ac, txtValue as Ai, classifyTurnRead as Al, findEndpoint as An, formatLocalTarget as Ao, FileUplink as Ar, readHandoffDone as As, didWebDocumentUrl as At, GROUP_READ_NOTE as B, pairedReplyAuthor as Ba, APP_STATEMENT_LIMITS as Bc, IdentityExchange as Bi, turnKeys as Bl, EngineError as Bn, callRtcConfig as Bo, mayPin as Br, setAckFrame as Bs, staticDidDocument as Bt, decodeCommunityLink as C, REMOVED_TEXT as Ca, readLinkRecord as Cc, encodeDnsQuery as Ci, devicePingFrame as Cl, pubkyHomeserverOf as Cn, AWAITING_PEER_MS as Co, rankHubs as Cr, handoffReleaseFrame as Cs, DID_JWS_MAX_LENGTH as Ct, utf8Decode as Cu, encodeGroupEntryLink as D, forwardedAgain as Da, APP_BUNDLE_MAGIC as Dc, recordsFromTxt as Di, TURN_PUT_WINDOW_MS as Dl, ENDPOINT as Dn, WATCH_PEER_MS as Do, shouldBeHub as Dr, newHandoffId as Ds, didGhostlyServiceEntry as Dt, decodeGroupEntryLink as E, parseLinkPreview as Ea, APP_BUNDLE_LIMITS as Ec, normalizeDomain as Ei, webCryptoSigner as El, decodeBolt11 as En, RELAY_POLL_INTERVALS as Eo, readLobby as Er, handoffVersions as Es, checkDidSignature as Et, groupWakeFrame as F, reactionEmoji as Fa, pacer as Fc, dialDescriptors as Fi, nextTurnPosition as Fl, INVITE_TAKEN as Fn, encodeControl as Fo, TypingSender as Fr, readHandoffVerified as Fs, normalizeDid as Ft, GROUP_EDIT_TEXT_BYTES as G, CRON_LINE as Ga, isAppKey as Gc, newIdentityBinding as Gi, HEDGE_MISSING_MS as Gl, GROUP_HAVE_FRAME as Gn, signalHasVideo as Go, WAKE_CALL_INTERVAL_MS as Gr, ENROLL_GRANT as Gs, encodeDidDhtPacket as Gt, frameBytes as H, replySnippet as Ha, appRef as Hc, emptyIdentityLedger as Hi, turnStatedVerifier as Hl, engineText as Hn, contactRtcConfig as Ho, pinIsNewer as Hr, signTombstone as Hs, didDhtDocument as Ht, groupWakes as I, reactionIsNewer as Ia, readAppBundle as Ic, IDENTITY_MAX_EVIDENCE as Ii, readTurnPacket as Il, LIVENESS_PING_MS as In, CALL_SIGNAL_MAX_AGE_MS as Io, sanitizeTypingStatus as Ir, sealHandoffPiece as Is, parseDid as It, mentionsMember as J, PR_STATES as Ja, readAppRevocations as Jc, lastSharedWithMe as Ji, RelaysFailedError as Jl, fetchesByItself as Jn, LEGACY_SERVICES as Jo, newWakeToken as Jr, enrollCancelFrame as Js, ETHEREUM_USDT as Jt, carryMentions as K, ITEM_STATES as Ka, isAppRef as Kc, receivedIdentityStatus as Ki, HEDGE_MS as Kl, GROUP_WANT_FRAME as Kn, emptyLinkRecords as Ko, WakeLimiter as Kr, ENROLL_HELLO as Ks, resolveDidDht as Kt, parseGroupWakeFrame as L, readReaction as La, readAppBundleAsync as Lc, IDENTITY_MAX_VALIDITY as Li, signTurnPacket as Ll, PAIRED_FRAME_TOO_LARGE as Ln, RTC_CONFIG as Lo, typingActivity as Lr, SET_ACK as Ls, parseDidDocument as Lt, readKnocks as M, ReactionWindow as Ma, assembleAppBundle as Mc, CapsExchange as Mi, TURN_LAST_SEQUENCE as Ml, parseCashuRequestPayload as Mn, webLocalFetch as Mo, transferStalled as Mr, readHandoffHello as Ms, didWebFileNames as Mt, GROUP_WAKE_FRAME as N, nextReactionNumber as Na, checkAppManifest as Nc, DHT_TEXT_CAPABILITY as Ni, TURN_MAX as Nl, parseFedimintRequestPayload as Nn, LIMITS as No, TYPING_KINDS as Nr, readHandoffPake as Ns, didWebFileUrl as Nt, entryParams as O, readForwarded as Oa, APP_ICON_PATH as Oc, recordsFromWellKnown as Oi, TURN_RAISE_READ_TIMEOUT_MS as Ol, cashuRequestPayload as On, presenceSeenAt as Oo, ChatFiles as Or, readHandoffAck as Os, didJwsAlg as Ot, GroupWakeLimiter as P, queueReaction as Pa, isAppUrl as Pc, capsDescriptors as Pi, firstDeviceSetSecret as Pl, GhostLink as Pn, decodeControl as Po, TYPING_REFRESH_MS as Pr, readHandoffTurnFrame as Ps, didWebHost as Pt, SshSigError as Q, TASK_STATUSES as Qa, parseImageMeta as Qc, TRANSPORTS as Qi, setLinkTraceSink as Ql, readGroupHave as Qn, HANDOFF_DONE as Qo, checkPushEndpoint as Qr, enrollGrantFrame as Qs, SEPOLIA_TEST_USDT as Qt, GROUP_LIMITS as R, validReactionNumber as Ra, sha256Paced as Rc, IDENTITY_REVOCATION_LABEL as Ri, signTurnRelease as Rl, pairedMessageFits as Rn, answersOffer as Ro, GROUP_PIN_FRAME as Rr, SET_UPDATE as Rs, parseDidSignaturePaste as Rt, communityHasFrame as S, MAX_REMOVAL_NUMBER as Sa, readKnockSlot as Sc, domainWellKnownFile as Si, deviceLinkPairing as Sl, homeserverWebEndpoint as Sn, DirectPathWatch as So, pickHubs as Sr, handoffPakeFrame as Ss, DID_FILE_MAX_BYTES as St, toZ32 as Su, KNOCK_TTL_MS as T, dhtEditId as Ta, seenEntry as Tc, nip05RootKey as Ti, seedSigner as Tl, resolveLightningDestination as Tn, EXPECT_PEER_MS as To, readBeaconHead as Tr, handoffStreamKey as Ts, checkDidJws as Tt, COMMUNITY_EDIT_FRAME as U, BUTTON_ID as Ua, checkAppRevokeStatement as Uc, identityRevocationValue as Ui, turnVerifierMark as Ul, parseEngineError as Un, extractParamsFromSdp as Uo, pinNumberHolds as Ur, verifySetUpdate as Us, didDhtFromPublicKey as Ut, GroupSession as V, readReply as Va, appFingerprint as Vc, boundVerifiedIdentity as Vi, turnName as Vl, engineError as Vn, callSignalHeardAt as Vo, nextPinNumber as Vr, setUpdateFrame as Vs, strictBase64Url as Vt, GROUP_EDIT_FRAME as W, BUTTON_STYLES as Wa, isAppHash as Wc, identityStatement as Wi, DEFAULT_RELAYS as Wl, GROUP_FILE_LIMITS as Wn, parseCallSignal as Wo, readPin as Wr, ENROLL_DONE as Ws, encodeDidDhtDeactivated as Wt, SSHSIG_MAX_ARMOR as X, RUN_RESULTS as Xa, signAppObject as Xc, emptyProofLedger as Xi, currentRelays as Xl, isGroupMessageId as Xn, HANDOFF_ACK as Xo, relayRequest as Xr, enrollDigits as Xs, ONCHAIN_PROVIDER as Xt, groupName as Y, ROUTINE_STATES as Ya, setAppSignatureFastPath as Yc, PeerProofs as Yi, SLOW_MS as Yl, groupFileFallback as Yn, serviceIdFromName as Yo, parseWakeFrame as Yr, enrollCancelReason as Ys, EVM_TEST_CHAINS as Yt, SSHSIG_NAMESPACE as Z, STATUS_CARD_LIMITS as Za, signAppRevocation as Zc, validExternalKey as Zi, normalizeRelayUrl as Zl, readGroupFileMeta as Zn, HANDOFF_CANCEL as Zo, wakeRequest as Zr, enrollDoneFrame as Zs, PaymentPreflightError as Zt, openGroupTyping as _, voiceDownloadName as _a, knockSlotRecords as _c, readManifest as _i, ENROLL_CAPABILITY as _l, newPubkyProofFolder as _n, parseGroupCommit as _o, lobbyKeys as _r, handoffDigest as _s, parseAtprotoDidDocument as _t, bytesEqual as _u, appStoreDecision as a, DHT_FILE_CAPABILITY as aa, endedRequests as ac, APPS_CAPABILITY as ai, readContactLink as al, assertWholeSats as an, statusCardBytes as ao, SIGNAL_REPLY_MS as ar, HANDOFF_TIMINGS as as, BitcoinAddressError as at, createRelayPayload as au, CommunitySession as b, EDIT_BUFFER_MS as ba, mergeContactKnocks as bc, dnsProofName as bi, deviceEchoNonce as bl, pubkyProofFile as bn, verifyCommitSignature as bo, mergeLobby as br, handoffManifestFrames as bs, verifyAtprotoRecordProof as bt, randomBytes as bu, planAppUpdate as c, sanitizeFileName as ca, planKnocks as cc, STATUS_CARD_CAPABILITY as ci, readDeviceInvite as cl, walletNetworkOf as cn, claimedTime as co, MESH_HUBS as cr, filePartName as cs, ATPROTO_FULL_SCOPE as ct, parseRelayPayload as cu, readAppStore as d, VOICE_LIMITS as da, turnOff as dc, HOLD_DATED_BACK_MS as di, decodeInviteCode as dl, sparkAddressKind as dn, shownTime as do, pickMeshHubs as dr, handoffAttemptSucceeded as ds, atprotoDidMethod as dt, identityFromSeedB64 as du, irohDescriptor as ea, enrollProofFrame as ec, APP_RANGE_LIMITS as ei, canonicalJson as el, TEST_USDT_FAUCET_AMOUNT as en, buttonLabelClash as eo, readGroupWantNo as er, HANDOFF_HELLO as es, parseSshSignature as et, budgetRetryMs as eu, readAppStoreSteps as f, VOICE_METER as fa, ContactRequestError as fc, HOLD_LIMITS as fi, encodeInviteCode as fl, sparkInvoiceDetails as fn, GROUP_ADMIN_OFF_ERROR as fo, COMMUNITY_TOPOLOGY as fr, handoffBusyFrame as fs, atprotoProofRecord as ft, publicKeyFromZ32 as fu, groupTypingEpoch as g, parseVoiceMeta as ga, knockSlotOf as gc, newMailbox as gi, DEVICES_CAPABILITY as gl, isPubkyProofFolder as gn, commitHash as go, freshHubs as gr, handoffDataFrame as gs, normalizeAtprotoHandle as gt, sanitizeDisplayText as gu, GroupTypingBoard as h, fileMessageText as ha, knockSlotIdentity as hc, isHoldUrl as hi, ownInviteRefusal as hl, isPubkyKey as hn, MEMBER_KEY as ho, doorHubs as hr, handoffContextProof as hs, isAtprotoDid as ht, sanitizeAvatar as hu, appRevocationFor as i, peekDhtMailbox as ia, clearMissed as ic, isAppVersion as ii, encodeContactLink as il, assertTokenUnits as in, sameButtonText as io, SIGNAL_HOLD_MS as ir, HANDOFF_REQUEST as is, verifyBitcoinMessage as it, RELAY_PAYLOAD_MAX_BYTES as iu, mergeKnocks as j, REACTION_LIMITS as ja, appViewOf as jc, wellKnownUrl as ji, turnPutSummary as jl, isFederationId as jn, parseLocalTarget as jo, transferEnded as jr, readHandoffHave as js, didWebFile as jt, knockIdentity as k, COMMUNITY_REACTION_FRAME as ka, APP_PERMISSIONS as kc, recordsName as ki, TURN_SETTLE_MS as kl, fedimintRequestPayload as kn, GhostlyHttpError as ko, FILE_LIMITS as kr, readHandoffCancel as ks, didSignedMessages as kt, APP_STORE_LIMITS as l, sanitizeMime as la, settleRequest as lc, UPGRADE_CAPABILITY as li, OwnInviteError as ll, SPARK_NETWORKS as ln, heardTime as lo, mayBeHub as lr, handoffAttemptAllowed as ls, ATPROTO_PROOF_COLLECTION as lt, createIdentity as lu, GROUP_TYPING_FRAME as m, downsamplePeaks as ma, contactDay as mc, HoldRefusedError as mi, inviteOwnership as ml, PUBKY_PROOF_MAX_BYTES as mn, MAX_GROUP_CHAIN as mo, beaconRecords as mr, handoffContext as ms, checkAtprotoProofRecord as mt, MAX_AVATAR_LENGTH as mu, readX401SdJwtVc as n, DHT_FILE_TOO_LARGE as na, readEnrollHello as nc, APP_DATA_MAX_BYTES as ni, readCanonicalJson as nl, WALLET_NETWORKS as nn, cardUrl as no, GROUP_SIGNAL_FRAME as nr, HANDOFF_PAKE as ns, sshSignCommand as nt, withRequestOptions as nu, appUpdateDecision as o, dhtFileId as oa, inboxRecord as oc, BUTTONS_CAPABILITY as oi, createDeviceInvite as ol, formatPaymentAmount as on, statusCardText as oo, groupSignalFrame as or, HANDOFF_VERIFIED as os, decodeAnyBitcoinAddress as ot, newerPacket as ou, signAppStore as p, baseMime as pa, REQUEST_LIFETIME_MS as pc, HoldKeys as pi, inviteLink as pl, isBitcoinAddress as pn, GROUP_MEMBER_CAP as po, beaconKeys as pr, handoffCancelFrame as ps, atprotoProofRkey as pt, verify as pu, parseCommunityEdit as q, PR_CHECKS as qa, readAppRevocation as qc, revokesIdentity as qi, RelayTransport as ql, GROUP_WANT_NO_FRAME as qn, HTTP_SERVICE_PROTO as qo, deviceWakeRequest as qr, ENROLL_PROOF as qs, signDidDhtPacket as qt, sameX401HolderJwk as r, DHT_MESSAGE_TTL as ra, verifyEnrollProof as rc, chatAppId as ri, createContactLink as rl, arkAddressPrefix as rn, checkStatusCard as ro, SIGNAL_FRESH_MS as rr, HANDOFF_PIECE_BYTES as rs, verifySshSignature as rt, PacketTooLargeError as ru, checkAppBeforeRun as s, formatFileSize as sa, newInbox as sc, EDIT_CAPABILITY as si, deviceInviteJoinerParams as sl, validatePaymentTarget as sn, arrivalKey as so, readGroupSignal as sr, NO_ATTEMPTS as ss, ATPROTO_DECLARED_SCOPE as st, openRelayPayload as su, newX401HolderKey as t, irohRelayUrl as ta, readEnrollGrant as tc, isServeId as ti, canonicalJsonBytes as tl, USDT_PUBLIC_RPC as tn, cardLine as to, CarriedTransport as tr, HANDOFF_OFFER as ts, sameSshKey as tt, isDiscoveryBudgetError as tu, checkAppStoreIndex as u, PLAYABLE_AUDIO as ua, takeRequest as uc, HOLD_CAPABILITY as ui, createChatInvite as ul, SPARK_PROVIDER as un, receivedTimestamp as uo, meshHubs as ur, handoffAttemptFailed as us, ATPROTO_PROOF_SCOPE as ut, identityFromSeed as uu, sealGroupTyping as v, voiceLevel as va, linkRecords as vc, DOMAIN_FILE_MAX_BYTES as vi, HANDOFF_CAPABILITY as vl, normalizePubkyKey as vn, rosterAdmin as vo, lobbyRecords as vr, handoffEphemeral as vs, shortAtprotoDid as vt, fromBase64Url as vu, encodeCommunityLink as w, RateWindow as wa, requestRecords as wc, isPublicAddress as wi, newDeviceSetSecret as wl, requestLnurlInvoice as wn, DHT_POLL_INTERVALS as wo, readBeacon as wr, handoffRetryAfter as ws, DidError as wt, utf8Encode as wu, GROUP_READ_NOTE_COMMUNITY as x, EDIT_RATE_WINDOW_MS as xa, openRequest as xc, domainTxtRecord as xi, deviceKeyZ32 as xl, pubkyProofPath as xn, edgeParams as xo, newerHead as xr, handoffOfferFrame as xs, DID_DOCUMENT_MAX_BYTES as xt, toBase64Url as xu, COMMUNITY_LIMITS as y, parseVideoMeta as ya, makeStampPaced as yc, decodeDnsResponse as yi, deviceEchoFrame as yl, pubkyProofCapability as yn, rosterHas as yo, mergeBeacon as yr, handoffHelloFrame as ys, AtprotoProofError as yt, isZ32Key as yu, GROUP_REACTED_FRAME as z, wireReaction as za, APP_PREFIXES as zc, IdentityCheckUnavailable as zi, turnInstance as zl, pairedMessageFrame as zn, buildSdpFromSignal as zo, PIN_LIMITS as zr, readSetUpdate as zs, signingKeys as zt };
35597
+ export { SshSigError as $, ROUTINE_STATES as $a, isAppHash as $c, validExternalKey as $i, DEFAULT_RELAYS as $l, readGroupHave as $n, parseCallSignal as $o, wakeRequest as $r, ENROLL_DONE as $s, SEPOLIA_TEST_USDT as $t, knockIdentity as A, parseLinkPreview as Aa, openRequest as Ac, recordsFromWellKnown as Ai, deviceKeyZ32 as Al, fedimintRequestPayload as An, DirectPathWatch as Ao, FILE_LIMITS as Ar, handoffOfferFrame as As, didSignedMessages as At, toBase64Url as Au, GROUP_REACTED_FRAME as B, reactionIsNewer as Ba, appViewOf as Bc, IDENTITY_REVOCATION_LABEL as Bi, turnPutSummary as Bl, pairedMessageFrame as Bn, parseLocalTarget as Bo, GROUP_PIN_FRAME as Br, readHandoffHave as Bs, signingKeys as Bt, communityHasFrame as C, EDIT_RATE_WINDOW_MS as Ca, contactDay as Cc, domainTxtRecord as Ci, inviteOwnership as Cl, homeserverWebEndpoint as Cn, rosterHas as Co, pickHubs as Cr, handoffContext as Cs, DID_FILE_MAX_BYTES as Ct, MAX_AVATAR_LENGTH as Cu, decodeGroupEntryLink as D, dhtEditId as Da, linkRecords as Dc, nip05RootKey as Di, HANDOFF_CAPABILITY as Dl, decodeBolt11 as Dn, RatchetBox as Do, readLobby as Dr, handoffEphemeral as Ds, checkDidSignature as Dt, fromBase64Url as Du, KNOCK_TTL_MS as E, RateWindow as Ea, knockSlotRecords as Ec, isPublicAddress as Ei, ENROLL_CAPABILITY as El, resolveLightningDestination as En, RATCHET_CAPABILITY as Eo, readBeaconHead as Er, handoffDigest as Es, checkDidJws as Et, bytesEqual as Eu, GroupWakeLimiter as F, REACTION_LIMITS as Fa, APP_BUNDLE_LIMITS as Fc, DHT_TEXT_CAPABILITY as Fi, webCryptoSigner as Fl, GhostLink as Fn, RELAY_POLL_INTERVALS as Fo, TYPING_KINDS as Fr, handoffVersions as Fs, didWebHost as Ft, GROUP_EDIT_FRAME as G, readReply as Ga, readAppBundle as Gc, identityRevocationValue as Gi, readTurnPacket as Gl, GROUP_FILE_LIMITS as Gn, CALL_SIGNAL_MAX_AGE_MS as Go, pinNumberHolds as Gr, sealHandoffPiece as Gs, encodeDidDhtDeactivated as Gt, GroupSession as H, validReactionNumber as Ha, checkAppManifest as Hc, IdentityExchange as Hi, TURN_MAX as Hl, engineError as Hn, LIMITS as Ho, mayPin as Hr, readHandoffPake as Hs, strictBase64Url as Ht, groupWakeFrame as I, ReactionWindow as Ia, APP_BUNDLE_MAGIC as Ic, capsDescriptors as Ii, TURN_PUT_WINDOW_MS as Il, INVITE_TAKEN as In, WATCH_PEER_MS as Io, TYPING_REFRESH_MS as Ir, newHandoffId as Is, normalizeDid as It, parseCommunityEdit as J, BUTTON_STYLES as Ja, APP_PREFIXES as Jc, receivedIdentityStatus as Ji, turnInstance as Jl, GROUP_WANT_NO_FRAME as Jn, buildSdpFromSignal as Jo, WakeLimiter as Jr, readSetUpdate as Js, signDidDhtPacket as Jt, GROUP_EDIT_TEXT_BYTES as K, replySnippet as Ka, readAppBundleAsync as Kc, identityStatement as Ki, signTurnPacket as Kl, GROUP_HAVE_FRAME as Kn, RTC_CONFIG as Ko, readPin as Kr, SET_ACK as Ks, encodeDidDhtPacket as Kt, groupWakes as L, nextReactionNumber as La, APP_ICON_PATH as Lc, dialDescriptors as Li, TURN_RAISE_READ_TIMEOUT_MS as Ll, LIVENESS_PING_MS as Ln, presenceSeenAt as Lo, TypingSender as Lr, readHandoffAck as Ls, parseDid as Lt, mergeKnocks as M, readForwarded as Ma, readLinkRecord as Mc, txtValue as Mi, devicePingFrame as Ml, isFederationId as Mn, DHT_POLL_INTERVALS as Mo, sentWhole as Mr, handoffReleaseFrame as Ms, didWebFile as Mt, utf8Decode as Mu, readKnocks as N, COMMUNITY_REACTION_FRAME as Na, requestRecords as Nc, wellKnownUrl as Ni, newDeviceSetSecret as Nl, parseCashuRequestPayload as Nn, EXPECT_PEER_MS as No, transferEnded as Nr, handoffRetryAfter as Ns, didWebFileNames as Nt, utf8Encode as Nu, encodeGroupEntryLink as O, LINK_TRAILING as Oa, makeStampPaced as Oc, normalizeDomain as Oi, deviceEchoFrame as Ol, ENDPOINT as On, emptyRatchetState as Oo, shouldBeHub as Or, handoffHelloFrame as Os, didGhostlyServiceEntry as Ot, isZ32Key as Ou, GROUP_WAKE_FRAME as P, GROUP_REACTION_FRAME as Pa, seenEntry as Pc, CapsExchange as Pi, seedSigner as Pl, parseFedimintRequestPayload as Pn, PRESENCE_WINDOW as Po, transferStalled as Pr, handoffStreamKey as Ps, didWebFileUrl as Pt, SSHSIG_NAMESPACE as Q, PR_STATES as Qa, checkAppRevokeStatement as Qc, emptyProofLedger as Qi, turnVerifierMark as Ql, readGroupFileMeta as Qn, extractParamsFromSdp as Qo, relayRequest as Qr, verifySetUpdate as Qs, PaymentPreflightError as Qt, parseGroupWakeFrame as R, queueReaction as Ra, APP_PERMISSIONS as Rc, IDENTITY_MAX_EVIDENCE as Ri, TURN_SETTLE_MS as Rl, PAIRED_FRAME_TOO_LARGE as Rn, GhostlyHttpError as Ro, sanitizeTypingStatus as Rr, readHandoffCancel as Rs, parseDidDocument as Rt, GROUP_READ_NOTE_COMMUNITY as S, EDIT_BUFFER_MS as Sa, REQUEST_LIFETIME_MS as Sc, dnsProofName as Si, inviteLink as Sl, pubkyProofPath as Sn, rosterAdmin as So, newerHead as Sr, handoffCancelFrame as Ss, DID_DOCUMENT_MAX_BYTES as St, verify as Su, encodeCommunityLink as T, REMOVED_TEXT as Ta, knockSlotOf as Tc, encodeDnsQuery as Ti, DEVICES_CAPABILITY as Tl, requestLnurlInvoice as Tn, edgeParams as To, readBeacon as Tr, handoffDataFrame as Ts, DidError as Tt, sanitizeDisplayText as Tu, frameBytes as U, wireReaction as Ua, isAppUrl as Uc, boundVerifiedIdentity as Ui, firstDeviceSetSecret as Ul, engineText as Un, decodeControl as Uo, nextPinNumber as Ur, readHandoffTurnFrame as Us, didDhtDocument as Ut, GROUP_READ_NOTE as V, readReaction as Va, assembleAppBundle as Vc, IdentityCheckUnavailable as Vi, TURN_LAST_SEQUENCE as Vl, EngineError as Vn, webLocalFetch as Vo, PIN_LIMITS as Vr, readHandoffHello as Vs, staticDidDocument as Vt, COMMUNITY_EDIT_FRAME as W, pairedReplyAuthor as Wa, pacer as Wc, emptyIdentityLedger as Wi, nextTurnPosition as Wl, parseEngineError as Wn, encodeControl as Wo, pinIsNewer as Wr, readHandoffVerified as Ws, didDhtFromPublicKey as Wt, groupName as X, ITEM_STATES as Xa, appFingerprint as Xc, lastSharedWithMe as Xi, turnName as Xl, groupFileFallback as Xn, callSignalHeardAt as Xo, newWakeToken as Xr, setUpdateFrame as Xs, EVM_TEST_CHAINS as Xt, mentionsMember as Y, CRON_LINE as Ya, APP_STATEMENT_LIMITS as Yc, revokesIdentity as Yi, turnKeys as Yl, fetchesByItself as Yn, callRtcConfig as Yo, deviceWakeRequest as Yr, setAckFrame as Ys, ETHEREUM_USDT as Yt, SSHSIG_MAX_ARMOR as Z, PR_CHECKS as Za, appRef as Zc, PeerProofs as Zi, turnStatedVerifier as Zl, isGroupMessageId as Zn, contactRtcConfig as Zo, parseWakeFrame as Zr, signTombstone as Zs, ONCHAIN_PROVIDER as Zt, groupTypingEpoch as _, fileMessageText as _a, planKnocks as _c, isHoldUrl as _i, readDeviceInvite as _l, isPubkyProofFolder as _n, GROUP_MEMBER_CAP as _o, freshHubs as _r, filePartName as _s, normalizeAtprotoHandle as _t, parseRelayPayload as _u, appRevocationFor as a, DHT_MESSAGE_TTL as aa, enrollDigits as ac, chatAppId as ai, signAppObject as al, assertTokenUnits as an, cardLine as ao, SIGNAL_HOLD_MS as ar, HANDOFF_ACK as as, verifyBitcoinMessage as at, currentRelays as au, COMMUNITY_LIMITS as b, voiceLevel as ba, turnOff as bc, DOMAIN_FILE_MAX_BYTES as bi, decodeInviteCode as bl, pubkyProofCapability as bn, commitHash as bo, mergeBeacon as br, handoffAttemptSucceeded as bs, AtprotoProofError as bt, identityFromSeedB64 as bu, checkAppBeforeRun as c, dhtFileId as ca, enrollHelloFrame as cc, BUTTONS_CAPABILITY as ci, readImageMeta as cl, validatePaymentTarget as cn, sameButtonText as co, readGroupSignal as cr, HANDOFF_HAVE as cs, ATPROTO_DECLARED_SCOPE as ct, traceLink as cu, checkAppStoreIndex as d, sanitizeMime as da, readEnrollHello as dc, UPGRADE_CAPABILITY as di, readCanonicalJson as dl, SPARK_PROVIDER as dn, arrivalKey as do, meshHubs as dr, HANDOFF_PAKE as ds, ATPROTO_PROOF_SCOPE as dt, withRequestOptions as du, TRANSPORTS as ea, ENROLL_GRANT as ec, checkPushEndpoint as ei, isAppKey as el, SEPOLIA_TEST_USDT_FAUCET as en, RUN_RESULTS as eo, readGroupWant as er, signalHasVideo as es, parseSshPublicKey as et, HEDGE_MISSING_MS as eu, readAppStore as f, PLAYABLE_AUDIO as fa, verifyEnrollProof as fc, HOLD_CAPABILITY as fi, createContactLink as fl, sparkAddressKind as fn, claimedTime as fo, pickMeshHubs as fr, HANDOFF_PIECE_BYTES as fs, atprotoDidMethod as ft, PacketTooLargeError as fu, GroupTypingBoard as g, downsamplePeaks as ga, newInbox as gc, HoldRefusedError as gi, deviceInviteJoinerParams as gl, isPubkyKey as gn, GROUP_ADMIN_OFF_ERROR as go, doorHubs as gr, NO_ATTEMPTS as gs, isAtprotoDid as gt, openRelayPayload as gu, GROUP_TYPING_FRAME as h, baseMime as ha, inboxRecord as hc, HoldKeys as hi, createDeviceInvite as hl, PUBKY_PROOF_MAX_BYTES as hn, shownTime as ho, beaconRecords as hr, HANDOFF_VERIFIED as hs, checkAtprotoProofRecord as ht, newerPacket as hu, addedAppPermissions as i, DHT_FILE_TOO_LARGE as ia, enrollCancelReason as ic, APP_DATA_MAX_BYTES as ii, setAppSignatureFastPath as il, arkAddressPrefix as in, buttonLabelClash as io, SIGNAL_FRESH_MS as ir, serviceIdFromName as is, verifySshSignature as it, SLOW_MS as iu, knockRecords as j, forwardedAgain as ja, readKnockSlot as jc, recordsName as ji, deviceLinkPairing as jl, findEndpoint as jn, AWAITING_PEER_MS as jo, FileUplink as jr, handoffPakeFrame as js, didWebDocumentUrl as jt, toZ32 as ju, entryParams as k, linkStop as ka, mergeContactKnocks as kc, recordsFromTxt as ki, deviceEchoNonce as kl, cashuRequestPayload as kn, ratchetSessionOf as ko, ChatFiles as kr, handoffManifestFrames as ks, didJwsAlg as kt, randomBytes as ku, planAppUpdate as l, formatFileSize as la, enrollProofFrame as lc, EDIT_CAPABILITY as li, canonicalJson as ll, walletNetworkOf as ln, statusCardBytes as lo, MESH_HUBS as lr, HANDOFF_HELLO as ls, ATPROTO_FULL_SCOPE as lt, budgetRetryMs as lu, signAppStore as m, VOICE_METER as ma, endedRequests as mc, HOLD_LIMITS as mi, readContactLink as ml, isBitcoinAddress as mn, receivedTimestamp as mo, beaconKeys as mr, HANDOFF_TIMINGS as ms, atprotoProofRkey as mt, createRelayPayload as mu, readX401SdJwtVc as n, irohDescriptor as na, ENROLL_PROOF as nc, APP_RANGE_LIMITS as ni, readAppRevocation as nl, USDT_PUBLIC_RPC as nn, TASK_STATUSES as no, CarriedTransport as nr, HTTP_SERVICE_PROTO as ns, sameSshKey as nt, RelayTransport as nu, appStoreDecision as o, peekDhtMailbox as oa, enrollDoneFrame as oc, isAppVersion as oi, signAppRevocation as ol, assertWholeSats as on, cardUrl as oo, SIGNAL_REPLY_MS as or, HANDOFF_CANCEL as os, BitcoinAddressError as ot, normalizeRelayUrl as ou, readAppStoreSteps as p, VOICE_LIMITS as pa, clearMissed as pc, HOLD_DATED_BACK_MS as pi, encodeContactLink as pl, sparkInvoiceDetails as pn, heardTime as po, COMMUNITY_TOPOLOGY as pr, HANDOFF_REQUEST as ps, atprotoProofRecord as pt, RELAY_PAYLOAD_MAX_BYTES as pu, carryMentions as q, BUTTON_ID as qa, sha256Paced as qc, newIdentityBinding as qi, signTurnRelease as ql, GROUP_WANT_FRAME as qn, answersOffer as qo, WAKE_CALL_INTERVAL_MS as qr, SET_UPDATE as qs, resolveDidDht as qt, sameX401HolderJwk as r, irohRelayUrl as ra, enrollCancelFrame as rc, isServeId as ri, readAppRevocations as rl, WALLET_NETWORKS as rn, appCardId as ro, GROUP_SIGNAL_FRAME as rr, LEGACY_SERVICES as rs, sshSignCommand as rt, RelaysFailedError as ru, appUpdateDecision as s, DHT_FILE_CAPABILITY as sa, enrollGrantFrame as sc, APPS_CAPABILITY as si, parseImageMeta as sl, formatPaymentAmount as sn, checkStatusCard as so, groupSignalFrame as sr, HANDOFF_DONE as ss, decodeAnyBitcoinAddress as st, setLinkTraceSink as su, newX401HolderKey as t, automaticTransport as ta, ENROLL_HELLO as tc, vapidKeysMatch as ti, isAppRef as tl, TEST_USDT_FAUCET_AMOUNT as tn, STATUS_CARD_LIMITS as to, readGroupWantNo as tr, emptyLinkRecords as ts, parseSshSignature as tt, HEDGE_MS as tu, APP_STORE_LIMITS as u, sanitizeFileName as ua, readEnrollGrant as uc, STATUS_CARD_CAPABILITY as ui, canonicalJsonBytes as ul, SPARK_NETWORKS as un, statusCardText as uo, mayBeHub as ur, HANDOFF_OFFER as us, ATPROTO_PROOF_COLLECTION as ut, isDiscoveryBudgetError as uu, openGroupTyping as v, parseVoiceMeta as va, settleRequest as vc, newMailbox as vi, OwnInviteError as vl, newPubkyProofFolder as vn, MAX_GROUP_CHAIN as vo, lobbyKeys as vr, handoffAttemptAllowed as vs, parseAtprotoDidDocument as vt, createIdentity as vu, decodeCommunityLink as w, MAX_REMOVAL_NUMBER as wa, knockSlotIdentity as wc, domainWellKnownFile as wi, ownInviteRefusal as wl, pubkyHomeserverOf as wn, verifyCommitSignature as wo, rankHubs as wr, handoffContextProof as ws, DID_JWS_MAX_LENGTH as wt, sanitizeAvatar as wu, CommunitySession as x, parseVideoMeta as xa, ContactRequestError as xc, decodeDnsResponse as xi, encodeInviteCode as xl, pubkyProofFile as xn, parseGroupCommit as xo, mergeLobby as xr, handoffBusyFrame as xs, verifyAtprotoRecordProof as xt, publicKeyFromZ32 as xu, sealGroupTyping as y, voiceDownloadName as ya, takeRequest as yc, readManifest as yi, createChatInvite as yl, normalizePubkyKey as yn, MEMBER_KEY as yo, lobbyRecords as yr, handoffAttemptFailed as ys, shortAtprotoDid as yt, identityFromSeed as yu, GROUP_LIMITS as z, reactionEmoji as za, appDigest as zc, IDENTITY_MAX_VALIDITY as zi, classifyTurnRead as zl, pairedMessageFits as zn, formatLocalTarget as zo, typingActivity as zr, readHandoffDone as zs, parseDidSignaturePaste as zt };
34416
35598
 
34417
- //# sourceMappingURL=src-DWw2hUE5.js.map
35599
+ //# sourceMappingURL=src-1RU4TilT.js.map