@ghostlytools/cli 1.10.2 → 1.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +4 -2
  2. package/dist/assets/{api-DcE4KylM.js → api-DgS7f5TT.js} +2 -2
  3. package/dist/assets/{api-EUGHGnRz.js → api-DkcMOWLX.js} +44 -19
  4. package/dist/assets/api-DkcMOWLX.js.map +1 -0
  5. package/dist/assets/{apiKit-CJVp_crp.js → apiKit-D6Oj-vFx.js} +27 -11
  6. package/dist/assets/apiKit-D6Oj-vFx.js.map +1 -0
  7. package/dist/assets/{apps-C54T_MOT.js → apps-B22SeD6T.js} +3 -3
  8. package/dist/assets/{apps-C54T_MOT.js.map → apps-B22SeD6T.js.map} +1 -1
  9. package/dist/assets/{apps-C-KbyLCa.js → apps-DgALLHzS.js} +1 -1
  10. package/dist/assets/{arkade-BmxJTa65.js → arkade-D5cPr_dV.js} +2 -2
  11. package/dist/assets/{arkade-BmxJTa65.js.map → arkade-D5cPr_dV.js.map} +1 -1
  12. package/dist/assets/{backup-C0Plp-DF.js → backup-DndsW2uX.js} +1 -1
  13. package/dist/assets/{backup-BxSH5BZG.js → backup-dzJLzg-k.js} +6 -6
  14. package/dist/assets/{backup-BxSH5BZG.js.map → backup-dzJLzg-k.js.map} +1 -1
  15. package/dist/assets/{blobFiles-BnjN_Vrz.js → blobFiles-XZ9PEXYy.js} +2 -2
  16. package/dist/assets/{blobFiles-BnjN_Vrz.js.map → blobFiles-XZ9PEXYy.js.map} +1 -1
  17. package/dist/assets/{buttons-B-ZJYdo0.js → buttons-ByKT_vP8.js} +4 -4
  18. package/dist/assets/{buttons-B-ZJYdo0.js.map → buttons-ByKT_vP8.js.map} +1 -1
  19. package/dist/assets/buttons-TVCNj280.js +2 -0
  20. package/dist/assets/{client-CDa87uYD.js → client-q7dVOtYb.js} +10 -4
  21. package/dist/assets/client-q7dVOtYb.js.map +1 -0
  22. package/dist/assets/{codec-D45W1L8n.js → codec-HD6iOn_D.js} +2 -2
  23. package/dist/assets/{codec-D45W1L8n.js.map → codec-HD6iOn_D.js.map} +1 -1
  24. package/dist/assets/{envelope-C3yFCQa-.js → envelope-C-0tfbOG.js} +2 -2
  25. package/dist/assets/{envelope-C3yFCQa-.js.map → envelope-C-0tfbOG.js.map} +1 -1
  26. package/dist/assets/{fileBytes-DjBYYyXT.js → fileBytes-BABGEF13.js} +2 -2
  27. package/dist/assets/{fileBytes-DjBYYyXT.js.map → fileBytes-BABGEF13.js.map} +1 -1
  28. package/dist/assets/{fileBytes-DMzrIdCu.js → fileBytes-CQQK2uOh.js} +1 -1
  29. package/dist/assets/{fileBytes-Douk1yOp.js → fileBytes-DqnfKIkj.js} +2 -2
  30. package/dist/assets/{fileBytes-Douk1yOp.js.map → fileBytes-DqnfKIkj.js.map} +1 -1
  31. package/dist/assets/fileBytesIdb-BtXATa7j.js +2 -0
  32. package/dist/assets/{fileBytesIdb-CkClu9YI.js → fileBytesIdb-DrXmDUSy.js} +2 -2
  33. package/dist/assets/{fileBytesIdb-CkClu9YI.js.map → fileBytesIdb-DrXmDUSy.js.map} +1 -1
  34. package/dist/assets/{fileBytesOpfs-WryQuOgK.js → fileBytesOpfs-udKCzcLe.js} +6 -9
  35. package/dist/assets/{fileBytesOpfs-WryQuOgK.js.map → fileBytesOpfs-udKCzcLe.js.map} +1 -1
  36. package/dist/assets/{fixedHosts-C6nCHjOa.js → fixedHosts-CN3CsslV.js} +7 -8
  37. package/dist/assets/fixedHosts-CN3CsslV.js.map +1 -0
  38. package/dist/assets/{groupFiles-DYopNE57.js → groupFiles-BFv9K_za.js} +256 -110
  39. package/dist/assets/groupFiles-BFv9K_za.js.map +1 -0
  40. package/dist/assets/{host-G5seUwaI.js → host-C-wwtVt2.js} +378 -60
  41. package/dist/assets/host-C-wwtVt2.js.map +1 -0
  42. package/dist/assets/{hyperdhtRelay-B_uHjg_r.js → hyperdhtRelay-B9EQTm_M.js} +2 -2
  43. package/dist/assets/{hyperdhtRelay-B_uHjg_r.js.map → hyperdhtRelay-B9EQTm_M.js.map} +1 -1
  44. package/dist/assets/{irohWeb-C-2oslSU.js → irohWeb-o0H_NlCF.js} +2 -2
  45. package/dist/assets/{irohWeb-C-2oslSU.js.map → irohWeb-o0H_NlCF.js.map} +1 -1
  46. package/dist/assets/{main-Dk--nD7X.js → main-CLUIPy4d.js} +49 -30
  47. package/dist/assets/main-CLUIPy4d.js.map +1 -0
  48. package/dist/assets/{mainline-HPlVrl8R.js → mainline-B2qmNsib.js} +155 -3
  49. package/dist/assets/mainline-B2qmNsib.js.map +1 -0
  50. package/dist/assets/{networkReason-CfpO9ayz.js → networkReason-BEl-DDWd.js} +4 -4
  51. package/dist/assets/{networkReason-CfpO9ayz.js.map → networkReason-BEl-DDWd.js.map} +1 -1
  52. package/dist/assets/{nwc-BY7BPttn.js → nwc-BNkhjJHN.js} +3 -3
  53. package/dist/assets/{nwc-BY7BPttn.js.map → nwc-BNkhjJHN.js.map} +1 -1
  54. package/dist/assets/{nwcProvider-CfpbNUf7.js → nwcProvider-CvaRJdHT.js} +2 -2
  55. package/dist/assets/{nwcProvider-CfpbNUf7.js.map → nwcProvider-CvaRJdHT.js.map} +1 -1
  56. package/dist/assets/{ownDid-DJFZM2cV.js → ownDid-D67KNdJq.js} +3 -2
  57. package/dist/assets/ownDid-D67KNdJq.js.map +1 -0
  58. package/dist/assets/{profiles-DKmZGXp6.js → profiles-QDB7V_Qt.js} +7 -5
  59. package/dist/assets/profiles-QDB7V_Qt.js.map +1 -0
  60. package/dist/assets/{registry-BUm4cAzV.js → registry-BKkSnpjL.js} +126 -19
  61. package/dist/assets/registry-BKkSnpjL.js.map +1 -0
  62. package/dist/assets/{registry-CAzrtV0_.js → registry-DN5a8Ul6.js} +1 -1
  63. package/dist/assets/{resolve-CDD4X68j.js → resolve-DhpAggDP.js} +24 -5
  64. package/dist/assets/resolve-DhpAggDP.js.map +1 -0
  65. package/dist/assets/{server-DcOsgYDU.js → server-7w2O5wsv.js} +956 -277
  66. package/dist/assets/server-7w2O5wsv.js.map +1 -0
  67. package/dist/assets/{src-D31D1_oY.js → src-BZkY6N3J.js} +909 -198
  68. package/dist/assets/src-BZkY6N3J.js.map +1 -0
  69. package/dist/assets/{sshForges-DerRwMf3.js → sshForges-Cxjt3c51.js} +2 -2
  70. package/dist/assets/{sshForges-DerRwMf3.js.map → sshForges-Cxjt3c51.js.map} +1 -1
  71. package/dist/assets/{translate-C-sj0VJe.js → translate-v8wF1GcF.js} +2 -2
  72. package/dist/assets/{translate-C-sj0VJe.js.map → translate-v8wF1GcF.js.map} +1 -1
  73. package/dist/assets/{usdt-DwHqp625.js → usdt-63gYjM5E.js} +7 -4
  74. package/dist/assets/usdt-63gYjM5E.js.map +1 -0
  75. package/dist/assets/{waitNotice-D52RWbV4.js → waitNotice-Ce3YCinu.js} +27 -5
  76. package/dist/assets/waitNotice-Ce3YCinu.js.map +1 -0
  77. package/dist/assets/{words-Db9WgatT.js → words-PUnyO4ph.js} +4 -4
  78. package/dist/assets/words-PUnyO4ph.js.map +1 -0
  79. package/dist/ghostly.mjs +1 -1
  80. package/package.json +1 -1
  81. package/dist/assets/api-EUGHGnRz.js.map +0 -1
  82. package/dist/assets/apiKit-CJVp_crp.js.map +0 -1
  83. package/dist/assets/buttons-DA3wZfG0.js +0 -2
  84. package/dist/assets/client-CDa87uYD.js.map +0 -1
  85. package/dist/assets/fileBytesIdb-CD5Uv490.js +0 -2
  86. package/dist/assets/fixedHosts-C6nCHjOa.js.map +0 -1
  87. package/dist/assets/groupFiles-DYopNE57.js.map +0 -1
  88. package/dist/assets/host-G5seUwaI.js.map +0 -1
  89. package/dist/assets/main-Dk--nD7X.js.map +0 -1
  90. package/dist/assets/mainline-HPlVrl8R.js.map +0 -1
  91. package/dist/assets/ownDid-DJFZM2cV.js.map +0 -1
  92. package/dist/assets/profiles-DKmZGXp6.js.map +0 -1
  93. package/dist/assets/registry-BUm4cAzV.js.map +0 -1
  94. package/dist/assets/resolve-CDD4X68j.js.map +0 -1
  95. package/dist/assets/server-DcOsgYDU.js.map +0 -1
  96. package/dist/assets/src-D31D1_oY.js.map +0 -1
  97. package/dist/assets/usdt-DwHqp625.js.map +0 -1
  98. package/dist/assets/waitNotice-D52RWbV4.js.map +0 -1
  99. package/dist/assets/words-Db9WgatT.js.map +0 -1
