@ghostlytools/sdk 1.13.2 → 1.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { o as __toESM } from "./rolldown-runtime-DpEnGzO4.js";
2
2
  import { a as concatBytes, c as fromZ32, d as toBase64, f as toBase64Url, h as utf8Encode, i as bytesEqual, l as isZ32Key, m as utf8Decode, n as decodeBolt11, o as fromBase64, p as toZ32, r as findBolt11, s as fromBase64Url, t as BOLT11_PATTERN, u as randomBytes } from "./bolt11-CRiQrma3.js";
3
- import { $ as DEFAULT_RELAYS, $t as decodeTxtPacket, A as identityRevocationValue, At as BREAKER_BASE_MS, B as applyIdentityEvent, Bt as withRequestOptions, C as IdentityCheckUnavailable, Ct as currentRelays, D as emptyIdentityLedger, Dt as setLinkTraceSink, E as boundVerifiedIdentity, Et as relayUrlProblem, F as receivedIdentityStatus, Ft as PublishFailedError, G as AWAITED_READS, Gt as createRelayPayload, H as ANSWER_READ_ALLOWANCE, Ht as PKARR_FUTURE_SKEW_MS, I as revokesIdentity, It as budgetRetryMs, J as BACKGROUND_WRITES_SHARE, Jt as openRelayPayload, K as BACKGROUND_REQUESTS_PER_MINUTE, Kt as measureRecords, L as signIdentityPresentation, Lt as heldBackError, M as identityStatementText, Mt as BREAKER_THRESHOLD, N as isIdentityBinding, Nt as RelayBreaker, O as identityPresentationBytes, Ot as traceLink, P as newIdentityBinding, Pt as DiscoveryBudgetError, Q as CHAT_WATCH_SHARE, Qt as decodeDnsAnswers, R as verifyIdentityPresentation, Rt as isDiscoveryBudgetError, S as IDENTITY_SUBJECT, St as WRITE_FIRST_MS, T as boundIdentityDisplay, Tt as readRelayBody, U as ANSWER_READ_FIRST_MS, Ut as PacketTooLargeError, V as lastSharedWithMe, Vt as MAX_DNS_PACKET_BYTES, W as ANSWER_READ_SPACING_MS, Wt as RELAY_PAYLOAD_MAX_BYTES, X as CHAT_RESERVE_MOST_SHARE, Xt as readOwnRelayPayload, Y as CHAT_RESERVE, Yt as parseRelayPayload, Z as CHAT_RESERVE_PER_CHAT, Zt as signRelayPayload, _ as IDENTITY_REUSE_CHECK_S, _n as stripHidden, _t as SLOW_DEMOTE_MS, a as IDENTITY_CLOCK_SKEW, an as createIdentity, at as GROUP_OVER_PACE_MS, b as IDENTITY_SEND_WINDOW_MS, bt as WATCH_SHARE, c as IDENTITY_MAX_CHECKS_PER_HOUR, cn as publicKeyFromZ32, ct as HEDGE_MISSING_MS, d as IDENTITY_MAX_RECEIVED, dn as verify, dt as RELAY_REQUESTS_PER_MINUTE, en as encodeTxtPacket, et as DEPARTED_READS, f as IDENTITY_MAX_VALIDITY, fn as MAX_NICK_LENGTH, ft as REQUESTS_PER_MINUTE, g as IDENTITY_RESEND_MS, gn as sanitizeNick, gt as SIGNALING_WINDOW_MS, h as IDENTITY_RESENDS, hn as sanitizeDisplayText, ht as SIGNALING_ALLOWANCE_SHARE, i as IDENTITY_CHECK_UNAVAILABLE, in as IDENTITY_MEMO_SIZE, it as GROUP_BURST_ONE_LINK, j as identityStatement, jt as BREAKER_MAX_MS, k as identityRefusal, kt as BREAKER_ALL_DOWN_PROBE_MS, l as IDENTITY_MAX_EVIDENCE, ln as setPublicKeyFastPath, lt as HEDGE_MS, m as IDENTITY_PROVIDER_ID, mn as hasVisible, mt as RelaysFailedError, n as isBitcoinAddress, nn as IDENTITY_MEMO_IDLE_MS, nt as FRESH_READ_MS, o as IDENTITY_FRAME_LIMIT, on as identityFromSeed, ot as GROUP_RATION_WINDOW_MS, p as IDENTITY_PROOF_CAPABILITY, pn as dropLoneJoiners, pt as RelayTransport, q as BACKGROUND_WHILE_SIGNALING, qt as newerPacket, r as IDENTITY_CHALLENGE_WINDOW, rn as IDENTITY_MEMO_MAX, rt as GROUP_BURST_MS, s as IDENTITY_FRAME_WINDOW_MS, sn as identityFromSeedB64, st as GROUP_SIGNALING_ALLOWANCE_SHARE, t as BITCOIN_NETWORKS, tn as readDnsName, tt as DOOR_FIRST_MS, u as IDENTITY_MAX_FRAME, un as sign, ut as PREVIOUS_DEFAULT_RELAYS, v as IDENTITY_REVOCATION_LABEL, vn as trimEndOf, vt as SLOW_MS, w as IdentityExchange, wt as normalizeRelayUrl, x as IDENTITY_STATEMENT_PREFIX, xt as WAY_BACK_SHARE, y as IDENTITY_SEND_LIMIT, yn as unwrapPasted, yt as TURN_SOURCE_TIMEOUT_MS, z as IDENTITY_TIMELINE_MAX, zt as publishedNowhere } from "./bitcoinAddress-BIW3tpJG.js";
4
- import { A as NIP05_PATH, B as parseDomainTxt, C as underLocalSuffix, D as DOMAIN_MAX_RECORDS, E as DOMAIN_FILE_MAX_BYTES, F as domainWellKnownFile, G as validDomainRecord, H as recordsFromWellKnown, I as encodeDnsQuery, J as encrypt, K as wellKnownUrl, L as isPublicAddress, M as decodeDnsResponse, N as dnsProofName, O as DOMAIN_METHODS, P as domainTxtRecord, R as nip05RootKey, S as readManifest, T as DNS_TYPE, U as recordsName, V as recordsFromTxt, W as txtValue, X as sealedLength, Y as generateEncryptionKey, Z as tryDecrypt, _ as HOLD_LIMITS, a as automaticTransport, b as isHoldUrl, c as irohDescriptor, d as relayUrl, f as relayUrlTooLong, g as HOLD_DATED_BACK_MS, h as HOLD_CAPABILITY, i as TRANSPORTS, j as WELL_KNOWN_PATH, k as DOMAIN_TXT_MAX_BYTES, l as irohRelayUrl, m as transportOrder, n as RELAY_URL, o as checkedDescriptors, p as relayedTransports, q as decrypt, r as RELAY_WITH_SECRETS, s as dialableIrohRelay, t as AUTOMATIC_ORDER, u as rankTransports, v as HoldKeys, w as DNS_LABEL, x as newMailbox, y as HoldRefusedError, z as normalizeDomain } from "./pairedTransports-BcTRg3tp.js";
3
+ import { $ as DEFAULT_RELAYS, $t as decodeTxtPacket, A as identityRevocationValue, At as BREAKER_BASE_MS, B as applyIdentityEvent, Bt as withRequestOptions, C as IdentityCheckUnavailable, Ct as currentRelays, D as emptyIdentityLedger, Dt as setLinkTraceSink, E as boundVerifiedIdentity, Et as relayUrlProblem, F as receivedIdentityStatus, Ft as PublishFailedError, G as AWAITED_READS, Gt as createRelayPayload, H as ANSWER_READ_ALLOWANCE, Ht as PKARR_FUTURE_SKEW_MS, I as revokesIdentity, It as budgetRetryMs, J as BACKGROUND_WRITES_SHARE, Jt as openRelayPayload, K as BACKGROUND_REQUESTS_PER_MINUTE, Kt as measureRecords, L as signIdentityPresentation, Lt as heldBackError, M as identityStatementText, Mt as BREAKER_THRESHOLD, N as isIdentityBinding, Nt as RelayBreaker, O as identityPresentationBytes, Ot as traceLink, P as newIdentityBinding, Pt as DiscoveryBudgetError, Q as CHAT_WATCH_SHARE, Qt as decodeDnsAnswers, R as verifyIdentityPresentation, Rt as isDiscoveryBudgetError, S as IDENTITY_SUBJECT, St as WRITE_FIRST_MS, T as boundIdentityDisplay, Tt as readRelayBody, U as ANSWER_READ_FIRST_MS, Ut as PacketTooLargeError, V as lastSharedWithMe, Vt as MAX_DNS_PACKET_BYTES, W as ANSWER_READ_SPACING_MS, Wt as RELAY_PAYLOAD_MAX_BYTES, X as CHAT_RESERVE_MOST_SHARE, Xt as readOwnRelayPayload, Y as CHAT_RESERVE, Yt as parseRelayPayload, Z as CHAT_RESERVE_PER_CHAT, Zt as signRelayPayload, _ as IDENTITY_REUSE_CHECK_S, _n as stripHidden, _t as SLOW_DEMOTE_MS, a as IDENTITY_CLOCK_SKEW, an as createIdentity, at as GROUP_OVER_PACE_MS, b as IDENTITY_SEND_WINDOW_MS, bt as WATCH_SHARE, c as IDENTITY_MAX_CHECKS_PER_HOUR, cn as publicKeyFromZ32, ct as HEDGE_MISSING_MS, d as IDENTITY_MAX_RECEIVED, dn as verify, dt as RELAY_REQUESTS_PER_MINUTE, en as encodeTxtPacket, et as DEPARTED_READS, f as IDENTITY_MAX_VALIDITY, fn as MAX_NICK_LENGTH, ft as REQUESTS_PER_MINUTE, g as IDENTITY_RESEND_MS, gn as sanitizeNick, gt as SIGNALING_WINDOW_MS, h as IDENTITY_RESENDS, hn as sanitizeDisplayText, ht as SIGNALING_ALLOWANCE_SHARE, i as IDENTITY_CHECK_UNAVAILABLE, in as IDENTITY_MEMO_SIZE, it as GROUP_BURST_ONE_LINK, j as identityStatement, jt as BREAKER_MAX_MS, k as identityRefusal, kt as BREAKER_ALL_DOWN_PROBE_MS, l as IDENTITY_MAX_EVIDENCE, ln as setPublicKeyFastPath, lt as HEDGE_MS, m as IDENTITY_PROVIDER_ID, mn as hasVisible, mt as RelaysFailedError, n as isBitcoinAddress, nn as IDENTITY_MEMO_IDLE_MS, nt as FRESH_READ_MS, o as IDENTITY_FRAME_LIMIT, on as identityFromSeed, ot as GROUP_RATION_WINDOW_MS, p as IDENTITY_PROOF_CAPABILITY, pn as dropLoneJoiners, pt as RelayTransport, q as BACKGROUND_WHILE_SIGNALING, qt as newerPacket, r as IDENTITY_CHALLENGE_WINDOW, rn as IDENTITY_MEMO_MAX, rt as GROUP_BURST_MS, s as IDENTITY_FRAME_WINDOW_MS, sn as identityFromSeedB64, st as GROUP_SIGNALING_ALLOWANCE_SHARE, t as BITCOIN_NETWORKS, tn as readDnsName, tt as DOOR_FIRST_MS, u as IDENTITY_MAX_FRAME, un as sign, ut as PREVIOUS_DEFAULT_RELAYS, v as IDENTITY_REVOCATION_LABEL, vn as trimEndOf, vt as SLOW_MS, w as IdentityExchange, wt as normalizeRelayUrl, x as IDENTITY_STATEMENT_PREFIX, xt as WAY_BACK_SHARE, y as IDENTITY_SEND_LIMIT, yn as unwrapPasted, yt as TURN_SOURCE_TIMEOUT_MS, z as IDENTITY_TIMELINE_MAX, zt as publishedNowhere } from "./bitcoinAddress-CDYL3yPz.js";
4
+ import { A as NIP05_PATH, B as parseDomainTxt, C as underLocalSuffix, D as DOMAIN_MAX_RECORDS, E as DOMAIN_FILE_MAX_BYTES, F as domainWellKnownFile, G as validDomainRecord, H as recordsFromWellKnown, I as encodeDnsQuery, J as encrypt, K as wellKnownUrl, L as isPublicAddress, M as decodeDnsResponse, N as dnsProofName, O as DOMAIN_METHODS, P as domainTxtRecord, R as nip05RootKey, S as readManifest, T as DNS_TYPE, U as recordsName, V as recordsFromTxt, W as txtValue, X as sealedLength, Y as generateEncryptionKey, Z as tryDecrypt, _ as HOLD_LIMITS, a as automaticTransport, b as isHoldUrl, c as irohDescriptor, d as relayUrl, f as relayUrlTooLong, g as HOLD_DATED_BACK_MS, h as HOLD_CAPABILITY, i as TRANSPORTS, j as WELL_KNOWN_PATH, k as DOMAIN_TXT_MAX_BYTES, l as irohRelayUrl, m as transportOrder, n as RELAY_URL, o as checkedDescriptors, p as relayedTransports, q as decrypt, r as RELAY_WITH_SECRETS, s as dialableIrohRelay, t as AUTOMATIC_ORDER, u as rankTransports, v as HoldKeys, w as DNS_LABEL, x as newMailbox, y as HoldRefusedError, z as normalizeDomain } from "./pairedTransports-CQGJfihi.js";
5
5
  import { xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
6
6
  import { ed25519, x25519 } from "@noble/curves/ed25519.js";
7
7
  import { sha256, sha512 } from "@noble/hashes/sha2.js";
@@ -5482,6 +5482,20 @@ function sanitizeRequestHeaders(headers) {
5482
5482
  return !DROPPED_REQUEST_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix));
