@ghostlytools/cli 1.10.3 → 1.10.5

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 (92) hide show
  1. package/dist/assets/{api-C4MLg5Rs.js → api-DppWqAP3.js} +12 -12
  2. package/dist/assets/api-DppWqAP3.js.map +1 -0
  3. package/dist/assets/{api-BdaxsDvA.js → api-K-i5MrP-.js} +2 -2
  4. package/dist/assets/{apiKit-BbNaxZGZ.js → apiKit-DFIho4Ev.js} +2 -2
  5. package/dist/assets/{apiKit-BbNaxZGZ.js.map → apiKit-DFIho4Ev.js.map} +1 -1
  6. package/dist/assets/{apps-BtGFth7o.js → apps-1MkGMH8m.js} +1 -1
  7. package/dist/assets/{apps-BluQgEhv.js → apps-yBnbEtfV.js} +3 -3
  8. package/dist/assets/{apps-BluQgEhv.js.map → apps-yBnbEtfV.js.map} +1 -1
  9. package/dist/assets/{arkade-DdZx4b_I.js → arkade-bFAS6imn.js} +2 -2
  10. package/dist/assets/{arkade-DdZx4b_I.js.map → arkade-bFAS6imn.js.map} +1 -1
  11. package/dist/assets/{backup-I1n7ccz7.js → backup-ejIX59o7.js} +1 -1
  12. package/dist/assets/{backup-DyDsW7sC.js → backup-vj4J7M3e.js} +6 -6
  13. package/dist/assets/{backup-DyDsW7sC.js.map → backup-vj4J7M3e.js.map} +1 -1
  14. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  15. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  16. package/dist/assets/{blobFiles-BnjN_Vrz.js → blobFiles-XZ9PEXYy.js} +2 -2
  17. package/dist/assets/{blobFiles-BnjN_Vrz.js.map → blobFiles-XZ9PEXYy.js.map} +1 -1
  18. package/dist/assets/{buttons-Do7dCku6.js → buttons-BoDMx3Ky.js} +3 -3
  19. package/dist/assets/{buttons-Do7dCku6.js.map → buttons-BoDMx3Ky.js.map} +1 -1
  20. package/dist/assets/buttons-DG1CKgAI.js +2 -0
  21. package/dist/assets/{client-CWsjRiH8.js → client-BQArefYa.js} +10 -4
  22. package/dist/assets/client-BQArefYa.js.map +1 -0
  23. package/dist/assets/{codec-DPaXhuYc.js → codec-_MwTUz5E.js} +2 -2
  24. package/dist/assets/{codec-DPaXhuYc.js.map → codec-_MwTUz5E.js.map} +1 -1
  25. package/dist/assets/{envelope-5Gu9yGk_.js → envelope-CeZBNGX-.js} +2 -2
  26. package/dist/assets/{envelope-5Gu9yGk_.js.map → envelope-CeZBNGX-.js.map} +1 -1
  27. package/dist/assets/{fileBytes-DjBYYyXT.js → fileBytes-BABGEF13.js} +2 -2
  28. package/dist/assets/{fileBytes-DjBYYyXT.js.map → fileBytes-BABGEF13.js.map} +1 -1
  29. package/dist/assets/{fileBytes-DMzrIdCu.js → fileBytes-CQQK2uOh.js} +1 -1
  30. package/dist/assets/{fileBytes-Douk1yOp.js → fileBytes-DqnfKIkj.js} +2 -2
  31. package/dist/assets/{fileBytes-Douk1yOp.js.map → fileBytes-DqnfKIkj.js.map} +1 -1
  32. package/dist/assets/fileBytesIdb-BtXATa7j.js +2 -0
  33. package/dist/assets/{fileBytesIdb-CkClu9YI.js → fileBytesIdb-DrXmDUSy.js} +2 -2
  34. package/dist/assets/{fileBytesIdb-CkClu9YI.js.map → fileBytesIdb-DrXmDUSy.js.map} +1 -1
  35. package/dist/assets/{fileBytesOpfs-WryQuOgK.js → fileBytesOpfs-udKCzcLe.js} +6 -9
  36. package/dist/assets/{fileBytesOpfs-WryQuOgK.js.map → fileBytesOpfs-udKCzcLe.js.map} +1 -1
  37. package/dist/assets/{fixedHosts-PR1BcfKX.js → fixedHosts-B_2Rvyja.js} +3 -3
  38. package/dist/assets/{fixedHosts-PR1BcfKX.js.map → fixedHosts-B_2Rvyja.js.map} +1 -1
  39. package/dist/assets/{groupFiles-BuToTMUk.js → groupFiles-D-ZUUHrx.js} +104 -81
  40. package/dist/assets/groupFiles-D-ZUUHrx.js.map +1 -0
  41. package/dist/assets/{host-fkQYBvKH.js → host-DFLzzKNr.js} +183 -41
  42. package/dist/assets/host-DFLzzKNr.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-DDCak5PY.js → hyperdhtRelay-CV6qMrom.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-DDCak5PY.js.map → hyperdhtRelay-CV6qMrom.js.map} +1 -1
  45. package/dist/assets/{irohWeb-B4_swKx0.js → irohWeb-C_Wnw7Q9.js} +7 -3
  46. package/dist/assets/irohWeb-C_Wnw7Q9.js.map +1 -0
  47. package/dist/assets/{main-ClYsttvY.js → main-xO8MnXxD.js} +19 -19
  48. package/dist/assets/{main-ClYsttvY.js.map → main-xO8MnXxD.js.map} +1 -1
  49. package/dist/assets/{mainline-Hsk2SZ1B.js → mainline-Bx184Ixg.js} +94 -2
  50. package/dist/assets/mainline-Bx184Ixg.js.map +1 -0
  51. package/dist/assets/{networkReason-C9Hr-hO7.js → networkReason-BlQhTbXk.js} +3 -3
  52. package/dist/assets/{networkReason-C9Hr-hO7.js.map → networkReason-BlQhTbXk.js.map} +1 -1
  53. package/dist/assets/{nwc-BbK6qNxS.js → nwc-B3-PHX0L.js} +3 -3
  54. package/dist/assets/{nwc-BbK6qNxS.js.map → nwc-B3-PHX0L.js.map} +1 -1
  55. package/dist/assets/{nwcProvider-D_tt2X3Z.js → nwcProvider-BeQBPB2q.js} +2 -2
  56. package/dist/assets/{nwcProvider-D_tt2X3Z.js.map → nwcProvider-BeQBPB2q.js.map} +1 -1
  57. package/dist/assets/{ownDid-DkK_jem4.js → ownDid-DAzW-Urb.js} +3 -2
  58. package/dist/assets/ownDid-DAzW-Urb.js.map +1 -0
  59. package/dist/assets/{profiles-aV9vaK0B.js → profiles-Bg43mRXu.js} +3 -3
  60. package/dist/assets/{profiles-aV9vaK0B.js.map → profiles-Bg43mRXu.js.map} +1 -1
  61. package/dist/assets/{registry-CEjnubep.js → registry-BDnsZJBi.js} +123 -17
  62. package/dist/assets/registry-BDnsZJBi.js.map +1 -0
  63. package/dist/assets/{registry-C9T6tYCO.js → registry-CAk2-5BQ.js} +1 -1
  64. package/dist/assets/{resolve-BBOrN13E.js → resolve-UAfshn6j.js} +2 -2
  65. package/dist/assets/{resolve-BBOrN13E.js.map → resolve-UAfshn6j.js.map} +1 -1
  66. package/dist/assets/{server-BJ3T-kx3.js → server-DYdR0_Fj.js} +738 -194
  67. package/dist/assets/server-DYdR0_Fj.js.map +1 -0
  68. package/dist/assets/{src-BIdfHB7t.js → src-BTRPAi5X.js} +710 -153
  69. package/dist/assets/src-BTRPAi5X.js.map +1 -0
  70. package/dist/assets/{sshForges-CRg-NGld.js → sshForges-KtHK5x1x.js} +2 -2
  71. package/dist/assets/{sshForges-CRg-NGld.js.map → sshForges-KtHK5x1x.js.map} +1 -1
  72. package/dist/assets/{translate-b0X61WMI.js → translate-CYuygrvA.js} +2 -2
  73. package/dist/assets/{translate-b0X61WMI.js.map → translate-CYuygrvA.js.map} +1 -1
  74. package/dist/assets/{usdt-6CQdfye1.js → usdt-Dw9IENe_.js} +3 -3
  75. package/dist/assets/{usdt-6CQdfye1.js.map → usdt-Dw9IENe_.js.map} +1 -1
  76. package/dist/assets/{words-Dk6o6wz4.js → words-BvdNuw_v.js} +3 -3
  77. package/dist/assets/words-BvdNuw_v.js.map +1 -0
  78. package/dist/ghostly.mjs +1 -1
  79. package/package.json +1 -1
  80. package/dist/assets/api-C4MLg5Rs.js.map +0 -1
  81. package/dist/assets/buttons-DpjwXePb.js +0 -2
  82. package/dist/assets/client-CWsjRiH8.js.map +0 -1
  83. package/dist/assets/fileBytesIdb-CD5Uv490.js +0 -2
  84. package/dist/assets/groupFiles-BuToTMUk.js.map +0 -1
  85. package/dist/assets/host-fkQYBvKH.js.map +0 -1
  86. package/dist/assets/irohWeb-B4_swKx0.js.map +0 -1
  87. package/dist/assets/mainline-Hsk2SZ1B.js.map +0 -1
  88. package/dist/assets/ownDid-DkK_jem4.js.map +0 -1
  89. package/dist/assets/registry-CEjnubep.js.map +0 -1
  90. package/dist/assets/server-BJ3T-kx3.js.map +0 -1
  91. package/dist/assets/src-BIdfHB7t.js.map +0 -1
  92. package/dist/assets/words-Dk6o6wz4.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
  };
@@ -1209,6 +1239,7 @@ var CATCH_UP_ASKER = {
1209
1239
  watch: false,
1210
1240
  watchWrite: false,
1211
1241
  departed: false,
1242
+ awaited: false,
1212
1243
  resume: false,
1213
1244
  back: false
1214
1245
  };
@@ -1299,6 +1330,47 @@ function looksLikeHost(text) {
1299
1330
  /** A relay the breaker leaves alone for failing (`RelayBreaker`): nothing was asked of it now. */
1300
1331
  var RelayLeftAloneError = class extends Error {};
1301
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
+ /**
1302
1374
  * A read the relays failed (or left alone for failing before), when its caller has another path to ask
1303
1375
  * (`RelayTransport.resolve` with `keptOnFailure` false): `kept` is the newest packet the relays gave for the key before.
1304
1376
  */
@@ -1322,7 +1394,9 @@ var RelayTransport = class {
1322
1394
  * records are written by every member, an inviter warms its contact's key with an empty packet, and this device's
1323
1395
  * own clock may have been set back since it last wrote. A relay and the DHT keep only the packet dated latest, so
1324
1396
  * one dated by this clock alone, when it is behind, was refused (409) or silently never read, until this clock
1325
- * 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).
1326
1400
  */
1327
1401
  seenTimestamp = /* @__PURE__ */ new Map();
1328
1402
  /**
@@ -1357,6 +1431,10 @@ var RelayTransport = class {
1357
1431
  spentAnswerAllowance = /* @__PURE__ */ new Map();
1358
1432
  /** Per contact, its departed reads past the limit in the last minute, every relay together (`DEPARTED_READS`). */
1359
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;
1360
1438
  /**
1361
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
1362
1440
  * it is under the watch share (`WATCH_SHARE`) and while the groups' reads are rationed (`GROUP_RATION_WINDOW_MS`). And
@@ -1409,6 +1487,10 @@ var RelayTransport = class {
1409
1487
  hedgeMs;
1410
1488
  /** Until when each relay found slow (`SLOW_MS`) goes after the others in a read (`readOrder`). */
1411
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();
1412
1494
  /** Keys whose last read was answered 404: their next read hedges later (`HEDGE_MISSING_MS`). */
1413
1495
  missing = /* @__PURE__ */ new Set();
1414
1496
  listeners = /* @__PURE__ */ new Set();
@@ -1465,6 +1547,24 @@ var RelayTransport = class {
1465
1547
  this.slowUntil.clear();
1466
1548
  this.changed("recovered");
1467
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
+ }
1468
1568
  /** Called when a relay trips or recovers. */
1469
1569
  subscribe(listener) {
1470
1570
  this.listeners.add(listener);
@@ -1500,7 +1600,7 @@ var RelayTransport = class {
1500
1600
  * Returns once one relay took the packet: the others finish in the background.
1501
1601
  */
1502
1602
  async publish(identity, records, options = {}) {
1503
- 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);
1504
1604
  await this.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putEverywhere(key, payload, timestamp, options, conflict), options);
1505
1605
  }
1506
1606
  /**
@@ -1539,7 +1639,7 @@ var RelayTransport = class {
1539
1639
  if (again || redated) return;
1540
1640
  redated = (async () => {
1541
1641
  const held = read ? await read().catch(() => null) : await this.heldAt(relay, key, asker(options, true));
1542
- if (held === null || held < timestamp) return false;
1642
+ if (held === null || held < timestamp || !withinSkew(held)) return false;
1543
1643
  traceLink(key, "publish-redated", {
1544
1644
  aheadMs: Number((held - timestamp) / 1000n),
1545
1645
  relay
@@ -1554,7 +1654,9 @@ var RelayTransport = class {
1554
1654
  await put(key, createRelayPayload(identity, records, timestamp), timestamp, conflict);
1555
1655
  } catch (error) {
1556
1656
  const pending = redated;
1557
- if (!pending || !await pending) throw error;
1657
+ if (!pending || !await pending.catch((later) => {
1658
+ throw laterRound(error, later);
1659
+ })) throw error;
1558
1660
  }
1559
1661
  }
1560
1662
  /** `PkarrTransport.publishHeld`: `publishDated`'s check before signing, for a payload signed elsewhere in this process. */
@@ -1620,7 +1722,7 @@ var RelayTransport = class {
1620
1722
  }
1621
1723
  /** A packet under this key was read (on a relay, or by the CLI on the DHT): its time, for `nextTimestamp`. */
1622
1724
  sawTimestamp(pubKeyZ32, timestamp) {
1623
- 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);
1624
1726
  }