@@ -599,6 +599,7 @@ function createRelayPayload(identity, records, timestampMicros = BigInt(Date.now
599
599
  */
600
600
  function signRelayPayload(identity, dnsPacket, seq) {
601
601
  if (dnsPacket.length > 1e3) throw new PacketTooLargeError(dnsPacket.length);
602
+ if (seq < 0n || seq >= 1n << 64n) throw new RangeError(`Sequence number ${seq} does not fit in 64 bits`);
602
603
  const signature = sign(signable(seq, dnsPacket), identity.seed);
603
604
  const timestamp = new Uint8Array(TIMESTAMP_LENGTH);
604
605
  new DataView(timestamp.buffer).setBigUint64(0, seq);
@@ -701,6 +702,7 @@ function withRequestOptions(transport, extra) {
701
702
  if (transport.turnRead) wrapped.turnRead = (pubKeyZ32, options) => transport.turnRead(pubKeyZ32, options);
702
703
  if (transport.turnPut) wrapped.turnPut = (pubKeyZ32, payload, conditions) => transport.turnPut(pubKeyZ32, payload, conditions);
703
704
  if (transport.turnWarm) wrapped.turnWarm = () => transport.turnWarm();
705
+ if (transport.forget) wrapped.forget = (keys) => transport.forget(keys);
704
706
  return wrapped;
705
707
  }
706
708
  /**
@@ -721,6 +723,30 @@ var DiscoveryBudgetError = class extends Error {
721
723
  function isDiscoveryBudgetError(error) {
722
724
  return error instanceof DiscoveryBudgetError || typeof error === "object" && error !== null && error.code === "discovery-budget" && typeof error.retryInMs === "number";
723
725
  }
726
+ /**
727
+ * A publish no relay took (`RelayTransport`), saying whether one of them may hold the packet all the same. Not
728
+ * `mayBeStored` only when every relay was not asked now (its budget, its rate limit, its breaker, its network
729
+ * cooldown), answered that it did not take it (a 4xx), or could not be reached before the request went (a refused
730
+ * connection or a name that does not resolve, where the runtime says so: Node does, a browser does not), or when there
731
+ * is no relay at all. A relay that did not answer in time, dropped the connection, or answered with a server error
732
+ * may have stored it. The message is the publish's usual one.
733
+ */
734
+ var PublishFailedError = class extends Error {
735
+ mayBeStored;
736
+ code = "publish-failed";
737
+ constructor(message, mayBeStored) {
738
+ super(message);
739
+ this.mayBeStored = mayBeStored;
740
+ }
741
+ };
742
+ /**
743
+ * Whether `error` is a publish that went nowhere (`PublishFailedError` with `mayBeStored` false), also from another
744
+ * copy of this module. Anything else (a timeout, the DHT's own failure beside the relays', a Desktop's error in
745
+ * words) may have left this device.
746
+ */
747
+ function publishedNowhere(error) {
748
+ return typeof error === "object" && error !== null && error.code === "publish-failed" && error.mayBeStored === false;
749
+ }
724
750
  /** When to try again after the budget held a request back: when it frees one, but never sooner than `min` nor later than `max`. */
725
751
  function budgetRetryMs(error, min, max) {
726
752
  return Math.min(max, Math.max(min, Number.isFinite(error.retryInMs) ? error.retryInMs : max));
@@ -904,6 +930,7 @@ var asker = (options, write) => ({
904
930
  watch: !!options.watch && !write,
905
931
  watchWrite: !!options.watch && write,
906
932
  departed: !!options.departed && !write,
933
+ awaited: !!options.awaited && !write,
907
934
  resume: !!options.resume && !write,
908
935
  back: !!options.back
909
936
  });
@@ -913,6 +940,8 @@ var isChat = (who) => !who.background && !who.group;
913
940
  var isChatSignal = (who) => who.signal && isChat(who);
914
941
  /** A 1:1 chat's read of a contact that just went away: a few may use the chat's allowance (`DEPARTED_READS`). */
915
942
  var isDepartedRead = (who) => who.departed && isChat(who);
943
+ /** A 1:1 chat's read of an invite this side made, its joiner due: a few may use the chat's allowance (`AWAITED_READS`). */
944
+ var isAwaitedRead = (who) => who.awaited && isChat(who);
916
945
  /** A group's edge looking fast for a signal (`GROUP_BURST_MS`). */
917
946
  var isGroupUrgentRead = (who) => who.group && who.urgent && !who.write && !who.background;
918
947
  /**
@@ -941,6 +970,7 @@ var ANSWER_READER = {
941
970
  watch: false,
942
971
  watchWrite: false,
943
972
  departed: false,
973
+ awaited: false,
944
974
  resume: false,
945
975
  back: false
946
976
  };
@@ -960,6 +990,13 @@ var firstWriter = (who) => !who.write || who.background ? null : who.group ? "gr
960
990
  /** 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`). */
961
991
  var staleTurn = (turn, now) => now - Math.max(turn.askedAt, turn.servedAt) >= 6e4;
962
992
  /**
993
+ * The times of `list` (oldest first) within the last `ms`. One dated after now, the device clock gone back since (an NTP
994
+ * step, a clock that ran ahead fixed by hand), counts as of now: as just spent, not for as long as the clock went back.
995
+ * Counted as they were, an hour's step back held every background read for 59 minutes, and a daemon with 50 contacts
996
+ * away read 4 of them in the next 15 (bug hunt, 2026-11-07).
997
+ */
998
+ var within = (list, now, ms) => list.map((at) => Math.min(at, now)).filter((at) => now - at < ms);
999
+ /**
963
1000
  * Keys and when each was last set, those of the last minute: how many and the latest, without walking them all (the
964
1001
  * chats that need a relay, `chatNeeds`). Each is set at the time it is set, so the sets come oldest first; a clock
965
1002
  * gone back makes the later ones as of now.
@@ -1202,6 +1239,7 @@ var CATCH_UP_ASKER = {
1202
1239
  watch: false,
1203
1240
  watchWrite: false,
1204
1241
  departed: false,
1242
+ awaited: false,
1205
1243
  resume: false,
1206
1244
  back: false
1207
1245
  };
@@ -1292,6 +1330,47 @@ function looksLikeHost(text) {
1292
1330
  /** A relay the breaker leaves alone for failing (`RelayBreaker`): nothing was asked of it now. */
1293
1331
  var RelayLeftAloneError = class extends Error {};
1294
1332
  /**
1333
+ * A relay a put did not get an answer from. `sent` false: the request never left (its network cooling down after a
1334
+ * failure, or a connection that could not be made, `connectFailed`); true: it may have reached the relay.
1335
+ */
1336
+ var RelayNoAnswerError = class extends Error {
1337
+ sent;
1338
+ constructor(message, sent) {
1339
+ super(message);
1340
+ this.sent = sent;
1341
+ }
1342
+ };
1343
+ /** What Node says of a connection it could not make: the request never left. A browser's TypeError says nothing either way. */
1344
+ var CONNECT_FAILURES = /* @__PURE__ */ new Set([
1345
+ "ECONNREFUSED",
1346
+ "ENOTFOUND",
1347
+ "EAI_AGAIN",
1348
+ "EHOSTUNREACH",
1349
+ "ENETUNREACH",
1350
+ "ENETDOWN",
1351
+ "EHOSTDOWN",
1352
+ "EADDRNOTAVAIL",
1353
+ "UND_ERR_CONNECT_TIMEOUT"
1354
+ ]);
1355
+ /** A fetch that failed before its request left this device: Node's `cause.code` (each of an AggregateError's, for several addresses). */
1356
+ function connectFailed(error) {
1357
+ const cause = error?.cause;
1358
+ if (!cause || typeof cause !== "object") return false;
1359
+ if (Array.isArray(cause.errors) && cause.errors.length) return cause.errors.every((e) => CONNECT_FAILURES.has(e?.code));
1360
+ return CONNECT_FAILURES.has(cause.code);
1361
+ }
1362
+ /**
1363
+ * The error a publish ends with after a second round dated past a relay's later copy failed too: one that may have
1364
+ * stored the first round's packet still may, whatever the second round's relays said.
1365
+ */
1366
+ function laterRound(first, later) {
1367
+ return publishedNowhere(later) && !publishedNowhere(first) ? new PublishFailedError(later.message, true) : later;
1368
+ }
1369
+ /** A packet date no further ahead of this clock than readers take (`newerPacket`): one this client may date past. */
1370
+ function withinSkew(timestamp) {
1371
+ return timestamp <= BigInt(Date.now() + PKARR_FUTURE_SKEW_MS) * 1000n;
1372
+ }
1373
+ /**
1295
1374
  * A read the relays failed (or left alone for failing before), when its caller has another path to ask
1296
1375
  * (`RelayTransport.resolve` with `keptOnFailure` false): `kept` is the newest packet the relays gave for the key before.
1297
1376
  */
@@ -1315,7 +1394,9 @@ var RelayTransport = class {
1315
1394
  * records are written by every member, an inviter warms its contact's key with an empty packet, and this device's
1316
1395
  * own clock may have been set back since it last wrote. A relay and the DHT keep only the packet dated latest, so
1317
1396
  * one dated by this clock alone, when it is behind, was refused (409) or silently never read, until this clock
1318
- * caught up with the other one: minutes, or an hour.
1397
+ * caught up with the other one: minutes, or an hour. Only up to `PKARR_FUTURE_SKEW_MS` ahead of this clock
1398
+ * (`withinSkew`): a packet one holder of a shared key dated further ahead must not date every later one of this
1399
+ * device past it (past 64 bits, unsignable; else ahead of every reader's clock, never taken over one dated now).
1319
1400
  */
1320
1401
  seenTimestamp = /* @__PURE__ */ new Map();
1321
1402
  /**
@@ -1350,6 +1431,10 @@ var RelayTransport = class {
1350
1431
  spentAnswerAllowance = /* @__PURE__ */ new Map();
1351
1432
  /** Per contact, its departed reads past the limit in the last minute, every relay together (`DEPARTED_READS`). */
1352
1433
  departedOver = /* @__PURE__ */ new Map();
1434
+ /** Per invite, its awaited reads past the limit in the last minute, every relay together (`AWAITED_READS`). */
1435
+ awaitedOver = /* @__PURE__ */ new Map();
1436
+ /** When an awaited invite's read last asked: the departed reads leave it room for a minute (`AWAITED_READS`). */
1437
+ awaitedAt = -Infinity;
1353
1438
  /**
1354
1439
  * Per key a group reads (not in the background), when a read of it last went out and when it last asked: whose turn
1355
1440
  * it is under the watch share (`WATCH_SHARE`) and while the groups' reads are rationed (`GROUP_RATION_WINDOW_MS`). And
@@ -1402,6 +1487,10 @@ var RelayTransport = class {
1402
1487
  hedgeMs;
1403
1488
  /** Until when each relay found slow (`SLOW_MS`) goes after the others in a read (`readOrder`). */
1404
1489
  slowUntil = /* @__PURE__ */ new Map();
1490
+ /** Per relay, when each of this client's requests still waiting for its answer went out (`unanswering`). */
1491
+ waiting = /* @__PURE__ */ new Map();
1492
+ /** When each relay last answered a request of this client, whatever it said (`unanswering`). */
1493
+ answeredAt = /* @__PURE__ */ new Map();
1405
1494
  /** Keys whose last read was answered 404: their next read hedges later (`HEDGE_MISSING_MS`). */
1406
1495
  missing = /* @__PURE__ */ new Set();
1407
1496
  listeners = /* @__PURE__ */ new Set();
@@ -1458,6 +1547,24 @@ var RelayTransport = class {
1458
1547
  this.slowUntil.clear();
1459
1548
  this.changed("recovered");
1460
1549
  }
1550
+ /**
1551
+ * `PkarrTransport.forget`: the packets and dates this client kept under these keys go, on every relay (`written`,
1552
+ * `newest`, `lastTimestamp`, `seenTimestamp`, `lastPut`). A spare invite replaced unused left them here for its two keys
1553
+ * for good: an idle CLI daemon gained 8 keys an hour (343 in `written` and 690 `lastPut` entries after a day). The maps
1554
+ * that bound themselves (`readAt`, `lastReadFrom`, `heldBack`, `missing`, the turns) and the catch-ups, which go once
1555
+ * put, are left as they are. A later put under one of these keys goes as a key's first.
1556
+ */
1557
+ forget(keys) {
1558
+ const gone = new Set(keys);
1559
+ if (gone.size === 0) return;
1560
+ for (const key of gone) for (const perKey of [
1561
+ this.lastTimestamp,
1562
+ this.seenTimestamp,
1563
+ this.newest,
1564
+ this.written
1565
+ ]) perKey.delete(key);
1566
+ for (const slot of this.lastPut.keys()) if (gone.has(slot.slice(slot.lastIndexOf(" ") + 1))) this.lastPut.delete(slot);
1567
+ }
1461
1568
  /** Called when a relay trips or recovers. */
1462
1569
  subscribe(listener) {
1463
1570
  this.listeners.add(listener);
@@ -1493,7 +1600,7 @@ var RelayTransport = class {
1493
1600
  * Returns once one relay took the packet: the others finish in the background.
1494
1601
  */
1495
1602
  async publish(identity, records, options = {}) {
1496
- if (this.relays.length === 0) throw new Error("No Pkarr relays configured");
1603
+ if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
1497
1604
  await this.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putEverywhere(key, payload, timestamp, options, conflict), options);
1498
1605
  }
1499
1606
  /**
@@ -1532,7 +1639,7 @@ var RelayTransport = class {
1532
1639
  if (again || redated) return;
1533
1640
  redated = (async () => {
1534
1641
  const held = read ? await read().catch(() => null) : await this.heldAt(relay, key, asker(options, true));
1535
- if (held === null || held < timestamp) return false;
1642
+ if (held === null || held < timestamp || !withinSkew(held)) return false;
1536
1643
  traceLink(key, "publish-redated", {
1537
1644
  aheadMs: Number((held - timestamp) / 1000n),
1538
1645
  relay
@@ -1547,7 +1654,9 @@ var RelayTransport = class {
1547
1654
  await put(key, createRelayPayload(identity, records, timestamp), timestamp, conflict);
1548
1655
  } catch (error) {
1549
1656
  const pending = redated;
1550
- if (!pending || !await pending) throw error;
1657
+ if (!pending || !await pending.catch((later) => {
1658
+ throw laterRound(error, later);
1659
+ })) throw error;
1551
1660
  }
1552
1661
  }
1553
1662
  /** `PkarrTransport.publishHeld`: `publishDated`'s check before signing, for a payload signed elsewhere in this process. */
@@ -1613,7 +1722,7 @@ var RelayTransport = class {
1613
1722
  }
1614
1723
  /** A packet under this key was read (on a relay, or by the CLI on the DHT): its time, for `nextTimestamp`. */
1615
1724
  sawTimestamp(pubKeyZ32, timestamp) {
1616
- if (timestamp > (this.seenTimestamp.get(pubKeyZ32) ?? 0n)) this.seenTimestamp.set(pubKeyZ32, timestamp);
1725
+ if (withinSkew(timestamp) && timestamp > (this.seenTimestamp.get(pubKeyZ32) ?? 0n)) this.seenTimestamp.set(pubKeyZ32, timestamp);
1617
1726
  }
1618
1727
  /**
1619
1728
  * Puts a payload `publishDated` just signed, dated `timestamp`, on every relay. Its signature is not checked: it was
@@ -1621,7 +1730,7 @@ var RelayTransport = class {
1621
1730
  * gives it.
1622
1731
  */
1623
1732
  async putSigned(pubKeyZ32, payload, timestamp, options = {}, conflict) {
1624
- if (this.relays.length === 0) throw new Error("No Pkarr relays configured");
1733
+ if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
1625
1734
  await this.putEverywhere(pubKeyZ32, payload, timestamp, options, conflict);
1626
1735
  }
1627
1736
  /**
@@ -1629,7 +1738,7 @@ var RelayTransport = class {
1629
1738
  * (`signedAt`) and is not checked again. `conflict`: as `publishDated` gives it.
1630
1739
  */
1631
1740
  async publishPayload(pubKeyZ32, payload, options = {}, conflict) {
1632
- if (this.relays.length === 0) throw new Error("No Pkarr relays configured");
1741
+ if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
1633
1742
  const seq = options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;
1634
1743
  if (options.signedAt === void 0 || !options.redate) return this.putEverywhere(pubKeyZ32, payload, seq, options, conflict);
1635
1744
  await this.putRedated(pubKeyZ32, payload, seq, options, PAYLOAD_REDATES);
@@ -1662,7 +1771,7 @@ var RelayTransport = class {
1662
1771
  if (left <= 0 || redated) return;
1663
1772
  redated = (async () => {
1664
1773
  const held = await this.heldAt(relay, key, asker(options, true));
1665
- if (held === null || held < timestamp) return false;
1774
+ if (held === null || held < timestamp || !withinSkew(held)) return false;
1666
1775
  if (this.lastTimestamp.get(key) !== timestamp) return true;
1667
1776
  const again = options.redate(held);
1668
1777
  if (!again) return true;
@@ -1682,7 +1791,9 @@ var RelayTransport = class {
1682
1791
  await this.putEverywhere(key, payload, timestamp, options, conflict);
1683
1792
  } catch (error) {
1684
1793
  const pending = redated;
1685
- if (!pending || !await pending) throw error;
1794
+ if (!pending || !await pending.catch((later) => {
1795
+ throw laterRound(error, later);
1796
+ })) throw error;
1686
1797
  }
1687
1798
  }
1688
1799
  /**
@@ -1708,11 +1819,15 @@ var RelayTransport = class {
1708
1819
  let first;
1709
1820
  const edgeSignal = isGroupSignal(asker(options, true));
1710
1821
  const failed = /* @__PURE__ */ new Set();
1711
- const puts = this.relays.map(async (relay) => {
1822
+ const nowhere = this.relays.map(() => false);
1823
+ const puts = this.relays.map(async (relay, i) => {
1712
1824
  const slot = `${relay} ${pubKeyZ32}`;
1713
1825
  const previous = this.lastPut.get(slot);
1714
1826
  this.lastPut.set(slot, timestamp);
1715
- if (first && isChat(asker(options, true)) && this.spareHeldFor(relay, Date.now()) > 0 && await answeredWithin(first, 3e3)) throw new DiscoveryBudgetError(Math.max(CATCH_UP_MIN_MS, this.spareHeldFor(relay, Date.now())));
1827
+ if (first && isChat(asker(options, true)) && this.spareHeldFor(relay, Date.now()) > 0 && await answeredWithin(first, 3e3)) {
1828
+ nowhere[i] = true;
1829
+ throw new DiscoveryBudgetError(Math.max(CATCH_UP_MIN_MS, this.spareHeldFor(relay, Date.now())));
1830
+ }
1716
1831
  let response;
1717
1832
  try {
1718
1833
  response = await this.put(relay, pubKeyZ32, payload, previous, asker(options, true), relay === probe, (ok) => {
@@ -1721,8 +1836,10 @@ var RelayTransport = class {
1721
1836
  if (response.status === 412) response = await this.put(relay, pubKeyZ32, payload, void 0, asker(options, true));
1722
1837
  } catch (error) {
1723
1838
  if (!isDiscoveryBudgetError(error) && !(error instanceof RelayLeftAloneError)) failed.add(relay);
1839
+ nowhere[i] = isDiscoveryBudgetError(error) || error instanceof RelayLeftAloneError || error instanceof RelayNoAnswerError && !error.sent;
1724
1840
  throw error;
1725
1841
  }
1842
+ nowhere[i] = response.status >= 400 && response.status < 500;
1726
1843
  if (response.status >= 500 || response.status === 428) failed.add(relay);
1727
1844
  if (response.status === 409) conflict?.(relay);
1728
1845
  if (response.status === 429) throw new DiscoveryBudgetError(this.coolDown(relay, response), `${relay} responded 429; retry shortly`);
@@ -1755,7 +1872,7 @@ var RelayTransport = class {
1755
1872
  const reasons = results.map((r) => r.status === "rejected" ? String(r.reason) : "").join("; ");
1756
1873
  if (waits.length === results.length) reject(new DiscoveryBudgetError(Math.min(...waits.map((e) => e.retryInMs)), `Publish held back on every relay: ${reasons}`));
1757
1874
  else if (waits.length && results.every((r, i) => held[i] !== null || leftAlone(r))) reject(new DiscoveryBudgetError(Math.min(...waits.map((e) => e.retryInMs)), `Publish held back on every relay not left alone: ${reasons}`));
1758
- else reject(/* @__PURE__ */ new Error(`Publish failed on every relay: ${reasons}`));
1875
+ else reject(new PublishFailedError(`Publish failed on every relay: ${reasons}`, !nowhere.every(Boolean)));
1759
1876
  });
1760
1877
  });
1761
1878
  }
@@ -1783,8 +1900,8 @@ var RelayTransport = class {
1783
1900
  async resolve(pubKeyZ32, options = {}, keptOnFailure = true) {
1784
1901
  if (this.relays.length === 0) throw new Error("No Pkarr relays configured");
1785
1902
  if (options.background && !options.urgent && !options.group) this.chatNeedLapsed(pubKeyZ32);
1786
- const readAt = this.readAt.get(pubKeyZ32);
1787
- if (readAt !== void 0 && Date.now() - readAt < this.freshReadMs) return this.newest.get(pubKeyZ32) ?? null;
1903
+ const readAt = this.readAt.get(pubKeyZ32), age = readAt === void 0 ? Infinity : Date.now() - readAt;
1904
+ if (age >= 0 && age < this.freshReadMs) return this.newest.get(pubKeyZ32) ?? null;
1788
1905
  const order = this.readOrder(pubKeyZ32);
1789
1906
  const probe = this.breaker.allDownProbe(this.relays);
1790
1907
  let budgetWait = Infinity, down = false;
@@ -1903,7 +2020,7 @@ var RelayTransport = class {
1903
2020
  }
1904
2021
  for (const loser of asked.values()) {
1905
2022
  loser.controller.abort();
1906
- if (outcome.kind === "packet" && loser.started <= attempt.started) this.slow(loser.relay);
2023
+ if (loser.started <= attempt.started && (outcome.kind === "packet" || Date.now() - loser.started >= 6e3)) this.slow(loser.relay);
1907
2024
  else this.breaker.cancel(loser.relay);
1908
2025
  }
1909
2026
  this.lastRelay = relay;
@@ -1925,7 +2042,8 @@ var RelayTransport = class {
1925
2042
  throw new Error("No Pkarr relay reachable");
1926
2043
  }
1927
2044
  /**
1928
- * The order a key's read asks the relays in: in turn per key (see `resolve`), relays found slow lately last. A relay
2045
+ * The order a key's read asks the relays in: in turn per key (see `resolve`), relays found slow lately or leaving a
2046
+ * request unanswered (`unanswering`) last. A relay
1929
2047
  * with a small share of its own (`RELAY_REQUESTS_PER_MINUTE` under `REQUESTS_PER_MINUTE`: pkarr.miguelmedeiros.dev's 5)
1930
2048
  * takes no turns: it comes after the others, for when they refuse, fail or are slow, unless every relay is one. In the
1931
2049
  * turn, it was spent in seconds and the relay after it took its turns too: pkarr.pubky.org got two reads in three and
@@ -1938,8 +2056,19 @@ var RelayTransport = class {
1938
2056
  const after = lastAt < 0 ? -1 : ring.findIndex((relay) => this.relays.indexOf(relay) > lastAt);
1939
2057
  const start = lastAt < 0 ? this.cursor++ : after < 0 ? 0 : after;
1940
2058
  const turn = [...ring.map((_, i) => ring[(start + i) % ring.length]), ...this.relays.filter((relay) => !ring.includes(relay))];
1941
- const now = Date.now(), slow = (relay) => (this.slowUntil.get(relay) ?? 0) > now;
1942
- return [...turn.filter((relay) => !slow(relay)), ...turn.filter(slow)];
2059
+ const now = Date.now(), behind = (relay) => (this.slowUntil.get(relay) ?? 0) > now || this.unanswering(relay, now);
2060
+ return [...turn.filter((relay) => !behind(relay)), ...turn.filter(behind)];
2061
+ }
2062
+ /**
2063
+ * A request of this client has waited on the relay for `HEDGE_MS` and it has answered none since: it goes after the
2064
+ * others in a read (`readOrder`), at no cost of a request. A relay that took connections and never answered held a
2065
+ * fresh device's first pairing at its turn: the key's last read had found nothing (`HEDGE_MISSING_MS`), so the read
2066
+ * waited 6 s on it before asking the relay that had held the packet all along (8 s join to live, not 2.5 s).
2067
+ */
2068
+ unanswering(relay, now) {
2069
+ const since = this.answeredAt.get(relay) ?? -Infinity;
2070
+ for (const request of this.waiting.get(relay) ?? []) if (request.at > since && now - request.at >= this.hedgeMs) return true;
2071
+ return false;
1943
2072
  }
1944
2073
  /** One GET of a key at one relay, which `controller` drops. Never rejects: what happened is the outcome. */
1945
2074
  readFromRelay(relay, pubKeyZ32) {
@@ -1992,7 +2121,7 @@ var RelayTransport = class {
1992
2121
  */
1993
2122
  hedgeRoom(relay) {
1994
2123
  const now = Date.now();
1995
- return (this.spent.get(relay) ?? []).filter((at) => now - at < 6e4).length < this.limitOf(relay) - this.reserveOf(relay);
2124
+ return within(this.spent.get(relay) ?? [], now, 6e4).length < this.limitOf(relay) - this.reserveOf(relay);
1996
2125
  }
1997
2126
  readAnsweredAt(pubKeyZ32) {
1998
2127
  return this.readAt.get(pubKeyZ32);
@@ -2089,7 +2218,7 @@ var RelayTransport = class {
2089
2218
  }
2090
2219
  /** `sent`: told, once the budget took the request, whether the relay takes the packet (a 2xx). */
2091
2220
  async put(relay, pubKeyZ32, payload, replaces, who, probe = false, sent) {
2092
- if (!probe && this.networkCoolingDown(relay, "PUT")) throw new Error(`${relay} did not answer a moment ago; retry shortly`);
2221
+ if (!probe && this.networkCoolingDown(relay, "PUT")) throw new RelayNoAnswerError(`${relay} did not answer a moment ago; retry shortly`, false);
2093
2222
  const limited = this.rateLimitedFor(relay);
2094
2223
  if (limited > 0) throw new DiscoveryBudgetError(limited, "Discovery relay is cooling down after a 429; retry shortly");
2095
2224
  const blocked = probe ? 0 : this.breaker.blockedFor(relay);
@@ -2109,13 +2238,13 @@ var RelayTransport = class {
2109
2238
  let response;
2110
2239
  try {
2111
2240
  response = await request;
2112
- } catch {
2241
+ } catch (error) {
2113
2242
  this.networkCooldown.set(`PUT ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
2114
2243
  this.answered(relay, {
2115
2244
  kind: "error",
2116
2245
  reason: "no answer"
2117
2246
  });
2118
- throw new Error(`${relay} did not answer`);
2247
+ throw new RelayNoAnswerError(`${relay} did not answer`, !connectFailed(error));
2119
2248
  }
2120
2249
  if (response.status === 429) this.answered(relay, {
2121
2250
  kind: "throttled",
@@ -2142,6 +2271,7 @@ var RelayTransport = class {
2142
2271
  }
2143
2272
  if (isGroupRead(who) || isChatWatch(who)) this.readAsked(key, who, now);
2144
2273
  if (isTurnRead(who)) this.turnAsked(key, who, now);
2274
+ if (isAwaitedRead(who)) this.awaitedAt = now;
2145
2275
  if (this.heldFor(relay, who, now, key) > 0) {
2146
2276
  if (isGroupRead(who) && (this.spent.get(relay)?.length ?? 0) >= this.limitOf(relay)) this.groupsFullAt.set(relay, now);
2147
2277
  if (isChat(who)) this.chatNeed(key, now, relay);
@@ -2183,7 +2313,8 @@ var RelayTransport = class {
2183
2313
  if (isGroupSignal(who) && !who.write && this.spent.get(relay).length >= this.limitOf(relay)) this.spentGroupOver.get(relay).push(now);
2184
2314
  if (isGroupSignal(who)) this.spentGroupSignal.get(relay).push(now);
2185
2315
  const departedOver = isDepartedRead(who) && this.spent.get(relay).length >= this.limitOf(relay);
2186
- if (departedOver) this.departedOverAdd(key, now);
2316
+ if (departedOver) this.overAdd(this.departedOver, key, now);
2317
+ if (isAwaitedRead(who) && this.spent.get(relay).length >= this.limitOf(relay)) this.overAdd(this.awaitedOver, key, now);
2187
2318
  this.spent.get(relay).push(now);
2188
2319
  if (who.background) this.spentBackground.get(relay).push(now);
2189
2320
  if (who.background && who.write) this.spentBackgroundWrites.get(relay).push(now);
@@ -2214,27 +2345,29 @@ var RelayTransport = class {
2214
2345
  * Who goes first: a chat's refused write holds back everything but chat writes; a group's refused write holds back
2215
2346
  * group reads and background requests, never a chat's. Background requests yield to a link that signals. A chat's
2216
2347
  * signaling goes over the limit by its allowance (`SIGNALING_ALLOWANCE_SHARE`), and so do a few of its reads of a
2217
- * contact that just went away (`DEPARTED_READS`). `ownAllowance` false: what holds an edge's read for its answer
2348
+ * contact that just went away (`DEPARTED_READS`) or of an invite awaited (`AWAITED_READS`). `ownAllowance` false: what holds an edge's read for its answer
2218
2349
  * without its own allowance (`ANSWER_READ_ALLOWANCE`).
2219
2350
  */
2220
2351
  heldFor(relay, who, now = Date.now(), key, turns = true, ownAllowance = true) {
2221
- const recent = (this.spent.get(relay) ?? []).filter((at) => now - at < 6e4);
2222
- const recentBackground = (this.spentBackground.get(relay) ?? []).filter((at) => now - at < 6e4);
2352
+ const recent = within(this.spent.get(relay) ?? [], now, 6e4);
2353
+ const recentBackground = within(this.spentBackground.get(relay) ?? [], now, 6e4);
2223
2354
  this.spent.set(relay, recent);
2224
2355
  this.spentBackground.set(relay, recentBackground);
2225
- const recentBackgroundWrites = (this.spentBackgroundWrites.get(relay) ?? []).filter((at) => now - at < 6e4);
2356
+ const recentBackgroundWrites = within(this.spentBackgroundWrites.get(relay) ?? [], now, 6e4);
2226
2357
  this.spentBackgroundWrites.set(relay, recentBackgroundWrites);
2227
2358
  const over = (list, limit) => list.length >= limit ? list[list.length - limit] + 6e4 - now : 0;
2228
2359
  const limit = this.limitOf(relay);
2229
- const departed = isDepartedRead(who) && key !== void 0 && recent.length >= limit && this.departedReads(key, now) < 6;
2230
- const share = isChatSignal(who) || departed ? SIGNALING_ALLOWANCE_SHARE : isGroupSignal(who) ? GROUP_SIGNALING_ALLOWANCE_SHARE : 0;
2231
- const allowance = share ? Math.max(0, Math.floor(limit * share) - (who.write ? 0 : 1)) : 0;
2232
- const groupSignaled = (this.spentGroupSignal.get(relay) ?? []).filter((at) => now - at < 6e4);
2360
+ const departed = isDepartedRead(who) && key !== void 0 && recent.length >= limit && this.overReads(this.departedOver, key, now) < 6;
2361
+ const awaited = isAwaitedRead(who) && key !== void 0 && recent.length >= limit && this.overReads(this.awaitedOver, key, now) < 4;
2362
+ const share = isChatSignal(who) || departed || awaited ? SIGNALING_ALLOWANCE_SHARE : isGroupSignal(who) ? GROUP_SIGNALING_ALLOWANCE_SHARE : 0;
2363
+ let allowance = share ? Math.max(0, Math.floor(limit * share) - (who.write ? 0 : 1)) : 0;
2364
+ if (departed && now - this.awaitedAt < 6e4) allowance = Math.max(0, allowance - 2);
2365
+ const groupSignaled = within(this.spentGroupSignal.get(relay) ?? [], now, 6e4);
2233
2366
  this.spentGroupSignal.set(relay, groupSignaled);
2234
2367
  const groupFloor = isGroupSignal(who) && groupSignaled.length < allowance;
2235
2368
  let wait = groupFloor ? 0 : over(recent, limit + allowance);
2236
2369
  const starved = key !== void 0 && this.starved(key, who, now);
2237
- const groupOver = (this.spentGroupOver.get(relay) ?? []).filter((at) => now - at < GROUP_OVER_PACE_MS);
2370
+ const groupOver = within(this.spentGroupOver.get(relay) ?? [], now, GROUP_OVER_PACE_MS);
2238
2371
  this.spentGroupOver.set(relay, groupOver);
2239
2372
  if (isGroupSignal(who) && !who.write && recent.length >= limit && groupOver.length > 0) wait = Math.max(wait, groupOver[groupOver.length - 1] + GROUP_OVER_PACE_MS - now);
2240
2373
  if (who.background && !starved) {
@@ -2244,16 +2377,16 @@ var RelayTransport = class {
2244
2377
  const signaling = this.urgentAt + SIGNALING_WINDOW_MS - now;
2245
2378
  if (signaling > 0 && !who.door) wait = Math.max(wait, Math.min(signaling, over(recentBackground, Math.min(this.backgroundWhileSignaling, Math.ceil(limit / 6)))));
2246
2379
  }
2247
- const burst = (this.spentGroupUrgent.get(relay) ?? []).filter((at) => now - at < GROUP_BURST_MS);
2380
+ const burst = within(this.spentGroupUrgent.get(relay) ?? [], now, GROUP_BURST_MS);
2248
2381
  this.spentGroupUrgent.set(relay, burst);
2249
- const answerBurst = (this.spentAnswerUrgent.get(relay) ?? []).filter((at) => now - at < GROUP_BURST_MS);
2382
+ const answerBurst = within(this.spentAnswerUrgent.get(relay) ?? [], now, GROUP_BURST_MS);
2250
2383
  this.spentAnswerUrgent.set(relay, answerBurst);
2251
2384
  if (isGroupUrgentRead(who)) {
2252
2385
  const most = Math.max(8, Math.floor(limit * GROUP_BURST_MS / 6e4));
2253
2386
  const spent = isGroupAnswerRead(who) ? answerBurst : burst;
2254
2387
  if (spent.length >= most) wait = Math.max(wait, spent[spent.length - most] + GROUP_BURST_MS - now);
2255
2388
  }
2256
- const watched = (this.spentWatch.get(relay) ?? []).filter((at) => now - at < GROUP_RATION_WINDOW_MS);
2389
+ const watched = within(this.spentWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
2257
2390
  this.spentWatch.set(relay, watched);
2258
2391
  let turn = 0;
2259
2392
  if (isWatch(who)) {
@@ -2261,14 +2394,14 @@ var RelayTransport = class {
2261
2394
  if (watched.length >= most) wait = Math.max(wait, watched[watched.length - most] + GROUP_RATION_WINDOW_MS - now);
2262
2395
  if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;
2263
2396
  }
2264
- const chatWatched = (this.spentChatWatch.get(relay) ?? []).filter((at) => now - at < GROUP_RATION_WINDOW_MS);
2397
+ const chatWatched = within(this.spentChatWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
2265
2398
  this.spentChatWatch.set(relay, chatWatched);
2266
2399
  if (isChatWatch(who) && !departed) {
2267
2400
  const most = Math.max(1, Math.ceil(limit * CHAT_WATCH_SHARE * GROUP_RATION_WINDOW_MS / 6e4));
2268
2401
  if (chatWatched.length >= most) wait = Math.max(wait, chatWatched[chatWatched.length - most] + GROUP_RATION_WINDOW_MS - now);
2269
2402
  if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;
2270
2403
  }
2271
- const rationed = (this.spentGroupReads.get(relay) ?? []).filter((at) => now - at < GROUP_RATION_WINDOW_MS);
2404
+ const rationed = within(this.spentGroupReads.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
2272
2405
  this.spentGroupReads.set(relay, rationed);
2273
2406
  const pastLimit = isGroupSignal(who) && recent.length >= limit;
2274
2407
  if (isGroupRead(who) && !pastLimit && now - (this.groupsFullAt.get(relay) ?? -Infinity) < GROUP_RATION_MS) {
@@ -2285,7 +2418,8 @@ var RelayTransport = class {
2285
2418
  const at = this.writeWaiting.get(`${lane} ${relay}`);
2286
2419
  return at !== void 0 && now - at < 5e3 ? at + WRITE_FIRST_MS - now : 0;
2287
2420
  };
2288
- if (writer !== "chat" && !departed && !starved) wait = Math.max(wait, waiting("chat"));
2421
+ const signalOver = isChatSignal(who) && !who.write && recent.length >= limit;
2422
+ if (writer !== "chat" && !departed && !awaited && !signalOver && !starved) wait = Math.max(wait, waiting("chat"));
2289
2423
  if ((writer === null && who.group && !pastLimit && !isGroupAnswerRead(who) || who.background) && !starved) wait = Math.max(wait, waiting("group"));
2290
2424
  if (isGroupSignal(who) && !isGroupAnswerRead(who)) {
2291
2425
  const ahead = this.answerReadAhead(relay, now);
@@ -2301,7 +2435,7 @@ var RelayTransport = class {
2301
2435
  * than it in the last minute, and none within `ANSWER_READ_SPACING_MS`. None where the groups have no allowance.
2302
2436
  */
2303
2437
  answerAllowanceFree(relay, now) {
2304
- const spent = (this.spentAnswerAllowance.get(relay) ?? []).filter((at) => now - at < 6e4);
2438
+ const spent = within(this.spentAnswerAllowance.get(relay) ?? [], now, 6e4);
2305
2439
  this.spentAnswerAllowance.set(relay, spent);
2306
2440
  const most = Math.min(3, Math.floor(this.limitOf(relay) * GROUP_SIGNALING_ALLOWANCE_SHARE));
2307
2441
  return spent.length < most && (spent.length === 0 || now - spent[spent.length - 1] >= 2e4);
@@ -2326,7 +2460,7 @@ var RelayTransport = class {
2326
2460
  }
2327
2461
  /** What is left of the community members' way back allowance on this relay (`WAY_BACK_SHARE`); its reads leave a write the last of it. */
2328
2462
  wayBackLeft(relay, who, now) {
2329
- const spent = (this.spentWayBack.get(relay) ?? []).filter((at) => now - at < 6e4);
2463
+ const spent = within(this.spentWayBack.get(relay) ?? [], now, 6e4);
2330
2464
  this.spentWayBack.set(relay, spent);
2331
2465
  return Math.floor(this.limitOf(relay) * WAY_BACK_SHARE) - (who.write ? 0 : 1) - spent.length;
2332
2466
  }
@@ -2373,9 +2507,17 @@ var RelayTransport = class {
2373
2507
  }
2374
2508
  /** Drops the turns asked and read over a minute ago, at most once in `TURNS_PRUNE_MS` (or when the clock went back). */
2375
2509
  pruneTurns(turns, now) {
2376
- if (Math.abs(now - (this.turnsPrunedAt.get(turns) ?? -Infinity)) < TURNS_PRUNE_MS) return;
2510
+ const prunedAt = this.turnsPrunedAt.get(turns) ?? -Infinity;
2511
+ if (Math.abs(now - prunedAt) < TURNS_PRUNE_MS) return;
2377
2512
  this.turnsPrunedAt.set(turns, now);
2378
- for (const [key, turn] of turns) if (staleTurn(turn, now)) turns.delete(key);
2513
+ const back = now < prunedAt;
2514
+ for (const [key, turn] of turns) {
2515
+ if (back) {
2516
+ turn.servedAt = Math.min(turn.servedAt, now);
2517
+ turn.askedAt = Math.min(turn.askedAt, now);
2518
+ }
2519
+ if (staleTurn(turn, now)) turns.delete(key);
2520
+ }
2379
2521
  }
2380
2522
  /**
2381
2523
  * Whether a key read in turn longer ago than `key`, still asking, would take this relay's next request: one read in the
@@ -2400,17 +2542,17 @@ var RelayTransport = class {
2400
2542
  const since = this.heldBack.get(key)?.since;
2401
2543
  return !who.group && !who.write && !who.door && since !== void 0 && now - since >= READ_STARVED_MS;
2402
2544
  }
2403
- /** This contact's departed reads past the limit in the last minute (`DEPARTED_READS`). */
2404
- departedReads(key, now) {
2405
- const reads = (this.departedOver.get(key) ?? []).filter((at) => now - at < 6e4);
2406
- if (reads.length) this.departedOver.set(key, reads);
2407
- else this.departedOver.delete(key);
2545
+ /** This key's departed or awaited reads past the limit in the last minute (`DEPARTED_READS`, `AWAITED_READS`). */
2546
+ overReads(over, key, now) {
2547
+ const reads = within(over.get(key) ?? [], now, 6e4);
2548
+ if (reads.length) over.set(key, reads);
2549
+ else over.delete(key);
2408
2550
  return reads.length;
2409
2551
  }
2410
- /** One more, the contacts with none in the last minute dropped. */
2411
- departedOverAdd(key, now) {
2412
- for (const [other, reads] of this.departedOver) if (now - reads[reads.length - 1] >= 6e4) this.departedOver.delete(other);
2413
- this.departedOver.set(key, [...this.departedOver.get(key) ?? [], now]);
2552
+ /** One more, the keys with none in the last minute dropped. */
2553
+ overAdd(over, key, now) {
2554
+ for (const [other, reads] of over) if (now - reads[reads.length - 1] >= 6e4) over.delete(other);
2555
+ over.set(key, [...over.get(key) ?? [], now]);
2414
2556
  }
2415
2557
  /** A chat's request of `key` asked urgently (it needs every relay), or the budget refused it on `relay` (it needs that one). */
2416
2558
  chatNeed(key, now, relay) {
@@ -2450,7 +2592,7 @@ var RelayTransport = class {
2450
2592
  spareHeldFor(relay, now) {
2451
2593
  const reserved = this.chatReservedFor(relay, now);
2452
2594
  if (reserved <= 0) return 0;
2453
- const recent = (this.spent.get(relay) ?? []).filter((at) => now - at < 6e4);
2595
+ const recent = within(this.spent.get(relay) ?? [], now, 6e4);
2454
2596
  const keep = this.limitOf(relay) - this.chatReserveOf(relay, now);
2455
2597
  return recent.length >= keep ? Math.min(reserved, recent[recent.length - keep] + 6e4 - now) : 0;
2456
2598
  }
@@ -2624,6 +2766,9 @@ var RelayTransport = class {
2624
2766
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
2625
2767
  const drop = () => controller.abort();
2626
2768
  cancel?.addEventListener("abort", drop, { once: true });
2769
+ const relay = url.slice(0, url.lastIndexOf("/")), request = { at: Date.now() };
2770
+ const waiting = this.waiting.get(relay) ?? /* @__PURE__ */ new Set();
2771
+ this.waiting.set(relay, waiting.add(request));
2627
2772
  try {
2628
2773
  const sent = Date.now();
2629
2774
  const response = await this.fetchFn(url, {
@@ -2631,10 +2776,12 @@ var RelayTransport = class {
2631
2776
  cache: "no-store",
2632
2777
  signal: controller.signal
2633
2778
  });
2779
+ this.answeredAt.set(relay, Date.now());
2634
2780
  this.serverTime(url, response, sent);
2635
2781
  await read?.(response, controller.signal);
2636
2782
  return response;
2637
2783
  } finally {
2784
+ waiting.delete(request);
2638
2785
  clearTimeout(timer);
2639
2786
  cancel?.removeEventListener("abort", drop);
2640
2787
  }
@@ -6149,11 +6296,16 @@ var NO_ATTEMPTS = {
6149
6296
  recent: [],
6150
6297
  total: 0
6151
6298
  };
6299
+ /**
6300
+ * When the lock-out ends by this clock, if it has not: one more than an hour away was stamped by a clock that ran ahead,
6301
+ * and is over (WISP 06 § Failure table, clocks wrong by days).
6302
+ */
6303
+ var lockedUntil = (attempts, now) => attempts?.until !== void 0 && now < attempts.until && attempts.until - now <= HANDOFF_ATTEMPTS.hourMs ? attempts.until : void 0;
6152
6304
  /** Whether a device may try now: `refused` after 15 failures with no success, until the person lets it try again. */
6153
6305
  function handoffAttemptAllowed(attempts, now) {
6154
6306
  if (!attempts) return "ok";
6155
6307
  if (attempts.total >= HANDOFF_ATTEMPTS.total) return "refused";
6156
- if (attempts.until !== void 0 && now < attempts.until) return "locked-out";
6308
+ if (lockedUntil(attempts, now) !== void 0) return "locked-out";
6157
6309
  return "ok";
6158
6310
  }
6159
6311
  /**
@@ -6161,17 +6313,18 @@ function handoffAttemptAllowed(attempts, now) {
6161
6313
  * outcome, and takes it back on success: a taker that stops after the second message has used a try.
6162
6314
  */
6163
6315
  function handoffAttemptFailed(attempts, now) {
6164
- const recent = [...(attempts?.recent ?? []).filter((at) => now - at < HANDOFF_ATTEMPTS.hourMs), now];
6316
+ const recent = [...(attempts?.recent ?? []).map((at) => Math.min(at, now)).filter((at) => now - at < HANDOFF_ATTEMPTS.hourMs), now];
6165
6317
  const total = (attempts?.total ?? 0) + 1;
6166
6318
  if (recent.length >= HANDOFF_ATTEMPTS.perHour) return {
6167
6319
  recent: [],
6168
6320
  total,
6169
6321
  until: now + HANDOFF_ATTEMPTS.hourMs
6170
6322
  };
6323
+ const until = lockedUntil(attempts, now);
6171
6324
  return {
6172
6325
  recent,
6173
6326
  total,
6174
- ...attempts?.until !== void 0 && now < attempts.until ? { until: attempts.until } : {}
6327
+ ...until !== void 0 ? { until } : {}
6175
6328
  };
6176
6329
  }
6177
6330
  /** A proof that held: the count starts again. */
@@ -6180,7 +6333,10 @@ var handoffAttemptSucceeded = () => ({
6180
6333
  total: 0
6181
6334
  });
6182
6335
  /** Seconds until a locked-out device may try again (for `handoff-busy`). */
6183
- var handoffRetryAfter = (attempts, now) => attempts?.until !== void 0 && attempts.until > now ? Math.ceil((attempts.until - now) / 1e3) : 0;
6336
+ var handoffRetryAfter = (attempts, now) => {
6337
+ const until = lockedUntil(attempts, now);
6338
+ return until !== void 0 ? Math.ceil((until - now) / 1e3) : 0;
6339
+ };
6184
6340
  var HTTP_SERVICE_PROTO = "ghostly-http/1";
6185
6341
  var MAX_NAME_LENGTH$1 = 48;
6186
6342
  var MAX_META_ENTRIES = 8;
@@ -7203,6 +7359,12 @@ var LIMITS = {
7203
7359
  maxConcurrentRequestsPerPeer: 32,
7204
7360
  /** Requests a client keeps in flight; the rest wait in a queue. */
7205
7361
  maxClientInFlight: 16,
7362
+ /**
7363
+ * Requests, and their bodies' bytes, a client keeps waiting for a slot: past either, a request is refused at once
7364
+ * (`busy`), so whatever asks (a contact's app in a viewer) cannot make it hold unbounded memory.
7365
+ */
7366
+ maxClientWaiting: 64,
7367
+ maxClientWaitingBodyBytes: 67108864,
7206
7368
  maxChatMessageBytes: 16384,
7207
7369
  maxFileBytes: 104857600,
7208
7370
  /** Files a peer may be sending us at once. */
@@ -7933,6 +8095,7 @@ var HttpClient = class {
7933
8095
  nextId = 1;
7934
8096
  streams = /* @__PURE__ */ new Map();
7935
8097
  waiting = [];
8098
+ waitingBytes = 0;
7936
8099
  inFlight = 0;
7937
8100
  closed = false;
7938
8101
  constructor(channel) {
@@ -7941,7 +8104,28 @@ var HttpClient = class {
7941
8104
  async request(serviceId, request) {
7942
8105
  if (this.closed) throw new GhostlyHttpError("closed", "Data link is closed");
7943
8106
  if (this.inFlight >= LIMITS.maxClientInFlight) {
7944
- await new Promise((resolve) => this.waiting.push(resolve));
8107
+ const bytes = request.body?.length ?? 0;
8108
+ if (this.waiting.length >= LIMITS.maxClientWaiting || this.waitingBytes + bytes > LIMITS.maxClientWaitingBodyBytes) throw new GhostlyHttpError("busy", "Too many requests waiting");
8109
+ this.waitingBytes += bytes;
8110
+ let leave = () => {};
8111
+ try {
8112
+ await new Promise((resolve, reject) => {
8113
+ const wake = () => {
8114
+ request.signal?.removeEventListener("abort", leave);
8115
+ resolve();
8116
+ };
8117
+ leave = () => {
8118
+ const at = this.waiting.indexOf(wake);
8119
+ if (at >= 0) this.waiting.splice(at, 1);
8120
+ reject(new GhostlyHttpError("aborted", "Request aborted"));
8121
+ };
8122
+ if (request.signal?.aborted) return leave();
8123
+ this.waiting.push(wake);
8124
+ request.signal?.addEventListener("abort", leave, { once: true });
8125
+ });
8126
+ } finally {
8127
+ this.waitingBytes -= bytes;
8128
+ }
7945
8129
  if (this.closed) throw new GhostlyHttpError("closed", "Data link is closed");
7946
8130
  }
7947
8131
  this.inFlight++;
@@ -8239,6 +8423,8 @@ var LinkSession = class {
8239
8423
  signalReadsLeft = 0;
8240
8424
  /** Fast reads still signaling while the contact's offer is due (`SIGNAL_DUE_READS`). */
8241
8425
  dueSignalReadsLeft = 0;
8426
+ /** This side just left DHT only and its presence is not out yet: the contact dials on it (`presenceDue`). */
8427
+ presenceDueOut = false;
8242
8428
  /** When the last `expectPeer` window ends (or ended): the pace slows down from there step by step. */
8243
8429
  expectUntil = 0;
8244
8430
  /**
@@ -8381,6 +8567,7 @@ var LinkSession = class {
8381
8567
  countUnusedInvite(this.transport, this, false);
8382
8568
  this.rtcSignal = null;
8383
8569
  this.callSignal = null;
8570
+ this.presenceDueOut = false;
8384
8571
  this.events.onStatus?.("offline");
8385
8572
  if (announce) try {
8386
8573
  await this.publishOnce(false);
@@ -8441,6 +8628,14 @@ var LinkSession = class {
8441
8628
  * the windows that look fast for the contact (`expectPeer`, `watchPeer`) end, and the link reads at its pace from the
8442
8629
  * next read on. An offer of this side's out keeps its window.
8443
8630
  */
8631
+ /**
8632
+ * This side just left DHT only: the contact that dials waits on its next packet that advertises, so that one is
8633
+ * signaling (`PkarrRequestOptions.signal`). As a plain write, an app that had spent its relay minute held it 55 s,
8634
+ * and the contact dialled only then.
8635
+ */
8636
+ presenceDue() {
8637
+ this.presenceDueOut = true;
8638
+ }
8444
8639
  calm() {
8445
8640
  if (this.rtcSignal !== null) return;
8446
8641
  this.fastPollUntil = this.fastStepsAfter = this.expectUntil = this.watchUntil = this.lingerUntil = this.dueSignalReadsLeft = 0;
@@ -8660,7 +8855,7 @@ var LinkSession = class {
8660
8855
  try {
8661
8856
  const awaited = this.connected || this.presence.online || this.sentBuffer.length > 0 || this.callSignal !== null || this.awaitingPeer();
8662
8857
  const takesBack = !rtcSignal && this.rtcSignalOut !== null;
8663
- const options = rtcSignal && rtcSignal !== this.rtcSignalOut ? { signal: true } : this.watching() ? { watch: true } : upkeep && (this.connected || takesBack) || !rtcSignal && !awaited ? { background: true } : void 0;
8858
+ const options = rtcSignal && rtcSignal !== this.rtcSignalOut || advertise && this.presenceDueOut ? { signal: true } : this.watching() ? { watch: true } : upkeep && (this.connected || takesBack) || !rtcSignal && !awaited ? { background: true } : void 0;
8664
8859
  this.wroteInBackground = options?.background === true;
8665
8860
  const held = this.transport.publishHeld?.(this.identity.pubKeyZ32, options);
8666
8861
  if (held) throw held;
@@ -8699,6 +8894,7 @@ var LinkSession = class {
8699
8894
  }
8700
8895
  const ms = Date.now() - started;
8701
8896
  this.lastPublishedAt = Date.now();
8897
+ if (advertise) this.presenceDueOut = false;
8702
8898
  const signalOut = !!rtcSignal && rtcSignal !== this.rtcSignalOut;
8703
8899
  this.signalReadsLeft = signalOut ? 3 : rtcSignal ? this.signalReadsLeft : 0;
8704
8900
  if (signalOut && this.fastPollUntil > 0) {
@@ -8758,6 +8954,7 @@ var LinkSession = class {
8758
8954
  }
8759
8955
  const watch = !signal && this.watching();
8760
8956
  const departed = !signal && Date.now() < this.departedUntil;
8957
+ const awaited = !signal && this.ownInvite() && this.awaitingPeer();
8761
8958
  const background = pace === "background" || pace === "connected" || pace === "idle" && !this.active;
8762
8959
  const resume = !signal && !watch && (this.resumeReads || Date.now() < this.awaitedUntil);
8763
8960
  let unread;
@@ -8767,6 +8964,7 @@ var LinkSession = class {
8767
8964
  ...signal && { signal },
8768
8965
  ...watch && { watch },
8769
8966
  ...departed && { departed },
8967
+ ...awaited && { awaited },
8770
8968
  ...resume && { resume }
8771
8969
  }, false).catch((error) => {
8772
8970
  if (!(error instanceof RelaysFailedError)) throw error;
@@ -12033,6 +12231,7 @@ function readDhtFile(raw, message) {
12033
12231
  }
12034
12232
  var DHT_MESSAGE_TTL = 3e5;
12035
12233
  var DHT_TEXT_TOO_LONG = `DHT text is limited to 256 UTF-8 bytes. Shorten it or choose a live connection.`;
12234
+ var DHT_PACKET_BUDGET = "Text and authentication exceed the DHT packet budget. Shorten the message.";
12036
12235
  var CONTROL_TTL = 6e5;
12037
12236
  /**
12038
12237
  * How far apart two devices' clocks may be for an envelope's expiry: a reader takes one until this long after `expires`
@@ -12059,7 +12258,10 @@ var MAX_ATTEMPTS = 8;
12059
12258
  var SEQUENCE_BLOCK = 64;
12060
12259
  /** The wait before publication attempt `attempts + 1` of a text, or of a receipt the contact still asks for. */
12061
12260
  var backoff = (attempts) => Math.min(6e4, 4e3 * 2 ** attempts);
12062
- /** The contact's mailbox is read this often while either side is DHT-only, and otherwise… */
12261
+ /**
12262
+ * The contact's mailbox is read this often while this side is DHT-only (a contact that chose it is read at the chat's
12263
+ * pace: `ACTIVE_DHT_POLL_MS` open, or on a daemon, `peerDhtPollMs`), and otherwise…
12264
+ */
12063
12265
  var DHT_POLL_MS = 4e3;
12064
12266
  var STREAM_POLL_MS = 3e4;
12065
12267
  /**
@@ -12068,6 +12270,7 @@ var STREAM_POLL_MS = 3e4;
12068
12270
  * each has seen the other leave).
12069
12271
  */
12070
12272
  var LEAVING_DHT_FAST_MS = 12e4;
12273
+ var LEAVING_PROBE_MAX_GAP_MS = 96e4;
12071
12274
  /** Only this often while layer 1 carries the chat (WISP 403, Q7): the relays' per-IP budget is shared by every chat. */
12072
12275
  var LIVE_POLL_MS = 3e5;
12073
12276
  /**
@@ -12134,6 +12337,11 @@ var DhtDelivery = class DhtDelivery {
12134
12337
  urgent = false;
12135
12338
  /** Reads left that are signaling: the contact is leaving DHT only, and the live link waits on them (`expect`). */
12136
12339
  signalReads = 0;
12340
+ /** The read as this side leaves DHT only, before the signaling ones (`setMode`): a plain one. */
12341
+ leavingRead = false;
12342
+ /** Until when a fresh link packet of the contact starts no signaling reads, and the wait it was held to (`peerLinkPacket`). */
12343
+ probeAt = 0;
12344
+ probeGap = 0;
12137
12345
  timer = null;
12138
12346
  /** The first control envelope of a start that waits (`firstControlAfterMs`). */
12139
12347
  controlTimer = null;
@@ -12153,12 +12361,19 @@ var DhtDelivery = class DhtDelivery {
12153
12361
  /** Until when the relays' request budget holds publications back: what is due then goes at once. */
12154
12362
  budgetUntil = 0;
12155
12363
  /**
12364
+ * This side left DHT only and no envelope saying so went out yet: the contact's live link waits on it (it holds this
12365
+ * side's offer until it reads that), so it goes as signaling (`PkarrRequestOptions.signal`).
12366
+ */
12367
+ leavingOut = false;
12368
+ /**
12156
12369
  * Until when it held this side's last read of the contact's mailbox back: the read goes again then, not at the next
12157
12370
  * poll. A chat in the background reads every 30 s, and one held back while its link was redialling read the contact
12158
12371
  * 60 s after its live link dropped, the chat "On DHT · retrying live" all along while the contact had chosen DHT only.
12159
12372
  */
12160
12373
  readHeldUntil = 0;
12161
12374
  errors = {};
12375
+ /** Texts whose last `send` went nowhere (`wentNowhereFor`), newest last. */
12376
+ wentNowhere = /* @__PURE__ */ new Set();
12162
12377
  /** When the device's network last came back (`networkBack`): a read or publication started before failed for want of it. */
12163
12378
  networkBackAt = -Infinity;
12164
12379
  foreignKeySeenAt;
@@ -12313,9 +12528,17 @@ var DhtDelivery = class DhtDelivery {
12313
12528
  }
12314
12529
  this.state = next;
12315
12530
  }
12531
+ /** The key an envelope between this side and `peer` is sealed with: the same for the same contact, so derived once. */
12532
+ sealedKeys;
12316
12533
  sealedKey(peer) {
12317
- const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.participation.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peer)));
12318
- return hkdf(sha256, shared, this.key, utf8Encode("ghostly-dht-participation-envelope/1"), 32);
12534
+ if (this.sealedKeys?.peer !== peer) {
12535
+ const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.participation.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peer)));
12536
+ this.sealedKeys = {
12537
+ peer,
12538
+ key: hkdf(sha256, shared, this.key, utf8Encode("ghostly-dht-participation-envelope/1"), 32)
12539
+ };
12540
+ }
12541
+ return this.sealedKeys.key;
12319
12542
  }
12320
12543
  signed(body, recipient = "invite") {
12321
12544
  return utf8Encode(JSON.stringify([
@@ -12330,6 +12553,32 @@ var DhtDelivery = class DhtDelivery {
12330
12553
  return this.envelope(body, recipient).records;
12331
12554
  }
12332
12555
  /**
12556
+ * Whether an envelope to `recipient` whose plaintext is this many bytes fits the packet: its size depends on the
12557
+ * length alone, so it is measured on a placeholder, with no signature, key or encryption.
12558
+ */
12559
+ fits(bytes, recipient) {
12560
+ if (bytes > MAX_ENVELOPE_PLAINTEXT) return false;
12561
+ const ratchet = this.ratcheted(recipient);
12562
+ const sealed = ratchet ? 4 * Math.ceil((66 + bytes) / 3) : sealedLength(bytes);
12563
+ const hint = recipient ? [{
12564
+ label: "_dmk",
12565
+ value: "A".repeat(sealedLength(utf8Encode(this.participation.pubKeyZ32).length)),
12566
+ ttl: ENVELOPE_TTL
12567
+ }] : [];
12568
+ return measureRecords(this.identity.pubKeyZ32, [{
12569
+ label: ratchet ? "_dr" : "_dm",
12570
+ value: "A".repeat(sealed),
12571
+ ttl: ENVELOPE_TTL
12572
+ }, ...hint]) <= ENVELOPE_PACKET_BYTES;
12573
+ }
12574
+ /**
12575
+ * Whether `body` fits an envelope to `recipient`, as `envelope` would find it, without building one: the signature is
12576
+ * always 86 characters of base64url.
12577
+ */
12578
+ bodyFits(body, recipient) {
12579
+ return this.fits(utf8Encode(JSON.stringify([body, "x".repeat(86)])).length, recipient);
12580
+ }
12581
+ /**
12333
12582
  * The envelope's records. Ratcheted (`ratcheted`), its `_dr` record is the right length but not sealed yet: `seal`
12334
12583
  * gives its bytes, under the chat's lock, once the publication is sure to go. Measuring a packet takes no key.
12335
12584
  */
@@ -12344,13 +12593,9 @@ var DhtDelivery = class DhtDelivery {
12344
12593
  const ratchet = this.ratcheted(recipient);
12345
12594
  const sealedBytes = (bytes) => ratchet ? 4 * Math.ceil((66 + bytes) / 3) : sealedLength(bytes);
12346
12595
  const label = ratchet ? "_dr" : "_dm";
12347
- const fits = (bytes) => bytes <= MAX_ENVELOPE_PLAINTEXT && measureRecords(this.identity.pubKeyZ32, [{
12348
- label,
12349
- value: "A".repeat(sealedBytes(bytes)),
12350
- ttl: ENVELOPE_TTL
12351
- }, ...hint]) <= ENVELOPE_PACKET_BYTES;
12596
+ const fits = (bytes) => this.fits(bytes, recipient);
12352
12597
  const bytes = utf8Encode(plaintext).length;
12353
- if (!fits(bytes)) throw new Error("Text and authentication exceed the DHT packet budget. Shorten the message.");
12598
+ if (!fits(bytes)) throw new Error(DHT_PACKET_BUDGET);
12354
12599
  let padded = bytes;
12355
12600
  for (let step = 512; step >= 1; step >>= 1) if (fits(padded + step)) padded += step;
12356
12601
  const full = plaintext + " ".repeat(padded - bytes);
@@ -12418,7 +12663,12 @@ var DhtDelivery = class DhtDelivery {
12418
12663
  this.lastPublish = 0;
12419
12664
  this.leavingUntil = mode === "stream" ? Date.now() + LEAVING_DHT_FAST_MS : 0;
12420
12665
  if (mode === "dht") this.signalReads = 0;
12421
- else if (this.state.peerMode === "dht") this.signalReads = 3;
12666
+ else if (this.state.peerMode === "dht") {
12667
+ this.signalReads = 3;
12668
+ this.leavingRead = true;
12669
+ }
12670
+ this.leavingOut = mode === "stream";
12671
+ if (this.leavingOut) this.budgetUntil = 0;
12422
12672
  this.changed();
12423
12673
  });
12424
12674
  this.tick();
@@ -12455,6 +12705,20 @@ var DhtDelivery = class DhtDelivery {
12455
12705
  this.tick();
12456
12706
  }
12457
12707
  /**
12708
+ * A fresh link packet of a contact still saying DHT only (`expect`, signaling). Nothing signed says it is the contact's,
12709
+ * and one that stays on DHT only (or anyone holding the invite) can put one before every read: the reads it starts are
12710
+ * then held to a wait that doubles from `LEAVING_PROBE_GAP_MS` to `LEAVING_PROBE_MAX_GAP_MS`, and start over once the
12711
+ * contact says it left. False when held. Its offer, signed by its pinned key, is not held (`expect` directly).
12712
+ */
12713
+ peerLinkPacket(ms) {
12714
+ const now = Date.now();
12715
+ if (now < this.probeAt && this.probeAt - now <= this.probeGap) return false;
12716
+ this.probeGap = Math.min(this.probeGap * 2 || 12e4, LEAVING_PROBE_MAX_GAP_MS);
12717
+ this.probeAt = now + this.probeGap;
12718
+ this.expect(ms, true);
12719
+ return true;
12720
+ }
12721
+ /**
12458
12722
  * Layer 1 carries the chat, or no longer does. While it does, the mailbox is read every 5 minutes, after one
12459
12723
  * last look as it goes live: a text the contact put on the DHT in the seconds before (after this side's last
12460
12724
  * read) would otherwise wait for the next look. That look is a background request, which yields to links that
@@ -12523,23 +12787,18 @@ var DhtDelivery = class DhtDelivery {
12523
12787
  const error = this.packetError(next.message, next.expires, next.reply, next.edit);
12524
12788
  return error && next.reply ? this.packetError(next.message, next.expires) : error;
12525
12789
  }
12790
+ /**
12791
+ * Measured, not built (`bodyFits`): the outbox asks it of every waiting text at each look, and a text that waits as no
12792
+ * relay takes it would cost a signature and a seal each time, for an answer that does not change.
12793
+ */
12526
12794
  packetError(message, expires, reply, edit) {
12527
- try {
12528
- this.records(this.body(this.sequence + 1, Date.now(), expires, message, this.state.receipt?.id ?? "abcdefghijklmnopqrstuv", reply, [], edit), this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12529
- return null;
12530
- } catch (error) {
12531
- return error instanceof Error ? error.message : String(error);
12532
- }
12795
+ const body = this.body(this.sequence + 1, Date.now(), expires, message, this.state.receipt?.id ?? "abcdefghijklmnopqrstuv", reply, [], edit);
12796
+ return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32) ? null : DHT_PACKET_BUDGET;
12533
12797
  }
12534
12798
  /** Whether a text with its hop count fits the packet and what a reader reads (`MAX_ENVELOPE_PLAINTEXT`). */
12535
12799
  roomForHops(message, expires, reply, forwarded) {
12536
12800
  const body = this.body(this.sequence + 1, Date.now(), expires, message, this.state.receipt?.id ?? "abcdefghijklmnopqrstuv", reply, [], void 0, forwarded);
12537
- try {
12538
- this.records(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12539
- } catch {
12540
- return false;
12541
- }
12542
- return utf8Encode(JSON.stringify([body, "x".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT;
12801
+ return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12543
12802
  }
12544
12803
  /**
12545
12804
  * `forwarded`: a forwarded text's hop count (WISP 403 § Forwards). Like a reply's id it goes only when the packet has
@@ -12547,11 +12806,13 @@ var DhtDelivery = class DhtDelivery {
12547
12806
  */
12548
12807
  async send(text, timestamp, id, reply, edit, forwarded) {
12549
12808
  return this.serialize(async () => {
12809
+ this.wentNowhere.delete(id);
12550
12810
  const error = this.validate(text, timestamp, id, reply, edit);
12551
12811
  if (error) return error;
12552
12812
  const now = Date.now(), pending = this.state.pending;
12553
12813
  const hops = edit ? void 0 : readForwarded(forwarded);
12554
- let next = pending?.message[0] === id && pending.expires > now ? pending : {
12814
+ const again = pending?.message[0] === id && pending.expires > now;
12815
+ let next = again ? pending : {
12555
12816
  message: [
12556
12817
  id,
12557
12818
  timestamp,
@@ -12587,12 +12848,27 @@ var DhtDelivery = class DhtDelivery {
12587
12848
  return null;
12588
12849
  }
12589
12850
  this.errors.publish = `DHT publication failed: ${String(error instanceof Error ? error.message : error)}. Bounded retry continues until expiry.`;
12851
+ if (!again && !edit && publishedNowhere(error) && this.state.pending?.message[0] === id) {
12852
+ await this.persist({
12853
+ ...this.state,
12854
+ pending: void 0
12855
+ });
12856
+ this.wentNowhere.add(id);
12857
+ if (this.wentNowhere.size > 64) this.wentNowhere.delete(this.wentNowhere.values().next().value);
12858
+ }
12590
12859
  this.changed();
12591
12860
  return this.errors.publish;
12592
12861
  }
12593
12862
  });
12594
12863
  }
12595
12864
  /**
12865
+ * The last `send` of this id failed with no relay holding it, and it was not out before (`PublishFailedError`): it
12866
+ * never left this device, and is no longer the floor's to publish.
12867
+ */
12868
+ wentNowhereFor(id) {
12869
+ return this.wentNowhere.has(id);
12870
+ }
12871
+ /**
12596
12872
  * The envelope a file's offer would go in, as `send` builds a text's: the most it can say that fits the packet and
12597
12873
  * what a reader reads (`MAX_ENVELOPE_PLAINTEXT`). Its meta goes first (a voice note's waveform thinned if it must),
12598
12874
  * then the reply's id, then the hop count; the name, size, type and id always. A string: why it cannot go.
@@ -12613,12 +12889,7 @@ var DhtDelivery = class DhtDelivery {
12613
12889
  const hops = readForwarded(forwarded);
12614
12890
  const fits = (element, withReply, withHops) => {
12615
12891
  const body = this.body(this.sequence + 1, now, expires, message, this.state.receipt?.id ?? "abcdefghijklmnopqrstuv", withReply ? reply : void 0, [], void 0, withHops ? hops : void 0, element);
12616
- try {
12617
- this.records(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12618
- } catch {
12619
- return false;
12620
- }
12621
- return utf8Encode(JSON.stringify([body, "x".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT;
12892
+ return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12622
12893
  };
12623
12894
  const elements = dhtFileElements(file), bare = elements[elements.length - 1];
12624
12895
  const found = [
@@ -12803,7 +13074,7 @@ var DhtDelivery = class DhtDelivery {
12803
13074
  const issued = Math.min(now, Math.max(now - DHT_ISSUED_BACK_MS, expires - (pending ? DHT_MESSAGE_TTL : CONTROL_TTL), (pending?.message[1] ?? 0) - 3e4));
12804
13075
  const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
12805
13076
  const away = !!this.options.credentials.peerKey && now - this.peerNewAt >= 6e5;
12806
- const options = keepAlive && (this.live || away) ? { background: true } : void 0;
13077
+ const options = this.leavingOut ? { signal: true } : keepAlive && (this.live || away) ? { background: true } : void 0;
12807
13078
  const held = this.options.transport.publishHeld?.(identity.pubKeyZ32, options);
12808
13079
  if (held) {
12809
13080
  await this.heldBack(held, now, {
@@ -12855,6 +13126,7 @@ var DhtDelivery = class DhtDelivery {
12855
13126
  throw error;
12856
13127
  }
12857
13128
  this.namedRev = body[8] ?? void 0;
13129
+ if (options?.signal) this.leavingOut = false;
12858
13130
  if (identity === this.identity) this.unsealedOut = !this.options.credentials.peerKey;
12859
13131
  delete this.errors.publish;
12860
13132
  this.changed();
@@ -13204,8 +13476,9 @@ var DhtDelivery = class DhtDelivery {
13204
13476
  await this.serialize(async () => {
13205
13477
  if (!this.running) return;
13206
13478
  const background = !this.urgent && this.pollMs >= STREAM_POLL_MS;
13207
- const signal = this.signalReads > 0;
13479
+ const signal = this.signalReads > 0 && !this.leavingRead;
13208
13480
  this.urgent = false;
13481
+ this.leavingRead = false;
13209
13482
  if (signal) this.signalReads--;
13210
13483
  if (!this.options.credentials.peerKey && !this.options.credentials.expectedPeerKey && !this.state.sequence) await this.publishOnTick();
13211
13484
  const readAt = Date.now();
@@ -13219,7 +13492,10 @@ var DhtDelivery = class DhtDelivery {
13219
13492
  else if (readAt >= this.networkBackAt) this.errors.read = `Could not read DHT delivery: ${error instanceof Error ? error.message : String(error)}`;
13220
13493
  }
13221
13494
  if (signal && this.readHeldUntil > 0) this.signalReads++;
13222
- if (this.state.peerMode !== "dht") this.signalReads = 0;
13495
+ if (this.state.peerMode !== "dht") {
13496
+ this.signalReads = 0;
13497
+ this.probeAt = this.probeGap = 0;
13498
+ }
13223
13499
  await this.publishOnTick();
13224
13500
  this.changed();
13225
13501
  });
@@ -13259,7 +13535,8 @@ var DhtDelivery = class DhtDelivery {
13259
13535
  if (this.mode === "dht" || this.state.peerMode === "dht" && now < this.leavingUntil || now < this.fastUntil) return DHT_POLL_MS;
13260
13536
  if (this.live) return LIVE_POLL_MS;
13261
13537
  if (this.state.pending && this.state.pending.expires > now) return DHT_POLL_MS;
13262
- return this.active ? ACTIVE_DHT_POLL_MS : STREAM_POLL_MS;
13538
+ if (this.active) return ACTIVE_DHT_POLL_MS;
13539
+ return this.state.peerMode === "dht" && this.options.peerDhtPollMs ? Math.min(this.options.peerDhtPollMs, STREAM_POLL_MS) : STREAM_POLL_MS;
13263
13540
  }
13264
13541
  /**
13265
13542
  * How long ago this side's invite was made (or joined), while nobody used it (or its inviter never answered,
@@ -14438,6 +14715,8 @@ var TransportSwitch = class {
14438
14715
  /** This side chose while no session was open: the next one begins with it as a choice. */
14439
14716
  apart = false;
14440
14717
  policiesRead = new RateWindow(10, POLICY_RECEIVE_WINDOW_MS);
14718
+ /** The session on which the contact's policy, the one read already, was said again and read for free (`handle`). */
14719
+ repeatRead = "";
14441
14720
  policyHeld = null;
14442
14721
  constructor(options) {
14443
14722
  this.options = options;
@@ -14752,7 +15031,8 @@ var TransportSwitch = class {
14752
15031
  if (frame.t === "paired-policy") {
14753
15032
  const policy = parsePolicy(frame.policy);
14754
15033
  if (!policy || this.remote && (policy.revision < this.remote.revision || policy.revision === this.remote.revision && JSON.stringify(policy) !== JSON.stringify(this.remote))) return true;
14755
- if (!this.policiesRead.take()) {
15034
+ if (!!this.remote && policy.revision === this.remote.revision && this.repeatRead !== this.context) this.repeatRead = this.context;
15035
+ else if (!this.policiesRead.take()) {
14756
15036
  if (this.policyHeld) this.policyHeld.frame = frame;
14757
15037
  else this.policyHeld = {
14758
15038
  frame,
@@ -15243,15 +15523,43 @@ var lastOf = (timeline, side, proofs) => {
15243
15523
  for (let i = timeline.length - 1; i >= 0; i--) if (timeline[i].side === side && proofs.includes(timeline[i].proof)) return i;
15244
15524
  return -1;
15245
15525
  };
15526
+ /** The contact's share of this kind still not verified (checking, or failed): the one its next attempt takes over. */
15527
+ var unverifiedOf = (timeline, provider) => {
15528
+ for (let i = timeline.length - 1; i >= 0; i--) {
15529
+ const e = timeline[i];
15530
+ if (e.side === "theirs" && e.kind === "shared" && e.state !== "verified" && e.provider === provider) return i;
15531
+ }
15532
+ return -1;
15533
+ };
15246
15534
  /**
15247
15535
  * The timeline after one step. A share already on it is updated in place, never repeated: a request sent again at
15248
15536
  * a reconnect, a second share of a proof the contact already verified. A new attempt after a failure or a stop is
15249
- * a new entry. A stop is written once; a withdrawal later found revoked becomes a revocation in place.
15537
+ * a new entry, except the contact's own not verified: those keep one entry per kind, which its next attempt takes
15538
+ * over in place (its id and time stay, so no new sound and the chat does not move). The ids and the kind are the
15539
+ * contact's to choose, so otherwise its requests alone could push every other entry, this side's too, out of the
15540
+ * bound. A stop is written once; a withdrawal later found revoked becomes a revocation in place.
15250
15541
  */
15251
15542
  function applyIdentityEvent(timeline, event, at) {
15252
15543
  const out = [...timeline];
15253
15544
  const i = lastOf(out, event.side, event.type === "result" ? [event.proof, event.requested] : [event.proof]);
15254
15545
  const last = i >= 0 ? out[i] : void 0;
15546
+ /** Puts the contact's attempt on the entry of its kind still not verified, if there is one. */
15547
+ const takeOver = (entry) => {
15548
+ const j = event.side === "theirs" ? unverifiedOf(out, entry.provider) : -1;
15549
+ if (j < 0) return false;
15550
+ out[j] = {
15551
+ id: out[j].id,
15552
+ proof: entry.proof,
15553
+ side: "theirs",
15554
+ kind: "shared",
15555
+ provider: entry.provider,
15556
+ ...entry.subject ? { subject: entry.subject } : {},
15557
+ state: entry.state,
15558
+ ...entry.error ? { error: entry.error } : {},
15559
+ at: out[j].at
15560
+ };
15561
+ return true;
15562
+ };
15255
15563
  const add = (entry) => {
15256
15564
  const prefix = `${entry.side}:${entry.proof}:`;
15257
15565
  let n = 0;
@@ -15272,6 +15580,12 @@ function applyIdentityEvent(timeline, event, at) {
15272
15580
  };
15273
15581
  break;
15274
15582
  }
15583
+ if (takeOver({
15584
+ proof: event.proof,
15585
+ provider: event.provider,
15586
+ subject: event.subject,
15587
+ state: "verifying"
15588
+ })) break;
15275
15589
  add({
15276
15590
  proof: event.proof,
15277
15591
  side: event.side,
@@ -15297,6 +15611,12 @@ function applyIdentityEvent(timeline, event, at) {
15297
15611
  };
15298
15612
  break;
15299
15613
  }
15614
+ if (!event.ok && event.provider && takeOver({
15615
+ proof: event.proof,
15616
+ provider: event.provider,
15617
+ subject: event.subject,
15618
+ ...settled
15619
+ })) break;
15300
15620
  if (event.provider) add({
15301
15621
  proof: event.proof,
15302
15622
  side: event.side,
@@ -15473,23 +15793,24 @@ function boundVerifiedIdentity(v) {
15473
15793
  if (!isInt$2(v.expiresAt)) throw new Error("Provider returned an invalid expiry");
15474
15794
  out.expiresAt = v.expiresAt;
15475
15795
  }
15476
- if (v.display) {
15477
- const d = v.display;
15478
- const display = {
15479
- source: clean$1(d.source, 120) ?? "Self-described",
15480
- fetchedAt: isInt$2(d.fetchedAt) ? d.fetchedAt : nowSeconds()
15481
- };
15482
- const name = clean$1(d.name, 64);
15483
- if (name) display.name = name;
15484
- if (typeof d.avatar === "string" && d.avatar.length <= 49152 && /^data:image\/(png|jpeg);base64,[A-Za-z0-9+/=]+$/.test(d.avatar)) display.avatar = d.avatar;
15485
- if (typeof d.url === "string" && d.url.length <= 512) try {
15486
- const u = new URL(d.url);
15487
- if (u.protocol === "https:" && !u.username && !u.password) display.url = u.href;
15488
- } catch {}
15489
- out.display = display;
15490
- }
15796
+ if (v.display) out.display = boundIdentityDisplay(v.display);
15491
15797
  return out;
15492
15798
  }
15799
+ /** Bounds a provider's public name/picture (from a proof or `lookupDisplay`): a name with nothing visible left is dropped. */
15800
+ function boundIdentityDisplay(d) {
15801
+ const display = {
15802
+ source: clean$1(d.source, 120) ?? "Self-described",
15803
+ fetchedAt: isInt$2(d.fetchedAt) ? d.fetchedAt : nowSeconds()
15804
+ };
15805
+ const name = clean$1(d.name, 64);
15806
+ if (name) display.name = name;
15807
+ if (typeof d.avatar === "string" && d.avatar.length <= 49152 && /^data:image\/(png|jpeg);base64,[A-Za-z0-9+/=]+$/.test(d.avatar)) display.avatar = d.avatar;
15808
+ if (typeof d.url === "string" && d.url.length <= 512) try {
15809
+ const u = new URL(d.url);
15810
+ if (u.protocol === "https:" && !u.username && !u.password) display.url = u.href;
15811
+ } catch {}
15812
+ return display;
15813
+ }
15493
15814
  var emptyIdentityLedger = () => ({
15494
15815
  challenges: [],
15495
15816
  shared: [],
@@ -15534,6 +15855,7 @@ var IdentityCheckUnavailable = class extends Error {
15534
15855
  /** What the contact is told when the check failed with an IdentityCheckUnavailable. */
15535
15856
  var IDENTITY_CHECK_UNAVAILABLE = "Your contact's app could not check it. Try again later.";
15536
15857
  var TOO_MANY_RECEIVED = "Your contact keeps too many identities from you already";
15858
+ var NEWER_HELD = "Your contact keeps a newer proof of this identity from you";
15537
15859
  var peerError = (e) => e instanceof IdentityCheckUnavailable ? IDENTITY_CHECK_UNAVAILABLE : shortError(e);
15538
15860
  var UNSUPPORTED_KIND = "Your contact's app cannot verify this kind of identity yet";
15539
15861
  var NOT_IN_PROFILE = "That identity is no longer in your profile";
@@ -15545,9 +15867,16 @@ var CONTACT_REFUSALS = /* @__PURE__ */ new Set([
15545
15867
  IDENTITY_CHECK_UNAVAILABLE,
15546
15868
  TOO_MANY_RECEIVED,
15547
15869
  REVOKED,
15548
- EXPIRED
15870
+ EXPIRED,
15871
+ NEWER_HELD
15549
15872
  ]);
15550
15873
  /**
15874
+ * Why a share of mine was not accepted, as this app may say it under my identity: one of the refusals above or my own
15875
+ * app's line; else nothing past "not verified". Any other words came from the contact (a ledger kept before this check)
15876
+ * and would read as this app's own notice.
15877
+ */
15878
+ var identityRefusal = (error) => typeof error === "string" && (CONTACT_REFUSALS.has(error) || error === NOT_IN_PROFILE) ? error : void 0;
15879
+ /**
15551
15880
  * The `idp-*` exchange of one conversation. Frames (all JSON, additive, over the paired channel,
15552
15881
  * only when both offers carry `identity-proof/1`):
15553
15882
  *
@@ -15564,6 +15893,8 @@ var IdentityExchange = class {
15564
15893
  requested = /* @__PURE__ */ new Set();
15565
15894
  /** The nonces of the presentations in their provider's check now. */
15566
15895
  checking = /* @__PURE__ */ new Set();
15896
+ /** When the contact's presentations were checked with their provider (seconds), for `IDENTITY_MAX_CHECKS_PER_HOUR`. */
15897
+ checks = [];
15567
15898
  constructor(options) {
15568
15899
  this.options = options;
15569
15900
  }
@@ -15964,6 +16295,10 @@ var IdentityExchange = class {
15964
16295
  let reason;
15965
16296
  /** Its owner withdrew the proof while this check ran: no result goes out (see below). */
15966
16297
  let withdrawn = false;
16298
+ /** The check could not run on this side (IdentityCheckUnavailable). */
16299
+ let unavailable = false;
16300
+ /** The same proof this side holds verified, checked recently: its answer is reused (`IDENTITY_REUSE_CHECK_S`). */
16301
+ let reused;
15967
16302
  try {
15968
16303
  const mayReplace = (r) => r.binding.provider === binding.provider && (r.binding.subject === binding.subject || r.verified.subject === binding.subject);
15969
16304
  if (revokedHere(this.options.storage.read().received, id)) throw new Error(REVOKED);
@@ -15971,13 +16306,21 @@ var IdentityExchange = class {
15971
16306
  if (JSON.stringify(evidence ?? null).length > 16384) throw new Error("Evidence too large");
15972
16307
  if (!verifyIdentityPresentation(binding.key, sig, id, scope, nonce, issuedAt)) throw new Error("The proof key did not sign this conversation's challenge");
15973
16308
  if (binding.issuedAt > now + 300) throw new Error("The proof is dated in the future");
15974
- const result = boundVerifiedIdentity(await this.options.verify(statement, evidence));
16309
+ const evidenceJson = JSON.stringify(evidence ?? null);
16310
+ reused = this.options.storage.read().received.find((r) => r.id === id && r.status === "verified" && r.presenter === scope.subject && r.audience === scope.audience && r.context === scope.context && r.checkedAt <= now && now - r.checkedAt < 3600 && JSON.stringify(r.evidence ?? null) === evidenceJson);
16311
+ if (!reused) {
16312
+ this.checks = this.checks.filter((t) => t > now - 3600 && t <= now);
16313
+ if (this.checks.length >= 20) throw new IdentityCheckUnavailable("Too many of this contact's proofs to check this hour");
16314
+ this.checks.push(now);
16315
+ }
16316
+ const result = reused ? reused.verified : boundVerifiedIdentity(await this.options.verify(statement, evidence));
15975
16317
  if (Math.min(binding.expiresAt, result.expiresAt ?? Infinity) <= now) throw new Error(EXPIRED);
15976
- if (await this.options.revoked?.(statement).catch(() => false)) throw new Error(REVOKED);
16318
+ if (!reused && await this.options.revoked?.(statement).catch(() => false)) throw new Error(REVOKED);
15977
16319
  verified = result;
15978
16320
  } catch (e) {
15979
16321
  error = peerError(e);
15980
16322
  reason = shortError(e);
16323
+ unavailable = e instanceof IdentityCheckUnavailable;
15981
16324
  }
15982
16325
  await this.options.storage.update((l) => {
15983
16326
  const challenge = challengeOf(l);
@@ -15993,11 +16336,27 @@ var IdentityExchange = class {
15993
16336
  verified = void 0;
15994
16337
  error = reason = REVOKED;
15995
16338
  }
16339
+ if (verified && l.received.some((r) => r.id !== id && r.binding.provider === binding.provider && r.verified.subject === subject && r.binding.issuedAt > binding.issuedAt && standing(r, now))) {
16340
+ verified = void 0;
16341
+ error = reason = NEWER_HELD;
16342
+ }
16343
+ const prior = reused && l.received.find((r) => r.id === id);
16344
+ if (verified && reused && prior?.status !== (withdrawn ? "withdrawn" : "verified")) {
16345
+ verified = void 0;
16346
+ error = IDENTITY_CHECK_UNAVAILABLE;
16347
+ reason = "It was checked again while it was presented";
16348
+ }
15996
16349
  const received = verified && receivedWithRoom(l.received, id, (r) => r.binding.provider === binding.provider && r.verified.subject === subject, now);
15997
16350
  if (verified && !received) {
15998
16351
  verified = void 0;
15999
16352
  error = reason = TOO_MANY_RECEIVED;
16000
16353
  }
16354
+ const held = verified ? void 0 : l.received.find((r) => r.id === id && r.presenter === scope.subject && r.audience === scope.audience && (r.status === "verified" || r.status === "unconfirmed"));
16355
+ const stands = held?.status === "verified" && unavailable;
16356
+ if (stands) {
16357
+ verified = held.verified;
16358
+ error = reason = void 0;
16359
+ }
16001
16360
  const logged = this.log(l, {
16002
16361
  type: "result",
16003
16362
  side: "theirs",
@@ -16008,10 +16367,20 @@ var IdentityExchange = class {
16008
16367
  ok: !!verified,
16009
16368
  ...reason ? { error: reason } : {}
16010
16369
  });
16011
- if (!verified || !received) return {
16370
+ if (stands) return {
16012
16371
  ...logged,
16013
16372
  challenges
16014
16373
  };
16374
+ if (!verified || !received) return {
16375
+ ...logged,
16376
+ challenges,
16377
+ received: held && !unavailable ? l.received.map((r) => r === held ? {
16378
+ ...r,
16379
+ checkedAt: now,
16380
+ status: "unconfirmed",
16381
+ error: reason
16382
+ } : r) : l.received
16383
+ };
16015
16384
  const record = {
16016
16385
  id,
16017
16386
  binding,
@@ -16020,8 +16389,8 @@ var IdentityExchange = class {
16020
16389
  presenter: scope.subject,
16021
16390
  audience: scope.audience,
16022
16391
  context: scope.context,
16023
- verifiedAt: now,
16024
- checkedAt: now,
16392
+ verifiedAt: prior?.verifiedAt ?? now,
16393
+ checkedAt: prior?.checkedAt ?? now,
16025
16394
  status: withdrawn ? "withdrawn" : "verified"
16026
16395
  };
16027
16396
  const kept = l.received.filter((r) => r.id !== id && !received.includes(r) && r.binding.provider === binding.provider && r.verified.subject === subject && r.status !== "withdrawn" && r.status !== "revoked").reduce((out, r) => this.log(out, {
@@ -20048,6 +20417,28 @@ var ChatFiles = class {
20048
20417
  });
20049
20418
  this.startNext();
20050
20419
  }
20420
+ /**
20421
+ * An offer taken here whose record or message the host could not store: refused, so its sender does not count it
20422
+ * delivered and keeps its Retry, and forgotten, so that retry is a new offer here. Nothing of it is reported changed
20423
+ * (there is nothing to write it to); what was stored of it is removed.
20424
+ */
20425
+ refuse(id, why) {
20426
+ const entry = this.entries.get(key("in", id));
20427
+ if (!entry || transferEnded(entry.record)) return;
20428
+ this.entries.delete(key("in", id));
20429
+ const incoming = entry.in;
20430
+ entry.record.state = "failed";
20431
+ clearTimeout(incoming.timer);
20432
+ clearTimeout(incoming.ackTimer);
20433
+ incoming.dropped = true;
20434
+ incoming.writing.then(() => incoming.target?.then((t) => t.discard())).catch(() => {});
20435
+ this.send({
20436
+ t: "pf-refuse",
20437
+ id,
20438
+ why
20439
+ });
20440
+ this.startNext();
20441
+ }
20051
20442
  pause(direction, id) {
20052
20443
  const entry = this.entry(direction, id), { record } = entry;
20053
20444
  if (transferEnded(record) || record.state === "verifying" || record.state === "paused" && record.pausedBy === "me") return;
@@ -22117,6 +22508,7 @@ var GhostLink = class {
22117
22508
  save: options.dht.save,
22118
22509
  pollMs: options.dht.pollMs,
22119
22510
  firstControlAfterMs: options.dht.firstControlAfterMs,
22511
+ ...options.dht.peerDhtPollMs && { peerDhtPollMs: options.dht.peerDhtPollMs },
22120
22512
  ...backsOff && { inviteMadeAt: options.madeAt ?? Date.now() },
22121
22513
  capsRev: options.dht.capsRev,
22122
22514
  peerCapsRev: options.dht.peerCapsRev,
@@ -22352,7 +22744,9 @@ var GhostLink = class {
22352
22744
  if (this.activeBinding) return;
22353
22745
  const wasLive = !!this.channel && this.paired?.state.status === "ready";
22354
22746
  this.detach();
22355
- if (wasLive) this.peerLost("closed");
22747
+ if (!wasLive) return;
22748
+ if (this.dataLink.state === "idle" && this.awaitsContactDial()) this.resumeAfterAbsence();
22749
+ this.peerLost("closed");
22356
22750
  },
22357
22751
  onState: (state) => {
22358
22752
  const was = this.lastDataLinkState;
@@ -22598,8 +22992,11 @@ var GhostLink = class {
22598
22992
  if (!this.dht || this.dht.peerMode !== "dht" || this.deliveryMode === "dht" || !presence.online) return;
22599
22993
  if (Date.now() - presenceSeenAt(presence) >= 3e4 || presence.lastPacketAt === this.leftDhtSeenFor) return;
22600
22994
  this.leftDhtSeenFor = presence.lastPacketAt;
22601
- traceLink(this.myPubKeyZ32, "peer-link-packet", { age: Date.now() - presenceSeenAt(presence) });
22602
- this.dht.expect(EXPECT_PEER_MS, true);
22995
+ const read = this.dht.peerLinkPacket(EXPECT_PEER_MS);
22996
+ traceLink(this.myPubKeyZ32, "peer-link-packet", {
22997
+ age: Date.now() - presenceSeenAt(presence),
22998
+ ...!read && { held: true }
22999
+ });
22603
23000
  }
22604
23001
  /**
22605
23002
  * The contact dials (a WebRTC offer signed by its pinned key, or a connection on a native endpoint) while its
@@ -22764,7 +23161,10 @@ var GhostLink = class {
22764
23161
  if (mode === "dht") {
22765
23162
  this.disconnect();
22766
23163
  this.heldSignal = null;
22767
- } else if (!this.quietForTaken) this.session.start();
23164
+ } else if (!this.quietForTaken) {
23165
+ if (this.myPubKeyZ32 > this.options.params.peerPubKeyZ32) this.session.presenceDue();
23166
+ this.session.start();
23167
+ }
22768
23168
  await this.dht.setMode(mode);
22769
23169
  if (mode === "dht") {
22770
23170
  await this.session.stop(false);
@@ -24192,6 +24592,10 @@ var GhostLink = class {
24192
24592
  get dhtPendingId() {
24193
24593
  return this.dht?.pendingId;
24194
24594
  }
24595
+ /** The last DHT send of this text went nowhere: no relay holds it, and it is off the floor (`DhtDelivery.wentNowhereFor`). */
24596
+ dhtWentNowhere(id) {
24597
+ return !!this.dht?.wentNowhereFor(id);
24598
+ }
24195
24599
  /** What went on the DHT floor under this id needs no more retries there (it went live, or was withdrawn). */
24196
24600
  async settleDht(id) {
24197
24601
  await this.dht?.acknowledge(id);
@@ -26990,6 +27394,54 @@ var HEIF_METADATA_ITEMS = /* @__PURE__ */ new Set([
26990
27394
  "mime",
26991
27395
  "uri "
26992
27396
  ]);
27397
+ /**
27398
+ * Item properties that only draw the picture: the codec's configuration (HEVC, AV1, AVC, VVC, JPEG, JPEG 2000,
27399
+ * uncompressed and its components, layered HEVC with its operating points and layers), the size (`ispe`), the bits
27400
+ * per channel (`pixi`), colour (`colr`, its light levels and display volumes `clli`, `mdcv`, `cclv`, `amve`), geometry
27401
+ * (`irot`, `imir`, `clap`, `pasp`, `rloc`, `iscl`), what an auxiliary image is (`auxC`: alpha, depth, a gain map), and
27402
+ * AV1's operating point and layers (`a1op`, `a1lx`).
27403
+ */
27404
+ var HEIF_DRAWS = /* @__PURE__ */ new Set([
27405
+ "hvcC",
27406
+ "av1C",
27407
+ "avcC",
27408
+ "vvcC",
27409
+ "jpgC",
27410
+ "j2kH",
27411
+ "uncC",
27412
+ "cmpd",
27413
+ "lhvC",
27414
+ "oinf",
27415
+ "tols",
27416
+ "lsel",
27417
+ "ispe",
27418
+ "pixi",
27419
+ "colr",
27420
+ "clli",
27421
+ "mdcv",
27422
+ "cclv",
27423
+ "amve",
27424
+ "irot",
27425
+ "imir",
27426
+ "clap",
27427
+ "pasp",
27428
+ "rloc",
27429
+ "iscl",
27430
+ "auxC",
27431
+ "a1op",
27432
+ "a1lx"
27433
+ ]);
27434
+ /** Item properties about the picture: its user description (name, description, tags), accessibility text, creation and modification times, TAI clock and timestamp; and `free`, `skip`. */
27435
+ var HEIF_ABOUT = /* @__PURE__ */ new Set([
27436
+ "udes",
27437
+ "altt",
27438
+ "crtt",
27439
+ "mdft",
27440
+ "taic",
27441
+ "itai",
27442
+ "free",
27443
+ "skip"
27444
+ ]);
26993
27445
  function boxes$1(b, start, end) {
26994
27446
  const found = [];
26995
27447
  for (let at = start; at < end;) {
@@ -27041,8 +27493,16 @@ function stripHeif(b) {
27041
27493
  check$1(at + 6 <= infe.end);
27042
27494
  if (HEIF_METADATA_ITEMS.has(text$1(b, at + 2, 4))) metadata.add(id);
27043
27495
  }
27044
- /** `free` and `skip` boxes, at the top and in `meta`: their bodies go as zeros. */
27045
- const space = [...top, ...children].filter((box) => box.type === "free" || box.type === "skip");
27496
+ const iprp = one("iprp"), properties = [];
27497
+ if (iprp) {
27498
+ const held = boxes$1(b, iprp.body, iprp.end);
27499
+ const ipco = held.filter((box) => box.type === "ipco");
27500
+ check$1(ipco.length === 1 && held.every((box) => box.type === "ipco" || box.type === "ipma"));
27501
+ properties.push(...boxes$1(b, ipco[0].body, ipco[0].end));
27502
+ check$1(properties.every((box) => HEIF_DRAWS.has(box.type) || HEIF_ABOUT.has(box.type)));
27503
+ }
27504
+ /** `free` and `skip` boxes, at the top and in `meta`, and the properties about the picture: their bodies go as zeros. */
27505
+ const space = [...[...top, ...children].filter((box) => box.type === "free" || box.type === "skip"), ...properties.filter((box) => HEIF_ABOUT.has(box.type))];
27046
27506
  const out = b.slice();
27047
27507
  const version = b[iloc.body];
27048
27508
  check$1(version <= 2);
@@ -27360,13 +27820,14 @@ async function withoutPictureMetadata(source, mime) {
27360
27820
  /**
27361
27821
  * What a video leaves with. An MP4 or QuickTime file says more than its frames: its `udta` and `meta` boxes hold where
27362
27822
  * it was recorded (`©xyz`, `com.apple.quicktime.location.ISO6709`), the device, often its software; a timed metadata
27363
- * track (an iPhone's location and motion, a GoPro's GPS) holds them sample by sample; the movie's, each track's and
27823
+ * track (an iPhone's location and motion, a GoPro's GPS) holds them sample by sample, a caption track (a drone's, a
27824
+ * dashcam's) a line of them each second; the movie's, each track's and
27364
27825
  * each track's media header (`mvhd`, `tkhd`, `mdhd`) say when it was recorded, to the second, and a camera's timecode
27365
27826
  * track the time of day. The sender removes them before the file is stored and its digest computed, without decoding
27366
27827
  * or re-encoding a frame: each such box becomes a `free` box of the same size, zeroed, the headers' creation and
27367
27828
  * modification times are zeroed (0 is "unknown"), the space already left in it (`free`, `skip`, `wide`: what an edit in
27368
27829
  * place left behind, a recorder's GPS log) is zeroed after its header, so are the names of its handlers and of the
27369
- * compressor that made its frames, and each metadata and timecode track's samples are zeroed where they are, so no
27830
+ * compressor that made its frames, and each metadata, timecode and caption track's samples are zeroed where they are, so no
27370
27831
  * offset in the file moves and it plays as it did. Only the boxes' headers, `moov` and `moof` are read; the
27371
27832
  * media goes untouched.
27372
27833
  *
@@ -27479,14 +27940,10 @@ var CONTAINERS = /* @__PURE__ */ new Set([
27479
27940
  "mvex",
27480
27941
  "traf"
27481
27942
  ]);
27482
- /** Track handlers kept as they are: picture, sound, text and subtitles, timecode, hints. `meta` tracks have their samples zeroed, `tmcd` ones too. */
27943
+ /** Track handlers kept as they are: picture, sound, timecode, hints. `meta` tracks have their samples zeroed, `tmcd` ones and `CAPTIONS` too. */
27483
27944
  var HANDLERS = /* @__PURE__ */ new Set([
27484
27945
  "vide",
27485
27946
  "soun",
27486
- "text",
27487
- "sbtl",
27488
- "subt",
27489
- "clcp",
27490
27947
  "tmcd",
27491
27948
  "hint",
27492
27949
  "auxv",
@@ -27495,6 +27952,16 @@ var HANDLERS = /* @__PURE__ */ new Set([
27495
27952
  "odsm",
27496
27953
  "subp"
27497
27954
  ]);
27955
+ /**
27956
+ * Text, subtitle and caption tracks: what a recorder writes there is a log (a drone's or a dashcam's GPS, home point,
27957
+ * date and time each second), so their samples are zeroed, in `moov`'s tables and in fragments alike; they show nothing.
27958
+ */
27959
+ var CAPTIONS = /* @__PURE__ */ new Set([
27960
+ "text",
27961
+ "sbtl",
27962
+ "subt",
27963
+ "clcp"
27964
+ ]);
27498
27965
  /** The handlers whose sample descriptions are a visual one's, a compressor's name in each. */
27499
27966
  var VISUAL = /* @__PURE__ */ new Set([
27500
27967
  "vide",
@@ -27657,7 +28124,8 @@ function defaultSampleSizes(moov) {
27657
28124
  * The byte ranges of a fragment's samples in the file, one per track run (`trun`), from its `moof` read whole (`at` its
27658
28125
  * offset in the file): each run starts at its data offset from its track fragment's base (`tfhd`'s base data offset,
27659
28126
  * else the `moof`'s start for the first track fragment or one that says so, else where the previous one's data ended),
27660
- * or where the previous run ended; its length is its samples' sizes, its own or `tfhd`'s or `trex`'s default.
28127
+ * or where the previous run ended; its length is its samples' sizes, its own or `tfhd`'s or `trex`'s default. Each
28128
+ * with its track's ID.
27661
28129
  */
27662
28130
  function fragmentRanges(b, at, sizes) {
27663
28131
  const ranges = [];
@@ -27675,7 +28143,8 @@ function fragmentRanges(b, at, sizes) {
27675
28143
  }
27676
28144
  if (flags & 2) field += 4;
27677
28145
  if (flags & 8) field += 4;
27678
- let size = sizes.get(u32be(b, tfhd.body + 4));
28146
+ const track = u32be(b, tfhd.body + 4);
28147
+ let size = sizes.get(track);
27679
28148
  if (flags & 16) {
27680
28149
  check(field + 4 <= tfhd.end);
27681
28150
  size = u32be(b, field);
@@ -27708,7 +28177,11 @@ function fragmentRanges(b, at, sizes) {
27708
28177
  length = count * size;
27709
28178
  }
27710
28179
  check(Number.isSafeInteger(next) && Number.isSafeInteger(next + length));
27711
- if (length) ranges.push([next, next + length]);
28180
+ if (length) ranges.push([
28181
+ next,
28182
+ next + length,
28183
+ track
28184
+ ]);
27712
28185
  next += length;
27713
28186
  }
27714
28187
  previous = next;
@@ -27723,12 +28196,13 @@ function selfContained(b, minf) {
27723
28196
  }
27724
28197
  /**
27725
28198
  * `moov` with its metadata boxes emptied and its headers' times zeroed, read whole: whether it has a video track, the
27726
- * byte ranges of its metadata and timecode tracks' samples (zeroed by the caller where they are), whether a metadata
27727
- * track has any, and every track's sample table.
28199
+ * byte ranges of its metadata, timecode and caption tracks' samples (zeroed by the caller where they are), whether it
28200
+ * has a metadata or timecode track, every track's sample table, and the IDs of its caption tracks (their samples in
28201
+ * fragments zeroed too).
27728
28202
  */
27729
28203
  function stripMoov(b) {
27730
28204
  let video = false, fragmented = false, metadata = false;
27731
- const zeroed = [], tables = [];
28205
+ const zeroed = [], tables = [], captions = /* @__PURE__ */ new Set();
27732
28206
  for (const box of boxes(b, header(b, 0, b.length).body, b.length)) {
27733
28207
  if (METADATA.has(box.type)) {
27734
28208
  empty(b, box);
@@ -27742,14 +28216,18 @@ function stripMoov(b) {
27742
28216
  emptyWithin(b, box.body, box.end);
27743
28217
  }
27744
28218
  if (box.type !== "trak") continue;
27745
- let mdia;
28219
+ let mdia, tkhd;
27746
28220
  for (const part of boxes(b, box.body, box.end)) {
27747
28221
  if (METADATA.has(part.type)) {
27748
28222
  empty(b, part);
27749
28223
  continue;
27750
28224
  }
27751
28225
  check(TRAK_KEEPS.has(part.type));
27752
- if (part.type === "tkhd") zeroTimes(b, part);
28226
+ if (part.type === "tkhd") {
28227
+ check(!tkhd);
28228
+ tkhd = part;
28229
+ zeroTimes(b, part);
28230
+ }
27753
28231
  if (part.type === "mdia") {
27754
28232
  check(!mdia);
27755
28233
  mdia = part;
@@ -27765,11 +28243,18 @@ function stripMoov(b) {
27765
28243
  tables.push(stbl);
27766
28244
  if (handler === "meta") {
27767
28245
  check(selfContained(b, minf));
27768
- const ranges = sampleRanges(b, stbl);
27769
- metadata ||= ranges.length > 0;
27770
- for (const range of ranges) zeroed.push(range);
27771
- } else if (handler === "tmcd" && selfContained(b, minf)) for (const range of sampleRanges(b, stbl)) zeroed.push(range);
27772
- else check(HANDLERS.has(handler));
28246
+ metadata = true;
28247
+ for (const range of sampleRanges(b, stbl)) zeroed.push(range);
28248
+ } else if (handler === "tmcd" && selfContained(b, minf)) {
28249
+ metadata = true;
28250
+ for (const range of sampleRanges(b, stbl)) zeroed.push(range);
28251
+ } else if (CAPTIONS.has(handler)) {
28252
+ check(selfContained(b, minf) && !!tkhd);
28253
+ const id = tkhd.body + 4 + (b[tkhd.body] === 1 ? 16 : 8);
28254
+ check(id + 4 <= tkhd.end);
28255
+ captions.add(u32be(b, id));
28256
+ for (const range of sampleRanges(b, stbl)) zeroed.push(range);
28257
+ } else check(HANDLERS.has(handler));
27773
28258
  if (handler === "vide") video = true;
27774
28259
  if (VISUAL.has(handler)) zeroCompressorNames(b, stbl);
27775
28260
  emptyWithin(b, box.body, box.end);
@@ -27779,7 +28264,8 @@ function stripMoov(b) {
27779
28264
  fragmented,
27780
28265
  metadata,
27781
28266
  zeroed,
27782
- tables
28267
+ tables,
28268
+ captions
27783
28269
  };
27784
28270
  }
27785
28271
  /**
@@ -27908,7 +28394,7 @@ async function videoMetadataPatches(file, mime) {
27908
28394
  }
27909
28395
  check(moovs.length === 1);
27910
28396
  const moov = await whole(source, moovs[0]);
27911
- const { video, fragmented, metadata, zeroed, tables } = stripMoov(moov);
28397
+ const { video, fragmented, metadata, zeroed, tables, captions } = stripMoov(moov);
27912
28398
  if (!video && !typed) return void 0;
27913
28399
  patches.push({
27914
28400
  start: moovs[0].start,
@@ -27923,10 +28409,13 @@ async function videoMetadataPatches(file, mime) {
27923
28409
  }
27924
28410
  }
27925
28411
  check(!fragmented || !metadata);
27926
- const sizes = dropped.length && fragmented ? defaultSampleSizes(moov) : void 0;
28412
+ const sizes = (dropped.length || captions.size) && fragmented ? defaultSampleSizes(moov) : void 0;
27927
28413
  for (const box of top) if (box.type === "moof") {
27928
28414
  const moof = await whole(source, box);
27929
- if (dropped.length) for (const [start, end] of fragmentRanges(moof, box.start, sizes ?? /* @__PURE__ */ new Map())) check(!meets(dropped, start, end));
28415
+ if (dropped.length || captions.size) for (const [start, end, track] of fragmentRanges(moof, box.start, sizes ?? /* @__PURE__ */ new Map())) {
28416
+ check(!meets(dropped, start, end));
28417
+ if (captions.has(track)) zeroed.push([start, end]);
28418
+ }
27930
28419
  emptyWithin(moof, box.body - box.start, moof.length);
27931
28420
  patches.push({
27932
28421
  start: box.start,
@@ -28265,7 +28754,8 @@ function parseLightningDestination(input) {
28265
28754
  };
28266
28755
  }
28267
28756
  var hex$1 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
28268
- var reason = (value) => typeof value === "string" ? value.replace(/\s+/g, " ").slice(0, 200) : "";
28757
+ /** A server's own words on one line, bounded, with no character that hides text or reorders what follows it. */
28758
+ var reason = (value) => typeof value === "string" ? stripHidden(value.replace(/\s+/g, " ")).slice(0, 200) : "";
28269
28759
  var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
28270
28760
  async function readBounded(response, maxBytes) {
28271
28761
  const reader = response.body?.getReader?.();
@@ -28416,6 +28906,16 @@ function invoiceCallbackUrl(params, amountSat, comment) {
28416
28906
  }
28417
28907
  return url.href;
28418
28908
  }
28909
+ /** A success action's link: HTTPS, bounded, and no user part ("https://www.paypal.com@evil.example" opens evil.example). */
28910
+ function successUrl(text) {
28911
+ if (!/^https:\/\//i.test(text) || text.length > LNURL_LIMITS.maxUrlLength) return false;
28912
+ try {
28913
+ const url = new URL(text);
28914
+ return !url.username && !url.password;
28915
+ } catch {
28916
+ return false;
28917
+ }
28918
+ }
28419
28919
  /**
28420
28920
  * Checks the invoice a service answered with (LUD-06): the amount asked, a payment hash, not expired, and
28421
28921
  * a commitment to the metadata the person was shown: the `h` tag is its sha256, or the invoice carries the
@@ -28425,7 +28925,7 @@ function parseInvoiceCallback(body, params, amountSat) {
28425
28925
  if (!isRecord(body) || typeof body.pr !== "string") throw new Error(`${params.callbackDomain} did not answer with an invoice`);
28426
28926
  const invoice = decodeBolt11(body.pr);
28427
28927
  if (!invoice) throw new Error(`${params.callbackDomain} answered with an invoice that does not decode`);
28428
- if (invoice.amountMsat !== BigInt(amountSat) * 1000n) throw new Error(`The invoice asks for ${invoice.amountSat === null ? "any amount" : `${invoice.amountSat.toLocaleString()} sats`}, not the ${amountSat.toLocaleString()} sats you chose`);
28928
+ if (invoice.amountMsat !== BigInt(amountSat) * 1000n) throw new Error(`The invoice asks for ${invoice.amountSat === null ? "any amount" : `${invoice.amountSat.toLocaleString("en-US")} sats`}, not the ${amountSat.toLocaleString("en-US")} sats you chose`);
28429
28929
  if (!invoice.paymentHash) throw new Error("The invoice has no payment hash");
28430
28930
  if (invoice.descriptionHash !== params.descriptionHash && invoice.description !== params.metadata) throw new Error("The invoice does not commit to what the service said the payment is for");
28431
28931
  if (invoice.expiresAt * 1e3 < Date.now()) throw new Error("The invoice the service answered with has already expired");
@@ -28436,7 +28936,7 @@ function parseInvoiceCallback(body, params, amountSat) {
28436
28936
  tag: "message",
28437
28937
  message: reason(action.message)
28438
28938
  };
28439
- else if (action.tag === "url" && typeof action.url === "string" && /^https:\/\//i.test(action.url) && action.url.length <= LNURL_LIMITS.maxUrlLength) successAction = {
28939
+ else if (action.tag === "url" && typeof action.url === "string" && successUrl(action.url)) successAction = {
28440
28940
  tag: "url",
28441
28941
  description: reason(action.description),
28442
28942
  url: action.url
@@ -29823,7 +30323,7 @@ function parseDidJws(input) {
29823
30323
  }
29824
30324
  if (!isObject$3(header)) throw new DidError("The JWS header is not a JSON object");
29825
30325
  const alg = header.alg;
29826
- if (typeof alg !== "string" || !DID_JWS_ALGS[alg]) throw new DidError(`The JWS uses ${typeof alg === "string" ? alg.slice(0, 16) : "no algorithm"}: Ghostly checks EdDSA, ES256K and ES256`);
30326
+ if (typeof alg !== "string" || !DID_JWS_ALGS[alg]) throw new DidError(`The JWS uses ${typeof alg === "string" ? "another algorithm" : "no algorithm"}: Ghostly checks EdDSA, ES256K and ES256`);
29827
30327
  if (header.kid !== void 0 && (typeof header.kid !== "string" || header.kid.length > 640)) throw new DidError("The JWS kid is not a key id");
29828
30328
  if (header.b64 !== void 0 && typeof header.b64 !== "boolean") throw new DidError("The JWS b64 header is not true or false");
29829
30329
  const crit = header.crit;
@@ -29870,7 +30370,7 @@ function verifyWith(key, signature, message, format = "compact") {
29870
30370
  return false;
29871
30371
  }
29872
30372
  }
29873
- var refusedKey = (key) => new DidError(`Signed by ${key.id}, which the DID document does not list under authentication or assertionMethod`);
30373
+ var refusedKey = () => new DidError("Signed by a key the DID document does not list under authentication or assertionMethod");
29874
30374
  /**
29875
30375
  * Which key of `doc` made this JWS over one of `messages` (the statement, and the statement with a
29876
30376
  * trailing newline some tools add). With a `kid`, only that key is tried. Refused unless the key is
@@ -29881,9 +30381,9 @@ function checkDidJws(input, messages, doc) {
29881
30381
  let candidates = doc.keys.filter((k) => k.curve === jws.curve);
29882
30382
  if (jws.kid !== void 0) {
29883
30383
  const kid = methodId(doc.did, jws.kid);
29884
- if (!kid) throw new DidError(`The JWS names key ${jws.kid.slice(0, 100)}, which is not a key of ${doc.did}`);
30384
+ if (!kid) throw new DidError(`The JWS names a key that is not a key of ${doc.did}`);
29885
30385
  candidates = candidates.filter((k) => k.id === kid);
29886
- if (!candidates.length) throw new DidError(doc.keys.some((k) => k.id === kid) ? `Key ${kid} is not a ${jws.curve} key: the JWS says ${jws.alg}` : `The DID document lists no key ${kid}`);
30386
+ if (!candidates.length) throw new DidError(doc.keys.some((k) => k.id === kid) ? `The key the JWS names is not a ${jws.curve} key: the JWS says ${jws.alg}` : "The DID document does not list the key the JWS names");
29887
30387
  }
29888
30388
  if (!candidates.length) throw new DidError(`The DID document lists no ${jws.curve} key for ${jws.alg}`);
29889
30389
  let inputs;
@@ -29905,7 +30405,7 @@ function checkDidJws(input, messages, doc) {
29905
30405
  alg: jws.alg
29906
30406
  };
29907
30407
  }
29908
- if (refused) throw refusedKey(refused);
30408
+ if (refused) throw refusedKey();
29909
30409
  throw new DidError("The JWS signature does not match: sign exactly the statement shown, with a key of this DID");
29910
30410
  }
29911
30411
  /**
@@ -29917,9 +30417,9 @@ function checkDidSignature(signature, messages, doc, vm) {
29917
30417
  let candidates = doc.keys;
29918
30418
  if (vm !== void 0) {
29919
30419
  const id = methodId(doc.did, vm);
29920
- if (!id) throw new DidError(`${vm.slice(0, 100)} is not a key of ${doc.did}`);
30420
+ if (!id) throw new DidError(`The proof names a key that is not a key of ${doc.did}`);
29921
30421
  candidates = candidates.filter((k) => k.id === id);
29922
- if (!candidates.length) throw new DidError(`The DID document lists no key ${id}`);
30422
+ if (!candidates.length) throw new DidError("The DID document does not list the key the proof names");
29923
30423
  }
29924
30424
  const der = signature.length !== 64 && signature[0] === 48;
29925
30425
  if (signature.length !== 64 && !der) throw new DidError("A signature is 64 bytes (or DER, for ECDSA)");
@@ -29938,7 +30438,7 @@ function checkDidSignature(signature, messages, doc, vm) {
29938
30438
  signature: canonical
29939
30439
  };
29940
30440
  }
29941
- if (refused) throw refusedKey(refused);
30441
+ if (refused) throw refusedKey();
29942
30442
  throw new DidError("The signature does not match: sign exactly the statement shown, with a key of this DID");
29943
30443
  }
29944
30444
  function parseDidSignaturePaste(pasted) {
@@ -31196,7 +31696,7 @@ function parseKeyBlob(blob) {
31196
31696
  if (blob.length > 1100) fail("SSH public key too large");
31197
31697
  const r = new Reader(blob);
31198
31698
  const type = r.text(64);
31199
- if (!SSH_KEY_TYPES.includes(type)) fail(`Unsupported SSH key type ${JSON.stringify(type)}`);
31699
+ if (!SSH_KEY_TYPES.includes(type)) fail(`Unsupported SSH key type${type === "ssh-dss" ? " \"ssh-dss\"" : ""}`);
31200
31700
  const key = {
31201
31701
  type,
31202
31702
  blob,
@@ -31309,7 +31809,7 @@ function ecdsaSignature(blob, size) {
31309
31809
  async function verifySshSignature(armored, message, options = {}) {
31310
31810
  const parsed = parseSshSignature(armored);
31311
31811
  const namespace = options.namespace ?? "ghostly";
31312
- if (parsed.namespace !== namespace) fail(`Signed for namespace ${JSON.stringify(parsed.namespace)}, not ${JSON.stringify(namespace)}. Use -n ${namespace}.`);
31812
+ if (parsed.namespace !== namespace) fail(`Signed for another namespace, not ${JSON.stringify(namespace)}. Use -n ${namespace}.`);
31313
31813
  const bytes = typeof message === "string" ? utf8Encode(message) : message;
31314
31814
  const digest = parsed.hashAlgorithm === "sha512" ? sha512(bytes) : sha256(bytes);
31315
31815
  const signed = concatBytes$1(utf8Encode("SSHSIG"), sshString(utf8Encode(parsed.namespace)), sshString(/* @__PURE__ */ new Uint8Array()), sshString(utf8Encode(parsed.hashAlgorithm)), sshString(digest));
@@ -31892,6 +32392,13 @@ var GROUP_LIMITS = {
31892
32392
  /** Frames waiting for an epoch (or its secret) that has not arrived yet. */
31893
32393
  waiting: 64,
31894
32394
  waitingBytes: 1048576,
32395
+ /**
32396
+ * Of those, and of the edits waiting, the ones signed by a key no recent commit names (a newcomer whose admission has
32397
+ * not come yet, or a key anyone can make up): the newest only, they go first, and they never say I am behind.
32398
+ */
32399
+ waitingStrangers: 8,
32400
+ /** How long a frame or edit waits: then it is dropped, and a later catch-up brings it again if it was real. */
32401
+ waitingMs: 12e4,
31895
32402
  /** Epoch secrets kept: past this, older epochs cannot be read or handed on. */
31896
32403
  secrets: 32,
31897
32404
  /** Secrets in one `group-secrets` frame: apps from before revision 0.9 drop a frame with more. */
@@ -31936,7 +32443,16 @@ var GROUP_LIMITS = {
31936
32443
  /** A received message is in the saved state within this long (`persistSoon`): a burst of them is one save, not one each. */
31937
32444
  saveWithinMs: 1e3,
31938
32445
  /** New name records of one member taken in `syncWindowMs` (WISP 902 § Messages, "The name record"): one a rename. */
31939
- namesPerMember: 4
32446
+ namesPerMember: 4,
32447
+ /**
32448
+ * Messages of one member taken per `messageWindowMs`, and the bytes of their frames, past a burst of twice its whole
32449
+ * log (`AuthorPace`); its edits the same, counted apart. As a community's (`COMMUNITY_LIMITS.messagesPerAuthor`): each
32450
+ * one taken is a row in every member's app and a frame each hub passes on. The rest are not taken now and come again
32451
+ * in a catch-up.
32452
+ */
32453
+ messagesPerAuthor: 30,
32454
+ messageBytesPerAuthor: 131072,
32455
+ messageWindowMs: 1e4
31940
32456
  };
31941
32457
  /** What every member should know about who can read what, in the words the apps show. */
31942
32458
  var GROUP_READ_NOTE = `Everyone in the group can read everything sent while they are a member. Someone removed keeps what they already received and cannot read what comes after; someone who joins later cannot read what came before. Messages go to each member; whoever was away gets what they missed from any member who has it (the group's last ${GROUP_LIMITS.relay} messages) when they meet again.`;
@@ -31945,6 +32461,55 @@ var GROUP_READ_NOTE = `Everyone in the group can read everything sent while they
31945
32461
  * answer: slices go one after another, each once my app handled the last (`CATCH_UP_PAUSE_MS` at most between them).
31946
32462
  */
31947
32463
  var ANSWER_WINDOW_MS$1 = 5e3;
32464
+ /**
32465
+ * One member's messages (or edits) taken: its whole log handed back at once twice over (`AUTHOR_BURST`: an edge opening
32466
+ * hears it, with what the member says live beside it, and the edits its app says again), then
32467
+ * `GROUP_LIMITS.messagesPerAuthor` and `messageBytesPerAuthor` per `messageWindowMs`, as a community's `MessagePace`.
32468
+ * One not taken is neither seen nor kept nor passed on, so a sync still names it (`miss`) and a catch-up hands it again.
32469
+ * What another member hands on in its answer to my sync (or what waited for a secret) is counted too, and may run the
32470
+ * author's allowance below nothing by one answer's worth (`AUTHOR_OWED`): a catch-up holds more than a burst, and lands
32471
+ * at once; the author's next frames wait until the pace pays it back. Not counted, a member at the other end of my sync
32472
+ * handed on all a second member signed, at any rate.
32473
+ */
32474
+ var AUTHOR_BURST = {
32475
+ frames: 2 * GROUP_LIMITS.outlog,
32476
+ bytes: 2 * GROUP_LIMITS.outlogBytes
32477
+ };
32478
+ /** How far below nothing an answer may run an author's allowance: all its messages one answer hands on, or edits. */
32479
+ var AUTHOR_OWED = {
32480
+ messages: {
32481
+ frames: GROUP_LIMITS.relay,
32482
+ bytes: GROUP_LIMITS.relayBytes
32483
+ },
32484
+ edits: {
32485
+ frames: GROUP_LIMITS.handOnEdits,
32486
+ bytes: GROUP_LIMITS.relayEditBytes
32487
+ }
32488
+ };
32489
+ var AuthorPace = class {
32490
+ owed;
32491
+ frames = AUTHOR_BURST.frames;
32492
+ bytes = AUTHOR_BURST.bytes;
32493
+ at;
32494
+ constructor(owed) {
32495
+ this.owed = owed;
32496
+ }
32497
+ /** `answer`: handed on in an answer to my sync, or waited, so it may run the allowance below nothing (`owed`). */
32498
+ take(bytes, now, answer = false) {
32499
+ const elapsed = Math.max(0, now - (this.at ?? now)) / GROUP_LIMITS.messageWindowMs;
32500
+ this.at = now;
32501
+ this.frames = Math.min(AUTHOR_BURST.frames, this.frames + elapsed * GROUP_LIMITS.messagesPerAuthor);
32502
+ this.bytes = Math.min(AUTHOR_BURST.bytes, this.bytes + elapsed * GROUP_LIMITS.messageBytesPerAuthor);
32503
+ const floor = answer ? this.owed : {
32504
+ frames: 0,
32505
+ bytes: 0
32506
+ };
32507
+ if (this.frames + floor.frames < 1 || this.bytes + floor.bytes < bytes) return false;
32508
+ this.frames -= 1;
32509
+ this.bytes -= bytes;
32510
+ return true;
32511
+ }
32512
+ };
31948
32513
  var MAX_TEXT_BOX$1 = Math.ceil((GROUP_LIMITS.textBytes + 16) * 4 / 3) + 4;
31949
32514
  /** Sixteen mentions as JSON, each a key and two offsets, with room to spare, sealed. */
31950
32515
  var MAX_MENTIONS_BOX = Math.ceil((MENTION_LIMITS.count * 96 + 16) * 4 / 3) + 4;
@@ -32275,6 +32840,20 @@ function isMessageFrame$1(v) {
32275
32840
  const f = v;
32276
32841
  return f.t === "group-msg" && typeof f.g === "string" && GROUP_ID.test(f.g) && Number.isSafeInteger(f.e) && f.e >= 0 && typeof f.s === "string" && MEMBER_KEY.test(f.s) && Number.isSafeInteger(f.n) && f.n >= 0 && Number.isSafeInteger(f.ts) && f.ts > 0 && typeof f.nn === "string" && f.nn.length === 32 && B64$1.test(f.nn) && typeof f.c === "string" && f.c.length <= MAX_TEXT_BOX$1 && B64$1.test(f.c) && typeof f.sig === "string" && f.sig.length === 86 && B64$1.test(f.sig);
32277
32842
  }
32843
+ /**
32844
+ * A waiting list past `max` places, past `waitingStrangers` of keys no recent commit names, or past its bytes (`heavy`):
32845
+ * which one goes, or -1. Such a key's oldest first, else the oldest of the author holding the most places, so one
32846
+ * author's frames for an epoch that never comes push out its own, not another member's.
32847
+ */
32848
+ function overflow(list, max, heavy = false) {
32849
+ const strangers = list.filter((w) => w.stranger).length;
32850
+ if (!list.length || !heavy && list.length <= max && strangers <= GROUP_LIMITS.waitingStrangers) return -1;
32851
+ if (strangers) return list.findIndex((w) => w.stranger);
32852
+ const places = /* @__PURE__ */ new Map();
32853
+ for (const w of list) places.set(w.frame.s, (places.get(w.frame.s) ?? 0) + 1);
32854
+ const most = Math.max(...places.values());
32855
+ return list.findIndex((w) => places.get(w.frame.s) === most);
32856
+ }
32278
32857
  /** The chain cut in consecutive pieces of at most `chainPiece` commits and `chainPieceBytes`: a roster of 32 makes a commit ~2.4 KB. */
32279
32858
  function chainPieces(chain) {
32280
32859
  const pieces = [];
@@ -32301,6 +32880,11 @@ var GroupSession = class {
32301
32880
  waitingBytes = 0;
32302
32881
  /** Edits for an epoch, or a secret, not here yet: tried again with the frames above. In memory only. */
32303
32882
  waitingEdits = [];
32883
+ /**
32884
+ * Members one of whose frames waited `waitingMs` for an epoch that never came → when it was dropped: until my chain
32885
+ * moves, theirs waiting say I am behind no more (`behind`). In memory only.
32886
+ */
32887
+ waitedInVain = /* @__PURE__ */ new Map();
32304
32888
  pendingCommits = /* @__PURE__ */ new Map();
32305
32889
  /** When each member was last asked to catch me up, so a stream of unreadable frames is one question, not a loop. */
32306
32890
  asked = /* @__PURE__ */ new Map();
@@ -32315,6 +32899,9 @@ var GroupSession = class {
32315
32899
  nameSaid;
32316
32900
  /** New name records taken per member, a few a minute (`GROUP_LIMITS.namesPerMember`). In memory only. */
32317
32901
  namesTaken = /* @__PURE__ */ new Map();
32902
+ /** Messages, and apart from them edits, taken per author (`AuthorPace`). In memory only. */
32903
+ messagePace = /* @__PURE__ */ new Map();
32904
+ editPace = /* @__PURE__ */ new Map();
32318
32905
  queue = Promise.resolve();
32319
32906
  /** One metadata frame that names a commit or an epoch I do not have yet: tried again when the chain moves. */
32320
32907
  pendingMeta;
@@ -32873,16 +33460,29 @@ var GroupSession = class {
32873
33460
  return false;
32874
33461
  }
32875
33462
  }
32876
- /** Another member's edit, kept to hand on: the latest per message; the oldest go once the log is full. False: one as new was kept. */
33463
+ /**
33464
+ * Another member's edit, kept to hand on: the latest per message. Full (in count or in bytes), the oldest of the author
33465
+ * who holds the most of it goes (the one just kept's own on a tie): an author's edits of messages that are not there,
33466
+ * which no keeper can tell (a hub cannot even open them), as many as it likes, push out only its own. False: one as
33467
+ * new was kept, or this one went.
33468
+ */
32877
33469
  keepEdit(frame) {
32878
33470
  const same = (f) => f.s === frame.s && f.e === frame.e && f.n === frame.n;
32879
33471
  const log = this.state.relayEdits ?? [];
32880
33472
  if (log.some((f) => same(f) && f.v >= frame.v)) return false;
32881
- const next = [...log.filter((f) => !same(f)), cleanEdit(frame)];
33473
+ const kept = cleanEdit(frame);
33474
+ const next = [...log.filter((f) => !same(f)), kept];
32882
33475
  let bytes = next.reduce((sum, f) => sum + f.c.length, 0);
32883
- while (next.length > GROUP_LIMITS.relayEdits || bytes > GROUP_LIMITS.relayEditBytes) bytes -= next.shift().c.length;
33476
+ while (next.length > GROUP_LIMITS.relayEdits || bytes > GROUP_LIMITS.relayEditBytes) {
33477
+ const byCount = next.length > GROUP_LIMITS.relayEdits;
33478
+ const held = /* @__PURE__ */ new Map();
33479
+ for (const f of next) held.set(f.s, (held.get(f.s) ?? 0) + (byCount ? 1 : f.c.length));
33480
+ let most = frame.s;
33481
+ for (const [author, amount] of held) if (amount > held.get(most)) most = author;
33482
+ bytes -= next.splice(next.findIndex((f) => f.s === most), 1)[0].c.length;
33483
+ }
32884
33484
  this.state.relayEdits = next;
32885
- return true;
33485
+ return next.includes(kept);
32886
33486
  }
32887
33487
  /** A frame of another member, kept to hand on; the oldest go once the log is full. */
32888
33488
  keep(frame) {
@@ -33214,9 +33814,14 @@ var GroupSession = class {
33214
33814
  await this.resealBehind();
33215
33815
  });
33216
33816
  }
33217
- /** Something is missing here: the current epoch's secret, a commit ahead of my chain, or the epoch of frames waiting. */
33817
+ /**
33818
+ * Something is missing here: the current epoch's secret, a commit ahead of my chain, or the epoch of a member's frames
33819
+ * waiting, unless one of that member's waited in vain since my chain last moved (`waitedInVain`).
33820
+ */
33218
33821
  get behind() {
33219
- return !this.state.secrets[this.epoch] || this.waiting.length > 0 || this.pendingCommits.size > 0;
33822
+ this.expireWaiting();
33823
+ const member = (w) => !w.stranger && !((this.waitedInVain.get(w.frame.s) ?? -Infinity) >= this.chainMovedAt);
33824
+ return !this.state.secrets[this.epoch] || this.waiting.some(member) || this.pendingCommits.size > 0;
33220
33825
  }
33221
33826
  async resealBehind() {
33222
33827
  const alone = new Set(this.state.alone ?? []);
@@ -33280,7 +33885,8 @@ var GroupSession = class {
33280
33885
  /**
33281
33886
  * Says an edit of one of my messages (WISP 902 § Edits): edit `v`, the whole new text and its mentions, sealed under
33282
33887
  * the key of the message's epoch and signed, to every member of that epoch still in the group, or to `to` alone (an
33283
- * edge that just opened). Someone admitted after the message cannot open it and is not sent it. The message's
33888
+ * edge that just opened). Someone admitted after the message cannot open it and is not sent it, but a hub I count on
33889
+ * (`hooks.carriers`), which carries it on to the members who can. The message's
33284
33890
  * epoch key must still be here: past `GROUP_LIMITS.secrets` epochs a message cannot be edited.
33285
33891
  */
33286
33892
  sendEdit(messageId, edit, to) {
@@ -33305,6 +33911,7 @@ var GroupSession = class {
33305
33911
  if (utf8Encode(plain).length > MAX_EDIT_PLAIN) return { error: "Message exceeds 16 KiB" };
33306
33912
  const copies = [ref, ...this.state.sent.filter((f) => f.o && f.o.e === ref.e && f.o.n === ref.n)];
33307
33913
  const told = /* @__PURE__ */ new Set();
33914
+ const carriers = this.hooks.carriers?.() ?? [];
33308
33915
  for (const copy of copies) {
33309
33916
  const readers = this.state.chain[copy.e]?.m, key = this.secret(copy.e);
33310
33917
  if (!readers || !key) continue;
@@ -33327,11 +33934,12 @@ var GroupSession = class {
33327
33934
  ...unsigned,
33328
33935
  sig: toBase64Url(sign(editSigned(unsigned), this.identity.seed))
33329
33936
  };
33330
- const members = (to === void 0 ? this.others : [to]).filter((k) => k !== this.myKey && !told.has(k) && rosterHas(this.roster, k) && rosterHas(readers, k));
33331
- for (const k of members) {
33937
+ const targets = (to === void 0 ? this.others : [to]).filter((k) => k !== this.myKey && rosterHas(this.roster, k));
33938
+ for (const k of targets.filter((k) => !told.has(k) && rosterHas(readers, k))) {
33332
33939
  this.hooks.send(k, frame);
33333
33940
  told.add(k);
33334
33941
  }
33942
+ for (const k of targets.filter((k) => carriers.includes(k) && !rosterHas(readers, k))) this.hooks.send(k, frame);
33335
33943
  }
33336
33944
  return { sent: told.size };
33337
33945
  });
@@ -33730,11 +34338,11 @@ var GroupSession = class {
33730
34338
  }
33731
34339
  const relayed = raw.s !== from;
33732
34340
  const now = this.now(), answer = (this.answering.get(from) ?? 0) > now;
33733
- if (answer) this.answering.set(from, now + ANSWER_WINDOW_MS$1);
33734
34341
  if (relayed && (!rosterHas(this.roster, from) || !this.handsOn(raw.s))) return;
33735
34342
  if (this.isDuplicate(raw)) return;
33736
34343
  const signedWhole = relayed && this.wholeSigned(raw);
33737
34344
  if (!signedWhole && !verify(fromBase64Url(raw.sig), messageSigned$1(raw), publicKeyFromZ32(raw.s))) return;
34345
+ if (answer) this.answering.set(from, now + ANSWER_WINDOW_MS$1);
33738
34346
  if (raw.e > this.epoch) {
33739
34347
  this.park(from, raw);
33740
34348
  return;
@@ -33754,6 +34362,7 @@ var GroupSession = class {
33754
34362
  delete raw.o;
33755
34363
  delete raw.xs;
33756
34364
  }
34365
+ if (!this.paced(this.messagePace, raw.s, frameBytes(raw), relayed && (answer || waited))) return;
33757
34366
  const first = raw.o === void 0 ? null : readFirstPlace(raw.o, raw.e);
33758
34367
  if (raw.o !== void 0 && !first) return;
33759
34368
  const secret = this.secret(raw.e);
@@ -33830,7 +34439,7 @@ var GroupSession = class {
33830
34439
  * 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
33831
34440
  * waits, as a message does. Taken, it is kept to hand on in turn.
33832
34441
  */
33833
- async receiveEdit(from, raw) {
34442
+ async receiveEdit(from, raw, waited = false) {
33834
34443
  if (!isEditFrame(raw) || raw.s === this.myKey || !rosterHas(this.roster, from)) return;
33835
34444
  const member = rosterHas(this.roster, raw.s);
33836
34445
  if (!verify(fromBase64Url(raw.sig), editSigned(raw), publicKeyFromZ32(raw.s))) return;
@@ -33839,7 +34448,15 @@ var GroupSession = class {
33839
34448
  return;
33840
34449
  }
33841
34450
  const commit = this.state.chain[raw.e];
33842
- if (!commit || !rosterHas(commit.m, raw.s) || !rosterHas(commit.m, this.myKey)) return;
34451
+ if (!commit || !rosterHas(commit.m, raw.s)) return;
34452
+ if (!(this.state.relayEdits ?? []).some((f) => f.s === raw.s && f.e === raw.e && f.n === raw.n && f.v >= raw.v) && !this.paced(this.editPace, raw.s, raw.c.length + 400, raw.s !== from && (this.awaitsAnswer(from) || waited))) return;
34453
+ if (!rosterHas(commit.m, this.myKey)) {
34454
+ if (member && this.keepEdit(raw)) {
34455
+ this.persistSoon();
34456
+ this.took(cleanEdit(raw));
34457
+ }
34458
+ return;
34459
+ }
33843
34460
  const secret = this.secret(raw.e);
33844
34461
  if (!secret) {
33845
34462
  if (raw.e >= this.epoch - GROUP_LIMITS.secrets) this.parkEdit(from, raw);
@@ -33874,18 +34491,27 @@ var GroupSession = class {
33874
34491
  ...rm ? { rm: true } : {}
33875
34492
  });
33876
34493
  if (this.keepEdit(raw)) {
33877
- await this.persist();
34494
+ this.persistSoon();
33878
34495
  this.took(cleanEdit(raw));
33879
34496
  }
33880
34497
  }
33881
34498
  parkEdit(from, frame) {
33882
34499
  if (frame.e > this.epoch + GROUP_LIMITS.secrets) return;
34500
+ this.expireWaiting();
33883
34501
  this.waitingEdits = [...this.waitingEdits.filter((w) => !(w.frame.s === frame.s && w.frame.e === frame.e && w.frame.n === frame.n && w.frame.v <= frame.v)), {
33884
34502
  from,
33885
- frame
33886
- }].slice(-GROUP_LIMITS.outlog);
34503
+ frame,
34504
+ at: this.now(),
34505
+ stranger: this.stranger(frame.s)
34506
+ }];
34507
+ for (let i; (i = overflow(this.waitingEdits, GROUP_LIMITS.outlog)) >= 0;) this.waitingEdits.splice(i, 1);
33887
34508
  this.ask(from);
33888
34509
  }
34510
+ paced(paces, author, bytes, answer) {
34511
+ let pace = paces.get(author);
34512
+ if (!pace) paces.set(author, pace = new AuthorPace(paces === this.editPace ? AUTHOR_OWED.edits : AUTHOR_OWED.messages));
34513
+ return pace.take(bytes, this.now(), answer);
34514
+ }
33889
34515
  wholeSigned(raw) {
33890
34516
  if (typeof raw.xs !== "string" || raw.xs.length !== 86 || !B64$1.test(raw.xs)) return false;
33891
34517
  try {
@@ -33994,15 +34620,31 @@ var GroupSession = class {
33994
34620
  }
33995
34621
  park(from, frame) {
33996
34622
  if (frame.e > this.epoch + GROUP_LIMITS.secrets) return;
34623
+ this.expireWaiting();
33997
34624
  if (this.waiting.some((w) => w.frame.s === frame.s && w.frame.e === frame.e && w.frame.n === frame.n)) return;
33998
34625
  this.waiting.push({
33999
34626
  from,
34000
- frame
34627
+ frame,
34628
+ at: this.now(),
34629
+ stranger: this.stranger(frame.s)
34001
34630
  });
34002
34631
  this.waitingBytes += frame.c.length;
34003
- while (this.waiting.length > GROUP_LIMITS.waiting || this.waitingBytes > GROUP_LIMITS.waitingBytes) this.waitingBytes -= this.waiting.shift().frame.c.length;
34632
+ for (let i; (i = overflow(this.waiting, GROUP_LIMITS.waiting, this.waitingBytes > GROUP_LIMITS.waitingBytes)) >= 0;) this.waitingBytes -= this.waiting.splice(i, 1)[0].frame.c.length;
34004
34633
  this.ask(from);
34005
34634
  }
34635
+ /** Not in the roster, nor in any of the last `secrets` commits: a key whose frames may be no member's. */
34636
+ stranger(key) {
34637
+ return !this.state.chain.slice(-GROUP_LIMITS.secrets).some((c) => rosterHas(c.m, key));
34638
+ }
34639
+ /** Frames and edits that waited `waitingMs`: dropped, and a member's noted (`waitedInVain`). */
34640
+ expireWaiting() {
34641
+ const now = this.now(), stale = (w) => now - w.at >= GROUP_LIMITS.waitingMs;
34642
+ if (!this.waiting.some(stale) && !this.waitingEdits.some(stale)) return;
34643
+ for (const w of this.waiting) if (stale(w) && !w.stranger) this.waitedInVain.set(w.frame.s, now);
34644
+ this.waiting = this.waiting.filter((w) => !stale(w));
34645
+ this.waitingBytes = this.waiting.reduce((sum, w) => sum + w.frame.c.length, 0);
34646
+ this.waitingEdits = this.waitingEdits.filter((w) => !stale(w));
34647
+ }
34006
34648
  /** Whoever sent something I cannot read yet is ahead of me, or holds a secret I lack: ask, but not in a loop. */
34007
34649
  ask(from) {
34008
34650
  const now = Date.now();
@@ -34026,7 +34668,7 @@ var GroupSession = class {
34026
34668
  for (const { from, frame } of ready) await this.receiveMessage(from, frame, true);
34027
34669
  const edits = this.waitingEdits.filter((w) => w.frame.e <= this.epoch && !!this.state.secrets[w.frame.e]);
34028
34670
  this.waitingEdits = this.waitingEdits.filter((w) => !edits.includes(w));
34029
- for (const { from, frame } of edits) await this.receiveEdit(from, frame);
34671
+ for (const { from, frame } of edits) await this.receiveEdit(from, frame, true);
34030
34672
  }
34031
34673
  async receiveCommit(from, frame) {
34032
34674
  const raw = frame.commit;
@@ -34614,6 +35256,12 @@ var COMMUNITY_LIMITS = {
34614
35256
  window: 64,
34615
35257
  /** Commits known off the main branch. */
34616
35258
  side: 512,
35259
+ /**
35260
+ * Of those, the branches one member's commit ends (its newest), and the commits it signed: a handful of races, and
35261
+ * one full run of its admissions (`memberAdmissions`, with the leaves among them). The admin's are not counted.
35262
+ */
35263
+ sideTips: 8,
35264
+ sideCommits: 64,
34617
35265
  /** Commits waiting for their parent. */
34618
35266
  pendingCommits: 64,
34619
35267
  /** Epoch secrets waiting for their commit. */
@@ -34622,6 +35270,11 @@ var COMMUNITY_LIMITS = {
34622
35270
  pendingMs: 12e4,
34623
35271
  waiting: 64,
34624
35272
  waitingBytes: 1048576,
35273
+ /**
35274
+ * Of those, the ones signed by a key no commit I know names (a newcomer whose admission has not come yet, or a key
35275
+ * anyone can make up): the newest only, they push out nobody else's, and they make no catch-up hurry.
35276
+ */
35277
+ waitingStrangers: 8,
34625
35278
  replay: 256,
34626
35279
  /** Commits in one welcome or chain piece. */
34627
35280
  chainPiece: 100,
@@ -35507,11 +36160,12 @@ var CommunitySession = class CommunitySession {
35507
36160
  * it was in. What one who left wrote while in the group is taken and handed on, its goodbye included, up to what the
35508
36161
  * member who committed the leave had heard of it then (its `group-left` mark), never past it: the leaver still holds
35509
36162
  * those epochs' secrets, and anything it signs later is not heard (WISP 903 § Leaving and removal). No mark here
35510
- * (one not come yet, or a committer's app before it) and nothing of it is heard.
36163
+ * (one not come yet, or a committer's app before it) and nothing of it is heard. A key let in only on a branch that
36164
+ * lost is heard no more either, as one removed, once this member knows it lost.
35511
36165
  */
35512
36166
  heardAfterOut(f) {
35513
36167
  const i = this.outIndex(f.s);
35514
- if (i < 0) return true;
36168
+ if (i < 0) return rosterHas(this.roster, f.s) || this.isRecentMember(f.s) || !this.lostAt(f.s);
35515
36169
  const commit = this.state.chain[i];
35516
36170
  if (commit.k !== "leave") return false;
35517
36171
  const high = this.state.left?.[communityCommitHash(commit)]?.hi[seenKey(f.e, f.h)];
@@ -35873,6 +36527,7 @@ var CommunitySession = class CommunitySession {
35873
36527
  }
35874
36528
  this.followEntry();
35875
36529
  this.pruneSide();
36530
+ this.state.pendingLeaves = this.state.pendingLeaves.filter((r) => rosterHas(this.roster, r.s));
35876
36531
  if (this.state.status !== status) await this.persist();
35877
36532
  else this.persistSoon();
35878
36533
  this.hooks.changed();
@@ -35953,10 +36608,45 @@ var CommunitySession = class CommunitySession {
35953
36608
  seedB64: ""
35954
36609
  };
35955
36610
  }
35956
- /** Side commits stay up to a bound, the most recent ones (a longer branch being assembled included). */
36611
+ /**
36612
+ * Side commits stay up to a bound, the most recent ones (a longer branch being assembled included), and a member's
36613
+ * newest only: past `sideTips` of the branches it ends or `sideCommits` of its commits, its oldest branch goes, from
36614
+ * the tip down, so nothing kept loses its parent. Each is weighed at every commit taken and saved with the group, so
36615
+ * what one member signs off the main branch costs every member a bounded amount. What it signs last is kept, so a
36616
+ * branch it grows still comes in commit by commit (one let go comes again from where it parts in a catch-up).
36617
+ */
35957
36618
  pruneSide() {
35958
- this.state.side = this.state.side.slice(-COMMUNITY_LIMITS.side);
35959
- const keep = new Set(this.state.side.map((c) => communityCommitHash(c)));
36619
+ const admin = this.admin, hashes = /* @__PURE__ */ new Map();
36620
+ const hash = (c) => {
36621
+ let h = hashes.get(c);
36622
+ if (!h) hashes.set(c, h = communityCommitHash(c));
36623
+ return h;
36624
+ };
36625
+ let side = this.state.side.slice(-COMMUNITY_LIMITS.side);
36626
+ for (;;) {
36627
+ const held = new Set(side.map(hash)), parents = new Set(side.map((c) => c.p)), drop = /* @__PURE__ */ new Set();
36628
+ const signed = /* @__PURE__ */ new Map(), tips = /* @__PURE__ */ new Map(), oldest = /* @__PURE__ */ new Map(), cut = /* @__PURE__ */ new Set();
36629
+ for (const c of side) signed.set(c.by, (signed.get(c.by) ?? 0) + 1);
36630
+ for (let i = side.length - 1; i >= 0; i--) {
36631
+ const c = side[i];
36632
+ if (!held.has(c.p) && !this.mainIndex.has(c.p)) {
36633
+ drop.add(c);
36634
+ continue;
36635
+ }
36636
+ if (parents.has(hash(c))) continue;
36637
+ const n = (tips.get(c.by) ?? 0) + 1;
36638
+ tips.set(c.by, n);
36639
+ if (c.by !== admin && n > COMMUNITY_LIMITS.sideTips) {
36640
+ drop.add(c);
36641
+ cut.add(c.by);
36642
+ } else oldest.set(c.by, c);
36643
+ }
36644
+ for (const [by, n] of signed) if (by !== admin && n > COMMUNITY_LIMITS.sideCommits && !cut.has(by) && oldest.has(by)) drop.add(oldest.get(by));
36645
+ if (!drop.size) break;
36646
+ side = side.filter((c) => !drop.has(c));
36647
+ }
36648
+ this.state.side = side;
36649
+ const keep = new Set(side.map(hash));
35960
36650
  for (const [h, c] of [...this.known]) {
35961
36651
  if (this.mainIndex.has(h)) {
35962
36652
  if (this.mainIndex.get(h) < this.state.chain.length - 1 - COMMUNITY_LIMITS.window) this.rosters.delete(h);
@@ -35985,9 +36675,20 @@ var CommunitySession = class CommunitySession {
35985
36675
  if (!Object.keys(bySender).length) delete this.state.seen[sender];
35986
36676
  }
35987
36677
  }
36678
+ /**
36679
+ * Those of the main branch's window always stay, the current epoch's included; side commits, however many are
36680
+ * kept, only get what is left of the bound, the most recent first.
36681
+ */
35988
36682
  pruneSecrets() {
35989
- const order = [...this.state.chain.slice(-COMMUNITY_LIMITS.window - 1), ...this.state.side].map((c) => communityCommitHash(c));
35990
- const keep = new Set(order.slice(-COMMUNITY_LIMITS.secrets));
36683
+ const keep = new Set(this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map((c) => communityCommitHash(c)));
36684
+ let room = COMMUNITY_LIMITS.secrets - [...keep].filter((h) => this.state.secrets[h]).length;
36685
+ for (let i = this.state.side.length - 1; i >= 0 && room > 0; i--) {
36686
+ const h = communityCommitHash(this.state.side[i]);
36687
+ if (this.state.secrets[h] && !keep.has(h)) {
36688
+ keep.add(h);
36689
+ room--;
36690
+ }
36691
+ }
35991
36692
  for (const h of Object.keys(this.state.secrets)) if (!keep.has(h)) delete this.state.secrets[h];
35992
36693
  }
35993
36694
  /** A derived epoch's secret, from its parent's, when that is held. */
@@ -36070,7 +36771,8 @@ var CommunitySession = class CommunitySession {
36070
36771
  this.requireMember();
36071
36772
  if (!this.isAdmin) throw new Error("Only the admin can do that");
36072
36773
  }
36073
- async commit(kind, fields, now) {
36774
+ /** `alongside`: what else the commit changes in the state, saved in the same write (only once the commit is signed). */
36775
+ async commit(kind, fields, now, alongside) {
36074
36776
  if (!this.adminWork) throw new Error(GROUP_ADMIN_OFF_ERROR);
36075
36777
  if (this.hooks.adminTurn && !await this.hooks.adminTurn()) throw engineError("groupTurnUnconfirmed");
36076
36778
  if (this.state.chain.length >= COMMUNITY_LIMITS.chain) throw new Error("This group has reached its membership history limit. Create a new group.");
@@ -36114,6 +36816,7 @@ var CommunitySession = class CommunitySession {
36114
36816
  this.state.seq = 0;
36115
36817
  this.state.seqH = hash;
36116
36818
  this.pruneSide();
36819
+ alongside?.();
36117
36820
  await this.persist();
36118
36821
  this.hooks.broadcast({
36119
36822
  t: "group-commit",
@@ -36275,12 +36978,12 @@ var CommunitySession = class CommunitySession {
36275
36978
  return this.serialize(async () => {
36276
36979
  this.requireAdmin();
36277
36980
  const entry = off ? null : identityFromSeedB64(toBase64Url(randomBytes(32)));
36278
- await this.commit("link", { x: entry?.pubKeyZ32 ?? "" }, now);
36279
- this.state.entry = {
36280
- key: entry?.pubKeyZ32 ?? "",
36281
- seedB64: entry?.seedB64 ?? ""
36282
- };
36283
- await this.persist();
36981
+ await this.commit("link", { x: entry?.pubKeyZ32 ?? "" }, now, () => {
36982
+ this.state.entry = {
36983
+ key: entry?.pubKeyZ32 ?? "",
36984
+ seedB64: entry?.seedB64 ?? ""
36985
+ };
36986
+ });
36284
36987
  if (entry) {
36285
36988
  const pause = pacer(ENTRY_SLICE_MS);
36286
36989
  for (const key of this.others) {
@@ -37231,19 +37934,25 @@ var CommunitySession = class CommunitySession {
37231
37934
  park(from, frame) {
37232
37935
  if (frame.e > this.epoch + COMMUNITY_LIMITS.window) return;
37233
37936
  if (this.waiting.some((w) => w.frame.s === frame.s && w.frame.e === frame.e && w.frame.h === frame.h && w.frame.n === frame.n)) return;
37937
+ const stranger = !rosterHas(this.roster, frame.s) && !this.isRecentMember(frame.s);
37234
37938
  this.waiting.push({
37235
37939
  from,
37236
- frame
37940
+ frame,
37941
+ stranger
37237
37942
  });
37238
37943
  this.waitingBytes += frame.c.length;
37239
- while (this.waiting.length > COMMUNITY_LIMITS.waiting || this.waitingBytes > COMMUNITY_LIMITS.waitingBytes) this.waitingBytes -= this.waiting.shift().frame.c.length;
37944
+ for (;;) {
37945
+ const strangers = this.waiting.filter((w) => w.stranger).length;
37946
+ if (strangers <= COMMUNITY_LIMITS.waitingStrangers && this.waiting.length <= COMMUNITY_LIMITS.waiting && this.waitingBytes <= COMMUNITY_LIMITS.waitingBytes) break;
37947
+ this.waitingBytes -= this.waiting.splice(strangers ? this.waiting.findIndex((w) => w.stranger) : 0, 1)[0].frame.c.length;
37948
+ }
37240
37949
  this.ask(from);
37241
37950
  }
37242
- /** Something is missing here: the current epoch's secret, or the epoch of frames waiting. */
37951
+ /** Something is missing here: the current epoch's secret, or the epoch of a member's frames waiting. */
37243
37952
  get needsCatchUp() {
37244
37953
  if (!this.isMember) return false;
37245
37954
  this.dropStale(this.pendingCommits, this.hooks.clock?.() ?? Date.now());
37246
- return !this.state.secrets[this.topHash] || this.waiting.length > 0 || this.pendingCommits.size > 0;
37955
+ return !this.state.secrets[this.topHash] || this.waiting.some((w) => !w.stranger) || this.pendingCommits.size > 0;
37247
37956
  }
37248
37957
  /** Asks a member I have an edge to for what I lack (the engine calls it now and then while `needsCatchUp`). */
37249
37958
  catchUp(to) {
@@ -37281,7 +37990,9 @@ var CommunitySession = class CommunitySession {
37281
37990
  if (!answered.take()) return;
37282
37991
  if (lost) {
37283
37992
  const at = this.mainIndex.get(frame.h);
37284
- const commits = this.state.chain.slice(at !== void 0 ? at + 1 : lost.fork + 1, lost.end + 1);
37993
+ let commits = this.state.chain.slice(at !== void 0 ? at + 1 : lost.fork + 1, lost.end + 1);
37994
+ const link = commits.findIndex((c) => c.k === "link" && !!c.x);
37995
+ if (link >= 0) commits = commits.slice(0, link);
37285
37996
  if (commits.length) this.answers.handOut(from, commits.map((commit) => ({
37286
37997
  t: "group-commit",
37287
37998
  v: 2,
@@ -37370,7 +38081,7 @@ var CommunitySession = class CommunitySession {
37370
38081
  const entry = this.entryFrame(from);
37371
38082
  if (entry) answer.push(entry);
37372
38083
  }
37373
- for (const request of this.state.pendingLeaves) answer.push({
38084
+ for (const request of this.state.pendingLeaves) if (rosterHas(this.roster, request.s)) answer.push({
37374
38085
  t: "group-leave",
37375
38086
  v: 2,
37376
38087
  g: this.id,
@@ -38262,6 +38973,6 @@ function readX401SdJwtVc(text) {
38262
38973
  };
38263
38974
  }
38264
38975
  //#endregion
38265
- export { SSHSIG_NAMESPACE as $, reactionEmoji as $a, requestRecords as $c, HoldKeys as $i, deviceLinkPairing as $l, engineError as $n, presenceSeenAt as $o, PIN_LIMITS as $r, handoffVersions as $s, ONCHAIN_PROVIDER as $t, isZ32Key as $u, knockIdentity as A, downsamplePeaks as Aa, verifyEnrollProof as Ac, IDENTITY_REVOCATION_LABEL as Ai, readImageMeta as Al, ENDPOINT as An, shownTime as Ao, lobbyKeys as Ar, HANDOFF_PIECE_BYTES as As, didJwsAlg as At, setLinkTraceSink as Au, GROUP_REACTED_FRAME as B, RateWindow as Ba, REQUEST_LIFETIME_MS as Bc, revokesIdentity as Bi, OwnInviteError as Bl, NO_PICTURE_METADATA as Bn, edgeParams as Bo, shouldBeHub as Br, handoffCancelFrame as Bs, parseDidSignaturePaste as Bt, parseRelayPayload as Bu, communityHasFrame as C, formatFileSize as Ca, enrollDigits as Cc, UPGRADE_CAPABILITY as Ci, readAppRevocation as Cl, pubkyProofFile as Cn, sameButtonText as Co, pickMeshHubs as Cr, HANDOFF_ACK as Cs, DID_DOCUMENT_MAX_BYTES as Ct, HEDGE_MS as Cu, decodeGroupEntryLink as D, VOICE_LIMITS as Da, enrollProofFrame as Dc, dialDescriptors as Di, signAppObject as Dl, requestLnurlInvoice as Dn, claimedTime as Do, doorHubs as Dr, HANDOFF_HELLO as Ds, checkDidJws as Dt, currentRelays as Du, KNOCK_TTL_MS as E, PLAYABLE_AUDIO as Ea, enrollHelloFrame as Ec, capsDescriptors as Ei, setAppSignatureFastPath as El, pubkyHomeserverOf as En, arrivalKey as Eo, beaconRecords as Er, HANDOFF_HAVE as Es, DidError as Et, SLOW_MS as Eu, GroupWakeLimiter as F, parseVideoMeta as Fa, planKnocks as Fc, identityRevocationValue as Fi, encodeContactLink as Fl, parseCashuRequestPayload as Fn, commitHash as Fo, pickHubs as Fr, filePartName as Fs, didWebFileUrl as Ft, PacketTooLargeError as Fu, GROUP_EDIT_FRAME as G, forwardedAgain as Ga, knockSlotOf as Gc, TRANSPORTS as Gi, inviteOwnership as Gl, GhostLink as Gn, DirectPathWatch as Go, transferEnded as Gr, handoffEphemeral as Gs, didDhtDocument as Gt, verify as Gu, GroupSession as H, LINK_TRAILING as Ha, contactAskerHolds as Hc, PeerProofs as Hi, decodeInviteCode as Hl, isStrippedPicture as Hn, RatchetBox as Ho, FILE_LIMITS as Hr, handoffContextProof as Hs, staticDidDocument as Ht, identityFromSeed as Hu, groupWakeFrame as I, EDIT_BUFFER_MS as Ia, settleRequest as Ic, identityStatement as Ii, readContactLink as Il, parseFedimintRequestPayload as In, parseGroupCommit as Io, rankHubs as Ir, handoffAttemptAllowed as Is, didWebHost as It, RELAY_PAYLOAD_MAX_BYTES as Iu, meshMessageRef as J, GROUP_REACTION_FRAME as Ja, makeStampPaced as Jc, irohDescriptor as Ji, ENROLL_CAPABILITY as Jl, PAIRED_FRAME_TOO_LARGE as Jn, DHT_POLL_INTERVALS as Jo, TYPING_REFRESH_MS as Jr, handoffOfferFrame as Js, encodeDidDhtPacket as Jt, hasVisible as Ju, GROUP_EDIT_TEXT_BYTES as K, readForwarded as Ka, knockSlotRecords as Kc, automaticTransport as Ki, ownInviteRefusal as Kl, INVITE_TAKEN as Kn, AWAITING_PEER_MS as Ko, transferStalled as Kr, handoffHelloFrame as Ks, didDhtFromPublicKey as Kt, MAX_AVATAR_LENGTH as Ku, groupWakes as L, EDIT_RATE_WINDOW_MS as La, takeRequest as Lc, isIdentityBinding as Li, createDeviceInvite as Ll, NO_VIDEO_METADATA as Ln, rosterAdmin as Lo, readBeacon as Lr, handoffAttemptFailed as Ls, normalizeDid as Lt, createRelayPayload as Lu, mergeKnocks as M, parseVoiceMeta as Ma, endedRequests as Mc, IdentityExchange as Mi, canonicalJsonBytes as Ml, fedimintRequestPayload as Mn, GROUP_MEMBER_CAP as Mo, mergeBeacon as Mr, HANDOFF_TIMINGS as Ms, didWebDocumentUrl as Mt, budgetRetryMs as Mu, readKnocks as N, voiceDownloadName as Na, inboxRecord as Nc, boundVerifiedIdentity as Ni, readCanonicalJson as Nl, findEndpoint as Nn, MAX_GROUP_CHAIN as No, mergeLobby as Nr, HANDOFF_VERIFIED as Ns, didWebFile as Nt, isDiscoveryBudgetError as Nu, encodeGroupEntryLink as O, VOICE_METER as Oa, readEnrollGrant as Oc, IDENTITY_MAX_EVIDENCE as Oi, signAppRevocation as Ol, resolveLightningDestination as On, heardTime as Oo, freshHubs as Or, HANDOFF_OFFER as Os, checkDidSignature as Ot, normalizeRelayUrl as Ou, GROUP_WAKE_FRAME as P, voiceLevel as Pa, newInbox as Pc, emptyIdentityLedger as Pi, createContactLink as Pl, isFederationId as Pn, MEMBER_KEY as Po, newerHead as Pr, NO_ATTEMPTS as Ps, didWebFileNames as Pt, withRequestOptions as Pu, SSHSIG_MAX_ARMOR as Q, queueReaction as Qa, readLinkRecord as Qc, HOLD_LIMITS as Qi, deviceKeyZ32 as Ql, EngineError as Qn, WATCH_PEER_MS as Qo, GROUP_PIN_FRAME as Qr, handoffStreamKey as Qs, EVM_TEST_CHAINS as Qt, fromBase64Url as Qu, parseGroupWakeFrame as R, MAX_REMOVAL_NUMBER as Ra, turnOff as Rc, newIdentityBinding as Ri, deviceInviteJoinerParams as Rl, videoMetadataPatches as Rn, rosterHas as Ro, readBeaconHead as Rr, handoffAttemptSucceeded as Rs, parseDid as Rt, newerPacket as Ru, GROUP_READ_NOTE_COMMUNITY as S, dhtFileId as Sa, enrollCancelReason as Sc, STATUS_CARD_CAPABILITY as Si, isAppRef as Sl, pubkyProofCapability as Sn, checkStatusCard as So, meshHubs as Sr, serviceIdFromName as Ss, verifyAtprotoRecordProof as St, HEDGE_MISSING_MS as Su, encodeCommunityLink as T, sanitizeMime as Ta, enrollGrantFrame as Tc, DHT_TEXT_CAPABILITY as Ti, readAppRevocations as Tl, homeserverWebEndpoint as Tn, statusCardText as To, beaconKeys as Tr, HANDOFF_DONE as Ts, DID_JWS_MAX_LENGTH as Tt, RelaysFailedError as Tu, frameBytes as U, linkStop as Ua, contactDay as Uc, emptyProofLedger as Ui, encodeInviteCode as Ul, stripPictureMetadata as Un, emptyRatchetState as Uo, FileUplink as Ur, handoffDataFrame as Us, strictBase64Url as Ut, identityFromSeedB64 as Uu, GROUP_READ_NOTE as V, dhtEditId as Va, contactAskerFrame as Vc, lastSharedWithMe as Vi, createChatInvite as Vl, PICTURE_METADATA_LIMITS as Vn, RATCHET_CAPABILITY as Vo, ChatFiles as Vr, handoffContext as Vs, signingKeys as Vt, createIdentity as Vu, COMMUNITY_EDIT_FRAME as W, parseLinkPreview as Wa, knockSlotIdentity as Wc, validExternalKey as Wi, inviteLink as Wl, withoutPictureMetadata as Wn, ratchetSessionOf as Wo, sentWhole as Wr, handoffDigest as Ws, DidDhtError as Wt, publicKeyFromZ32 as Wu, mentionsMember as X, ReactionWindow as Xa, openRequest as Xc, HOLD_CAPABILITY as Xi, deviceEchoFrame as Xl, pairedMessageFits as Xn, PRESENCE_WINDOW as Xo, sanitizeTypingStatus as Xr, handoffReleaseFrame as Xs, signDidDhtPacket as Xt, stripHidden as Xu, parseCommunityEdit as Y, REACTION_LIMITS as Ya, mergeContactKnocks as Yc, irohRelayUrl as Yi, HANDOFF_CAPABILITY as Yl, pairedEditFits as Yn, EXPECT_PEER_MS as Yo, TypingSender as Yr, handoffPakeFrame as Ys, resolveDidDht as Yt, sanitizeDisplayText as Yu, groupName as Z, nextReactionNumber as Za, readKnockSlot as Zc, HOLD_DATED_BACK_MS as Zi, deviceEchoNonce as Zl, pairedMessageFrame as Zn, RELAY_POLL_INTERVALS as Zo, typingActivity as Zr, handoffRetryAfter as Zs, ETHEREUM_USDT as Zt, bytesEqual as Zu, groupTypingEpoch as _, wellKnownUrl as _a, ENROLL_DONE as _c, chatAppId as _i, appRef as _l, PUBKY_PROOF_MAX_BYTES as _n, appCardId as _o, SIGNAL_REPLY_MS as _r, parseCallSignal as _s, isAtprotoDid as _t, turnKeys as _u, appRevocationFor as a, decodeDnsResponse as aa, readHandoffHello as ac, WAKE_CALL_INTERVAL_MS as ai, appDigest as al, WALLET_NETWORKS as an, readReply as ao, GROUP_WANT_NO_FRAME as ar, decodeControl as as, verifySshSignature as at, TURN_RAISE_READ_TIMEOUT_MS as au, COMMUNITY_LIMITS as b, peekDhtMailbox as ba, ENROLL_PROOF as bc, BUTTONS_CAPABILITY as bi, isAppHash as bl, newPubkyProofFolder as bn, cardLine as bo, MESH_HUBS as br, HTTP_SERVICE_PROTO as bs, shortAtprotoDid as bt, turnVerifierMark as bu, checkAppBeforeRun as c, domainWellKnownFile as ca, readHandoffVerified as cc, newWakeToken as ci, checkAppManifest as cl, assertWholeSats as cn, BUTTON_STYLES as co, isGroupMessageId as cr, CALL_SIGNAL_MAX_AGE_MS as cs, decodeAnyBitcoinAddress as ct, turnPutSummary as cu, checkAppStoreIndex as d, nip05RootKey as da, SET_UPDATE as dc, wakeRequest as di, readAppBundle as dl, walletNetworkOf as dn, PR_CHECKS as do, readGroupWant as dr, answersOffer as ds, ATPROTO_PROOF_COLLECTION as dt, firstDeviceSetSecret as du, HoldRefusedError as ea, newHandoffId as ec, randomBytes as ed, mayPin as ei, seenEntry as el, PaymentPreflightError as en, reactionIsNewer as eo, engineText as er, GhostlyHttpError as es, SshSigError as et, devicePingFrame as eu, readAppStore as f, normalizeDomain as fa, readSetUpdate as fc, checkPushEndpoint as fi, readAppBundleAsync as fl, SPARK_NETWORKS as fn, PR_STATES as fo, readGroupWantNo as fr, buildSdpFromSignal as fs, ATPROTO_PROOF_SCOPE as ft, nextTurnPosition as fu, GroupTypingBoard as g, txtValue as ga, verifySetUpdate as gc, APP_DATA_MAX_BYTES as gi, appFingerprint as gl, isBitcoinAddress as gn, TASK_STATUSES as go, SIGNAL_HOLD_MS as gr, extractParamsFromSdp as gs, checkAtprotoProofRecord as gt, turnInstance as gu, GROUP_TYPING_FRAME as h, recordsName as ha, signTombstone as hc, isServeId as hi, APP_STATEMENT_LIMITS as hl, sparkInvoiceDetails as hn, STATUS_CARD_LIMITS as ho, SIGNAL_FRESH_MS as hr, contactRtcConfig as hs, atprotoProofRkey as ht, signTurnRelease as hu, addedAppPermissions as i, DOMAIN_FILE_MAX_BYTES as ia, readHandoffHave as ic, utf8Encode as id, readPin as ii, APP_PERMISSIONS as il, USDT_PUBLIC_RPC as in, pairedReplyAuthor as io, GROUP_WANT_FRAME as ir, LIMITS as is, sshSignCommand as it, TURN_PUT_WINDOW_MS as iu, knockRecords as j, fileMessageText as ja, clearMissed as jc, IdentityCheckUnavailable as ji, canonicalJson as jl, cashuRequestPayload as jn, GROUP_ADMIN_OFF_ERROR as jo, lobbyRecords as jr, HANDOFF_REQUEST as js, didSignedMessages as jt, traceLink as ju, entryParams as k, baseMime as ka, readEnrollHello as kc, IDENTITY_MAX_VALIDITY as ki, parseImageMeta as kl, decodeBolt11 as kn, receivedTimestamp as ko, hubRank as kr, HANDOFF_PAKE as ks, didGhostlyServiceEntry as kt, relayUrlProblem as ku, planAppUpdate as l, encodeDnsQuery as la, sealHandoffPiece as lc, parseWakeFrame as li, isAppUrl as ll, formatPaymentAmount as ln, CRON_LINE as lo, readGroupFileMeta as lr, QUICK_REDIAL_MS as ls, ATPROTO_DECLARED_SCOPE as lt, TURN_LAST_SEQUENCE as lu, signAppStore as m, recordsFromWellKnown as ma, setUpdateFrame as mc, APP_RANGE_LIMITS as mi, APP_PREFIXES as ml, sparkAddressKind as mn, RUN_RESULTS as mo, GROUP_SIGNAL_FRAME as mr, callSignalHeardAt as ms, atprotoProofRecord as mt, signTurnPacket as mu, readX401SdJwtVc as n, newMailbox as na, readHandoffCancel as nc, toZ32 as nd, pinIsNewer as ni, APP_BUNDLE_MAGIC as nl, SEPOLIA_TEST_USDT_FAUCET as nn, validReactionNumber as no, GROUP_FILE_LIMITS as nr, parseLocalTarget as ns, parseSshSignature as nt, seedSigner as nu, appStoreDecision as o, dnsProofName as oa, readHandoffPake as oc, WakeLimiter as oi, appViewOf as ol, arkAddressPrefix as on, replySnippet as oo, fetchesByItself as or, encodeControl as os, verifyBitcoinMessage as ot, TURN_SETTLE_MS as ou, readAppStoreSteps as p, recordsFromTxt as pa, setAckFrame as pc, vapidKeysMatch as pi, sha256Paced as pl, SPARK_PROVIDER as pn, ROUTINE_STATES as po, CarriedTransport as pr, callRtcConfig as ps, atprotoDidMethod as pt, readTurnPacket as pu, carryMentions as q, COMMUNITY_REACTION_FRAME as qa, linkRecords as qc, dialableIrohRelay as qi, DEVICES_CAPABILITY as ql, LIVENESS_PING_MS as qn, DAEMON_WATCH_PEER_IDLE_MS as qo, TYPING_KINDS as qr, handoffManifestFrames as qs, encodeDidDhtDeactivated as qt, sanitizeAvatar as qu, sameX401HolderJwk as r, readManifest as ra, readHandoffDone as rc, utf8Decode as rd, pinNumberHolds as ri, APP_ICON_PATH as rl, TEST_USDT_FAUCET_AMOUNT as rn, wireReaction as ro, GROUP_HAVE_FRAME as rr, webLocalFetch as rs, sameSshKey as rt, webCryptoSigner as ru, appUpdateDecision as s, domainTxtRecord as sa, readHandoffTurnFrame as sc, deviceWakeRequest as si, assembleAppBundle as sl, assertTokenUnits as sn, BUTTON_ID as so, groupFileFallback as sr, BURST_RING_MS as ss, BitcoinAddressError as st, classifyTurnRead as su, newX401HolderKey as t, isHoldUrl as ta, readHandoffAck as tc, toBase64Url as td, nextPinNumber as ti, APP_BUNDLE_LIMITS as tl, SEPOLIA_TEST_USDT as tn, readReaction as to, parseEngineError as tr, formatLocalTarget as ts, parseSshPublicKey as tt, newDeviceSetSecret as tu, APP_STORE_LIMITS as u, isPublicAddress as ua, SET_ACK as uc, relayRequest as ui, pacer as ul, validatePaymentTarget as un, ITEM_STATES as uo, readGroupHave as ur, RTC_CONFIG as us, ATPROTO_FULL_SCOPE as ut, TURN_MAX as uu, openGroupTyping as v, DHT_FILE_TOO_LARGE as va, ENROLL_GRANT as vc, isAppVersion as vi, appRefPublisher as vl, isPubkyKey as vn, appCardUrl as vo, groupSignalFrame as vr, signalHasVideo as vs, normalizeAtprotoHandle as vt, turnName as vu, decodeCommunityLink as w, sanitizeFileName as wa, enrollDoneFrame as wc, CapsExchange as wi, readAppRevocationShape as wl, pubkyProofPath as wn, statusCardBytes as wo, COMMUNITY_TOPOLOGY as wr, HANDOFF_CANCEL as ws, DID_FILE_MAX_BYTES as wt, RelayTransport as wu, CommunitySession as x, DHT_FILE_CAPABILITY as xa, enrollCancelFrame as xc, EDIT_CAPABILITY as xi, isAppKey as xl, normalizePubkyKey as xn, cardUrl as xo, mayBeHub as xr, LEGACY_SERVICES as xs, AtprotoProofError as xt, DEFAULT_RELAYS as xu, sealGroupTyping as y, DHT_MESSAGE_TTL as ya, ENROLL_HELLO as yc, APPS_CAPABILITY as yi, checkAppRevokeStatement as yl, isPubkyProofFolder as yn, buttonLabelClash as yo, readGroupSignal as yr, emptyLinkRecords as ys, parseAtprotoDidDocument as yt, turnStatedVerifier as yu, GROUP_LIMITS as z, REMOVED_TEXT as za, ContactRequestError as zc, receivedIdentityStatus as zi, readDeviceInvite as zl, withoutVideoMetadata as zn, verifyCommitSignature as zo, readLobby as zr, handoffBusyFrame as zs, parseDidDocument as zt, openRelayPayload as zu };
38976
+ export { SSHSIG_NAMESPACE as $, ReactionWindow as $a, openRequest as $c, HOLD_DATED_BACK_MS as $i, deviceEchoFrame as $l, engineError as $n, PRESENCE_WINDOW as $o, PIN_LIMITS as $r, handoffReleaseFrame as $s, ONCHAIN_PROVIDER as $t, sanitizeDisplayText as $u, knockIdentity as A, VOICE_LIMITS as Aa, enrollProofFrame as Ac, IDENTITY_REVOCATION_LABEL as Ai, signAppObject as Al, ENDPOINT as An, claimedTime as Ao, lobbyKeys as Ar, HANDOFF_HELLO as As, didJwsAlg as At, currentRelays as Au, GROUP_REACTED_FRAME as B, EDIT_RATE_WINDOW_MS as Ba, takeRequest as Bc, newIdentityBinding as Bi, createDeviceInvite as Bl, NO_PICTURE_METADATA as Bn, rosterAdmin as Bo, shouldBeHub as Br, handoffAttemptFailed as Bs, parseDidSignaturePaste as Bt, RELAY_PAYLOAD_MAX_BYTES as Bu, communityHasFrame as C, peekDhtMailbox as Ca, ENROLL_PROOF as Cc, UPGRADE_CAPABILITY as Ci, isAppHash as Cl, pubkyProofFile as Cn, cardLine as Co, pickMeshHubs as Cr, HTTP_SERVICE_PROTO as Cs, DID_DOCUMENT_MAX_BYTES as Ct, turnVerifierMark as Cu, decodeGroupEntryLink as D, sanitizeFileName as Da, enrollDoneFrame as Dc, dialDescriptors as Di, readAppRevocationShape as Dl, requestLnurlInvoice as Dn, statusCardBytes as Do, doorHubs as Dr, HANDOFF_CANCEL as Ds, checkDidJws as Dt, RelayTransport as Du, KNOCK_TTL_MS as E, formatFileSize as Ea, enrollDigits as Ec, capsDescriptors as Ei, readAppRevocation as El, pubkyHomeserverOf as En, sameButtonText as Eo, beaconRecords as Er, HANDOFF_ACK as Es, DidError as Et, HEDGE_MS as Eu, GroupWakeLimiter as F, parseVoiceMeta as Fa, endedRequests as Fc, emptyIdentityLedger as Fi, canonicalJsonBytes as Fl, parseCashuRequestPayload as Fn, GROUP_MEMBER_CAP as Fo, pickHubs as Fr, HANDOFF_TIMINGS as Fs, didWebFileUrl as Ft, DiscoveryBudgetError as Fu, GROUP_EDIT_FRAME as G, LINK_TRAILING as Ga, contactAskerHolds as Gc, emptyProofLedger as Gi, decodeInviteCode as Gl, GhostLink as Gn, RatchetBox as Go, transferEnded as Gr, handoffContextProof as Gs, didDhtDocument as Gt, createIdentity as Gu, GroupSession as H, REMOVED_TEXT as Ha, ContactRequestError as Hc, revokesIdentity as Hi, readDeviceInvite as Hl, isStrippedPicture as Hn, verifyCommitSignature as Ho, FILE_LIMITS as Hr, handoffBusyFrame as Hs, staticDidDocument as Ht, newerPacket as Hu, groupWakeFrame as I, voiceDownloadName as Ia, inboxRecord as Ic, identityRefusal as Ii, readCanonicalJson as Il, parseFedimintRequestPayload as In, MAX_GROUP_CHAIN as Io, rankHubs as Ir, HANDOFF_VERIFIED as Is, didWebHost as It, budgetRetryMs as Iu, meshMessageRef as J, forwardedAgain as Ja, knockSlotOf as Jc, automaticTransport as Ji, inviteOwnership as Jl, PAIRED_FRAME_TOO_LARGE as Jn, DirectPathWatch as Jo, TYPING_REFRESH_MS as Jr, handoffEphemeral as Js, encodeDidDhtPacket as Jt, publicKeyFromZ32 as Ju, GROUP_EDIT_TEXT_BYTES as K, linkStop as Ka, contactDay as Kc, validExternalKey as Ki, encodeInviteCode as Kl, INVITE_TAKEN as Kn, emptyRatchetState as Ko, transferStalled as Kr, handoffDataFrame as Ks, didDhtFromPublicKey as Kt, identityFromSeed as Ku, groupWakes as L, voiceLevel as La, newInbox as Lc, identityRevocationValue as Li, createContactLink as Ll, NO_VIDEO_METADATA as Ln, MEMBER_KEY as Lo, readBeacon as Lr, NO_ATTEMPTS as Ls, normalizeDid as Lt, isDiscoveryBudgetError as Lu, mergeKnocks as M, baseMime as Ma, readEnrollHello as Mc, IdentityExchange as Mi, parseImageMeta as Ml, fedimintRequestPayload as Mn, receivedTimestamp as Mo, mergeBeacon as Mr, HANDOFF_PAKE as Ms, didWebDocumentUrl as Mt, relayUrlProblem as Mu, readKnocks as N, downsamplePeaks as Na, verifyEnrollProof as Nc, boundIdentityDisplay as Ni, readImageMeta as Nl, findEndpoint as Nn, shownTime as No, mergeLobby as Nr, HANDOFF_PIECE_BYTES as Ns, didWebFile as Nt, setLinkTraceSink as Nu, encodeGroupEntryLink as O, sanitizeMime as Oa, enrollGrantFrame as Oc, IDENTITY_MAX_EVIDENCE as Oi, readAppRevocations as Ol, resolveLightningDestination as On, statusCardText as Oo, freshHubs as Or, HANDOFF_DONE as Os, checkDidSignature as Ot, RelaysFailedError as Ou, GROUP_WAKE_FRAME as P, fileMessageText as Pa, clearMissed as Pc, boundVerifiedIdentity as Pi, canonicalJson as Pl, isFederationId as Pn, GROUP_ADMIN_OFF_ERROR as Po, newerHead as Pr, HANDOFF_REQUEST as Ps, didWebFileNames as Pt, traceLink as Pu, SSHSIG_MAX_ARMOR as Q, REACTION_LIMITS as Qa, mergeContactKnocks as Qc, HOLD_CAPABILITY as Qi, HANDOFF_CAPABILITY as Ql, EngineError as Qn, EXPECT_PEER_MS as Qo, GROUP_PIN_FRAME as Qr, handoffPakeFrame as Qs, EVM_TEST_CHAINS as Qt, hasVisible as Qu, parseGroupWakeFrame as R, parseVideoMeta as Ra, planKnocks as Rc, identityStatement as Ri, encodeContactLink as Rl, videoMetadataPatches as Rn, commitHash as Ro, readBeaconHead as Rr, filePartName as Rs, parseDid as Rt, withRequestOptions as Ru, GROUP_READ_NOTE_COMMUNITY as S, DHT_MESSAGE_TTL as Sa, ENROLL_HELLO as Sc, STATUS_CARD_CAPABILITY as Si, checkAppRevokeStatement as Sl, pubkyProofCapability as Sn, buttonLabelClash as So, meshHubs as Sr, emptyLinkRecords as Ss, verifyAtprotoRecordProof as St, turnStatedVerifier as Su, encodeCommunityLink as T, dhtFileId as Ta, enrollCancelReason as Tc, DHT_TEXT_CAPABILITY as Ti, isAppRef as Tl, homeserverWebEndpoint as Tn, checkStatusCard as To, beaconKeys as Tr, serviceIdFromName as Ts, DID_JWS_MAX_LENGTH as Tt, HEDGE_MISSING_MS as Tu, frameBytes as U, RateWindow as Ua, REQUEST_LIFETIME_MS as Uc, lastSharedWithMe as Ui, OwnInviteError as Ul, stripPictureMetadata as Un, edgeParams as Uo, FileUplink as Ur, handoffCancelFrame as Us, strictBase64Url as Ut, openRelayPayload as Uu, GROUP_READ_NOTE as V, MAX_REMOVAL_NUMBER as Va, turnOff as Vc, receivedIdentityStatus as Vi, deviceInviteJoinerParams as Vl, PICTURE_METADATA_LIMITS as Vn, rosterHas as Vo, ChatFiles as Vr, handoffAttemptSucceeded as Vs, signingKeys as Vt, createRelayPayload as Vu, COMMUNITY_EDIT_FRAME as W, dhtEditId as Wa, contactAskerFrame as Wc, PeerProofs as Wi, createChatInvite as Wl, withoutPictureMetadata as Wn, RATCHET_CAPABILITY as Wo, sentWhole as Wr, handoffContext as Ws, DidDhtError as Wt, parseRelayPayload as Wu, mentionsMember as X, COMMUNITY_REACTION_FRAME as Xa, linkRecords as Xc, irohDescriptor as Xi, DEVICES_CAPABILITY as Xl, pairedMessageFits as Xn, DAEMON_WATCH_PEER_IDLE_MS as Xo, sanitizeTypingStatus as Xr, handoffManifestFrames as Xs, signDidDhtPacket as Xt, MAX_AVATAR_LENGTH as Xu, parseCommunityEdit as Y, readForwarded as Ya, knockSlotRecords as Yc, dialableIrohRelay as Yi, ownInviteRefusal as Yl, pairedEditFits as Yn, AWAITING_PEER_MS as Yo, TypingSender as Yr, handoffHelloFrame as Ys, resolveDidDht as Yt, verify as Yu, groupName as Z, GROUP_REACTION_FRAME as Za, makeStampPaced as Zc, irohRelayUrl as Zi, ENROLL_CAPABILITY as Zl, pairedMessageFrame as Zn, DHT_POLL_INTERVALS as Zo, typingActivity as Zr, handoffOfferFrame as Zs, ETHEREUM_USDT as Zt, sanitizeAvatar as Zu, groupTypingEpoch as _, recordsName as _a, setUpdateFrame as _c, chatAppId as _i, APP_PREFIXES as _l, PUBKY_PROOF_MAX_BYTES as _n, RUN_RESULTS as _o, SIGNAL_REPLY_MS as _r, callSignalHeardAt as _s, isAtprotoDid as _t, signTurnPacket as _u, appRevocationFor as a, readManifest as aa, readHandoffCancel as ac, toBase64Url as ad, WAKE_CALL_INTERVAL_MS as ai, APP_BUNDLE_MAGIC as al, WALLET_NETWORKS as an, validReactionNumber as ao, GROUP_WANT_NO_FRAME as ar, parseLocalTarget as as, verifySshSignature as at, seedSigner as au, COMMUNITY_LIMITS as b, ACTIVE_DHT_POLL_MS as ba, ENROLL_DONE as bc, BUTTONS_CAPABILITY as bi, appRef as bl, newPubkyProofFolder as bn, appCardId as bo, MESH_HUBS as br, parseCallSignal as bs, shortAtprotoDid as bt, turnKeys as bu, checkAppBeforeRun as c, dnsProofName as ca, readHandoffHello as cc, utf8Encode as cd, newWakeToken as ci, appDigest as cl, assertWholeSats as cn, readReply as co, isGroupMessageId as cr, decodeControl as cs, decodeAnyBitcoinAddress as ct, TURN_RAISE_READ_TIMEOUT_MS as cu, checkAppStoreIndex as d, encodeDnsQuery as da, readHandoffVerified as dc, wakeRequest as di, checkAppManifest as dl, walletNetworkOf as dn, BUTTON_STYLES as do, readGroupWant as dr, CALL_SIGNAL_MAX_AGE_MS as ds, ATPROTO_PROOF_COLLECTION as dt, turnPutSummary as du, HOLD_LIMITS as ea, handoffRetryAfter as ec, stripHidden as ed, mayPin as ei, readKnockSlot as el, PaymentPreflightError as en, nextReactionNumber as eo, engineText as er, RELAY_POLL_INTERVALS as es, SshSigError as et, deviceEchoNonce as eu, readAppStore as f, isPublicAddress as fa, sealHandoffPiece as fc, checkPushEndpoint as fi, isAppUrl as fl, SPARK_NETWORKS as fn, CRON_LINE as fo, readGroupWantNo as fr, QUICK_REDIAL_MS as fs, ATPROTO_PROOF_SCOPE as ft, TURN_LAST_SEQUENCE as fu, GroupTypingBoard as g, recordsFromWellKnown as ga, setAckFrame as gc, APP_DATA_MAX_BYTES as gi, sha256Paced as gl, isBitcoinAddress as gn, ROUTINE_STATES as go, SIGNAL_HOLD_MS as gr, callRtcConfig as gs, checkAtprotoProofRecord as gt, readTurnPacket as gu, GROUP_TYPING_FRAME as h, recordsFromTxt as ha, readSetUpdate as hc, isServeId as hi, readAppBundleAsync as hl, sparkInvoiceDetails as hn, PR_STATES as ho, SIGNAL_FRESH_MS as hr, buildSdpFromSignal as hs, atprotoProofRkey as ht, nextTurnPosition as hu, addedAppPermissions as i, newMailbox as ia, readHandoffAck as ic, randomBytes as id, readPin as ii, APP_BUNDLE_LIMITS as il, USDT_PUBLIC_RPC as in, readReaction as io, GROUP_WANT_FRAME as ir, formatLocalTarget as is, sshSignCommand as it, newDeviceSetSecret as iu, knockRecords as j, VOICE_METER as ja, readEnrollGrant as jc, IdentityCheckUnavailable as ji, signAppRevocation as jl, cashuRequestPayload as jn, heardTime as jo, lobbyRecords as jr, HANDOFF_OFFER as js, didSignedMessages as jt, normalizeRelayUrl as ju, entryParams as k, PLAYABLE_AUDIO as ka, enrollHelloFrame as kc, IDENTITY_MAX_VALIDITY as ki, setAppSignatureFastPath as kl, decodeBolt11 as kn, arrivalKey as ko, hubRank as kr, HANDOFF_HAVE as ks, didGhostlyServiceEntry as kt, SLOW_MS as ku, planAppUpdate as l, domainTxtRecord as la, readHandoffPake as lc, parseWakeFrame as li, appViewOf as ll, formatPaymentAmount as ln, replySnippet as lo, readGroupFileMeta as lr, encodeControl as ls, ATPROTO_DECLARED_SCOPE as lt, TURN_SETTLE_MS as lu, signAppStore as m, normalizeDomain as ma, SET_UPDATE as mc, APP_RANGE_LIMITS as mi, readAppBundle as ml, sparkAddressKind as mn, PR_CHECKS as mo, GROUP_SIGNAL_FRAME as mr, answersOffer as ms, atprotoProofRecord as mt, firstDeviceSetSecret as mu, readX401SdJwtVc as n, HoldRefusedError as na, handoffVersions as nc, fromBase64Url as nd, pinIsNewer as ni, requestRecords as nl, SEPOLIA_TEST_USDT_FAUCET as nn, reactionEmoji as no, GROUP_FILE_LIMITS as nr, presenceSeenAt as ns, parseSshSignature as nt, deviceLinkPairing as nu, appStoreDecision as o, DOMAIN_FILE_MAX_BYTES as oa, readHandoffDone as oc, toZ32 as od, WakeLimiter as oi, APP_ICON_PATH as ol, arkAddressPrefix as on, wireReaction as oo, fetchesByItself as or, webLocalFetch as os, verifyBitcoinMessage as ot, webCryptoSigner as ou, readAppStoreSteps as p, nip05RootKey as pa, SET_ACK as pc, vapidKeysMatch as pi, pacer as pl, SPARK_PROVIDER as pn, ITEM_STATES as po, CarriedTransport as pr, RTC_CONFIG as ps, atprotoDidMethod as pt, TURN_MAX as pu, carryMentions as q, parseLinkPreview as qa, knockSlotIdentity as qc, TRANSPORTS as qi, inviteLink as ql, LIVENESS_PING_MS as qn, ratchetSessionOf as qo, TYPING_KINDS as qr, handoffDigest as qs, encodeDidDhtDeactivated as qt, identityFromSeedB64 as qu, sameX401HolderJwk as r, isHoldUrl as ra, newHandoffId as rc, isZ32Key as rd, pinNumberHolds as ri, seenEntry as rl, TEST_USDT_FAUCET_AMOUNT as rn, reactionIsNewer as ro, GROUP_HAVE_FRAME as rr, GhostlyHttpError as rs, sameSshKey as rt, devicePingFrame as ru, appUpdateDecision as s, decodeDnsResponse as sa, readHandoffHave as sc, utf8Decode as sd, deviceWakeRequest as si, APP_PERMISSIONS as sl, assertTokenUnits as sn, pairedReplyAuthor as so, groupFileFallback as sr, LIMITS as ss, BitcoinAddressError as st, TURN_PUT_WINDOW_MS as su, newX401HolderKey as t, HoldKeys as ta, handoffStreamKey as tc, bytesEqual as td, nextPinNumber as ti, readLinkRecord as tl, SEPOLIA_TEST_USDT as tn, queueReaction as to, parseEngineError as tr, WATCH_PEER_MS as ts, parseSshPublicKey as tt, deviceKeyZ32 as tu, APP_STORE_LIMITS as u, domainWellKnownFile as ua, readHandoffTurnFrame as uc, relayRequest as ui, assembleAppBundle as ul, validatePaymentTarget as un, BUTTON_ID as uo, readGroupHave as ur, BURST_RING_MS as us, ATPROTO_FULL_SCOPE as ut, classifyTurnRead as uu, openGroupTyping as v, txtValue as va, signTombstone as vc, isAppVersion as vi, APP_STATEMENT_LIMITS as vl, isPubkyKey as vn, STATUS_CARD_LIMITS as vo, groupSignalFrame as vr, contactRtcConfig as vs, normalizeAtprotoHandle as vt, signTurnRelease as vu, decodeCommunityLink as w, DHT_FILE_CAPABILITY as wa, enrollCancelFrame as wc, CapsExchange as wi, isAppKey as wl, pubkyProofPath as wn, cardUrl as wo, COMMUNITY_TOPOLOGY as wr, LEGACY_SERVICES as ws, DID_FILE_MAX_BYTES as wt, DEFAULT_RELAYS as wu, CommunitySession as x, DHT_FILE_TOO_LARGE as xa, ENROLL_GRANT as xc, EDIT_CAPABILITY as xi, appRefPublisher as xl, normalizePubkyKey as xn, appCardUrl as xo, mayBeHub as xr, signalHasVideo as xs, AtprotoProofError as xt, turnName as xu, sealGroupTyping as y, wellKnownUrl as ya, verifySetUpdate as yc, APPS_CAPABILITY as yi, appFingerprint as yl, isPubkyProofFolder as yn, TASK_STATUSES as yo, readGroupSignal as yr, extractParamsFromSdp as ys, parseAtprotoDidDocument as yt, turnInstance as yu, GROUP_LIMITS as z, EDIT_BUFFER_MS as za, settleRequest as zc, isIdentityBinding as zi, readContactLink as zl, withoutVideoMetadata as zn, parseGroupCommit as zo, readLobby as zr, handoffAttemptAllowed as zs, parseDidDocument as zt, PacketTooLargeError as zu };
38266
38977
 
38267
- //# sourceMappingURL=src-D31D1_oY.js.map
38978
+ //# sourceMappingURL=src-BZkY6N3J.js.map