5483
5483
  });
5484
5484
  }
5485
+ /**
5486
+ * A cookie's `Path` as the client sees the app: without the target's base path, which the client never sees (as
5487
+ * `relativizeLocation` takes it off), so a cookie the app keeps on `/notes` is sent back to its `/home` at `/`. One
5488
+ * outside the base path would never be sent at all and goes on `/`; one that does not start with `/` the browser
5489
+ * ignores, so it stays.
5490
+ */
5491
+ function cookieOnClient(cookie, target) {
5492
+ if (!target.basePath) return cookie;
5493
+ return cookie.replace(/;\s*path\s*=\s*([^;]*)/gi, (attribute, value) => {
5494
+ const path = value.trim();
5495
+ if (!path.startsWith("/")) return attribute;
5496
+ return `; Path=${path === target.basePath || path.startsWith(`${target.basePath}/`) ? path.slice(target.basePath.length) || "/" : "/"}`;
5497
+ });
5498
+ }
5485
5499
  /** `from`: the local URL of the request answered, the one a relative `Location` is read against. */
5486
5500
  function sanitizeResponseHeaders(headers, target, from) {
5487
5501
  const out = [];
@@ -5492,7 +5506,7 @@ function sanitizeResponseHeaders(headers, target, from) {
5492
5506
  if (lower === "location" || lower === "content-location") {
5493
5507
  const location = relativizeLocation(value, target, from);
5494
5508
  if (location !== null) out.push([name, location]);
5495
- } else if (lower === "set-cookie") out.push([name, value.replace(/;\s*domain\s*=[^;]*/gi, "")]);
5509
+ } else if (lower === "set-cookie") out.push([name, cookieOnClient(value.replace(/;\s*domain\s*=[^;]*/gi, ""), target)]);
5496
5510
  else out.push([name, value]);
5497
5511
  }