1625
1727
  /**
1626
1728
  * Puts a payload `publishDated` just signed, dated `timestamp`, on every relay. Its signature is not checked: it was
@@ -1628,7 +1730,7 @@ var RelayTransport = class {
1628
1730
  * gives it.
1629
1731
  */
1630
1732
  async putSigned(pubKeyZ32, payload, timestamp, options = {}, conflict) {
1631
- 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);
1632
1734
  await this.putEverywhere(pubKeyZ32, payload, timestamp, options, conflict);
1633
1735
  }
1634
1736
  /**
@@ -1636,7 +1738,7 @@ var RelayTransport = class {
1636
1738
  * (`signedAt`) and is not checked again. `conflict`: as `publishDated` gives it.
1637
1739
  */
1638
1740
  async publishPayload(pubKeyZ32, payload, options = {}, conflict) {
1639
- 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);
1640
1742
  const seq = options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;
1641
1743
  if (options.signedAt === void 0 || !options.redate) return this.putEverywhere(pubKeyZ32, payload, seq, options, conflict);
1642
1744
  await this.putRedated(pubKeyZ32, payload, seq, options, PAYLOAD_REDATES);
@@ -1669,7 +1771,7 @@ var RelayTransport = class {
1669
1771
  if (left <= 0 || redated) return;
1670
1772
  redated = (async () => {
1671
1773
  const held = await this.heldAt(relay, key, asker(options, true));
1672
- if (held === null || held < timestamp) return false;
1774
+ if (held === null || held < timestamp || !withinSkew(held)) return false;
1673
1775
  if (this.lastTimestamp.get(key) !== timestamp) return true;
1674
1776
  const again = options.redate(held);
1675
1777
  if (!again) return true;
@@ -1689,7 +1791,9 @@ var RelayTransport = class {
1689
1791
  await this.putEverywhere(key, payload, timestamp, options, conflict);
1690
1792
  } catch (error) {
1691
1793
  const pending = redated;
1692
- if (!pending || !await pending) throw error;
1794
+ if (!pending || !await pending.catch((later) => {
1795
+ throw laterRound(error, later);
1796
+ })) throw error;
1693
1797
  }
1694
1798
  }
1695
1799
  /**
@@ -1715,11 +1819,15 @@ var RelayTransport = class {
1715
1819
  let first;
1716
1820
  const edgeSignal = isGroupSignal(asker(options, true));
1717
1821
  const failed = /* @__PURE__ */ new Set();
1718
- const puts = this.relays.map(async (relay) => {
1822
+ const nowhere = this.relays.map(() => false);
1823
+ const puts = this.relays.map(async (relay, i) => {
1719
1824
  const slot = `${relay} ${pubKeyZ32}`;
1720
1825
  const previous = this.lastPut.get(slot);
1721
1826
  this.lastPut.set(slot, timestamp);
1722
- 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
+ }
1723
1831
  let response;
1724
1832
  try {
1725
1833
  response = await this.put(relay, pubKeyZ32, payload, previous, asker(options, true), relay === probe, (ok) => {
@@ -1728,8 +1836,10 @@ var RelayTransport = class {
1728
1836
  if (response.status === 412) response = await this.put(relay, pubKeyZ32, payload, void 0, asker(options, true));
1729
1837
  } catch (error) {
1730
1838
  if (!isDiscoveryBudgetError(error) && !(error instanceof RelayLeftAloneError)) failed.add(relay);
1839
+ nowhere[i] = isDiscoveryBudgetError(error) || error instanceof RelayLeftAloneError || error instanceof RelayNoAnswerError && !error.sent;
1731
1840
  throw error;
1732
1841
  }
1842
+ nowhere[i] = response.status >= 400 && response.status < 500;
1733
1843
  if (response.status >= 500 || response.status === 428) failed.add(relay);
1734
1844
  if (response.status === 409) conflict?.(relay);
1735
1845
  if (response.status === 429) throw new DiscoveryBudgetError(this.coolDown(relay, response), `${relay} responded 429; retry shortly`);
@@ -1762,7 +1872,7 @@ var RelayTransport = class {
1762
1872
  const reasons = results.map((r) => r.status === "rejected" ? String(r.reason) : "").join("; ");
1763
1873
  if (waits.length === results.length) reject(new DiscoveryBudgetError(Math.min(...waits.map((e) => e.retryInMs)), `Publish held back on every relay: ${reasons}`));
1764
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}`));
1765
- 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)));
1766
1876
  });
1767
1877
  });
1768
1878
  }
@@ -1910,7 +2020,7 @@ var RelayTransport = class {
1910
2020
  }
1911
2021
  for (const loser of asked.values()) {
1912
2022
  loser.controller.abort();
1913
- 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);
1914
2024
  else this.breaker.cancel(loser.relay);
1915
2025
  }
1916
2026
  this.lastRelay = relay;
@@ -1932,7 +2042,8 @@ var RelayTransport = class {
1932
2042
  throw new Error("No Pkarr relay reachable");
1933
2043
  }
1934
2044
  /**
1935
- * 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
1936
2047
  * with a small share of its own (`RELAY_REQUESTS_PER_MINUTE` under `REQUESTS_PER_MINUTE`: pkarr.miguelmedeiros.dev's 5)
1937
2048
  * takes no turns: it comes after the others, for when they refuse, fail or are slow, unless every relay is one. In the
1938
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
@@ -1945,8 +2056,19 @@ var RelayTransport = class {
1945
2056
  const after = lastAt < 0 ? -1 : ring.findIndex((relay) => this.relays.indexOf(relay) > lastAt);
1946
2057
  const start = lastAt < 0 ? this.cursor++ : after < 0 ? 0 : after;
1947
2058
  const turn = [...ring.map((_, i) => ring[(start + i) % ring.length]), ...this.relays.filter((relay) => !ring.includes(relay))];
1948
- const now = Date.now(), slow = (relay) => (this.slowUntil.get(relay) ?? 0) > now;
1949
- 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;
1950
2072
  }
1951
2073
  /** One GET of a key at one relay, which `controller` drops. Never rejects: what happened is the outcome. */
1952
2074
  readFromRelay(relay, pubKeyZ32) {
@@ -2096,7 +2218,7 @@ var RelayTransport = class {
2096
2218
  }
2097
2219
  /** `sent`: told, once the budget took the request, whether the relay takes the packet (a 2xx). */
2098
2220
  async put(relay, pubKeyZ32, payload, replaces, who, probe = false, sent) {
2099
- 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);
2100
2222
  const limited = this.rateLimitedFor(relay);
2101
2223
  if (limited > 0) throw new DiscoveryBudgetError(limited, "Discovery relay is cooling down after a 429; retry shortly");
2102
2224
  const blocked = probe ? 0 : this.breaker.blockedFor(relay);
@@ -2116,13 +2238,13 @@ var RelayTransport = class {
2116
2238
  let response;
2117
2239
  try {
2118
2240
  response = await request;
2119
- } catch {
2241
+ } catch (error) {
2120
2242
  this.networkCooldown.set(`PUT ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
2121
2243
  this.answered(relay, {
2122
2244
  kind: "error",
2123
2245
  reason: "no answer"
2124
2246
  });
2125
- throw new Error(`${relay} did not answer`);
2247
+ throw new RelayNoAnswerError(`${relay} did not answer`, !connectFailed(error));
2126
2248
  }
2127
2249
  if (response.status === 429) this.answered(relay, {
2128
2250
  kind: "throttled",
@@ -2149,6 +2271,7 @@ var RelayTransport = class {
2149
2271
  }
2150
2272
  if (isGroupRead(who) || isChatWatch(who)) this.readAsked(key, who, now);
2151
2273
  if (isTurnRead(who)) this.turnAsked(key, who, now);
2274
+ if (isAwaitedRead(who)) this.awaitedAt = now;
2152
2275
  if (this.heldFor(relay, who, now, key) > 0) {
2153
2276
  if (isGroupRead(who) && (this.spent.get(relay)?.length ?? 0) >= this.limitOf(relay)) this.groupsFullAt.set(relay, now);
2154
2277
  if (isChat(who)) this.chatNeed(key, now, relay);
@@ -2190,7 +2313,8 @@ var RelayTransport = class {
2190
2313
  if (isGroupSignal(who) && !who.write && this.spent.get(relay).length >= this.limitOf(relay)) this.spentGroupOver.get(relay).push(now);
2191
2314
  if (isGroupSignal(who)) this.spentGroupSignal.get(relay).push(now);
2192
2315
  const departedOver = isDepartedRead(who) && this.spent.get(relay).length >= this.limitOf(relay);
2193
- 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);
2194
2318
  this.spent.get(relay).push(now);
2195
2319
  if (who.background) this.spentBackground.get(relay).push(now);
2196
2320
  if (who.background && who.write) this.spentBackgroundWrites.get(relay).push(now);
@@ -2221,7 +2345,7 @@ var RelayTransport = class {
2221
2345
  * Who goes first: a chat's refused write holds back everything but chat writes; a group's refused write holds back
2222
2346
  * group reads and background requests, never a chat's. Background requests yield to a link that signals. A chat's
2223
2347
  * signaling goes over the limit by its allowance (`SIGNALING_ALLOWANCE_SHARE`), and so do a few of its reads of a
2224
- * 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
2225
2349
  * without its own allowance (`ANSWER_READ_ALLOWANCE`).
2226
2350
  */
2227
2351
  heldFor(relay, who, now = Date.now(), key, turns = true, ownAllowance = true) {
@@ -2233,9 +2357,11 @@ var RelayTransport = class {
2233
2357
  this.spentBackgroundWrites.set(relay, recentBackgroundWrites);
2234
2358
  const over = (list, limit) => list.length >= limit ? list[list.length - limit] + 6e4 - now : 0;
2235
2359
  const limit = this.limitOf(relay);
2236
- const departed = isDepartedRead(who) && key !== void 0 && recent.length >= limit && this.departedReads(key, now) < 6;
2237
- const share = isChatSignal(who) || departed ? SIGNALING_ALLOWANCE_SHARE : isGroupSignal(who) ? GROUP_SIGNALING_ALLOWANCE_SHARE : 0;
2238
- const allowance = share ? Math.max(0, Math.floor(limit * share) - (who.write ? 0 : 1)) : 0;
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);
2239
2365
  const groupSignaled = within(this.spentGroupSignal.get(relay) ?? [], now, 6e4);
2240
2366
  this.spentGroupSignal.set(relay, groupSignaled);
2241
2367
  const groupFloor = isGroupSignal(who) && groupSignaled.length < allowance;
@@ -2292,7 +2418,8 @@ var RelayTransport = class {
2292
2418
  const at = this.writeWaiting.get(`${lane} ${relay}`);
2293
2419
  return at !== void 0 && now - at < 5e3 ? at + WRITE_FIRST_MS - now : 0;
2294
2420
  };
2295
- 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"));
2296
2423
  if ((writer === null && who.group && !pastLimit && !isGroupAnswerRead(who) || who.background) && !starved) wait = Math.max(wait, waiting("group"));
2297
2424
  if (isGroupSignal(who) && !isGroupAnswerRead(who)) {
2298
2425
  const ahead = this.answerReadAhead(relay, now);
@@ -2415,17 +2542,17 @@ var RelayTransport = class {
2415
2542
  const since = this.heldBack.get(key)?.since;
2416
2543
  return !who.group && !who.write && !who.door && since !== void 0 && now - since >= READ_STARVED_MS;
2417
2544
  }
2418
- /** This contact's departed reads past the limit in the last minute (`DEPARTED_READS`). */
2419
- departedReads(key, now) {
2420
- const reads = within(this.departedOver.get(key) ?? [], now, 6e4);
2421
- if (reads.length) this.departedOver.set(key, reads);
2422
- 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);
2423
2550
  return reads.length;
2424
2551
  }
2425
- /** One more, the contacts with none in the last minute dropped. */
2426
- departedOverAdd(key, now) {
2427
- for (const [other, reads] of this.departedOver) if (now - reads[reads.length - 1] >= 6e4) this.departedOver.delete(other);
2428
- 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]);
2429
2556
  }
2430
2557
  /** A chat's request of `key` asked urgently (it needs every relay), or the budget refused it on `relay` (it needs that one). */
2431
2558
  chatNeed(key, now, relay) {
@@ -2639,6 +2766,9 @@ var RelayTransport = class {
2639
2766
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
2640
2767
  const drop = () => controller.abort();
2641
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));
2642
2772
  try {
2643
2773
  const sent = Date.now();
2644
2774
  const response = await this.fetchFn(url, {
@@ -2646,10 +2776,12 @@ var RelayTransport = class {
2646
2776
  cache: "no-store",
2647
2777
  signal: controller.signal
2648
2778
  });
2779
+ this.answeredAt.set(relay, Date.now());
2649
2780
  this.serverTime(url, response, sent);
2650
2781
  await read?.(response, controller.signal);
2651
2782
  return response;
2652
2783
  } finally {
2784
+ waiting.delete(request);
2653
2785
  clearTimeout(timer);
2654
2786
  cancel?.removeEventListener("abort", drop);
2655
2787
  }
@@ -6164,11 +6296,16 @@ var NO_ATTEMPTS = {
6164
6296
  recent: [],
6165
6297
  total: 0
6166
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;
6167
6304
  /** Whether a device may try now: `refused` after 15 failures with no success, until the person lets it try again. */
6168
6305
  function handoffAttemptAllowed(attempts, now) {
6169
6306
  if (!attempts) return "ok";
6170
6307
  if (attempts.total >= HANDOFF_ATTEMPTS.total) return "refused";
6171
- if (attempts.until !== void 0 && now < attempts.until) return "locked-out";
6308
+ if (lockedUntil(attempts, now) !== void 0) return "locked-out";
6172
6309
  return "ok";
6173
6310
  }
6174
6311
  /**
@@ -6176,17 +6313,18 @@ function handoffAttemptAllowed(attempts, now) {
6176
6313
  * outcome, and takes it back on success: a taker that stops after the second message has used a try.
6177
6314
  */
6178
6315
  function handoffAttemptFailed(attempts, now) {
6179
- 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];
6180
6317
  const total = (attempts?.total ?? 0) + 1;
6181
6318
  if (recent.length >= HANDOFF_ATTEMPTS.perHour) return {
6182
6319
  recent: [],
6183
6320
  total,
6184
6321
  until: now + HANDOFF_ATTEMPTS.hourMs
6185
6322
  };
6323
+ const until = lockedUntil(attempts, now);
6186
6324
  return {
6187
6325
  recent,
6188
6326
  total,
6189
- ...attempts?.until !== void 0 && now < attempts.until ? { until: attempts.until } : {}
6327
+ ...until !== void 0 ? { until } : {}
6190
6328
  };
6191
6329
  }
6192
6330
  /** A proof that held: the count starts again. */
@@ -6195,7 +6333,10 @@ var handoffAttemptSucceeded = () => ({
6195
6333
  total: 0
6196
6334
  });
6197
6335
  /** Seconds until a locked-out device may try again (for `handoff-busy`). */
6198
- 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
+ };
6199
6340
  var HTTP_SERVICE_PROTO = "ghostly-http/1";
6200
6341
  var MAX_NAME_LENGTH$1 = 48;
6201
6342
  var MAX_META_ENTRIES = 8;
@@ -7218,6 +7359,12 @@ var LIMITS = {
7218
7359
  maxConcurrentRequestsPerPeer: 32,
7219
7360
  /** Requests a client keeps in flight; the rest wait in a queue. */
7220
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,
7221
7368
  maxChatMessageBytes: 16384,
7222
7369
  maxFileBytes: 104857600,
7223
7370
  /** Files a peer may be sending us at once. */
@@ -7948,6 +8095,7 @@ var HttpClient = class {
7948
8095
  nextId = 1;
7949
8096
  streams = /* @__PURE__ */ new Map();
7950
8097
  waiting = [];
8098
+ waitingBytes = 0;
7951
8099
  inFlight = 0;
7952
8100
  closed = false;
7953
8101
  constructor(channel) {
@@ -7956,7 +8104,28 @@ var HttpClient = class {
7956
8104
  async request(serviceId, request) {
7957
8105
  if (this.closed) throw new GhostlyHttpError("closed", "Data link is closed");
7958
8106
  if (this.inFlight >= LIMITS.maxClientInFlight) {
7959
- 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
+ }
7960
8129
  if (this.closed) throw new GhostlyHttpError("closed", "Data link is closed");
7961
8130
  }
7962
8131
  this.inFlight++;
@@ -8254,6 +8423,8 @@ var LinkSession = class {
8254
8423
  signalReadsLeft = 0;
8255
8424
  /** Fast reads still signaling while the contact's offer is due (`SIGNAL_DUE_READS`). */
8256
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;
8257
8428
  /** When the last `expectPeer` window ends (or ended): the pace slows down from there step by step. */
8258
8429
  expectUntil = 0;
8259
8430
  /**
@@ -8396,6 +8567,7 @@ var LinkSession = class {
8396
8567
  countUnusedInvite(this.transport, this, false);
8397
8568
  this.rtcSignal = null;
8398
8569
  this.callSignal = null;
8570
+ this.presenceDueOut = false;
8399
8571
  this.events.onStatus?.("offline");
8400
8572
  if (announce) try {
8401
8573
  await this.publishOnce(false);
@@ -8456,6 +8628,14 @@ var LinkSession = class {
8456
8628
  * the windows that look fast for the contact (`expectPeer`, `watchPeer`) end, and the link reads at its pace from the
8457
8629
  * next read on. An offer of this side's out keeps its window.
8458
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
+ }
8459
8639
  calm() {
8460
8640
  if (this.rtcSignal !== null) return;
8461
8641
  this.fastPollUntil = this.fastStepsAfter = this.expectUntil = this.watchUntil = this.lingerUntil = this.dueSignalReadsLeft = 0;
@@ -8675,7 +8855,7 @@ var LinkSession = class {
8675
8855
  try {
8676
8856
  const awaited = this.connected || this.presence.online || this.sentBuffer.length > 0 || this.callSignal !== null || this.awaitingPeer();
8677
8857
  const takesBack = !rtcSignal && this.rtcSignalOut !== null;
8678
- 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;
8679
8859
  this.wroteInBackground = options?.background === true;
8680
8860
  const held = this.transport.publishHeld?.(this.identity.pubKeyZ32, options);
8681
8861
  if (held) throw held;
@@ -8714,6 +8894,7 @@ var LinkSession = class {
8714
8894
  }
8715
8895
  const ms = Date.now() - started;
8716
8896
  this.lastPublishedAt = Date.now();
8897
+ if (advertise) this.presenceDueOut = false;
8717
8898
  const signalOut = !!rtcSignal && rtcSignal !== this.rtcSignalOut;
8718
8899
  this.signalReadsLeft = signalOut ? 3 : rtcSignal ? this.signalReadsLeft : 0;
8719
8900
  if (signalOut && this.fastPollUntil > 0) {
@@ -8773,6 +8954,7 @@ var LinkSession = class {
8773
8954
  }
8774
8955
  const watch = !signal && this.watching();
8775
8956
  const departed = !signal && Date.now() < this.departedUntil;
8957
+ const awaited = !signal && this.ownInvite() && this.awaitingPeer();
8776
8958
  const background = pace === "background" || pace === "connected" || pace === "idle" && !this.active;
8777
8959
  const resume = !signal && !watch && (this.resumeReads || Date.now() < this.awaitedUntil);
8778
8960
  let unread;
@@ -8782,6 +8964,7 @@ var LinkSession = class {
8782
8964
  ...signal && { signal },
8783
8965
  ...watch && { watch },
8784
8966
  ...departed && { departed },
8967
+ ...awaited && { awaited },
8785
8968
  ...resume && { resume }
8786
8969
  }, false).catch((error) => {
8787
8970
  if (!(error instanceof RelaysFailedError)) throw error;
@@ -12048,6 +12231,7 @@ function readDhtFile(raw, message) {
12048
12231
  }
12049
12232
  var DHT_MESSAGE_TTL = 3e5;
12050
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.";
12051
12235
  var CONTROL_TTL = 6e5;
12052
12236
  /**
12053
12237
  * How far apart two devices' clocks may be for an envelope's expiry: a reader takes one until this long after `expires`
@@ -12086,6 +12270,7 @@ var STREAM_POLL_MS = 3e4;
12086
12270
  * each has seen the other leave).
12087
12271
  */
12088
12272
  var LEAVING_DHT_FAST_MS = 12e4;
12273
+ var LEAVING_PROBE_MAX_GAP_MS = 96e4;
12089
12274
  /** Only this often while layer 1 carries the chat (WISP 403, Q7): the relays' per-IP budget is shared by every chat. */
12090
12275
  var LIVE_POLL_MS = 3e5;
12091
12276
  /**
@@ -12152,6 +12337,11 @@ var DhtDelivery = class DhtDelivery {
12152
12337
  urgent = false;
12153
12338
  /** Reads left that are signaling: the contact is leaving DHT only, and the live link waits on them (`expect`). */
12154
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;
12155
12345
  timer = null;
12156
12346
  /** The first control envelope of a start that waits (`firstControlAfterMs`). */
12157
12347
  controlTimer = null;
@@ -12171,12 +12361,19 @@ var DhtDelivery = class DhtDelivery {
12171
12361
  /** Until when the relays' request budget holds publications back: what is due then goes at once. */
12172
12362
  budgetUntil = 0;
12173
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
+ /**
12174
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
12175
12370
  * poll. A chat in the background reads every 30 s, and one held back while its link was redialling read the contact
12176
12371
  * 60 s after its live link dropped, the chat "On DHT · retrying live" all along while the contact had chosen DHT only.
12177
12372
  */
12178
12373
  readHeldUntil = 0;
12179
12374
  errors = {};
12375
+ /** Texts whose last `send` went nowhere (`wentNowhereFor`), newest last. */
12376
+ wentNowhere = /* @__PURE__ */ new Set();
12180
12377
  /** When the device's network last came back (`networkBack`): a read or publication started before failed for want of it. */
12181
12378
  networkBackAt = -Infinity;
12182
12379
  foreignKeySeenAt;
@@ -12331,9 +12528,17 @@ var DhtDelivery = class DhtDelivery {
12331
12528
  }
12332
12529
  this.state = next;
12333
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;
12334
12533
  sealedKey(peer) {
12335
- const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.participation.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peer)));
12336
- 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;
12337
12542
  }
12338
12543
  signed(body, recipient = "invite") {
12339
12544
  return utf8Encode(JSON.stringify([
@@ -12348,6 +12553,32 @@ var DhtDelivery = class DhtDelivery {
12348
12553
  return this.envelope(body, recipient).records;
12349
12554
  }
12350
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
+ /**
12351
12582
  * The envelope's records. Ratcheted (`ratcheted`), its `_dr` record is the right length but not sealed yet: `seal`
12352
12583
  * gives its bytes, under the chat's lock, once the publication is sure to go. Measuring a packet takes no key.
12353
12584
  */
@@ -12362,13 +12593,9 @@ var DhtDelivery = class DhtDelivery {
12362
12593
  const ratchet = this.ratcheted(recipient);
12363
12594
  const sealedBytes = (bytes) => ratchet ? 4 * Math.ceil((66 + bytes) / 3) : sealedLength(bytes);
12364
12595
  const label = ratchet ? "_dr" : "_dm";
12365
- const fits = (bytes) => bytes <= MAX_ENVELOPE_PLAINTEXT && measureRecords(this.identity.pubKeyZ32, [{
12366
- label,
12367
- value: "A".repeat(sealedBytes(bytes)),
12368
- ttl: ENVELOPE_TTL
12369
- }, ...hint]) <= ENVELOPE_PACKET_BYTES;
12596
+ const fits = (bytes) => this.fits(bytes, recipient);
12370
12597
  const bytes = utf8Encode(plaintext).length;
12371
- 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);
12372
12599
  let padded = bytes;
12373
12600
  for (let step = 512; step >= 1; step >>= 1) if (fits(padded + step)) padded += step;
12374
12601
  const full = plaintext + " ".repeat(padded - bytes);
@@ -12436,7 +12663,12 @@ var DhtDelivery = class DhtDelivery {
12436
12663
  this.lastPublish = 0;
12437
12664
  this.leavingUntil = mode === "stream" ? Date.now() + LEAVING_DHT_FAST_MS : 0;
12438
12665
  if (mode === "dht") this.signalReads = 0;
12439
- 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;
12440
12672
  this.changed();
12441
12673
  });
12442
12674
  this.tick();
@@ -12473,6 +12705,20 @@ var DhtDelivery = class DhtDelivery {
12473
12705
  this.tick();
12474
12706
  }
12475
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
+ /**
12476
12722
  * Layer 1 carries the chat, or no longer does. While it does, the mailbox is read every 5 minutes, after one
12477
12723
  * last look as it goes live: a text the contact put on the DHT in the seconds before (after this side's last
12478
12724
  * read) would otherwise wait for the next look. That look is a background request, which yields to links that
@@ -12541,23 +12787,18 @@ var DhtDelivery = class DhtDelivery {
12541
12787
  const error = this.packetError(next.message, next.expires, next.reply, next.edit);
12542
12788
  return error && next.reply ? this.packetError(next.message, next.expires) : error;
12543
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
+ */
12544
12794
  packetError(message, expires, reply, edit) {
12545
- try {
12546
- 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);
12547
- return null;
12548
- } catch (error) {
12549
- return error instanceof Error ? error.message : String(error);
12550
- }
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;
12551
12797
  }
12552
12798
  /** Whether a text with its hop count fits the packet and what a reader reads (`MAX_ENVELOPE_PLAINTEXT`). */
12553
12799
  roomForHops(message, expires, reply, forwarded) {
12554
12800
  const body = this.body(this.sequence + 1, Date.now(), expires, message, this.state.receipt?.id ?? "abcdefghijklmnopqrstuv", reply, [], void 0, forwarded);
12555
- try {
12556
- this.records(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12557
- } catch {
12558
- return false;
12559
- }
12560
- return utf8Encode(JSON.stringify([body, "x".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT;
12801
+ return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12561
12802
  }
12562
12803
  /**
12563
12804
  * `forwarded`: a forwarded text's hop count (WISP 403 § Forwards). Like a reply's id it goes only when the packet has
@@ -12565,11 +12806,13 @@ var DhtDelivery = class DhtDelivery {
12565
12806
  */
12566
12807
  async send(text, timestamp, id, reply, edit, forwarded) {
12567
12808
  return this.serialize(async () => {
12809
+ this.wentNowhere.delete(id);
12568
12810
  const error = this.validate(text, timestamp, id, reply, edit);
12569
12811
  if (error) return error;
12570
12812
  const now = Date.now(), pending = this.state.pending;
12571
12813
  const hops = edit ? void 0 : readForwarded(forwarded);
12572
- 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 : {
12573
12816
  message: [
12574
12817
  id,
12575
12818
  timestamp,
@@ -12605,12 +12848,27 @@ var DhtDelivery = class DhtDelivery {
12605
12848
  return null;
12606
12849
  }
12607
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
+ }
12608
12859
  this.changed();
12609
12860
  return this.errors.publish;
12610
12861
  }
12611
12862
  });
12612
12863
  }
12613
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
+ /**
12614
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
12615
12873
  * what a reader reads (`MAX_ENVELOPE_PLAINTEXT`). Its meta goes first (a voice note's waveform thinned if it must),
12616
12874
  * then the reply's id, then the hop count; the name, size, type and id always. A string: why it cannot go.
@@ -12631,12 +12889,7 @@ var DhtDelivery = class DhtDelivery {
12631
12889
  const hops = readForwarded(forwarded);
12632
12890
  const fits = (element, withReply, withHops) => {
12633
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);
12634
- try {
12635
- this.records(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12636
- } catch {
12637
- return false;
12638
- }
12639
- return utf8Encode(JSON.stringify([body, "x".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT;
12892
+ return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);
12640
12893
  };
12641
12894
  const elements = dhtFileElements(file), bare = elements[elements.length - 1];
12642
12895
  const found = [
@@ -12821,7 +13074,7 @@ var DhtDelivery = class DhtDelivery {
12821
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));
12822
13075
  const identity = !reseal && this.state.peerPinned && this.state.peerPinned !== "can" && this.pinned()?.identity || this.identity;
12823
13076
  const away = !!this.options.credentials.peerKey && now - this.peerNewAt >= 6e5;
12824
- 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;
12825
13078
  const held = this.options.transport.publishHeld?.(identity.pubKeyZ32, options);
12826
13079
  if (held) {
12827
13080
  await this.heldBack(held, now, {
@@ -12873,6 +13126,7 @@ var DhtDelivery = class DhtDelivery {
12873
13126
  throw error;
12874
13127
  }
12875
13128
  this.namedRev = body[8] ?? void 0;
13129
+ if (options?.signal) this.leavingOut = false;
12876
13130
  if (identity === this.identity) this.unsealedOut = !this.options.credentials.peerKey;
12877
13131
  delete this.errors.publish;
12878
13132
  this.changed();
@@ -13222,8 +13476,9 @@ var DhtDelivery = class DhtDelivery {
13222
13476
  await this.serialize(async () => {
13223
13477
  if (!this.running) return;
13224
13478
  const background = !this.urgent && this.pollMs >= STREAM_POLL_MS;
13225
- const signal = this.signalReads > 0;
13479
+ const signal = this.signalReads > 0 && !this.leavingRead;
13226
13480
  this.urgent = false;
13481
+ this.leavingRead = false;
13227
13482
  if (signal) this.signalReads--;
13228
13483
  if (!this.options.credentials.peerKey && !this.options.credentials.expectedPeerKey && !this.state.sequence) await this.publishOnTick();
13229
13484
  const readAt = Date.now();
@@ -13237,7 +13492,10 @@ var DhtDelivery = class DhtDelivery {
13237
13492
  else if (readAt >= this.networkBackAt) this.errors.read = `Could not read DHT delivery: ${error instanceof Error ? error.message : String(error)}`;
13238
13493
  }
13239
13494
  if (signal && this.readHeldUntil > 0) this.signalReads++;
13240
- 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
+ }
13241
13499
  await this.publishOnTick();
13242
13500
  this.changed();
13243
13501
  });
@@ -14457,6 +14715,8 @@ var TransportSwitch = class {
14457
14715
  /** This side chose while no session was open: the next one begins with it as a choice. */
14458
14716
  apart = false;
14459
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 = "";
14460
14720
  policyHeld = null;
14461
14721
  constructor(options) {
14462
14722
  this.options = options;
@@ -14771,7 +15031,8 @@ var TransportSwitch = class {
14771
15031
  if (frame.t === "paired-policy") {
14772
15032
  const policy = parsePolicy(frame.policy);
14773
15033
  if (!policy || this.remote && (policy.revision < this.remote.revision || policy.revision === this.remote.revision && JSON.stringify(policy) !== JSON.stringify(this.remote))) return true;
14774
- 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()) {
14775
15036
  if (this.policyHeld) this.policyHeld.frame = frame;
14776
15037
  else this.policyHeld = {
14777
15038
  frame,
@@ -15262,15 +15523,43 @@ var lastOf = (timeline, side, proofs) => {
15262
15523
  for (let i = timeline.length - 1; i >= 0; i--) if (timeline[i].side === side && proofs.includes(timeline[i].proof)) return i;
15263
15524
  return -1;
15264
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
+ };
15265
15534
  /**
15266
15535
  * The timeline after one step. A share already on it is updated in place, never repeated: a request sent again at
15267
15536
  * a reconnect, a second share of a proof the contact already verified. A new attempt after a failure or a stop is
15268
- * 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.
15269
15541
  */
15270
15542
  function applyIdentityEvent(timeline, event, at) {
15271
15543
  const out = [...timeline];
15272
15544
  const i = lastOf(out, event.side, event.type === "result" ? [event.proof, event.requested] : [event.proof]);
15273
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
+ };
15274
15563
  const add = (entry) => {
15275
15564
  const prefix = `${entry.side}:${entry.proof}:`;
15276
15565
  let n = 0;
@@ -15291,6 +15580,12 @@ function applyIdentityEvent(timeline, event, at) {
15291
15580
  };
15292
15581
  break;
15293
15582
  }
15583
+ if (takeOver({
15584
+ proof: event.proof,
15585
+ provider: event.provider,
15586
+ subject: event.subject,
15587
+ state: "verifying"
15588
+ })) break;
15294
15589
  add({
15295
15590
  proof: event.proof,
15296
15591
  side: event.side,
@@ -15316,6 +15611,12 @@ function applyIdentityEvent(timeline, event, at) {
15316
15611
  };
15317
15612
  break;
15318
15613
  }
15614
+ if (!event.ok && event.provider && takeOver({
15615
+ proof: event.proof,
15616
+ provider: event.provider,
15617
+ subject: event.subject,
15618
+ ...settled
15619
+ })) break;
15319
15620
  if (event.provider) add({
15320
15621
  proof: event.proof,
15321
15622
  side: event.side,
@@ -15554,6 +15855,7 @@ var IdentityCheckUnavailable = class extends Error {
15554
15855
  /** What the contact is told when the check failed with an IdentityCheckUnavailable. */
15555
15856
  var IDENTITY_CHECK_UNAVAILABLE = "Your contact's app could not check it. Try again later.";
15556
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";
15557
15859
  var peerError = (e) => e instanceof IdentityCheckUnavailable ? IDENTITY_CHECK_UNAVAILABLE : shortError(e);
15558
15860
  var UNSUPPORTED_KIND = "Your contact's app cannot verify this kind of identity yet";
15559
15861
  var NOT_IN_PROFILE = "That identity is no longer in your profile";
@@ -15565,7 +15867,8 @@ var CONTACT_REFUSALS = /* @__PURE__ */ new Set([
15565
15867
  IDENTITY_CHECK_UNAVAILABLE,
15566
15868
  TOO_MANY_RECEIVED,
15567
15869
  REVOKED,
15568
- EXPIRED
15870
+ EXPIRED,
15871
+ NEWER_HELD
15569
15872
  ]);
15570
15873
  /**
15571
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
@@ -15590,6 +15893,8 @@ var IdentityExchange = class {
15590
15893
  requested = /* @__PURE__ */ new Set();
15591
15894
  /** The nonces of the presentations in their provider's check now. */
15592
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 = [];
15593
15898
  constructor(options) {
15594
15899
  this.options = options;
15595
15900
  }
@@ -15990,6 +16295,10 @@ var IdentityExchange = class {
15990
16295
  let reason;
15991
16296
  /** Its owner withdrew the proof while this check ran: no result goes out (see below). */
15992
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;
15993
16302
  try {
15994
16303
  const mayReplace = (r) => r.binding.provider === binding.provider && (r.binding.subject === binding.subject || r.verified.subject === binding.subject);
15995
16304
  if (revokedHere(this.options.storage.read().received, id)) throw new Error(REVOKED);
@@ -15997,13 +16306,21 @@ var IdentityExchange = class {
15997
16306
  if (JSON.stringify(evidence ?? null).length > 16384) throw new Error("Evidence too large");
15998
16307
  if (!verifyIdentityPresentation(binding.key, sig, id, scope, nonce, issuedAt)) throw new Error("The proof key did not sign this conversation's challenge");
15999
16308
  if (binding.issuedAt > now + 300) throw new Error("The proof is dated in the future");
16000
- 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));
16001
16317
  if (Math.min(binding.expiresAt, result.expiresAt ?? Infinity) <= now) throw new Error(EXPIRED);
16002
- 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);
16003
16319
  verified = result;
16004
16320
  } catch (e) {
16005
16321
  error = peerError(e);
16006
16322
  reason = shortError(e);
16323
+ unavailable = e instanceof IdentityCheckUnavailable;
16007
16324
  }
16008
16325
  await this.options.storage.update((l) => {
16009
16326
  const challenge = challengeOf(l);
@@ -16019,11 +16336,27 @@ var IdentityExchange = class {
16019
16336
  verified = void 0;
16020
16337
  error = reason = REVOKED;
16021
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
+ }
16022
16349
  const received = verified && receivedWithRoom(l.received, id, (r) => r.binding.provider === binding.provider && r.verified.subject === subject, now);
16023
16350
  if (verified && !received) {
16024
16351
  verified = void 0;
16025
16352
  error = reason = TOO_MANY_RECEIVED;
16026
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
+ }
16027
16360
  const logged = this.log(l, {
16028
16361
  type: "result",
16029
16362
  side: "theirs",
@@ -16034,10 +16367,20 @@ var IdentityExchange = class {
16034
16367
  ok: !!verified,
16035
16368
  ...reason ? { error: reason } : {}
16036
16369
  });
16037
- if (!verified || !received) return {
16370
+ if (stands) return {
16038
16371
  ...logged,
16039
16372
  challenges
16040
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
+ };
16041
16384
  const record = {
16042
16385
  id,
16043
16386
  binding,
@@ -16046,8 +16389,8 @@ var IdentityExchange = class {
16046
16389
  presenter: scope.subject,
16047
16390
  audience: scope.audience,
16048
16391
  context: scope.context,
16049
- verifiedAt: now,
16050
- checkedAt: now,
16392
+ verifiedAt: prior?.verifiedAt ?? now,
16393
+ checkedAt: prior?.checkedAt ?? now,
16051
16394
  status: withdrawn ? "withdrawn" : "verified"
16052
16395
  };
16053
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, {
@@ -16409,9 +16752,12 @@ var CapsExchange = class {
16409
16752
  running = false;
16410
16753
  lastRead = 0;
16411
16754
  readTimer = null;
16755
+ readBackground = false;
16412
16756
  /** The newest revision of the contact's record an envelope named, and the reads made again since for it. */
16413
16757
  named = -1;
16414
16758
  retries = 0;
16759
+ /** A revision named since the last new record read started the read-again chain: the next ones named are only background reads. */
16760
+ chased = false;
16415
16761
  retryTimer = null;
16416
16762
  /** What the last publication of this run carried. */
16417
16763
  lastOut;
@@ -16525,22 +16871,38 @@ var CapsExchange = class {
16525
16871
  const age = Date.now() - (this.state.publishedAt ?? 0);
16526
16872
  this.timer = setTimeout(() => void this.update().catch(() => {}), inMs ?? Math.max(6e4, 36e5 - age));
16527
16873
  }
16528
- /** An envelope named this revision of the contact's record: read it when it is newer than the one known. */
16874
+ /**
16875
+ * An envelope named this revision of the contact's record: read it when it is newer than the one known. The number is
16876
+ * the contact's word, not a record: read at the spacing. The first one named since the last new record read is read as
16877
+ * the chat's own (not background) and starts the read-again chain over: a chat waits on it (a transport chosen, a
16878
+ * descriptor), and while a link signals the relays hand a held background read the old copy. Any other is background
16879
+ * upkeep until a new record is read. An envelope every 4 s naming a higher one each time made 45 reads a minute.
16880
+ */
16529
16881
  peerRev(rev) {
16530
16882
  if (!Number.isSafeInteger(rev) || rev <= (this.state.peer?.rev ?? -1)) return;
16531
- if (rev > this.named) {
16532
- this.named = rev;
16883
+ const chase = rev > this.named && !this.chased;
16884
+ if (rev > this.named) this.named = rev;
16885
+ if (chase) {
16886
+ this.chased = true;
16533
16887
  this.retries = 0;
16534
16888
  }
16535
- this.refresh(true);
16889
+ this.refresh(false, !chase);
16536
16890
  }
16537
- /** Reads the contact's record now (or right after the last read, when that was a moment ago). */
16538
- refresh(force = false) {
16539
- if (!this.running || this.readTimer) return;
16891
+ /**
16892
+ * Reads the contact's record now (or right after the last read, when that was a moment ago). `background`: upkeep,
16893
+ * on the background share of the relays' budget; a read asked for meanwhile that is not makes it one that is not.
16894
+ */
16895
+ refresh(force = false, background = false) {
16896
+ if (!this.running) return;
16897
+ if (this.readTimer) {
16898
+ this.readBackground &&= background;
16899
+ return;
16900
+ }
16901
+ this.readBackground = background;
16540
16902
  const wait = force ? 0 : Math.max(0, this.lastRead + CAPS_READ_SPACING_MS - Date.now());
16541
16903
  const run = () => {
16542
16904
  this.readTimer = null;
16543
- this.read().catch(() => {});
16905
+ this.read(this.readBackground ? { background: true } : void 0).catch(() => {});
16544
16906
  };
16545
16907
  if (!wait) {
16546
16908
  this.readTimer = setTimeout(run, 0);
@@ -16549,11 +16911,11 @@ var CapsExchange = class {
16549
16911
  this.readTimer = setTimeout(run, wait);
16550
16912
  }
16551
16913
  /** Reads and checks the contact's record; the last good one stays when this one is refused. */
16552
- read() {
16914
+ read(options) {
16553
16915
  return this.serialize(async () => {
16554
16916
  if (!this.running) return this.state.peer;
16555
16917
  this.lastRead = Date.now();
16556
- const packet = await this.options.transport.resolve(this.keys.peerAddress);
16918
+ const packet = await this.options.transport.resolve(this.keys.peerAddress, options);
16557
16919
  if (!packet || !this.running) return this.state.peer;
16558
16920
  let record;
16559
16921
  try {
@@ -16568,6 +16930,7 @@ var CapsExchange = class {
16568
16930
  if (this.state.peer && record.rev === this.state.peer.rev && record.author === this.state.peer.author) return this.state.peer;
16569
16931
  await this.persist({ peer: record });
16570
16932
  this.retries = 0;
16933
+ this.chased = false;
16571
16934
  this.options.changed?.(record);
16572
16935
  return record;
16573
16936
  }, "readChain").finally(() => this.readAgainIfBehind());
@@ -16576,7 +16939,8 @@ var CapsExchange = class {
16576
16939
  * Read again in a moment, a few times at most, while the record known is short of what the contact has: of the
16577
16940
  * revision an envelope named, or of a descriptor for a native transport it lists (its endpoint was still starting)
16578
16941
  * that this side runs too. Its next revision, with the descriptor, is named only once, by an envelope that may
16579
- * come before the record is out; without it neither side could dial the other.
16942
+ * come before the record is out; without it neither side could dial the other. Started over only by a new record read,
16943
+ * the first revision named after one, or this side's own endpoint coming up: the chat's reads, not background ones.
16580
16944
  */
16581
16945
  readAgainIfBehind() {
16582
16946
  if (this.retryTimer) clearTimeout(this.retryTimer);
@@ -22649,8 +23013,11 @@ var GhostLink = class {
22649
23013
  if (!this.dht || this.dht.peerMode !== "dht" || this.deliveryMode === "dht" || !presence.online) return;
22650
23014
  if (Date.now() - presenceSeenAt(presence) >= 3e4 || presence.lastPacketAt === this.leftDhtSeenFor) return;
22651
23015
  this.leftDhtSeenFor = presence.lastPacketAt;
22652
- traceLink(this.myPubKeyZ32, "peer-link-packet", { age: Date.now() - presenceSeenAt(presence) });
22653
- this.dht.expect(EXPECT_PEER_MS, true);
23016
+ const read = this.dht.peerLinkPacket(EXPECT_PEER_MS);
23017
+ traceLink(this.myPubKeyZ32, "peer-link-packet", {
23018
+ age: Date.now() - presenceSeenAt(presence),
23019
+ ...!read && { held: true }
23020
+ });
22654
23021
  }
22655
23022
  /**
22656
23023
  * The contact dials (a WebRTC offer signed by its pinned key, or a connection on a native endpoint) while its
@@ -22658,14 +23025,22 @@ var GhostLink = class {
22658
23025
  * room for the presence `peerMayHaveLeftDht` looks at, so the mailbox is read now and at the DHT pace for a while
22659
23026
  * here too. The offer is kept and answered, and the dial taken, once that read unblocks the stream. False when
22660
23027
  * something else blocks it (this side is DHT-only, the contact is not pinned, or the offer is not the contact's).
23028
+ * A connection on a native endpoint (no `signal`) proves nothing yet: anyone who can dial the endpoint can open one,
23029
+ * with any identities, and only the session it carries, which waits for this read, authenticates it. The reads it
23030
+ * starts are held as a fresh link packet's are (`peerLinkPacket`); the connection is kept for them all the same.
22661
23031
  */
22662
23032
  peerDialsFromDht(signal) {
22663
23033
  if (!this.dht || this.dht.peerMode !== "dht" || this.deliveryMode === "dht") return false;
22664
23034
  const credentials = this.options.pairing?.credentials;
22665
23035
  if (!credentials?.peerKey) return false;
22666
23036
  if (signal !== void 0 && !verifyPairedSignal(signal, this.options.params.peerPubKeyZ32, this.myPubKeyZ32, credentials.peerKey, true)) return false;
22667
- traceLink(this.myPubKeyZ32, "peer-dials", { signal: signal !== void 0 });
22668
- this.dht.expect(EXPECT_PEER_MS, true);
23037
+ let read = true;
23038
+ if (signal !== void 0) this.dht.expect(EXPECT_PEER_MS, true);
23039
+ else read = this.dht.peerLinkPacket(EXPECT_PEER_MS);
23040
+ traceLink(this.myPubKeyZ32, "peer-dials", {
23041
+ signal: signal !== void 0,
23042
+ ...!read && { held: true }
23043
+ });
22669
23044
  return true;
22670
23045
  }
22671
23046
  get isDataLinkOpen() {
@@ -22815,7 +23190,10 @@ var GhostLink = class {
22815
23190
  if (mode === "dht") {
22816
23191
  this.disconnect();
22817
23192
  this.heldSignal = null;
22818
- } else if (!this.quietForTaken) this.session.start();
23193
+ } else if (!this.quietForTaken) {
23194
+ if (this.myPubKeyZ32 > this.options.params.peerPubKeyZ32) this.session.presenceDue();
23195
+ this.session.start();
23196
+ }
22819
23197
  await this.dht.setMode(mode);
22820
23198
  if (mode === "dht") {
22821
23199
  await this.session.stop(false);
@@ -24243,6 +24621,10 @@ var GhostLink = class {
24243
24621
  get dhtPendingId() {
24244
24622
  return this.dht?.pendingId;
24245
24623
  }
24624
+ /** The last DHT send of this text went nowhere: no relay holds it, and it is off the floor (`DhtDelivery.wentNowhereFor`). */
24625
+ dhtWentNowhere(id) {
24626
+ return !!this.dht?.wentNowhereFor(id);
24627
+ }
24246
24628
  /** What went on the DHT floor under this id needs no more retries there (it went live, or was withdrawn). */
24247
24629
  async settleDht(id) {
24248
24630
  await this.dht?.acknowledge(id);
@@ -27467,13 +27849,14 @@ async function withoutPictureMetadata(source, mime) {
27467
27849
  /**
27468
27850
  * What a video leaves with. An MP4 or QuickTime file says more than its frames: its `udta` and `meta` boxes hold where
27469
27851
  * it was recorded (`©xyz`, `com.apple.quicktime.location.ISO6709`), the device, often its software; a timed metadata
27470
- * track (an iPhone's location and motion, a GoPro's GPS) holds them sample by sample; the movie's, each track's and
27852
+ * track (an iPhone's location and motion, a GoPro's GPS) holds them sample by sample, a caption track (a drone's, a
27853
+ * dashcam's) a line of them each second; the movie's, each track's and
27471
27854
  * each track's media header (`mvhd`, `tkhd`, `mdhd`) say when it was recorded, to the second, and a camera's timecode
27472
27855
  * track the time of day. The sender removes them before the file is stored and its digest computed, without decoding
27473
27856
  * or re-encoding a frame: each such box becomes a `free` box of the same size, zeroed, the headers' creation and
27474
27857
  * modification times are zeroed (0 is "unknown"), the space already left in it (`free`, `skip`, `wide`: what an edit in
27475
27858
  * place left behind, a recorder's GPS log) is zeroed after its header, so are the names of its handlers and of the
27476
- * compressor that made its frames, and each metadata and timecode track's samples are zeroed where they are, so no
27859
+ * compressor that made its frames, and each metadata, timecode and caption track's samples are zeroed where they are, so no
27477
27860
  * offset in the file moves and it plays as it did. Only the boxes' headers, `moov` and `moof` are read; the
27478
27861
  * media goes untouched.
27479
27862
  *
@@ -27586,14 +27969,10 @@ var CONTAINERS = /* @__PURE__ */ new Set([
27586
27969
  "mvex",
27587
27970
  "traf"
27588
27971
  ]);
27589
- /** Track handlers kept as they are: picture, sound, text and subtitles, timecode, hints. `meta` tracks have their samples zeroed, `tmcd` ones too. */
27972
+ /** Track handlers kept as they are: picture, sound, timecode, hints. `meta` tracks have their samples zeroed, `tmcd` ones and `CAPTIONS` too. */
27590
27973
  var HANDLERS = /* @__PURE__ */ new Set([
27591
27974
  "vide",
27592
27975
  "soun",
27593
- "text",
27594
- "sbtl",
27595
- "subt",
27596
- "clcp",
27597
27976
  "tmcd",
27598
27977
  "hint",
27599
27978
  "auxv",
@@ -27602,6 +27981,16 @@ var HANDLERS = /* @__PURE__ */ new Set([
27602
27981
  "odsm",
27603
27982
  "subp"
27604
27983
  ]);
27984
+ /**
27985
+ * Text, subtitle and caption tracks: what a recorder writes there is a log (a drone's or a dashcam's GPS, home point,
27986
+ * date and time each second), so their samples are zeroed, in `moov`'s tables and in fragments alike; they show nothing.
27987
+ */
27988
+ var CAPTIONS = /* @__PURE__ */ new Set([
27989
+ "text",
27990
+ "sbtl",
27991
+ "subt",
27992
+ "clcp"
27993
+ ]);
27605
27994
  /** The handlers whose sample descriptions are a visual one's, a compressor's name in each. */
27606
27995
  var VISUAL = /* @__PURE__ */ new Set([
27607
27996
  "vide",
@@ -27764,7 +28153,8 @@ function defaultSampleSizes(moov) {
27764
28153
  * The byte ranges of a fragment's samples in the file, one per track run (`trun`), from its `moof` read whole (`at` its
27765
28154
  * offset in the file): each run starts at its data offset from its track fragment's base (`tfhd`'s base data offset,
27766
28155
  * else the `moof`'s start for the first track fragment or one that says so, else where the previous one's data ended),
27767
- * or where the previous run ended; its length is its samples' sizes, its own or `tfhd`'s or `trex`'s default.
28156
+ * or where the previous run ended; its length is its samples' sizes, its own or `tfhd`'s or `trex`'s default. Each
28157
+ * with its track's ID.
27768
28158
  */
27769
28159
  function fragmentRanges(b, at, sizes) {
27770
28160
  const ranges = [];
@@ -27782,7 +28172,8 @@ function fragmentRanges(b, at, sizes) {
27782
28172
  }
27783
28173
  if (flags & 2) field += 4;
27784
28174
  if (flags & 8) field += 4;
27785
- let size = sizes.get(u32be(b, tfhd.body + 4));
28175
+ const track = u32be(b, tfhd.body + 4);
28176
+ let size = sizes.get(track);
27786
28177
  if (flags & 16) {
27787
28178
  check(field + 4 <= tfhd.end);
27788
28179
  size = u32be(b, field);
@@ -27815,7 +28206,11 @@ function fragmentRanges(b, at, sizes) {
27815
28206
  length = count * size;
27816
28207
  }
27817
28208
  check(Number.isSafeInteger(next) && Number.isSafeInteger(next + length));
27818
- if (length) ranges.push([next, next + length]);
28209
+ if (length) ranges.push([
28210
+ next,
28211
+ next + length,
28212
+ track
28213
+ ]);
27819
28214
  next += length;
27820
28215
  }
27821
28216
  previous = next;
@@ -27830,12 +28225,13 @@ function selfContained(b, minf) {
27830
28225
  }
27831
28226
  /**
27832
28227
  * `moov` with its metadata boxes emptied and its headers' times zeroed, read whole: whether it has a video track, the
27833
- * byte ranges of its metadata and timecode tracks' samples (zeroed by the caller where they are), whether it has a
27834
- * metadata or timecode track, and every track's sample table.
28228
+ * byte ranges of its metadata, timecode and caption tracks' samples (zeroed by the caller where they are), whether it
28229
+ * has a metadata or timecode track, every track's sample table, and the IDs of its caption tracks (their samples in
28230
+ * fragments zeroed too).
27835
28231
  */
27836
28232
  function stripMoov(b) {
27837
28233
  let video = false, fragmented = false, metadata = false;
27838
- const zeroed = [], tables = [];
28234
+ const zeroed = [], tables = [], captions = /* @__PURE__ */ new Set();
27839
28235
  for (const box of boxes(b, header(b, 0, b.length).body, b.length)) {
27840
28236
  if (METADATA.has(box.type)) {
27841
28237
  empty(b, box);
@@ -27849,14 +28245,18 @@ function stripMoov(b) {
27849
28245
  emptyWithin(b, box.body, box.end);
27850
28246
  }
27851
28247
  if (box.type !== "trak") continue;
27852
- let mdia;
28248
+ let mdia, tkhd;
27853
28249
  for (const part of boxes(b, box.body, box.end)) {
27854
28250
  if (METADATA.has(part.type)) {
27855
28251
  empty(b, part);
27856
28252
  continue;
27857
28253
  }
27858
28254
  check(TRAK_KEEPS.has(part.type));
27859
- if (part.type === "tkhd") zeroTimes(b, part);
28255
+ if (part.type === "tkhd") {
28256
+ check(!tkhd);
28257
+ tkhd = part;
28258
+ zeroTimes(b, part);
28259
+ }
27860
28260
  if (part.type === "mdia") {
27861
28261
  check(!mdia);
27862
28262
  mdia = part;
@@ -27877,6 +28277,12 @@ function stripMoov(b) {
27877
28277
  } else if (handler === "tmcd" && selfContained(b, minf)) {
27878
28278
  metadata = true;
27879
28279
  for (const range of sampleRanges(b, stbl)) zeroed.push(range);
28280
+ } else if (CAPTIONS.has(handler)) {
28281
+ check(selfContained(b, minf) && !!tkhd);
28282
+ const id = tkhd.body + 4 + (b[tkhd.body] === 1 ? 16 : 8);
28283
+ check(id + 4 <= tkhd.end);
28284
+ captions.add(u32be(b, id));
28285
+ for (const range of sampleRanges(b, stbl)) zeroed.push(range);
27880
28286
  } else check(HANDLERS.has(handler));
27881
28287
  if (handler === "vide") video = true;
27882
28288
  if (VISUAL.has(handler)) zeroCompressorNames(b, stbl);
@@ -27887,7 +28293,8 @@ function stripMoov(b) {
27887
28293
  fragmented,
27888
28294
  metadata,
27889
28295
  zeroed,
27890
- tables
28296
+ tables,
28297
+ captions
27891
28298
  };
27892
28299
  }
27893
28300
  /**
@@ -28016,7 +28423,7 @@ async function videoMetadataPatches(file, mime) {
28016
28423
  }
28017
28424
  check(moovs.length === 1);
28018
28425
  const moov = await whole(source, moovs[0]);
28019
- const { video, fragmented, metadata, zeroed, tables } = stripMoov(moov);
28426
+ const { video, fragmented, metadata, zeroed, tables, captions } = stripMoov(moov);
28020
28427
  if (!video && !typed) return void 0;
28021
28428
  patches.push({
28022
28429
  start: moovs[0].start,
@@ -28031,10 +28438,13 @@ async function videoMetadataPatches(file, mime) {
28031
28438
  }
28032
28439
  }
28033
28440
  check(!fragmented || !metadata);
28034
- const sizes = dropped.length && fragmented ? defaultSampleSizes(moov) : void 0;
28441
+ const sizes = (dropped.length || captions.size) && fragmented ? defaultSampleSizes(moov) : void 0;
28035
28442
  for (const box of top) if (box.type === "moof") {
28036
28443
  const moof = await whole(source, box);
28037
- if (dropped.length) for (const [start, end] of fragmentRanges(moof, box.start, sizes ?? /* @__PURE__ */ new Map())) check(!meets(dropped, start, end));
28444
+ if (dropped.length || captions.size) for (const [start, end, track] of fragmentRanges(moof, box.start, sizes ?? /* @__PURE__ */ new Map())) {
28445
+ check(!meets(dropped, start, end));
28446
+ if (captions.has(track)) zeroed.push([start, end]);
28447
+ }
28038
28448
  emptyWithin(moof, box.body - box.start, moof.length);
28039
28449
  patches.push({
28040
28450
  start: box.start,
@@ -28373,7 +28783,8 @@ function parseLightningDestination(input) {
28373
28783
  };
28374
28784
  }
28375
28785
  var hex$1 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
28376
- var reason = (value) => typeof value === "string" ? value.replace(/\s+/g, " ").slice(0, 200) : "";
28786
+ /** A server's own words on one line, bounded, with no character that hides text or reorders what follows it. */
28787
+ var reason = (value) => typeof value === "string" ? stripHidden(value.replace(/\s+/g, " ")).slice(0, 200) : "";
28377
28788
  var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
28378
28789
  async function readBounded(response, maxBytes) {
28379
28790
  const reader = response.body?.getReader?.();
@@ -28524,6 +28935,16 @@ function invoiceCallbackUrl(params, amountSat, comment) {
28524
28935
  }
28525
28936
  return url.href;
28526
28937
  }
28938
+ /** A success action's link: HTTPS, bounded, and no user part ("https://www.paypal.com@evil.example" opens evil.example). */
28939
+ function successUrl(text) {
28940
+ if (!/^https:\/\//i.test(text) || text.length > LNURL_LIMITS.maxUrlLength) return false;
28941
+ try {
28942
+ const url = new URL(text);
28943
+ return !url.username && !url.password;
28944
+ } catch {
28945
+ return false;
28946
+ }
28947
+ }
28527
28948
  /**
28528
28949
  * Checks the invoice a service answered with (LUD-06): the amount asked, a payment hash, not expired, and
28529
28950
  * a commitment to the metadata the person was shown: the `h` tag is its sha256, or the invoice carries the
@@ -28533,7 +28954,7 @@ function parseInvoiceCallback(body, params, amountSat) {
28533
28954
  if (!isRecord(body) || typeof body.pr !== "string") throw new Error(`${params.callbackDomain} did not answer with an invoice`);
28534
28955
  const invoice = decodeBolt11(body.pr);
28535
28956
  if (!invoice) throw new Error(`${params.callbackDomain} answered with an invoice that does not decode`);
28536
- 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`);
28957
+ 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`);
28537
28958
  if (!invoice.paymentHash) throw new Error("The invoice has no payment hash");
28538
28959
  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");
28539
28960
  if (invoice.expiresAt * 1e3 < Date.now()) throw new Error("The invoice the service answered with has already expired");
@@ -28544,7 +28965,7 @@ function parseInvoiceCallback(body, params, amountSat) {
28544
28965
  tag: "message",
28545
28966
  message: reason(action.message)
28546
28967
  };
28547
- else if (action.tag === "url" && typeof action.url === "string" && /^https:\/\//i.test(action.url) && action.url.length <= LNURL_LIMITS.maxUrlLength) successAction = {
28968
+ else if (action.tag === "url" && typeof action.url === "string" && successUrl(action.url)) successAction = {
28548
28969
  tag: "url",
28549
28970
  description: reason(action.description),
28550
28971
  url: action.url
@@ -29931,7 +30352,7 @@ function parseDidJws(input) {
29931
30352
  }
29932
30353
  if (!isObject$3(header)) throw new DidError("The JWS header is not a JSON object");
29933
30354
  const alg = header.alg;
29934
- 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`);
30355
+ 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`);
29935
30356
  if (header.kid !== void 0 && (typeof header.kid !== "string" || header.kid.length > 640)) throw new DidError("The JWS kid is not a key id");
29936
30357
  if (header.b64 !== void 0 && typeof header.b64 !== "boolean") throw new DidError("The JWS b64 header is not true or false");
29937
30358
  const crit = header.crit;
@@ -29978,7 +30399,7 @@ function verifyWith(key, signature, message, format = "compact") {
29978
30399
  return false;
29979
30400
  }
29980
30401
  }
29981
- var refusedKey = (key) => new DidError(`Signed by ${key.id}, which the DID document does not list under authentication or assertionMethod`);
30402
+ var refusedKey = () => new DidError("Signed by a key the DID document does not list under authentication or assertionMethod");
29982
30403
  /**
29983
30404
  * Which key of `doc` made this JWS over one of `messages` (the statement, and the statement with a
29984
30405
  * trailing newline some tools add). With a `kid`, only that key is tried. Refused unless the key is
@@ -29989,9 +30410,9 @@ function checkDidJws(input, messages, doc) {
29989
30410
  let candidates = doc.keys.filter((k) => k.curve === jws.curve);
29990
30411
  if (jws.kid !== void 0) {
29991
30412
  const kid = methodId(doc.did, jws.kid);
29992
- if (!kid) throw new DidError(`The JWS names key ${jws.kid.slice(0, 100)}, which is not a key of ${doc.did}`);
30413
+ if (!kid) throw new DidError(`The JWS names a key that is not a key of ${doc.did}`);
29993
30414
  candidates = candidates.filter((k) => k.id === kid);
29994
- 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}`);
30415
+ 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");
29995
30416
  }
29996
30417
  if (!candidates.length) throw new DidError(`The DID document lists no ${jws.curve} key for ${jws.alg}`);
29997
30418
  let inputs;
@@ -30013,7 +30434,7 @@ function checkDidJws(input, messages, doc) {
30013
30434
  alg: jws.alg
30014
30435
  };
30015
30436
  }
30016
- if (refused) throw refusedKey(refused);
30437
+ if (refused) throw refusedKey();
30017
30438
  throw new DidError("The JWS signature does not match: sign exactly the statement shown, with a key of this DID");
30018
30439
  }
30019
30440
  /**
@@ -30025,9 +30446,9 @@ function checkDidSignature(signature, messages, doc, vm) {
30025
30446
  let candidates = doc.keys;
30026
30447
  if (vm !== void 0) {
30027
30448
  const id = methodId(doc.did, vm);
30028
- if (!id) throw new DidError(`${vm.slice(0, 100)} is not a key of ${doc.did}`);
30449
+ if (!id) throw new DidError(`The proof names a key that is not a key of ${doc.did}`);
30029
30450
  candidates = candidates.filter((k) => k.id === id);
30030
- if (!candidates.length) throw new DidError(`The DID document lists no key ${id}`);
30451
+ if (!candidates.length) throw new DidError("The DID document does not list the key the proof names");
30031
30452
  }
30032
30453
  const der = signature.length !== 64 && signature[0] === 48;
30033
30454
  if (signature.length !== 64 && !der) throw new DidError("A signature is 64 bytes (or DER, for ECDSA)");
@@ -30046,7 +30467,7 @@ function checkDidSignature(signature, messages, doc, vm) {
30046
30467
  signature: canonical
30047
30468
  };
30048
30469
  }
30049
- if (refused) throw refusedKey(refused);
30470
+ if (refused) throw refusedKey();
30050
30471
  throw new DidError("The signature does not match: sign exactly the statement shown, with a key of this DID");
30051
30472
  }
30052
30473
  function parseDidSignaturePaste(pasted) {
@@ -31304,7 +31725,7 @@ function parseKeyBlob(blob) {
31304
31725
  if (blob.length > 1100) fail("SSH public key too large");
31305
31726
  const r = new Reader(blob);
31306
31727
  const type = r.text(64);
31307
- if (!SSH_KEY_TYPES.includes(type)) fail(`Unsupported SSH key type ${JSON.stringify(type)}`);
31728
+ if (!SSH_KEY_TYPES.includes(type)) fail(`Unsupported SSH key type${type === "ssh-dss" ? " \"ssh-dss\"" : ""}`);
31308
31729
  const key = {
31309
31730
  type,
31310
31731
  blob,
@@ -31417,7 +31838,7 @@ function ecdsaSignature(blob, size) {
31417
31838
  async function verifySshSignature(armored, message, options = {}) {
31418
31839
  const parsed = parseSshSignature(armored);
31419
31840
  const namespace = options.namespace ?? "ghostly";
31420
- if (parsed.namespace !== namespace) fail(`Signed for namespace ${JSON.stringify(parsed.namespace)}, not ${JSON.stringify(namespace)}. Use -n ${namespace}.`);
31841
+ if (parsed.namespace !== namespace) fail(`Signed for another namespace, not ${JSON.stringify(namespace)}. Use -n ${namespace}.`);
31421
31842
  const bytes = typeof message === "string" ? utf8Encode(message) : message;
31422
31843
  const digest = parsed.hashAlgorithm === "sha512" ? sha512(bytes) : sha256(bytes);
31423
31844
  const signed = concatBytes$1(utf8Encode("SSHSIG"), sshString(utf8Encode(parsed.namespace)), sshString(/* @__PURE__ */ new Uint8Array()), sshString(utf8Encode(parsed.hashAlgorithm)), sshString(digest));
@@ -32000,6 +32421,13 @@ var GROUP_LIMITS = {
32000
32421
  /** Frames waiting for an epoch (or its secret) that has not arrived yet. */
32001
32422
  waiting: 64,
32002
32423
  waitingBytes: 1048576,
32424
+ /**
32425
+ * Of those, and of the edits waiting, the ones signed by a key no recent commit names (a newcomer whose admission has
32426
+ * not come yet, or a key anyone can make up): the newest only, they go first, and they never say I am behind.
32427
+ */
32428
+ waitingStrangers: 8,
32429
+ /** How long a frame or edit waits: then it is dropped, and a later catch-up brings it again if it was real. */
32430
+ waitingMs: 12e4,
32003
32431
  /** Epoch secrets kept: past this, older epochs cannot be read or handed on. */
32004
32432
  secrets: 32,
32005
32433
  /** Secrets in one `group-secrets` frame: apps from before revision 0.9 drop a frame with more. */
@@ -32067,23 +32495,45 @@ var ANSWER_WINDOW_MS$1 = 5e3;
32067
32495
  * hears it, with what the member says live beside it, and the edits its app says again), then
32068
32496
  * `GROUP_LIMITS.messagesPerAuthor` and `messageBytesPerAuthor` per `messageWindowMs`, as a community's `MessagePace`.
32069
32497
  * 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.
32070
- * What another member hands on in its answer to my sync is not counted: it took each at its author's pace already, and
32071
- * a catch-up holds many.
32498
+ * What another member hands on in its answer to my sync (or what waited for a secret) is counted too, and may run the
32499
+ * author's allowance below nothing by one answer's worth (`AUTHOR_OWED`): a catch-up holds more than a burst, and lands
32500
+ * 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
32501
+ * handed on all a second member signed, at any rate.
32072
32502
  */
32073
32503
  var AUTHOR_BURST = {
32074
32504
  frames: 2 * GROUP_LIMITS.outlog,
32075
32505
  bytes: 2 * GROUP_LIMITS.outlogBytes
32076
32506
  };
32507
+ /** How far below nothing an answer may run an author's allowance: all its messages one answer hands on, or edits. */
32508
+ var AUTHOR_OWED = {
32509
+ messages: {
32510
+ frames: GROUP_LIMITS.relay,
32511
+ bytes: GROUP_LIMITS.relayBytes
32512
+ },
32513
+ edits: {
32514
+ frames: GROUP_LIMITS.handOnEdits,
32515
+ bytes: GROUP_LIMITS.relayEditBytes
32516
+ }
32517
+ };
32077
32518
  var AuthorPace = class {
32519
+ owed;
32078
32520
  frames = AUTHOR_BURST.frames;
32079
32521
  bytes = AUTHOR_BURST.bytes;
32080
32522
  at;
32081
- take(bytes, now) {
32523
+ constructor(owed) {
32524
+ this.owed = owed;
32525
+ }
32526
+ /** `answer`: handed on in an answer to my sync, or waited, so it may run the allowance below nothing (`owed`). */
32527
+ take(bytes, now, answer = false) {
32082
32528
  const elapsed = Math.max(0, now - (this.at ?? now)) / GROUP_LIMITS.messageWindowMs;
32083
32529
  this.at = now;
32084
32530
  this.frames = Math.min(AUTHOR_BURST.frames, this.frames + elapsed * GROUP_LIMITS.messagesPerAuthor);
32085
32531
  this.bytes = Math.min(AUTHOR_BURST.bytes, this.bytes + elapsed * GROUP_LIMITS.messageBytesPerAuthor);
32086
- if (this.frames < 1 || this.bytes < bytes) return false;
32532
+ const floor = answer ? this.owed : {
32533
+ frames: 0,
32534
+ bytes: 0
32535
+ };
32536
+ if (this.frames + floor.frames < 1 || this.bytes + floor.bytes < bytes) return false;
32087
32537
  this.frames -= 1;
32088
32538
  this.bytes -= bytes;
32089
32539
  return true;
@@ -32419,6 +32869,20 @@ function isMessageFrame$1(v) {
32419
32869
  const f = v;
32420
32870
  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);
32421
32871
  }
32872
+ /**
32873
+ * A waiting list past `max` places, past `waitingStrangers` of keys no recent commit names, or past its bytes (`heavy`):
32874
+ * which one goes, or -1. Such a key's oldest first, else the oldest of the author holding the most places, so one
32875
+ * author's frames for an epoch that never comes push out its own, not another member's.
32876
+ */
32877
+ function overflow(list, max, heavy = false) {
32878
+ const strangers = list.filter((w) => w.stranger).length;
32879
+ if (!list.length || !heavy && list.length <= max && strangers <= GROUP_LIMITS.waitingStrangers) return -1;
32880
+ if (strangers) return list.findIndex((w) => w.stranger);
32881
+ const places = /* @__PURE__ */ new Map();
32882
+ for (const w of list) places.set(w.frame.s, (places.get(w.frame.s) ?? 0) + 1);
32883
+ const most = Math.max(...places.values());
32884
+ return list.findIndex((w) => places.get(w.frame.s) === most);
32885
+ }
32422
32886
  /** The chain cut in consecutive pieces of at most `chainPiece` commits and `chainPieceBytes`: a roster of 32 makes a commit ~2.4 KB. */
32423
32887
  function chainPieces(chain) {
32424
32888
  const pieces = [];
@@ -32445,6 +32909,11 @@ var GroupSession = class {
32445
32909
  waitingBytes = 0;
32446
32910
  /** Edits for an epoch, or a secret, not here yet: tried again with the frames above. In memory only. */
32447
32911
  waitingEdits = [];
32912
+ /**
32913
+ * Members one of whose frames waited `waitingMs` for an epoch that never came → when it was dropped: until my chain
32914
+ * moves, theirs waiting say I am behind no more (`behind`). In memory only.
32915
+ */
32916
+ waitedInVain = /* @__PURE__ */ new Map();
32448
32917
  pendingCommits = /* @__PURE__ */ new Map();
32449
32918
  /** When each member was last asked to catch me up, so a stream of unreadable frames is one question, not a loop. */
32450
32919
  asked = /* @__PURE__ */ new Map();
@@ -33374,9 +33843,14 @@ var GroupSession = class {
33374
33843
  await this.resealBehind();
33375
33844
  });
33376
33845
  }
33377
- /** Something is missing here: the current epoch's secret, a commit ahead of my chain, or the epoch of frames waiting. */
33846
+ /**
33847
+ * Something is missing here: the current epoch's secret, a commit ahead of my chain, or the epoch of a member's frames
33848
+ * waiting, unless one of that member's waited in vain since my chain last moved (`waitedInVain`).
33849
+ */
33378
33850
  get behind() {
33379
- return !this.state.secrets[this.epoch] || this.waiting.length > 0 || this.pendingCommits.size > 0;
33851
+ this.expireWaiting();
33852
+ const member = (w) => !w.stranger && !((this.waitedInVain.get(w.frame.s) ?? -Infinity) >= this.chainMovedAt);
33853
+ return !this.state.secrets[this.epoch] || this.waiting.some(member) || this.pendingCommits.size > 0;
33380
33854
  }
33381
33855
  async resealBehind() {
33382
33856
  const alone = new Set(this.state.alone ?? []);
@@ -33893,11 +34367,11 @@ var GroupSession = class {
33893
34367
  }
33894
34368
  const relayed = raw.s !== from;
33895
34369
  const now = this.now(), answer = (this.answering.get(from) ?? 0) > now;
33896
- if (answer) this.answering.set(from, now + ANSWER_WINDOW_MS$1);
33897
34370
  if (relayed && (!rosterHas(this.roster, from) || !this.handsOn(raw.s))) return;
33898
34371
  if (this.isDuplicate(raw)) return;
33899
34372
  const signedWhole = relayed && this.wholeSigned(raw);
33900
34373
  if (!signedWhole && !verify(fromBase64Url(raw.sig), messageSigned$1(raw), publicKeyFromZ32(raw.s))) return;
34374
+ if (answer) this.answering.set(from, now + ANSWER_WINDOW_MS$1);
33901
34375
  if (raw.e > this.epoch) {
33902
34376
  this.park(from, raw);
33903
34377
  return;
@@ -33917,7 +34391,7 @@ var GroupSession = class {
33917
34391
  delete raw.o;
33918
34392
  delete raw.xs;
33919
34393
  }
33920
- if (!(relayed && (answer || waited)) && !this.paced(this.messagePace, raw.s, frameBytes(raw))) return;
34394
+ if (!this.paced(this.messagePace, raw.s, frameBytes(raw), relayed && (answer || waited))) return;
33921
34395
  const first = raw.o === void 0 ? null : readFirstPlace(raw.o, raw.e);
33922
34396
  if (raw.o !== void 0 && !first) return;
33923
34397
  const secret = this.secret(raw.e);
@@ -34004,7 +34478,7 @@ var GroupSession = class {
34004
34478
  }
34005
34479
  const commit = this.state.chain[raw.e];
34006
34480
  if (!commit || !rosterHas(commit.m, raw.s)) return;
34007
- if (!(this.state.relayEdits ?? []).some((f) => f.s === raw.s && f.e === raw.e && f.n === raw.n && f.v >= raw.v) && !(raw.s !== from && (this.awaitsAnswer(from) || waited)) && !this.paced(this.editPace, raw.s, raw.c.length + 400)) return;
34481
+ 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;
34008
34482
  if (!rosterHas(commit.m, this.myKey)) {
34009
34483
  if (member && this.keepEdit(raw)) {
34010
34484
  this.persistSoon();
@@ -34052,16 +34526,20 @@ var GroupSession = class {
34052
34526
  }
34053
34527
  parkEdit(from, frame) {
34054
34528
  if (frame.e > this.epoch + GROUP_LIMITS.secrets) return;
34529
+ this.expireWaiting();
34055
34530
  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)), {
34056
34531
  from,
34057
- frame
34058
- }].slice(-GROUP_LIMITS.outlog);
34532
+ frame,
34533
+ at: this.now(),
34534
+ stranger: this.stranger(frame.s)
34535
+ }];
34536
+ for (let i; (i = overflow(this.waitingEdits, GROUP_LIMITS.outlog)) >= 0;) this.waitingEdits.splice(i, 1);
34059
34537
  this.ask(from);
34060
34538
  }
34061
- paced(paces, author, bytes) {
34539
+ paced(paces, author, bytes, answer) {
34062
34540
  let pace = paces.get(author);
34063
- if (!pace) paces.set(author, pace = new AuthorPace());
34064
- return pace.take(bytes, this.now());
34541
+ if (!pace) paces.set(author, pace = new AuthorPace(paces === this.editPace ? AUTHOR_OWED.edits : AUTHOR_OWED.messages));
34542
+ return pace.take(bytes, this.now(), answer);
34065
34543
  }
34066
34544
  wholeSigned(raw) {
34067
34545
  if (typeof raw.xs !== "string" || raw.xs.length !== 86 || !B64$1.test(raw.xs)) return false;
@@ -34171,15 +34649,31 @@ var GroupSession = class {
34171
34649
  }
34172
34650
  park(from, frame) {
34173
34651
  if (frame.e > this.epoch + GROUP_LIMITS.secrets) return;
34652
+ this.expireWaiting();
34174
34653
  if (this.waiting.some((w) => w.frame.s === frame.s && w.frame.e === frame.e && w.frame.n === frame.n)) return;
34175
34654
  this.waiting.push({
34176
34655
  from,
34177
- frame
34656
+ frame,
34657
+ at: this.now(),
34658
+ stranger: this.stranger(frame.s)
34178
34659
  });
34179
34660
  this.waitingBytes += frame.c.length;
34180
- while (this.waiting.length > GROUP_LIMITS.waiting || this.waitingBytes > GROUP_LIMITS.waitingBytes) this.waitingBytes -= this.waiting.shift().frame.c.length;
34661
+ 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;
34181
34662
  this.ask(from);
34182
34663
  }
34664
+ /** Not in the roster, nor in any of the last `secrets` commits: a key whose frames may be no member's. */
34665
+ stranger(key) {
34666
+ return !this.state.chain.slice(-GROUP_LIMITS.secrets).some((c) => rosterHas(c.m, key));
34667
+ }
34668
+ /** Frames and edits that waited `waitingMs`: dropped, and a member's noted (`waitedInVain`). */
34669
+ expireWaiting() {
34670
+ const now = this.now(), stale = (w) => now - w.at >= GROUP_LIMITS.waitingMs;
34671
+ if (!this.waiting.some(stale) && !this.waitingEdits.some(stale)) return;
34672
+ for (const w of this.waiting) if (stale(w) && !w.stranger) this.waitedInVain.set(w.frame.s, now);
34673
+ this.waiting = this.waiting.filter((w) => !stale(w));
34674
+ this.waitingBytes = this.waiting.reduce((sum, w) => sum + w.frame.c.length, 0);
34675
+ this.waitingEdits = this.waitingEdits.filter((w) => !stale(w));
34676
+ }
34183
34677
  /** Whoever sent something I cannot read yet is ahead of me, or holds a secret I lack: ask, but not in a loop. */
34184
34678
  ask(from) {
34185
34679
  const now = Date.now();
@@ -34791,6 +35285,12 @@ var COMMUNITY_LIMITS = {
34791
35285
  window: 64,
34792
35286
  /** Commits known off the main branch. */
34793
35287
  side: 512,
35288
+ /**
35289
+ * Of those, the branches one member's commit ends (its newest), and the commits it signed: a handful of races, and
35290
+ * one full run of its admissions (`memberAdmissions`, with the leaves among them). The admin's are not counted.
35291
+ */
35292
+ sideTips: 8,
35293
+ sideCommits: 64,
34794
35294
  /** Commits waiting for their parent. */
34795
35295
  pendingCommits: 64,
34796
35296
  /** Epoch secrets waiting for their commit. */
@@ -34799,6 +35299,11 @@ var COMMUNITY_LIMITS = {
34799
35299
  pendingMs: 12e4,
34800
35300
  waiting: 64,
34801
35301
  waitingBytes: 1048576,
35302
+ /**
35303
+ * Of those, the ones signed by a key no commit I know names (a newcomer whose admission has not come yet, or a key
35304
+ * anyone can make up): the newest only, they push out nobody else's, and they make no catch-up hurry.
35305
+ */
35306
+ waitingStrangers: 8,
34802
35307
  replay: 256,
34803
35308
  /** Commits in one welcome or chain piece. */
34804
35309
  chainPiece: 100,
@@ -36132,10 +36637,45 @@ var CommunitySession = class CommunitySession {
36132
36637
  seedB64: ""
36133
36638
  };
36134
36639
  }
36135
- /** Side commits stay up to a bound, the most recent ones (a longer branch being assembled included). */
36640
+ /**
36641
+ * Side commits stay up to a bound, the most recent ones (a longer branch being assembled included), and a member's
36642
+ * newest only: past `sideTips` of the branches it ends or `sideCommits` of its commits, its oldest branch goes, from
36643
+ * the tip down, so nothing kept loses its parent. Each is weighed at every commit taken and saved with the group, so
36644
+ * what one member signs off the main branch costs every member a bounded amount. What it signs last is kept, so a
36645
+ * branch it grows still comes in commit by commit (one let go comes again from where it parts in a catch-up).
36646
+ */
36136
36647
  pruneSide() {
36137
- this.state.side = this.state.side.slice(-COMMUNITY_LIMITS.side);
36138
- const keep = new Set(this.state.side.map((c) => communityCommitHash(c)));
36648
+ const admin = this.admin, hashes = /* @__PURE__ */ new Map();
36649
+ const hash = (c) => {
36650
+ let h = hashes.get(c);
36651
+ if (!h) hashes.set(c, h = communityCommitHash(c));
36652
+ return h;
36653
+ };
36654
+ let side = this.state.side.slice(-COMMUNITY_LIMITS.side);
36655
+ for (;;) {
36656
+ const held = new Set(side.map(hash)), parents = new Set(side.map((c) => c.p)), drop = /* @__PURE__ */ new Set();
36657
+ const signed = /* @__PURE__ */ new Map(), tips = /* @__PURE__ */ new Map(), oldest = /* @__PURE__ */ new Map(), cut = /* @__PURE__ */ new Set();
36658
+ for (const c of side) signed.set(c.by, (signed.get(c.by) ?? 0) + 1);
36659
+ for (let i = side.length - 1; i >= 0; i--) {
36660
+ const c = side[i];
36661
+ if (!held.has(c.p) && !this.mainIndex.has(c.p)) {
36662
+ drop.add(c);
36663
+ continue;
36664
+ }
36665
+ if (parents.has(hash(c))) continue;
36666
+ const n = (tips.get(c.by) ?? 0) + 1;
36667
+ tips.set(c.by, n);
36668
+ if (c.by !== admin && n > COMMUNITY_LIMITS.sideTips) {
36669
+ drop.add(c);
36670
+ cut.add(c.by);
36671
+ } else oldest.set(c.by, c);
36672
+ }
36673
+ for (const [by, n] of signed) if (by !== admin && n > COMMUNITY_LIMITS.sideCommits && !cut.has(by) && oldest.has(by)) drop.add(oldest.get(by));
36674
+ if (!drop.size) break;
36675
+ side = side.filter((c) => !drop.has(c));
36676
+ }
36677
+ this.state.side = side;
36678
+ const keep = new Set(side.map(hash));
36139
36679
  for (const [h, c] of [...this.known]) {
36140
36680
  if (this.mainIndex.has(h)) {
36141
36681
  if (this.mainIndex.get(h) < this.state.chain.length - 1 - COMMUNITY_LIMITS.window) this.rosters.delete(h);
@@ -36164,9 +36704,20 @@ var CommunitySession = class CommunitySession {
36164
36704
  if (!Object.keys(bySender).length) delete this.state.seen[sender];
36165
36705
  }
36166
36706
  }
36707
+ /**
36708
+ * Those of the main branch's window always stay, the current epoch's included; side commits, however many are
36709
+ * kept, only get what is left of the bound, the most recent first.
36710
+ */
36167
36711
  pruneSecrets() {
36168
- const order = [...this.state.chain.slice(-COMMUNITY_LIMITS.window - 1), ...this.state.side].map((c) => communityCommitHash(c));
36169
- const keep = new Set(order.slice(-COMMUNITY_LIMITS.secrets));
36712
+ const keep = new Set(this.state.chain.slice(-COMMUNITY_LIMITS.window - 1).map((c) => communityCommitHash(c)));
36713
+ let room = COMMUNITY_LIMITS.secrets - [...keep].filter((h) => this.state.secrets[h]).length;
36714
+ for (let i = this.state.side.length - 1; i >= 0 && room > 0; i--) {
36715
+ const h = communityCommitHash(this.state.side[i]);
36716
+ if (this.state.secrets[h] && !keep.has(h)) {
36717
+ keep.add(h);
36718
+ room--;
36719
+ }
36720
+ }
36170
36721
  for (const h of Object.keys(this.state.secrets)) if (!keep.has(h)) delete this.state.secrets[h];
36171
36722
  }
36172
36723
  /** A derived epoch's secret, from its parent's, when that is held. */
@@ -37412,19 +37963,25 @@ var CommunitySession = class CommunitySession {
37412
37963
  park(from, frame) {
37413
37964
  if (frame.e > this.epoch + COMMUNITY_LIMITS.window) return;
37414
37965
  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;
37966
+ const stranger = !rosterHas(this.roster, frame.s) && !this.isRecentMember(frame.s);
37415
37967
  this.waiting.push({
37416
37968
  from,
37417
- frame
37969
+ frame,
37970
+ stranger
37418
37971
  });
37419
37972
  this.waitingBytes += frame.c.length;
37420
- while (this.waiting.length > COMMUNITY_LIMITS.waiting || this.waitingBytes > COMMUNITY_LIMITS.waitingBytes) this.waitingBytes -= this.waiting.shift().frame.c.length;
37973
+ for (;;) {
37974
+ const strangers = this.waiting.filter((w) => w.stranger).length;
37975
+ if (strangers <= COMMUNITY_LIMITS.waitingStrangers && this.waiting.length <= COMMUNITY_LIMITS.waiting && this.waitingBytes <= COMMUNITY_LIMITS.waitingBytes) break;
37976
+ this.waitingBytes -= this.waiting.splice(strangers ? this.waiting.findIndex((w) => w.stranger) : 0, 1)[0].frame.c.length;
37977
+ }
37421
37978
  this.ask(from);
37422
37979
  }
37423
- /** Something is missing here: the current epoch's secret, or the epoch of frames waiting. */
37980
+ /** Something is missing here: the current epoch's secret, or the epoch of a member's frames waiting. */
37424
37981
  get needsCatchUp() {
37425
37982
  if (!this.isMember) return false;
37426
37983
  this.dropStale(this.pendingCommits, this.hooks.clock?.() ?? Date.now());
37427
- return !this.state.secrets[this.topHash] || this.waiting.length > 0 || this.pendingCommits.size > 0;
37984
+ return !this.state.secrets[this.topHash] || this.waiting.some((w) => !w.stranger) || this.pendingCommits.size > 0;
37428
37985
  }
37429
37986
  /** Asks a member I have an edge to for what I lack (the engine calls it now and then while `needsCatchUp`). */
37430
37987
  catchUp(to) {
@@ -38447,4 +39004,4 @@ function readX401SdJwtVc(text) {
38447
39004
  //#endregion
38448
39005
  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 };
38449
39006
 
38450
- //# sourceMappingURL=src-BIdfHB7t.js.map
39007
+ //# sourceMappingURL=src-BTRPAi5X.js.map