5498
5512
  return out;
@@ -5500,15 +5514,17 @@ function sanitizeResponseHeaders(headers, target, from) {
5500
5514
  /**
5501
5515
  * The contact's headers a viewer does not pass on: each makes the browser send something to a place it names, outside
5502
5516
  * `connect-src` (violation and network-error reports, and the endpoints they go to; `Link` preloads, prefetches and
5503
- * early connections). With Hide my IP from contacts on, that place would learn this device's address. The same list
5504
- * as the CLI's `OPENED_SERVICE_DROPPED_HEADERS` and Desktop's `DROPPED_HEADERS`.
5517
+ * early connections; `Speculation-Rules` prefetches and prerenders). With Hide my IP from contacts on, that place would
5518
+ * learn this device's address. The same list as the CLI's `OPENED_SERVICE_DROPPED_HEADERS` and Desktop's
5519
+ * `DROPPED_HEADERS`.
5505
5520
  */
5506
5521
  var VIEWER_DROPPED_HEADERS = [
5507
5522
  "content-security-policy-report-only",
5508
5523
  "reporting-endpoints",
5509
5524
  "report-to",
5510
5525
  "nel",
5511
- "link"
5526
+ "link",
5527
+ "speculation-rules"
5512
5528
  ];
5513
5529
  /** The directives of a contact's policy that send reports to a URL it names, dropped from it (`OPENED_SERVICE_DROPPED_DIRECTIVES`). */
5514
5530
  var VIEWER_DROPPED_DIRECTIVES = ["report-uri", "report-to"];
@@ -6147,12 +6163,15 @@ var HttpClient = class {
6147
6163
  * the same script, so it is the same worker; the page's revoke of the blob's URL drops the guard's own a minute later.
6148
6164
  * A `data:` worker, and a blob made in another window, in a worker or already revoked, run as they were. Once per
6149
6165
  * window, whichever guard runs first (`ghostlyWorkerGuard`, `CLIPBOARD_GUARD_SCRIPT` does the same).
6166
+ * - takes out each `<script type="speculationrules">` as it is put in the page, a shadow tree the page makes included:
6167
+ * Chromium would prefetch or prerender the pages it lists on a server the contact names, which no policy covers
6168
+ * (`'unsafe-inline'` lets inline rules in); the `Speculation-Rules` header is not passed on (`VIEWER_DROPPED_HEADERS`).
6150
6169
  * It uses nothing the page can change after it ran (the page's own code runs later, in the same realm).
6151
6170
  *
6152
6171
  * What a script put in the page cannot do, so where the viewer does not run it per document this is not a guarantee:
6153
6172
  * a frame's window read by its index (`window[0]`, never through the frame element) while the frame's page is still
6154
- * on its way, and a `srcdoc` frame inside a shadow tree written in the HTML the page itself sends, run before the
6155
- * guard is there.
6173
+ * on its way, and a `srcdoc` frame or speculation rules inside a shadow tree written in the HTML the page itself sends,
6174
+ * run before the guard is there.
6156
6175
  * No backslash, `${` or backtick in it: Desktop's copy (`SERVICE_GUARD`, apps/desktop/src/viewer.rs) is the same text.
6157
6176
  */
6158
6177
  var VIEWER_GUARD_SCRIPT = `(function noWebRtc(w) {
@@ -6247,6 +6266,12 @@ var VIEWER_GUARD_SCRIPT = `(function noWebRtc(w) {
6247
6266
  if (doc === null || apply(slice, doc, [0, own.length]) === own) return;
6248
6267
  try { apply(setAttribute, frame, ["srcdoc", own + doc]); } catch (e) { apply(removeAttribute, frame, ["srcdoc"]); }
6249
6268
  };
6269
+ const trim = String.prototype.trim;
6270
+ const drop = w.Element.prototype.remove;
6271
+ const unruled = (script) => {
6272
+ const type = apply(getAttribute, script, ["type"]);
6273
+ if (type !== null && apply(lower, apply(trim, type, []), []) === "speculationrules") apply(drop, script, []);
6274
+ };
6250
6275
  const Observer = w.MutationObserver;
6251
6276
  const observe = Observer.prototype.observe;
6252
6277
  const watch = (root, all) => {
@@ -6255,6 +6280,10 @@ var VIEWER_GUARD_SCRIPT = `(function noWebRtc(w) {
6255
6280
  const frames = apply(all, root, ["iframe[srcdoc]"]);
6256
6281
  for (let i = apply(size, frames, []); i-- > 0;) first(frames[i]);
6257
6282
  } catch (e) {}
6283
+ try {
6284
+ const scripts = apply(all, root, ["script"]);
6285
+ for (let i = apply(size, scripts, []); i-- > 0;) unruled(scripts[i]);
6286
+ } catch (e) {}
6258
6287
  sweep();
6259
6288
  };
6260
6289
  apply(observe, new Observer(scan), [root, { subtree: true, childList: true, attributes: true, attributeFilter: ["srcdoc"] }]);
@@ -6333,7 +6362,7 @@ var VIEWER_GUARD_SCRIPT = `(function noWebRtc(w) {
6333
6362
  } catch (e) {}
6334
6363
  })(window)`;
6335
6364
  /** `VIEWER_GUARD_SCRIPT`'s hash, as a CSP source: a contact's own policy that would refuse it is given it (`allowingViewerGuard`). */
6336
- var VIEWER_GUARD_HASH = "'sha256-DweV0mr/eyHFWESxtsRrzk0i6VjF4GSCokjozAiXkbQ='";
6365
+ var VIEWER_GUARD_HASH = "'sha256-G1zc09L4CUQu4pukd7RlHvzFZthzzsUsbF0WwoT+KBo='";
6337
6366
  /**
6338
6367
  * With the guard, where it is put in the page and not run by the viewer in every frame: frames only from the app's own
6339
6368
  * origin (a `data:` or `blob:` frame would run before the guard could), and Trusted Types, which hands each
@@ -16831,8 +16860,13 @@ var FILE_LIMITS = {
16831
16860
  maxUnfinishedIncoming: 256,
16832
16861
  /** Files one contact sends at once; accepted ones beyond wait their turn. */
16833
16862
  maxActiveIncoming: 3,
16834
- /** An offer nobody answered ends after this long. */
16863
+ /**
16864
+ * An offer nobody answered ends after this long. So does a file taken here and arriving (`active`, not paused) of which
16865
+ * no byte came for this long while a session was open (`ChatFiles.sweep`).
16866
+ */
16835
16867
  offerTtlMs: 6048e5,
16868
+ /** While a session is open, its files are swept (`ChatFiles.sweep`) this often. */
16869
+ sweepEveryMs: 36e5,
16836
16870
  /**
16837
16871
  * No answer while something is outstanding: the sender offers again, which puts both sides back in step. Nothing
16838
16872
  * arriving for a file under way: the receiver says again where it stands.
@@ -17235,6 +17269,8 @@ var ChatFiles = class {
17235
17269
  * every trial of a larger one (a fifth of the rate on a wavering path). Confirmed chunk by chunk, it is what each sends with.
17236
17270
  */
17237
17271
  refill = 0;
17272
+ /** Sweeps while a session is open (`FILE_LIMITS.sweepEveryMs`). */
17273
+ sweeper;
17238
17274
  constructor(host) {
17239
17275
  this.host = host;
17240
17276
  }
@@ -17268,7 +17304,8 @@ var ChatFiles = class {
17268
17304
  stored: record.confirmed,
17269
17305
  acked: record.confirmed,
17270
17306
  checkpointed: record.confirmed,
17271
- writing: Promise.resolve()
17307
+ writing: Promise.resolve(),
17308
+ quietState: record.state
17272
17309
  };
17273
17310
  const replaced = this.entries.get(key(record.direction, record.id));
17274
17311
  if (replaced) this.unended.delete(replaced);
@@ -17320,9 +17357,32 @@ var ChatFiles = class {
17320
17357
  return entry.in && !transferEnded(entry.record) ? Math.max(entry.in.stored, entry.record.confirmed) : entry.record.confirmed;
17321
17358
  }
17322
17359
  changed(entry, progress = false) {
17360
+ if (entry.in && (progress || entry.in.quietState !== entry.record.state)) this.stirred(entry);
17323
17361
  this.track(entry);
17324
17362
  this.host.changed({ ...entry.record }, this.moved(entry), progress);
17325
17363
  }
17364
+ /** An incoming file's idle count starts again: from now while a session is open, from the next one otherwise. */
17365
+ stirred(entry) {
17366
+ const incoming = entry.in;
17367
+ entry.record.idleMs = void 0;
17368
+ incoming.quietState = entry.record.state;
17369
+ incoming.quietFrom = this.attached ? this.now() : void 0;
17370
+ }
17371
+ /**
17372
+ * How long an incoming file went with no byte and no change of state while a session was open: what its record kept,
17373
+ * and this session's stretch. Time with no session (closed, the app gone, either side away) does not count.
17374
+ */
17375
+ idleFor(entry, now) {
17376
+ const from = entry.in.quietFrom;
17377
+ return (entry.record.idleMs ?? 0) + (from === void 0 ? 0 : Math.max(0, now - from));
17378
+ }
17379
+ /** The idle time so far goes into the record, kept with it from now on; the stretch counted here starts again. */
17380
+ foldIdle(entry, now) {
17381
+ const idle = this.idleFor(entry, now);
17382
+ entry.record.idleMs = idle || void 0;
17383
+ entry.in.quietFrom = this.attached ? now : void 0;
17384
+ return idle;
17385
+ }
17326
17386
  /**
17327
17387
  * Keeps `unended` to the entries of this chat not ended. Each change of a record's state is reported (`changed`),
17328
17388
  * so that is where a file that ended leaves it, and one taken or sent again comes back.
@@ -17355,6 +17415,15 @@ var ChatFiles = class {
17355
17415
  t: "pf-abort",
17356
17416
  id
17357
17417
  })) this.unsaid.delete(id);
17418
+ const now = this.now();
17419
+ for (const entry of this.unended) if (entry.in) {
17420
+ entry.record.idleMs = this.idleFor(entry, now) || void 0;
17421
+ entry.in.quietFrom = now;
17422
+ entry.in.quietState = entry.record.state;
17423
+ }
17424
+ clearInterval(this.sweeper);
17425
+ this.sweeper = setInterval(() => this.sweep(), FILE_LIMITS.sweepEveryMs);
17426
+ this.sweeper.unref?.();
17358
17427
  this.sweep();
17359
17428
  for (const entry of this.entries.values()) {
17360
17429
  if (transferEnded(entry.record)) continue;
@@ -17381,6 +17450,9 @@ var ChatFiles = class {
17381
17450
  this.moving.clear();
17382
17451
  this.held.clear();
17383
17452
  this.host.uplink?.leave(this);
17453
+ clearInterval(this.sweeper);
17454
+ this.sweeper = void 0;
17455
+ const now = this.now();
17384
17456
  for (const entry of this.entries.values()) {
17385
17457
  if (entry.out) {
17386
17458
  entry.out.generation++;
@@ -17394,18 +17466,49 @@ var ChatFiles = class {
17394
17466
  clearTimeout(entry.in.ackTimer);
17395
17467
  entry.in.ackTimer = void 0;
17396
17468
  }
17397
- if (entry.in && !transferEnded(entry.record)) this.checkpoint(entry);
17469
+ if (entry.in && !transferEnded(entry.record)) {
17470
+ if (entry.in.quietFrom !== void 0 && this.foldIdle(entry, now) >= FILE_LIMITS.stallMs && entry.record.state === "active") this.changed(entry);
17471
+ this.checkpoint(entry);
17472
+ }
17398
17473
  }
17399
17474
  }
17475
+ /** The app stops: no more sweeps. */
17476
+ stop() {
17477
+ clearInterval(this.sweeper);
17478
+ this.sweeper = void 0;
17479
+ }
17400
17480
  /**
17401
- * Offers ended by their time to live. The host calls it now and then; `attach` does too. A file taken here and waiting
17402
- * its turn ends too once nothing of it arrived in that time: its sender never sent it. Offered again, it is taken
17403
- * again (`retakeAgreed`).
17481
+ * Offers ended by their time to live. The host calls it now and then; `attach` does too, and it runs every
17482
+ * `FILE_LIMITS.sweepEveryMs` while a session is open. A file taken here and waiting its turn ends too once nothing of
17483
+ * it arrived in that time: its sender never sent it. Offered again, it is taken again (`retakeAgreed`). So does one
17484
+ * arriving (`active`) that had no byte and no change of state for that long while a session was open (`idleFor`):
17485
+ * paused there or here, or with no session, it waits as long as it takes (WISP 501 § Consent).
17404
17486
  */
17405
17487
  sweep() {
17406
17488
  const now = this.now();
17489
+ let freed = false;
17407
17490
  for (const entry of this.entries.values()) {
17408
17491
  const { record } = entry;
17492
+ if (record.direction === "in" && record.state === "active") {
17493
+ const incoming = entry.in;
17494
+ if (!this.attached || incoming.verifying || incoming.starting) continue;
17495
+ if (this.idleFor(entry, now) < FILE_LIMITS.offerTtlMs) {
17496
+ if (incoming.quietFrom !== void 0 && now - incoming.quietFrom >= FILE_LIMITS.stallMs) {
17497
+ this.foldIdle(entry, now);
17498
+ this.changed(entry);
17499
+ }
17500
+ continue;
17501
+ }
17502
+ this.discardStored(entry);
17503
+ this.end(entry, "failed", "The offer expired");
17504
+ this.send({
17505
+ t: "pf-refuse",
17506
+ id: record.id,
17507
+ why: "expired"
17508
+ });
17509
+ freed = true;
17510
+ continue;
17511
+ }
17409
17512
  if (![
17410
17513
  "queued",
17411
17514
  "offered",
@@ -17423,6 +17526,7 @@ var ChatFiles = class {
17423
17526
  id: record.id
17424
17527
  });
17425
17528
  }
17529
+ if (freed) this.startNext();
17426
17530
  }
17427
17531
  async sayRoom() {
17428
17532
  const room = await this.host.room?.().catch(() => null);
@@ -28216,9 +28320,18 @@ function acceptUrl(text) {
28216
28320
  if (url.username || url.password) throw new Error("That LNURL carries credentials, which is not allowed");
28217
28321
  return url;
28218
28322
  }
28323
+ /**
28324
+ * Text without what a link leaves out at its end (`linkTail`): a direction mark a right-to-left sentence puts after it,
28325
+ * another character that draws as nothing, an emoji. Taken off one by one: linear however many there are.
28326
+ */
28327
+ function withoutTail(text) {
28328
+ let end = text.length;
28329
+ for (let tail = linkTail(text, end); tail; tail = linkTail(text, end)) end -= tail;
28330
+ return text.slice(0, end);
28331
+ }
28219
28332
  /** Reads what was pasted as a Lightning address or an LNURL; null when it is neither. Throws when it is one, but a bad one. */
28220
28333
  function parseLightningDestination(input) {
28221
- const text = input.trim().replace(/^(lightning:|⚡\s*)/i, "").trim();
28334
+ const text = withoutTail(input.trim()).replace(/^(lightning:|⚡\s*)/i, "").trim();
28222
28335
  if (!text) return null;
28223
28336
  if (LNURL_BECH32.test(text)) {
28224
28337
  let decoded;
@@ -28264,10 +28377,8 @@ function parseLightningDestination(input) {
28264
28377
  function findLightningDestination(text) {
28265
28378
  const match = LIGHTNING_DESTINATION_PATTERN.exec(text);
28266
28379
  if (!match) return null;
28267
- const start = match.index;
28268
- let stop = start + text.slice(start).search(/\s|$/);
28269
- while (stop > start && "),.;:!?".includes(text[stop - 1])) stop--;
28270
- const token = text.slice(start, stop);
28380
+ const start = match.index, end = text.slice(start).search(/\s|$/);
28381
+ const token = linkEnd(text.slice(start, start + end));
28271
28382
  let destination;
28272
28383
  try {
28273
28384
  destination = parseLightningDestination(token);
@@ -29380,7 +29491,8 @@ function seqDate(seq) {
29380
29491
  /**
29381
29492
  * Resolves a did:dht through Pkarr relays: one GET to each, all at once, and the newest packet that
29382
29493
  * checks out wins (the highest sequence number; on a tie, the relay listed first), so a relay holding
29383
- * an older version cannot bring back a removed key or undo a deactivation. Each answer is bounded to
29494
+ * an older version cannot bring back a removed key or undo a deactivation. It waits for every relay
29495
+ * that answers within the fetch's timeout, not only the first. Each answer is bounded to
29384
29496
  * a BEP44 item, its signature checked against the DID's key and its records parsed strictly; a relay
29385
29497
  * that has nothing, fails or serves a packet that does not check out does not count. A deactivated DID
29386
29498
  * resolves (`metadata.deactivated`); everything else that goes wrong throws a `DidDhtError`.
@@ -32098,6 +32210,12 @@ var GROUP_LIMITS = {
32098
32210
  /** Own messages kept for catch-up: count and total ciphertext bytes. */
32099
32211
  outlog: 32,
32100
32212
  outlogBytes: 131072,
32213
+ /**
32214
+ * Own messages past that log that members may not have taken (`GroupState.owed`): count and total ciphertext bytes.
32215
+ * With the log, the 256 a member takes in one answer.
32216
+ */
32217
+ owed: 224,
32218
+ owedBytes: 524288,
32101
32219
  /** Frames waiting for an epoch (or its secret) that has not arrived yet. */
32102
32220
  waiting: 64,
32103
32221
  waitingBytes: 1048576,
@@ -32185,6 +32303,7 @@ var GROUP_TAKEOVER_META_MS = 6e5;
32185
32303
  * hears it, with what the member says live beside it, and the edits its app says again), then
32186
32304
  * `GROUP_LIMITS.messagesPerAuthor` and `messageBytesPerAuthor` per `messageWindowMs`, as a community's `MessagePace`.
32187
32305
  * 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.
32306
+ * Every member refuses the same live frames, so only the author holds them: past its log, it keeps them (`owed`).
32188
32307
  * What another member hands on in its answer to my sync (or what waited for a secret) is counted too, and may run the
32189
32308
  * author's allowance below nothing by one answer's worth (`AUTHOR_OWED`): a catch-up holds more than a burst, and lands
32190
32309
  * 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
@@ -32205,25 +32324,47 @@ var AUTHOR_OWED = {
32205
32324
  bytes: GROUP_LIMITS.relayEditBytes
32206
32325
  }
32207
32326
  };
32327
+ /**
32328
+ * The pace my own frames go at, as members count it, with half their burst and the room left spent on a frame it does
32329
+ * not take (one a member may take still): an edge opening hands my log again, and frames arrive closer together than I
32330
+ * said them, so a frame members refuse is never one this takes.
32331
+ */
32332
+ var OWN_BURST = {
32333
+ frames: GROUP_LIMITS.outlog,
32334
+ bytes: GROUP_LIMITS.outlogBytes
32335
+ };
32208
32336
  var AuthorPace = class {
32209
32337
  owed;
32210
- frames = AUTHOR_BURST.frames;
32211
- bytes = AUTHOR_BURST.bytes;
32338
+ burst;
32339
+ frames;
32340
+ bytes;
32212
32341
  at;
32213
- constructor(owed) {
32342
+ constructor(owed, burst = AUTHOR_BURST) {
32214
32343
  this.owed = owed;
32344
+ this.burst = burst;
32345
+ this.frames = burst.frames;
32346
+ this.bytes = burst.bytes;
32215
32347
  }
32216
- /** `answer`: handed on in an answer to my sync, or waited, so it may run the allowance below nothing (`owed`). */
32217
- take(bytes, now, answer = false) {
32348
+ /**
32349
+ * `answer`: handed on in an answer to my sync, or waited, so it may run the allowance below nothing (`owed`).
32350
+ * `spend`: one not taken still spends what is left of the allowance.
32351
+ */
32352
+ take(bytes, now, answer = false, spend = false) {
32218
32353
  const elapsed = Math.max(0, now - (this.at ?? now)) / GROUP_LIMITS.messageWindowMs;
32219
32354
  this.at = now;
32220
- this.frames = Math.min(AUTHOR_BURST.frames, this.frames + elapsed * GROUP_LIMITS.messagesPerAuthor);
32221
- this.bytes = Math.min(AUTHOR_BURST.bytes, this.bytes + elapsed * GROUP_LIMITS.messageBytesPerAuthor);
32355
+ this.frames = Math.min(this.burst.frames, this.frames + elapsed * GROUP_LIMITS.messagesPerAuthor);
32356
+ this.bytes = Math.min(this.burst.bytes, this.bytes + elapsed * GROUP_LIMITS.messageBytesPerAuthor);
32222
32357
  const floor = answer ? this.owed : {
32223
32358
  frames: 0,
32224
32359
  bytes: 0
32225
32360
  };
32226
- if (this.frames + floor.frames < 1 || this.bytes + floor.bytes < bytes) return false;
32361
+ if (this.frames + floor.frames < 1 || this.bytes + floor.bytes < bytes) {
32362
+ if (spend) {
32363
+ this.frames = Math.max(0, this.frames - 1);
32364
+ this.bytes = Math.max(0, this.bytes - bytes);
32365
+ }
32366
+ return false;
32367
+ }
32227
32368
  this.frames -= 1;
32228
32369
  this.bytes -= bytes;
32229
32370
  return true;
@@ -32536,6 +32677,21 @@ function missingIn(frame, from) {
32536
32677
  };
32537
32678
  }
32538
32679
  /**
32680
+ * Whether a member's sync shows it holds my frame `f`: it has seen up to it, and does not name it missing among all its
32681
+ * gaps, or among the newest it names when they are more than a sync holds (`GROUP_LIMITS.miss`).
32682
+ */
32683
+ function heldIn(frame) {
32684
+ const have = frame.have && typeof frame.have === "object" ? frame.have : {};
32685
+ const miss = frame.miss && typeof frame.miss === "object" ? frame.miss : {};
32686
+ return (f) => {
32687
+ const high = have[f.s]?.[f.e];
32688
+ if (!Number.isSafeInteger(high) || high < f.n) return false;
32689
+ const gaps = miss[f.s]?.[f.e];
32690
+ if (!Array.isArray(gaps)) return true;
32691
+ return !gaps.includes(f.n) && (gaps.length < GROUP_LIMITS.miss || gaps.some((n) => typeof n === "number" && n < f.n));
32692
+ };
32693
+ }
32694
+ /**
32539
32695
  * My own messages and the ones I kept of other members, as one list for a member catching up: each log keeps its own
32540
32696
  * order (mine as I sent them, the others' as they reached me, which no member's clock can change), and the two are
32541
32697
  * merged by the time each frame says, mine first when they say the same. A member whose clock is off moves only
@@ -32626,6 +32782,17 @@ var GroupSession = class {
32626
32782
  namesTaken = /* @__PURE__ */ new Map();
32627
32783
  /** Messages, and apart from them edits, taken per author (`AuthorPace`). In memory only. */
32628
32784
  messagePace = /* @__PURE__ */ new Map();
32785
+ /**
32786
+ * My own frames as members pace them (`OWN_BURST`), and those of mine in `sent` it did not take: one of them that falls
32787
+ * out of `sent` goes to `owed`. Then, per frame of `owed`, the members whose sync showed they hold it. In memory only:
32788
+ * after a start, each owed frame waits for a sync of every member.
32789
+ */
32790
+ ownPace = new AuthorPace({
32791
+ frames: 0,
32792
+ bytes: 0
32793
+ }, OWN_BURST);
32794
+ overPace = /* @__PURE__ */ new Set();
32795
+ owedHeld = /* @__PURE__ */ new Map();
32629
32796
  editPace = /* @__PURE__ */ new Map();
32630
32797
  queue = Promise.resolve();
32631
32798
  /** Metadata frames that name a commit or an epoch I do not have yet, one signed by the admin and one by anyone else (`waitMeta`): tried again when the chain moves. */
@@ -32664,6 +32831,12 @@ var GroupSession = class {
32664
32831
  */
32665
32832
  heard = /* @__PURE__ */ new Map();
32666
32833
  /**
32834
+ * Per author and epoch, the highest number of its own signed frames I did not take at its pace (`AuthorPace`): what
32835
+ * `lacking` names, so the author is asked for it again (it keeps it, `GroupState.owed`). Every member refuses the
32836
+ * same frames of a burst, all past the last one it took, so nothing else shows they are missing. In memory only.
32837
+ */
32838
+ refused = /* @__PURE__ */ new Map();
32839
+ /**
32667
32840
  * Per member: until when what comes over its edge may be its answer to my sync (`syncFrame`), a catch-up and not a
32668
32841
  * message written just now. Each frame of the answer keeps it open: it goes a slice at a time. In memory only.
32669
32842
  */
@@ -32941,7 +33114,11 @@ var GroupSession = class {
32941
33114
  */
32942
33115
  lacking() {
32943
33116
  const out = /* @__PURE__ */ new Map();
32944
- for (const sender of /* @__PURE__ */ new Set([...Object.keys(this.state.seen), ...this.heard.keys()])) {
33117
+ for (const sender of /* @__PURE__ */ new Set([
33118
+ ...Object.keys(this.state.seen),
33119
+ ...this.heard.keys(),
33120
+ ...this.refused.keys()
33121
+ ])) {
32945
33122
  if (sender === this.myKey || !rosterHas(this.roster, sender)) continue;
32946
33123
  const marks = Object.entries(this.missOf(sender)).map(([e, gaps]) => `${e}:${gaps.join(".")}`);
32947
33124
  if (marks.length) out.set(sender, marks.join(","));
@@ -32952,16 +33129,24 @@ var GroupSession = class {
32952
33129
  * What a sync names in `miss` for one sender now: per epoch, the newest `GROUP_LIMITS.miss` numbers that never arrived.
32953
33130
  * And, for an epoch of which none arrived, the newest numbers another member said it has (`heard`): a member back
32954
33131
  * after someone joined, whose author wrote 32 since (all its own answer holds), had nothing below them to ask for.
33132
+ * And, first, the oldest of those past the highest seen up to the highest of its frames I refused at its pace
33133
+ * (`refused`): its answer brings them oldest first, so what is named changes as they come.
32955
33134
  */
32956
33135
  missOf(sender) {
32957
33136
  const out = {};
32958
- const seen = this.state.seen[sender] ?? {};
32959
- for (const [e, entry] of Object.entries(seen)) {
32960
- const gaps = this.gaps(entry);
33137
+ const seen = this.state.seen[sender] ?? {}, refused = this.refused.get(sender);
33138
+ for (const e of /* @__PURE__ */ new Set([...Object.keys(seen), ...[...refused?.keys() ?? []].map(String)])) {
33139
+ const entry = seen[e] ?? {
33140
+ high: -1,
33141
+ window: []
33142
+ }, top = refused?.get(Number(e)) ?? -1;
33143
+ const gaps = [];
33144
+ for (let n = entry.high + 1; n <= top && gaps.length < GROUP_LIMITS.miss; n++) gaps.push(n);
33145
+ if (entry.high >= 0) gaps.push(...this.gaps(entry).slice(0, GROUP_LIMITS.miss - gaps.length));
32961
33146
  if (gaps.length) out[e] = gaps;
32962
33147
  }
32963
33148
  for (const [e, high] of this.heard.get(sender) ?? []) {
32964
- if (seen[e]) continue;
33149
+ if (seen[e] || out[e]) continue;
32965
33150
  const numbers = [];
32966
33151
  for (let n = high; n >= 0 && numbers.length < GROUP_LIMITS.miss; n--) numbers.push(n);
32967
33152
  out[e] = numbers;
@@ -33349,6 +33534,7 @@ var GroupSession = class {
33349
33534
  this.state.statusReason = reason;
33350
33535
  this.state.secrets = {};
33351
33536
  this.state.sent = [];
33537
+ delete this.state.owed;
33352
33538
  delete this.state.unsaid;
33353
33539
  this.state.relay = [];
33354
33540
  if (this.onRows) this.onRows = [];
@@ -33404,6 +33590,7 @@ var GroupSession = class {
33404
33590
  this.state.unsaid = [...this.state.unsaid ?? [], ownKey(frame)];
33405
33591
  const unsend = async (free) => {
33406
33592
  this.state.sent = this.state.sent.filter((f) => f !== frame);
33593
+ this.overPace.delete(ownKey(frame));
33407
33594
  this.state.unsaid = (this.state.unsaid ?? []).filter((key) => key !== ownKey(frame));
33408
33595
  if (free && this.state.seqEpoch === epoch && this.state.seq === n + 1) this.state.seq = n;
33409
33596
  await this.persist().catch(() => {});
@@ -33551,11 +33738,46 @@ var GroupSession = class {
33551
33738
  } : {}
33552
33739
  };
33553
33740
  }
33554
- /** Into my bounded log, for members who missed it. */
33741
+ /** Into my bounded log, for members who missed it; one said past the pace members apply goes on to `owed` when it falls out. */
33555
33742
  logOwn(frame) {
33743
+ if (!this.ownPace.take(frameBytes(frame), this.now(), false, true)) this.overPace.add(ownKey(frame));
33556
33744
  this.state.sent.push(frame);
33557
33745
  let bytes = this.state.sent.reduce((sum, f) => sum + f.c.length, 0);
33558
- while (this.state.sent.length > GROUP_LIMITS.outlog || bytes > GROUP_LIMITS.outlogBytes) bytes -= this.state.sent.shift().c.length;
33746
+ while (this.state.sent.length > GROUP_LIMITS.outlog || bytes > GROUP_LIMITS.outlogBytes) {
33747
+ const out = this.state.sent.shift();
33748
+ bytes -= out.c.length;
33749
+ if (this.overPace.delete(ownKey(out))) this.owe(out);
33750
+ }
33751
+ }
33752
+ owe(frame) {
33753
+ const owed = [...this.state.owed ?? [], frame];
33754
+ let bytes = owed.reduce((sum, f) => sum + f.c.length, 0);
33755
+ while (owed.length > GROUP_LIMITS.owed || bytes > GROUP_LIMITS.owedBytes) {
33756
+ const gone = owed.shift();
33757
+ bytes -= gone.c.length;
33758
+ this.owedHeld.delete(ownKey(gone));
33759
+ }
33760
+ this.state.owed = owed;
33761
+ }
33762
+ /** Drops from `owed` each frame every other member of its epoch has shown, in a sync, that it holds. */
33763
+ owedTaken(from, frame) {
33764
+ if (!this.state.owed?.length) return;
33765
+ const holds = heldIn(frame);
33766
+ const owed = this.state.owed.filter((f) => {
33767
+ const key = ownKey(f);
33768
+ let held = this.owedHeld.get(key);
33769
+ if (holds(f)) {
33770
+ if (!held) this.owedHeld.set(key, held = /* @__PURE__ */ new Set());
33771
+ held.add(from);
33772
+ }
33773
+ const readers = this.state.chain[f.e]?.m;
33774
+ const waits = !!readers && this.others.some((k) => rosterHas(readers, k) && !held?.has(k));
33775
+ if (!waits) this.owedHeld.delete(key);
33776
+ return waits;
33777
+ });
33778
+ if (owed.length === this.state.owed.length) return;
33779
+ this.state.owed = owed;
33780
+ this.persistSoon();
33559
33781
  }
33560
33782
  /**
33561
33783
  * My message `id` was deleted for everyone: its frame, and each copy said again, keep their place in my log (`nextSeq`,
@@ -33566,7 +33788,7 @@ var GroupSession = class {
33566
33788
  * I cannot sign theirs, and its author hands it on. Saved soon, as a community's `forget`; `flush` writes it now.
33567
33789
  */
33568
33790
  forget(id) {
33569
- const sent = this.state.sent.map((f) => !f.c ? f : this.messageIdOf(f) === id ? {
33791
+ const emptied = (f) => !f.c ? f : this.messageIdOf(f) === id ? {
33570
33792
  t: f.t,
33571
33793
  g: f.g,
33572
33794
  e: f.e,
@@ -33577,11 +33799,13 @@ var GroupSession = class {
33577
33799
  c: "",
33578
33800
  sig: "",
33579
33801
  ...f.o ? { o: f.o } : {}
33580
- } : this.unquoted(f, id));
33802
+ } : this.unquoted(f, id);
33803
+ const sent = this.state.sent.map(emptied), owed = this.state.owed?.map(emptied);
33581
33804
  const gone = (f) => this.messageIdOf(f) === id || !!this.quoting(f, id);
33582
33805
  const relay = this.state.relay?.filter((f) => !gone(f)), rows = this.onRows?.filter((f) => !gone(f));
33583
- if (sent.every((f, i) => f === this.state.sent[i]) && relay?.length === this.state.relay?.length && rows?.length === this.onRows?.length) return;
33806
+ if (sent.every((f, i) => f === this.state.sent[i]) && (owed ?? []).every((f, i) => f === this.state.owed[i]) && relay?.length === this.state.relay?.length && rows?.length === this.onRows?.length) return;
33584
33807
  this.state.sent = sent;
33808
+ if (owed) this.state.owed = owed;
33585
33809
  if (relay) this.state.relay = relay;
33586
33810
  if (rows) this.onRows = rows;
33587
33811
  this.persistSoon();
@@ -34194,7 +34418,12 @@ var GroupSession = class {
34194
34418
  delete raw.o;
34195
34419
  delete raw.xs;
34196
34420
  }
34197
- if (!this.paced(this.messagePace, raw.s, frameBytes(raw), relayed && (answer || waited))) return;
34421
+ if (!this.paced(this.messagePace, raw.s, frameBytes(raw), relayed && (answer || waited))) {
34422
+ let byEpoch = this.refused.get(raw.s);
34423
+ if (!byEpoch) this.refused.set(raw.s, byEpoch = /* @__PURE__ */ new Map());
34424
+ byEpoch.set(raw.e, Math.max(byEpoch.get(raw.e) ?? -1, raw.n));
34425
+ return;
34426
+ }
34198
34427
  const first = raw.o === void 0 ? null : readFirstPlace(raw.o, raw.e);
34199
34428
  if (raw.o !== void 0 && !first) return;
34200
34429
  const secret = this.secret(raw.e);
@@ -34449,6 +34678,10 @@ var GroupSession = class {
34449
34678
  for (const e of Object.keys(bySender)) if (Number(e) < this.epoch - GROUP_LIMITS.secrets) delete bySender[e];
34450
34679
  if (!Object.keys(bySender).length) delete this.state.seen[sender];
34451
34680
  }
34681
+ for (const [sender, byEpoch] of this.refused) {
34682
+ for (const e of byEpoch.keys()) if (e < this.epoch - GROUP_LIMITS.secrets) byEpoch.delete(e);
34683
+ if (!byEpoch.size) this.refused.delete(sender);
34684
+ }
34452
34685
  }
34453
34686
  park(from, frame) {
34454
34687
  if (frame.e > this.epoch + GROUP_LIMITS.secrets) return;
@@ -34621,6 +34854,7 @@ var GroupSession = class {
34621
34854
  if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(GROUP_LIMITS.syncAnswers, GROUP_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
34622
34855
  if (!answered.take()) return;
34623
34856
  this.hear(frame);
34857
+ this.owedTaken(from, frame);
34624
34858
  await this.vouch(from, frame.mt);
34625
34859
  if (frame.e > this.epoch) {
34626
34860
  this.syncedEpoch.set(from, frame.e);
@@ -34697,13 +34931,13 @@ var GroupSession = class {
34697
34931
  handOut(to, frames) {
34698
34932
  this.answers.handOut(to, frames);
34699
34933
  }
34700
- /** My own messages a member's sync says it lacks, from my bounded log, for the epochs it was a member of. */
34934
+ /** My own messages a member's sync says it lacks, from my bounded log (and `owed`), for the epochs it was a member of. */
34701
34935
  handOwn(to, frame) {
34702
34936
  for (const sent of this.ownLacked(to, frame)) this.hooks.send(to, sent);
34703
34937
  }
34704
34938
  ownLacked(to, frame) {
34705
34939
  const lacks = missingIn(frame, to);
34706
- return this.state.sent.filter((sent) => this.state.chain[sent.e] && rosterHas(this.state.chain[sent.e].m, to) && lacks(sent) && !this.isRemoved(sent));
34940
+ return [...this.state.owed ?? [], ...this.state.sent].filter((sent) => this.state.chain[sent.e] && rosterHas(this.state.chain[sent.e].m, to) && lacks(sent) && !this.isRemoved(sent));
34707
34941
  }
34708
34942
  /** A frame of a message deleted for everyone (`hooks.removed`, or one of mine `forget` emptied): handed to nobody, its removal is what they get. */
34709
34943
  isRemoved(f) {