@ghostlytools/sdk 1.12.1 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/bitcoinAddress-BbPG0DF7.js +3927 -0
  2. package/dist/bitcoinAddress-BbPG0DF7.js.map +1 -0
  3. package/dist/core.js +496 -2386
  4. package/dist/core.js.map +1 -1
  5. package/dist/index.js +3 -3
  6. package/dist/index.js.map +1 -1
  7. package/dist/{pairedTransports-CkYMAoYN.js → pairedTransports-C0I24YFz.js} +9 -291
  8. package/dist/pairedTransports-C0I24YFz.js.map +1 -0
  9. package/dist/testing.js +2 -2
  10. package/dist/types/browser/src/proofs/contract.d.ts +5 -0
  11. package/dist/types/browser/src/proofs/pkarrRelays.d.ts +4 -0
  12. package/dist/types/browser/src/proofs/verify.d.ts +3 -0
  13. package/dist/types/core/src/chatFiles.d.ts +16 -0
  14. package/dist/types/core/src/clipboardGuard.d.ts +5 -3
  15. package/dist/types/core/src/dhtDelivery.d.ts +20 -0
  16. package/dist/types/core/src/domainProofs.d.ts +2 -1
  17. package/dist/types/core/src/ghostlink.d.ts +30 -0
  18. package/dist/types/core/src/groupCalls.d.ts +56 -0
  19. package/dist/types/core/src/groupCommunity.d.ts +15 -1
  20. package/dist/types/core/src/groupSession.d.ts +15 -1
  21. package/dist/types/core/src/index.d.ts +1 -1
  22. package/dist/types/core/src/relay.d.ts +14 -1
  23. package/dist/types/core/src/statusCards.d.ts +6 -0
  24. package/dist/types/core/src/viewerGuard.d.ts +10 -3
  25. package/dist/{verify-CSo7-43-.js → verify-BoVhjvc_.js} +24 -5
  26. package/dist/verify-BoVhjvc_.js.map +1 -0
  27. package/package.json +1 -1
  28. package/dist/bitcoinAddress-C2MAmcDT.js +0 -1225
  29. package/dist/bitcoinAddress-C2MAmcDT.js.map +0 -1
  30. package/dist/pairedTransports-CkYMAoYN.js.map +0 -1
  31. package/dist/verify-CSo7-43-.js.map +0 -1
package/dist/core.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { o as __toESM } from "./rolldown-runtime-DpEnGzO4.js";
2
- import { $ as openRelayPayload, A as WELL_KNOWN_PATH, B as recordsFromTxt, C as DNS_LABEL, D as DOMAIN_METHODS, E as DOMAIN_MAX_RECORDS, F as encodeDnsQuery, G as wellKnownUrl, H as recordsName, I as isPublicAddress, J as PacketTooLargeError, K as MAX_DNS_PACKET_BYTES, L as nip05RootKey, M as dnsProofName, N as domainTxtRecord, O as DOMAIN_TXT_MAX_BYTES, P as domainWellKnownFile, Q as newerPacket, R as normalizeDomain, S as readManifest, T as DOMAIN_FILE_MAX_BYTES, U as txtValue, V as recordsFromWellKnown, W as validDomainRecord, X as createRelayPayload, Y as RELAY_PAYLOAD_MAX_BYTES, Z as measureRecords, _ as HOLD_LIMITS, a as automaticTransport, at as encodeTxtPacket, b as isHoldUrl, c as irohDescriptor, ct as encrypt, d as relayUrl, dt as tryDecrypt, et as parseRelayPayload, f as relayUrlTooLong, g as HOLD_DATED_BACK_MS, h as HOLD_CAPABILITY, i as TRANSPORTS, it as decodeTxtPacket, j as decodeDnsResponse, k as NIP05_PATH, l as irohRelayUrl, lt as generateEncryptionKey, m as transportOrder, n as RELAY_URL, nt as signRelayPayload, o as checkedDescriptors, ot as readDnsName, p as relayedTransports, q as PKARR_FUTURE_SKEW_MS, r as RELAY_WITH_SECRETS, rt as decodeDnsAnswers, s as dialableIrohRelay, st as decrypt, t as AUTOMATIC_ORDER, tt as readOwnRelayPayload, u as rankTransports, ut as sealedLength, v as HoldKeys, w as DNS_TYPE, x as newMailbox, y as HoldRefusedError, z as parseDomainTxt } from "./pairedTransports-CkYMAoYN.js";
3
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";
4
- import { $ as stripHidden, A as newIdentityBinding, B as IDENTITY_MEMO_SIZE, C as emptyIdentityLedger, D as identityStatement, E as identityRevocationValue, F as IDENTITY_TIMELINE_MAX, G as setPublicKeyFastPath, H as identityFromSeed, I as applyIdentityEvent, J as MAX_NICK_LENGTH, K as sign, L as lastSharedWithMe, M as revokesIdentity, N as signIdentityPresentation, O as identityStatementText, P as verifyIdentityPresentation, Q as sanitizeNick, R as IDENTITY_MEMO_IDLE_MS, S as boundVerifiedIdentity, T as identityRefusal, U as identityFromSeedB64, V as createIdentity, W as publicKeyFromZ32, X as hasVisible, Y as dropLoneJoiners, Z as sanitizeDisplayText, _ as IDENTITY_STATEMENT_PREFIX, a as IDENTITY_CLOCK_SKEW, b as IdentityExchange, c as IDENTITY_MAX_CHECKS_PER_HOUR, d as IDENTITY_MAX_RECEIVED, et as trimEndOf, f as IDENTITY_MAX_VALIDITY, g as IDENTITY_REVOCATION_LABEL, h as IDENTITY_REUSE_CHECK_S, i as IDENTITY_CHECK_UNAVAILABLE, j as receivedIdentityStatus, k as isIdentityBinding, l as IDENTITY_MAX_EVIDENCE, m as IDENTITY_PROVIDER_ID, n as isBitcoinAddress, o as IDENTITY_FRAME_LIMIT, p as IDENTITY_PROOF_CAPABILITY, q as verify, r as IDENTITY_CHALLENGE_WINDOW, s as IDENTITY_FRAME_WINDOW_MS, t as BITCOIN_NETWORKS, tt as unwrapPasted, u as IDENTITY_MAX_FRAME, v as IDENTITY_SUBJECT, w as identityPresentationBytes, x as boundIdentityDisplay, y as IdentityCheckUnavailable, z as IDENTITY_MEMO_MAX } from "./bitcoinAddress-C2MAmcDT.js";
3
+ import { $ as GROUP_BURST_ONE_LINK, $t as IDENTITY_MEMO_SIZE, A as newIdentityBinding, At as PublishFailedError, B as ANSWER_READ_SPACING_MS, Bt as createRelayPayload, C as emptyIdentityLedger, Ct as traceLink, D as identityStatement, Dt as BREAKER_THRESHOLD, E as identityRevocationValue, Et as BREAKER_MAX_MS, F as IDENTITY_TIMELINE_MAX, Ft as withRequestOptions, G as CHAT_RESERVE, Gt as readOwnRelayPayload, H as BACKGROUND_REQUESTS_PER_MINUTE, Ht as newerPacket, I as applyIdentityEvent, It as MAX_DNS_PACKET_BYTES, J as CHAT_WATCH_SHARE, Jt as decodeTxtPacket, K as CHAT_RESERVE_MOST_SHARE, Kt as signRelayPayload, L as lastSharedWithMe, Lt as PKARR_FUTURE_SKEW_MS, M as revokesIdentity, Mt as heldBackError, N as signIdentityPresentation, Nt as isDiscoveryBudgetError, O as identityStatementText, Ot as RelayBreaker, P as verifyIdentityPresentation, Pt as publishedNowhere, Q as GROUP_BURST_MS, Qt as IDENTITY_MEMO_MAX, R as ANSWER_READ_ALLOWANCE, Rt as PacketTooLargeError, S as boundVerifiedIdentity, St as setLinkTraceSink, T as identityRefusal, Tt as BREAKER_BASE_MS, U as BACKGROUND_WHILE_SIGNALING, Ut as openRelayPayload, V as AWAITED_READS, Vt as measureRecords, W as BACKGROUND_WRITES_SHARE, Wt as parseRelayPayload, X as DEPARTED_READS, Xt as readDnsName, Y as DEFAULT_RELAYS, Yt as encodeTxtPacket, Z as FRESH_READ_MS, Zt as IDENTITY_MEMO_IDLE_MS, _ as IDENTITY_STATEMENT_PREFIX, _t as WRITE_FIRST_MS, a as IDENTITY_CLOCK_SKEW, an as sign, at as PREVIOUS_DEFAULT_RELAYS, b as IdentityExchange, bt as readRelayBody, c as IDENTITY_MAX_CHECKS_PER_HOUR, cn as dropLoneJoiners, ct as RelayTransport, d as IDENTITY_MAX_RECEIVED, dn as sanitizeNick, dt as SIGNALING_WINDOW_MS, en as createIdentity, et as GROUP_OVER_PACE_MS, f as IDENTITY_MAX_VALIDITY, fn as stripHidden, ft as SLOW_DEMOTE_MS, g as IDENTITY_REVOCATION_LABEL, gt as WAY_BACK_SHARE, h as IDENTITY_REUSE_CHECK_S, ht as WATCH_SHARE, i as IDENTITY_CHECK_UNAVAILABLE, in as setPublicKeyFastPath, it as HEDGE_MS, j as receivedIdentityStatus, jt as budgetRetryMs, k as isIdentityBinding, kt as DiscoveryBudgetError, l as IDENTITY_MAX_EVIDENCE, ln as hasVisible, lt as RelaysFailedError, m as IDENTITY_PROVIDER_ID, mn as unwrapPasted, mt as TURN_SOURCE_TIMEOUT_MS, n as isBitcoinAddress, nn as identityFromSeedB64, nt as GROUP_SIGNALING_ALLOWANCE_SHARE, o as IDENTITY_FRAME_LIMIT, on as verify, ot as RELAY_REQUESTS_PER_MINUTE, p as IDENTITY_PROOF_CAPABILITY, pn as trimEndOf, pt as SLOW_MS, q as CHAT_RESERVE_PER_CHAT, qt as decodeDnsAnswers, r as IDENTITY_CHALLENGE_WINDOW, rn as publicKeyFromZ32, rt as HEDGE_MISSING_MS, s as IDENTITY_FRAME_WINDOW_MS, sn as MAX_NICK_LENGTH, st as REQUESTS_PER_MINUTE, t as BITCOIN_NETWORKS, tn as identityFromSeed, tt as GROUP_RATION_WINDOW_MS, u as IDENTITY_MAX_FRAME, un as sanitizeDisplayText, ut as SIGNALING_ALLOWANCE_SHARE, v as IDENTITY_SUBJECT, vt as currentRelays, w as identityPresentationBytes, wt as BREAKER_ALL_DOWN_PROBE_MS, x as boundIdentityDisplay, xt as relayUrlProblem, y as IdentityCheckUnavailable, yt as normalizeRelayUrl, z as ANSWER_READ_FIRST_MS, zt as RELAY_PAYLOAD_MAX_BYTES } from "./bitcoinAddress-BbPG0DF7.js";
4
+ import { A as WELL_KNOWN_PATH, B as recordsFromTxt, C as DNS_LABEL, D as DOMAIN_METHODS, E as DOMAIN_MAX_RECORDS, F as encodeDnsQuery, G as wellKnownUrl, H as recordsName, I as isPublicAddress, J as generateEncryptionKey, K as decrypt, L as nip05RootKey, M as dnsProofName, N as domainTxtRecord, O as DOMAIN_TXT_MAX_BYTES, P as domainWellKnownFile, R as normalizeDomain, S as readManifest, T as DOMAIN_FILE_MAX_BYTES, U as txtValue, V as recordsFromWellKnown, W as validDomainRecord, X as tryDecrypt, Y as sealedLength, _ 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 decodeDnsResponse, k as NIP05_PATH, l as irohRelayUrl, m as transportOrder, n as RELAY_URL, o as checkedDescriptors, p as relayedTransports, q as encrypt, r as RELAY_WITH_SECRETS, s as dialableIrohRelay, t as AUTOMATIC_ORDER, u as rankTransports, v as HoldKeys, w as DNS_TYPE, x as newMailbox, y as HoldRefusedError, z as parseDomainTxt } from "./pairedTransports-C0I24YFz.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";
@@ -67,2360 +67,6 @@ function sanitizeAvatar(value) {
67
67
  if (!size || size.width < 1 || size.height < 1 || size.width > 512 || size.height > 512) return;
68
68
  return value;
69
69
  }
70
- // ../core/src/transport.ts
71
- /**
72
- * `transport` with `extra` added to every request's options: a group's edges say `group` so. The optional methods
73
- * stay optional (a caller reads `configure` as "the DHT is reached directly").
74
- */
75
- function withRequestOptions(transport, extra) {
76
- const wrapped = {
77
- publish: (identity, records, options) => transport.publish(identity, records, {
78
- ...options,
79
- ...extra
80
- }),
81
- resolve: (pubKeyZ32, options) => transport.resolve(pubKeyZ32, {
82
- ...options,
83
- ...extra
84
- }),
85
- describe: () => transport.describe()
86
- };
87
- if (transport.publishPayload) wrapped.publishPayload = (pubKeyZ32, payload, options) => transport.publishPayload(pubKeyZ32, payload, {
88
- ...options,
89
- ...extra
90
- });
91
- if (transport.discovery) wrapped.discovery = () => transport.discovery();
92
- if (transport.subscribe) wrapped.subscribe = (listener) => transport.subscribe(listener);
93
- if (transport.networkChanged) wrapped.networkChanged = () => transport.networkChanged();
94
- if (transport.readAnsweredAt) wrapped.readAnsweredAt = (pubKeyZ32) => transport.readAnsweredAt(pubKeyZ32);
95
- if (transport.readHeldBackFor) wrapped.readHeldBackFor = (pubKeyZ32) => transport.readHeldBackFor(pubKeyZ32);
96
- if (transport.publishHeld) wrapped.publishHeld = (pubKeyZ32, options) => transport.publishHeld(pubKeyZ32, {
97
- ...options,
98
- ...extra
99
- });
100
- if (transport.onServerTime) wrapped.onServerTime = (listener) => transport.onServerTime(listener);
101
- if (transport.configure) wrapped.configure = (options) => transport.configure(options);
102
- if (transport.turnRead) wrapped.turnRead = (pubKeyZ32, options) => transport.turnRead(pubKeyZ32, options);
103
- if (transport.turnPut) wrapped.turnPut = (pubKeyZ32, payload, conditions) => transport.turnPut(pubKeyZ32, payload, conditions);
104
- if (transport.turnWarm) wrapped.turnWarm = () => transport.turnWarm();
105
- if (transport.forget) wrapped.forget = (keys) => transport.forget(keys);
106
- return wrapped;
107
- }
108
- /**
109
- * A request the transport held back to stay within a request budget, its own or a relay's rate limit: nothing went
110
- * out, and the same request goes through once the budget frees one, in about `retryInMs`. A wait, never a failure:
111
- * whoever publishes tries again then, and says nothing is wrong meanwhile.
112
- */
113
- var DiscoveryBudgetError = class extends Error {
114
- constructor(retryInMs, message = "Discovery request budget reached; retry shortly") {
115
- const errors = Error;
116
- const limit = errors.stackTraceLimit;
117
- if (typeof limit === "number") errors.stackTraceLimit = 0;
118
- try {
119
- super(message);
120
- } finally {
121
- if (typeof limit === "number") errors.stackTraceLimit = limit;
122
- }
123
- this.code = "discovery-budget";
124
- this.retryInMs = retryInMs;
125
- this.name = "DiscoveryBudgetError";
126
- }
127
- };
128
- /** Whether `error` is a request the budget held back (`DiscoveryBudgetError`), also from another copy of this module. */
129
- function isDiscoveryBudgetError(error) {
130
- return error instanceof DiscoveryBudgetError || typeof error === "object" && error !== null && error.code === "discovery-budget" && typeof error.retryInMs === "number";
131
- }
132
- /**
133
- * A publish no relay took (`RelayTransport`), saying whether one of them may hold the packet all the same. Not
134
- * `mayBeStored` only when every relay was not asked now (its budget, its rate limit, its breaker, its network
135
- * cooldown), answered that it did not take it (a 4xx), or could not be reached before the request went (a refused
136
- * connection or a name that does not resolve, where the runtime says so: Node does, a browser does not), or when there
137
- * is no relay at all. A relay that did not answer in time, dropped the connection, or answered with a server error
138
- * may have stored it. The message is the publish's usual one.
139
- */
140
- var PublishFailedError = class extends Error {
141
- mayBeStored;
142
- code = "publish-failed";
143
- constructor(message, mayBeStored) {
144
- super(message);
145
- this.mayBeStored = mayBeStored;
146
- }
147
- };
148
- /**
149
- * Whether `error` is a publish that went nowhere (`PublishFailedError` with `mayBeStored` false), also from another
150
- * copy of this module. Anything else (a timeout, the DHT's own failure beside the relays', a Desktop's error in
151
- * words) may have left this device.
152
- */
153
- function publishedNowhere(error) {
154
- return typeof error === "object" && error !== null && error.code === "publish-failed" && error.mayBeStored === false;
155
- }
156
- /**
157
- * A publish Ghostly Desktop's Rust relay client held back, as it says it in words (`pkarr_network.rs`
158
- * `publish_failure`: "Publish held back on every relay…; retry in N ms: …"), as the `DiscoveryBudgetError` it is: every
159
- * relay held the packet back for its rate limit, or held it back beside relays left alone for failing, and nothing failed
160
- * now. Anything else is returned as it came.
161
- */
162
- function heldBackError(error) {
163
- const text = typeof error === "string" ? error : error instanceof Error ? error.message : "";
164
- const wait = /^Publish held back [^;]*; retry in (\d+) ms/.exec(text);
165
- return wait ? new DiscoveryBudgetError(Number(wait[1]), text) : error;
166
- }
167
- /** When to try again after the budget held a request back: when it frees one, but never sooner than `min` nor later than `max`. */
168
- function budgetRetryMs(error, min, max) {
169
- return Math.min(max, Math.max(min, Number.isFinite(error.retryInMs) ? error.retryInMs : max));
170
- }
171
- // ../core/src/relayBreaker.ts
172
- /**
173
- * A circuit breaker per Pkarr relay. A relay that failed `threshold` times in a row (no answer, a server error,
174
- * its own rate limit, 429, or an answer too slow to use, `SLOW_MS` in relay.ts) is left alone for a while: a minute the first time, twice as long each time it
175
- * trips again, five minutes at most. When the wait is over, one request goes to it (the probe); an answer
176
- * closes the breaker, a failure opens it again for longer. The relays still closed take its turns meanwhile.
177
- *
178
- * Only what the relay did counts: a request this client held back for its own budget is not a failure, and an
179
- * answer the protocol expects (404, 409, 412, 428) is a relay working as it should.
180
- */
181
- /** Failures in a row that trip a relay's breaker. */
182
- var BREAKER_THRESHOLD = 3;
183
- /** How long a relay is left alone the first time its breaker trips; doubled on each trip in a row. */
184
- var BREAKER_BASE_MS = 6e4;
185
- /** The longest a relay is left alone. */
186
- var BREAKER_MAX_MS = 3e5;
187
- /**
188
- * While every relay is left alone for failing, one of them is asked this often anyway: with nothing else to try, a
189
- * long wait only delays noticing that they answer again (a link stayed down minutes after the relays came back).
190
- */
191
- var BREAKER_ALL_DOWN_PROBE_MS = 15e3;
192
- var RelayBreaker = class {
193
- options;
194
- circuits = /* @__PURE__ */ new Map();
195
- threshold;
196
- baseMs;
197
- maxMs;
198
- allDownProbeMs;
199
- now;
200
- /** When a relay was last asked because every relay was left alone. */
201
- lastAllDownProbe = -Infinity;
202
- constructor(options = {}) {
203
- this.options = options;
204
- this.threshold = options.threshold ?? 3;
205
- this.baseMs = options.baseMs ?? 6e4;
206
- this.maxMs = options.maxMs ?? 3e5;
207
- this.allDownProbeMs = options.allDownProbeMs ?? 15e3;
208
- this.now = options.now ?? Date.now;
209
- }
210
- circuit(relay) {
211
- let circuit = this.circuits.get(relay);
212
- if (!circuit) this.circuits.set(relay, circuit = {
213
- failures: 0,
214
- trips: 0,
215
- openUntil: 0,
216
- probing: false
217
- });
218
- return circuit;
219
- }
220
- /** How long the relay is still left alone, in ms; 0 when a request may go (closed, or its probe is due). */
221
- blockedFor(relay) {
222
- const circuit = this.circuits.get(relay);
223
- if (!circuit || circuit.openUntil === 0) return 0;
224
- const left = circuit.openUntil - this.now();
225
- if (left > 0) return left;
226
- return circuit.probing ? this.baseMs : 0;
227
- }
228
- /** Why the relay is left alone, while it is: its rate limit or failures. */
229
- blockedKind(relay) {
230
- return this.blockedFor(relay) > 0 ? this.circuits.get(relay)?.kind : void 0;
231
- }
232
- /** A request is going to the relay now: its probe, when the wait is over. Call only when `blockedFor` is 0. */
233
- begin(relay) {
234
- const circuit = this.circuits.get(relay);
235
- if (circuit && circuit.openUntil !== 0 && circuit.openUntil <= this.now()) circuit.probing = true;
236
- }
237
- /**
238
- * When every relay of `relays` is left alone for failing (none for its rate limit, none with its probe due or out),
239
- * the one whose wait ends first may be asked now, once every `BREAKER_ALL_DOWN_PROBE_MS`. Returns it, or null. The
240
- * caller marks the request with `beginAllDown` when it really goes (a request its budget holds back is no probe).
241
- */
242
- allDownProbe(relays) {
243
- const now = this.now();
244
- if (!relays.length || now - this.lastAllDownProbe < this.allDownProbeMs) return null;
245
- let pick = null, soonest = Infinity;
246
- for (const relay of relays) {
247
- const circuit = this.circuits.get(relay);
248
- if (!circuit || circuit.openUntil <= now || circuit.probing || circuit.kind !== "error") return null;
249
- if (circuit.openUntil < soonest) {
250
- soonest = circuit.openUntil;
251
- pick = relay;
252
- }
253
- }
254
- return pick;
255
- }
256
- /** The probe `allDownProbe` named is going now: its answer closes the breaker, a failure trips it again. */
257
- beginAllDown(relay) {
258
- const circuit = this.circuits.get(relay);
259
- if (circuit) circuit.probing = true;
260
- this.lastAllDownProbe = this.now();
261
- }
262
- /**
263
- * A request that went to the relay was dropped before it answered, by this client (another relay answered first), or
264
- * its answer says nothing either way: a probe among them is no longer out, and the next request may probe again.
265
- */
266
- cancel(relay) {
267
- const circuit = this.circuits.get(relay);
268
- if (circuit) circuit.probing = false;
269
- }
270
- /**
271
- * The relay answered: whatever was wrong is over. When it was left alone and so was every other relay of `relays`
272
- * (by default those that failed), for failing, the outage is over for them too: they are asked again now, not at the
273
- * end of a wait of up to `BREAKER_MAX_MS` (two clients whose probes another relay answered each would share none
274
- * for minutes). Their trips stay: one really down trips again at once, for longer.
275
- */
276
- success(relay, relays = [...this.circuits.keys()]) {
277
- const circuit = this.circuits.get(relay);
278
- if (!circuit) return;
279
- const recovered = circuit.openUntil !== 0;
280
- this.circuits.delete(relay);
281
- if (!recovered) return;
282
- const others = relays.filter((r) => r !== relay).map((r) => this.circuits.get(r));
283
- if (others.length && others.every((other) => !!other && other.openUntil !== 0 && other.kind === "error")) {
284
- const now = this.now();
285
- for (const other of others) other.openUntil = Math.min(other.openUntil, now);
286
- }
287
- this.options.onRecover?.(relay);
288
- }
289
- /**
290
- * The relay failed a request; a probe that fails trips it again at once. While it is left alone and no probe is out,
291
- * a failure is a request sent before it tripped (a start burst): already counted in, it trips nothing again.
292
- */
293
- failure(relay, kind, reason) {
294
- const circuit = this.circuit(relay);
295
- if (!circuit.probing && circuit.openUntil > this.now()) return;
296
- circuit.failures++;
297
- circuit.kind = kind;
298
- circuit.reason = reason;
299
- if (circuit.probing || circuit.failures >= this.threshold) this.trip(relay, circuit);
300
- }
301
- trip(relay, circuit) {
302
- this.lastAllDownProbe = Math.max(this.lastAllDownProbe, this.now());
303
- const forMs = Math.min(this.baseMs * 2 ** circuit.trips, this.maxMs);
304
- circuit.openUntil = this.now() + forMs;
305
- circuit.trips++;
306
- circuit.failures = 0;
307
- circuit.probing = false;
308
- this.options.onTrip?.(relay, circuit.reason ?? "", forMs);
309
- }
310
- /** How long until a relay left alone is asked again: its wait, or the next probe while every relay of `relays` is left alone. */
311
- askedAgainIn(relay, relays) {
312
- const wait = this.blockedFor(relay);
313
- if (!relays.every((r) => this.blockedFor(r) > 0)) return wait;
314
- return Math.min(wait, Math.max(0, this.lastAllDownProbe + this.allDownProbeMs - this.now()));
315
- }
316
- /** A new network: every relay starts fresh. */
317
- reset() {
318
- this.circuits.clear();
319
- this.lastAllDownProbe = -Infinity;
320
- }
321
- /**
322
- * Each relay's health, in the order given. While every one is left alone for failing, `until` is the next probe
323
- * (`allDownProbe`, every 15 s), whose answer ends the wait of them all: said as the end of each one's wait, a daemon's
324
- * `status` and the connection panel named a time up to 5 minutes after the relays were seen answering again.
325
- */
326
- health(relays) {
327
- const allDown = relays.length > 0 && relays.every((relay) => this.blockedFor(relay) > 0 && this.circuits.get(relay)?.kind === "error");
328
- return relays.map((relay) => {
329
- const circuit = this.circuits.get(relay);
330
- if (!circuit || circuit.openUntil === 0 || this.blockedFor(relay) === 0) return {
331
- relay,
332
- state: "ok"
333
- };
334
- const until = allDown ? this.now() + this.askedAgainIn(relay, relays) : Math.max(circuit.openUntil, this.now());
335
- return {
336
- relay,
337
- state: circuit.kind === "throttled" ? "throttled" : "failing",
338
- until,
339
- ...circuit.reason && { reason: circuit.reason }
340
- };
341
- });
342
- }
343
- };
344
- // ../core/src/linkTrace.ts
345
- var sink = null;
346
- /** Where the lines go besides the console; `null` removes it. */
347
- function setLinkTraceSink(next) {
348
- sink = next;
349
- }
350
- function traceLink(me, step, detail) {
351
- const console_ = globalThis.__ghostlyLinkTrace;
352
- if (!console_ && !sink) return;
353
- const line = JSON.stringify({
354
- t: Date.now(),
355
- me: me.slice(0, 6),
356
- step,
357
- ...detail
358
- });
359
- if (console_) console.debug(`[ghostly:link] ${line}`);
360
- try {
361
- sink?.(line);
362
- } catch {}
363
- }
364
- // ../core/src/relay.ts
365
- var asker = (options, write) => ({
366
- background: !!options.background,
367
- group: !!options.group,
368
- urgent: !!options.urgent,
369
- door: !!options.door,
370
- write,
371
- signal: !!options.signal,
372
- watch: !!options.watch && !write,
373
- watchWrite: !!options.watch && write,
374
- departed: !!options.departed && !write,
375
- awaited: !!options.awaited && !write,
376
- resume: !!options.resume && !write,
377
- back: !!options.back
378
- });
379
- /** A 1:1 chat's request: neither a group's nor a background one. */
380
- var isChat = (who) => !who.background && !who.group;
381
- /** A 1:1 chat's offer or answer, or its read for the answer to its offer: it may use the allowance (`SIGNALING_ALLOWANCE_SHARE`). */
382
- var isChatSignal = (who) => who.signal && isChat(who);
383
- /** A 1:1 chat's read of a contact that just went away: a few may use the chat's allowance (`DEPARTED_READS`). */
384
- var isDepartedRead = (who) => who.departed && isChat(who);
385
- /** 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`). */
386
- var isAwaitedRead = (who) => who.awaited && isChat(who);
387
- /** A group's edge looking fast for a signal (`GROUP_BURST_MS`). */
388
- var isGroupUrgentRead = (who) => who.group && who.urgent && !who.write && !who.background;
389
- /**
390
- * A group edge's read for a member that went away from a live session and has not shown itself back (`WATCH_SHARE`).
391
- * A 1:1 chat's is not one: chats have their own reserve (`CHAT_RESERVE`), and a chat watching its contact must not wait
392
- * behind the edges that watch the same contact.
393
- */
394
- var isWatch = (who) => who.watch && who.group && !who.write;
395
- /** A 1:1 chat's read of a contact that went away from a live session and has not shown itself back (`CHAT_WATCH_SHARE`). */
396
- var isChatWatch = (who) => who.watch && isChat(who);
397
- /**
398
- * A group edge's request for a member that may be back: it may use the groups' allowance (`GROUP_SIGNALING_ALLOWANCE_SHARE`).
399
- * So may its reads of a member that was live when this app last ran, until one is answered (`resume`): its offer waits on them.
400
- */
401
- var isGroupSignal = (who) => who.group && !who.background && (who.signal || isWatch(who) || who.watchWrite || who.resume);
402
- /** A group edge's read for the signal it waits for, the answer to its offer (`signal`): first on the floor (`ANSWER_READ_FIRST_MS`). */
403
- var isGroupAnswerRead = (who) => isGroupSignal(who) && who.signal && !who.write;
404
- /** Such a read, as the budget weighs it (`ANSWER_READ_FIRST_MS`). */
405
- var ANSWER_READER = {
406
- background: false,
407
- group: true,
408
- urgent: true,
409
- door: false,
410
- write: false,
411
- signal: true,
412
- watch: false,
413
- watchWrite: false,
414
- departed: false,
415
- awaited: false,
416
- resume: false,
417
- back: false
418
- };
419
- /** A community member's way back to its group while it has no edge up: it may use its own allowance (`WAY_BACK_SHARE`). */
420
- var isWayBack = (who) => who.back && who.group && !who.background;
421
- /** Watch reads that the same other limits hold take turns together: urgent or not, background or not; the chats' on their own. */
422
- var watchLane = (who) => isChat(who) ? "chat" : `${+who.urgent}${+who.background}`;
423
- /** A group's read that is not a background one: an edge's, a private group's knock poll (`GROUP_RATION_WINDOW_MS`). */
424
- var isGroupRead = (who) => who.group && !who.write && !who.background;
425
- /**
426
- * A read that takes its turn per key with the others (`READ_TURN_MS`): a background one, and a 1:1 chat's at any pace.
427
- * Not a community door's bell.
428
- */
429
- var isTurnRead = (who) => !who.write && !who.door && (who.background || !who.group);
430
- /** A write that goes first once the budget frees a request (see `WRITE_FIRST_MS`): a chat's or a group's, never a background one. */
431
- var firstWriter = (who) => !who.write || who.background ? null : who.group ? "group" : "chat";
432
- /** A key's turn neither asked nor read in the last minute: it is dropped, and asking again starts a new one (`TURNS_PRUNE_MS`). */
433
- var staleTurn = (turn, now) => now - Math.max(turn.askedAt, turn.servedAt) >= 6e4;
434
- /**
435
- * The times of `list` (oldest first) within the last `ms`. One dated after now, the device clock gone back since (an NTP
436
- * step, a clock that ran ahead fixed by hand), counts as of now: as just spent, not for as long as the clock went back.
437
- * Counted as they were, an hour's step back held every background read for 59 minutes, and a daemon with 50 contacts
438
- * away read 4 of them in the next 15 (bug hunt, 2026-11-07).
439
- * `list` itself when every time is already so (the usual case): `heldFor` reads eight lists at each request the budget
440
- * holds, and copying each twice was a third of the CPU of a daemon whose 200 contacts were away.
441
- */
442
- var within$1 = (list, now, ms) => {
443
- let kept = true;
444
- for (const at of list) if (at > now || now - at >= ms) {
445
- kept = false;
446
- break;
447
- }
448
- return kept ? list : list.map((at) => Math.min(at, now)).filter((at) => now - at < ms);
449
- };
450
- /**
451
- * Keys and when each was last set, those of the last minute: how many and the latest, without walking them all (the
452
- * chats that need a relay, `chatNeeds`). Each is set at the time it is set, so the sets come oldest first; a clock
453
- * gone back makes the later ones as of now.
454
- */
455
- var RecentKeys = class {
456
- at = /* @__PURE__ */ new Map();
457
- /** Every set, oldest first, from `head`; one a later set or a delete replaced is skipped. */
458
- order = [];
459
- head = 0;
460
- set(key, now) {
461
- this.prune(now);
462
- this.at.set(key, now);
463
- this.order.push([key, now]);
464
- }
465
- delete(key) {
466
- this.at.delete(key);
467
- }
468
- size(now) {
469
- this.prune(now);
470
- return this.at.size;
471
- }
472
- /** When the key set last was, -Infinity with none in the last minute. */
473
- latest(now) {
474
- this.prune(now);
475
- while (this.order.length > this.head) {
476
- const [key, at] = this.order[this.order.length - 1];
477
- if (this.at.get(key) === at) return at;
478
- this.order.pop();
479
- }
480
- return -Infinity;
481
- }
482
- /** The keys set in the last minute, oldest first. */
483
- *entries(now) {
484
- this.prune(now);
485
- for (let i = this.head; i < this.order.length; i++) if (this.at.get(this.order[i][0]) === this.order[i][1]) yield this.order[i];
486
- }
487
- /** Drops the keys set a minute ago or more. */
488
- prune(now) {
489
- if (this.order.length > this.head && now < this.order[this.order.length - 1][1]) {
490
- for (const [key, at] of this.at) this.at.set(key, Math.min(at, now));
491
- this.order = [...this.at].sort((a, b) => a[1] - b[1]);
492
- this.head = 0;
493
- }
494
- while (this.head < this.order.length) {
495
- const [key, at] = this.order[this.head];
496
- if (this.at.get(key) === at) {
497
- if (now - at < 6e4) break;
498
- this.at.delete(key);
499
- }
500
- this.head++;
501
- }
502
- if (this.head > 64 && this.head * 2 > this.order.length) {
503
- this.order = this.order.slice(this.head);
504
- this.head = 0;
505
- }
506
- }
507
- };
508
- /**
509
- * Public Pkarr relays. They are generic Pkarr infrastructure (an HTTP bridge to
510
- * the Mainline DHT), not a Ghostly backend: they only ever see signed,
511
- * encrypted packets. Every client uses this list: the browser clients read and
512
- * write through it, Ghostly Desktop writes to it (so browser contacts see its
513
- * packets) and reads from it only when "Also use Pkarr relays" is on. Adding a
514
- * relay is one line here; see docs/RELAYS.md for how one is chosen.
515
- */
516
- var DEFAULT_RELAYS = [
517
- "https://pkarr.pubky.org",
518
- "https://pkarr.pubky.app",
519
- "https://pkarr.miguelmedeiros.dev"
520
- ];
521
- /**
522
- * Relay lists that were the defaults once: a profile that still has one gets today's defaults. When a relay
523
- * joins `DEFAULT_RELAYS`, the list as it was goes here, so profiles on the old defaults move with it.
524
- */
525
- var PREVIOUS_DEFAULT_RELAYS = [["https://pkarr.pubky.org", "https://pkarr.pubky.app"]];
526
- /** The defaults for `relays` when it is one of the old default lists, `relays` itself otherwise. */
527
- function currentRelays(relays) {
528
- const same = (a, b) => a.length === b.length && a.every((relay, i) => relay === b[i]);
529
- return PREVIOUS_DEFAULT_RELAYS.some((old) => same(old, relays)) ? [...DEFAULT_RELAYS] : relays;
530
- }
531
- /**
532
- * Requests this client allows itself per relay and minute. Relays limit by IP
533
- * (120 a minute when this was written) and one address is often shared by
534
- * several peers: two browser profiles, a tab and an extension, a household.
535
- */
536
- var REQUESTS_PER_MINUTE = 30;
537
- /**
538
- * Of those, what background requests (`{ background: true }`: periodic looks at shared records, as a
539
- * community group's hub makes) may spend, counted on their own: the rest is kept for links, whose
540
- * signaling cannot wait, and a burst of signaling does not hold the background ones back afterwards.
541
- */
542
- var BACKGROUND_REQUESTS_PER_MINUTE = 20;
543
- /**
544
- * Of the background share, what background writes may spend in a minute on a relay (10 of the 20): the rest is kept
545
- * for background reads. Those writes are mostly the upkeep of chats whose contacts are away (the link's heartbeat, the
546
- * DHT floor's keep-alive, the capability record), about one a minute for every two chats. A profile with 200 such chats
547
- * spent the share on them, and on one relay 147 of its 200 contacts were not read once in 25 minutes: a contact back
548
- * then went unnoticed (bug hunt, 2026-11-01). Upkeep held back goes when a request of this share frees.
549
- */
550
- var BACKGROUND_WRITES_SHARE = 1 / 2;
551
- /**
552
- * A link's write the budget refused (its presence, its offer, its answer) goes first when the minute
553
- * frees a request: reads on that relay wait this long after the refusal. A link that polls fast for a
554
- * peer while its offer waits would otherwise take every request the minute frees, and the offer (the
555
- * only thing that peer is waiting for) would go out only once the polling slowed down, half a minute later.
556
- */
557
- var WRITE_FIRST_MS = 5e3;
558
- /**
559
- * Once a 1:1 chat needs the relays (the budget refused one of its requests there, or it read urgently anywhere: it polls
560
- * fast for a signal due any moment), group requests and background ones leave it the last this many of each minute (more
561
- * for several chats, `CHAT_RESERVE_PER_CHAT`), for a minute. Groups that spend the whole budget spend it over the minute, so the chat then takes the next request that frees, within
562
- * seconds, and has room for what follows (the receipt). Waiting for a refusal was too late when a contact went away
563
- * from a chat and from groups at once: the chat and the groups' edges all watched fast for it, the edges spent both
564
- * relays' minute in 40 s, and the chat read the contact's offer half a minute late (2026-09-27). A chat with nothing
565
- * to wait for leaves groups the whole budget: a community door alone costs about 22 requests a minute, and a reserve
566
- * kept for any chat starved a new group's edges. The reserve is per chat: a chat that reads its contact at a slow pace
567
- * again (it is live) gives its part back at once. Kept for the minute, a daemon back after a restart with its chats
568
- * live in 18 s held a group's edge that had just missed its read for 48 s more (bug hunt r6a, 2026-09-29).
569
- */
570
- var CHAT_RESERVE = 10;
571
- /**
572
- * …and more while several chats need the relays at once: this many requests each (a read, an offer or answer, the read
573
- * for the answer to it), up to `CHAT_RESERVE_MOST_SHARE` of the minute. Background requests leave it too, not the
574
- * groups' alone: the looks of chats whose contacts are not there, and their presence (upkeep, `LinkSession`). An app
575
- * opened while 30 of its 50 chats' contacts were online spent both relays' minute in its first second, on the presence
576
- * of the chats whose contacts were long gone, its groups' records and every chat's first read: 12 of the 30 offers and
577
- * answers went out, no read for an answer could, and 0 of the 30 chats were live 60 s after the start (bug hunt,
578
- * 2026-10-13).
579
- */
580
- var CHAT_RESERVE_PER_CHAT = 3;
581
- /** The most of a relay's minute the chats' reserve takes, however many chats need it: the rest stays for everything else. */
582
- var CHAT_RESERVE_MOST_SHARE = 5 / 6;
583
- /**
584
- * A 1:1 chat's signaling (a new offer or answer, and its reads for the answer to its offer, `signal`) may go over a
585
- * relay's minute by this fraction of it: 6 on a relay of 30, 12 on one of 60, 1 on a relay of 5 (relay.pkarr.org and
586
- * pkarr.miguelmedeiros.dev allow 10), and never more than that in any minute; its reads leave the last of those to a write. Everything else still stops at
587
- * the limit. The minute before a chat leaves DHT only can be spent by then (the pairing, the texts over the DHT), and
588
- * its offer or answer, the one thing the contact waits for, then waited 40 s for requests to age out while the
589
- * contact's attempt gave up: the matrix's extension chat stayed "On DHT · retrying live" 46 times in 120 (2026-09-30).
590
- */
591
- var SIGNALING_ALLOWANCE_SHARE = 1 / 5;
592
- /**
593
- * A 1:1 chat's reads of a contact that went away from a live session, in their first seconds (`departed`,
594
- * `DEPARTED_READ_MS` in link.ts), may go over a relay's minute within the chat's allowance (`SIGNALING_ALLOWANCE_SHARE`):
595
- * at most this many of each contact's in a minute, every relay together, leaving the last of the allowance to an offer or
596
- * answer. Their fast poll reads every 2 s, on the relays in turn: 6 cover 12 s from the goodbye, by when an app that
597
- * restarts has its offer out (2.5 to 10 s in the lab of #1441), and add at most 3 to a relay's minute. They wait for no
598
- * write the minute refused: that write cannot go before the minute frees anyway. A daemon restarted 20 s after its last
599
- * restart found its contact's minute spent on both relays: every read of it was held back, the offer it published as it
600
- * came up was never read, and the chat came back only through the race's DHT dial, 8 s on (2026-10-07).
601
- */
602
- var DEPARTED_READS = 6;
603
- /**
604
- * A 1:1 chat's reads of an invite this side made, while its joiner is due and has not shown (`awaited`, `AWAITING_PEER_MS`
605
- * in link.ts), may go over a relay's minute within the chat's allowance (`SIGNALING_ALLOWANCE_SHARE`) the same way: at
606
- * most this many in a minute, every invite and every relay together. And while one asked in the last minute, the departed
607
- * reads leave them half of that on each relay: the last `AWAITED_READS / 2` of the allowance's reads (`DEPARTED_READS`
608
- * then take at most 3 on a relay of 30, against 5). Read every 2 to 4 s, they cover the seconds in which a joiner that
609
- * opened the link at once knocks. Within the chats' allowance, they add nothing to what a relay may see in a minute
610
- * (`WAY_BACK_SHARE`): 36 at most from the chats on a relay of 30, none past 5 on a relay of 5. An inviter pairing one joiner after
611
- * another on relays of 30 spent the minute on both 12 s in (two pairings, about 15 requests a relay each), the departed
612
- * reads of the contact that had just left took the allowance, and the third invite's key was read once, then not until
613
- * the minute freed: the joiner's knock 48 s late, and join to live in 60 s, against 2.6 and 4.6 s (CLI lab, 2026-11-07).
614
- * Not this many per invite: a web profile with 150 chats added from old sessions, each an invite awaited from that start,
615
- * had their reads take the whole allowance at every refill, and a live contact's reads after a reload went once a
616
- * minute: the chat came back in 2 to 7 min, against 41 to 69 s before (2026-11-07).
617
- */
618
- var AWAITED_READS = 4;
619
- /**
620
- * A group edge's requests for a member that may be back may go over a relay's minute by this fraction of it (4 on a
621
- * relay of 30, 8 on one of 60, none on a relay of 5): its reads of a member that went away and its packet
622
- * written meanwhile, which that member reads first when it is back (`watch`), its offer or answer, and its reads for
623
- * the answer to its offer (`signal`). Its reads leave the last of those to a write and go
624
- * one at a time (`GROUP_OVER_PACE_MS`), so the allowance lasts until the member is back, and the read that finds its
625
- * offer still has the answer behind it. Less than a chat's (`SIGNALING_ALLOWANCE_SHARE`), which keeps room past the
626
- * groups'. A private group's admin that had just let members in and seen them restart had spent its minute in 30 s;
627
- * a member back then, with no other member online to carry its offer, had it read only when the minute freed: 18 to
628
- * 42 s later, one round in four of the member-back runs (2026-10-03).
629
- *
630
- * It is also theirs whatever the chats do: while the edges' signaling has had fewer than that many requests on a relay
631
- * in the last minute, neither the limit, nor the chats' own allowance past it, nor their reserve (`CHAT_RESERVE`) holds
632
- * it back. Its reads leave the last of it to a write there too. A daemon with 30 chats and 5 groups, back after a
633
- * restart, had its chats signal for 332 s: they kept their reserve, their allowance took what the limit left, and the
634
- * edges got nothing. By then their attempts had failed and backed off, and the group members were reachable again 13
635
- * to 25 min after the restart (CLI bug hunt, 2026-10-08).
636
- *
637
- * An edge back after a restart reads its member before it offers (`resume`), and those reads are on the floor too: as
638
- * plain reads, they waited behind the chats as before, and the edges never got to signal. The same daemon had its first
639
- * member back 71 to 367 s after the restart, and group texts sent in its first minutes were read 2 to 7 min late (CLI
640
- * bug hunt, 2026-10-14).
641
- */
642
- var GROUP_SIGNALING_ALLOWANCE_SHARE = 2 / 15;
643
- /**
644
- * A community member's way back to its group while it has no edge up (its readings of the beacon, its request in a hub's
645
- * lobby: `back`) may go past everything that holds a group's request back by this fraction of a relay's minute (6 on a
646
- * relay of 30, 12 on one of 60, 1 on a relay of 5), its own: not the edges' (`GROUP_SIGNALING_ALLOWANCE_SHARE`),
647
- * and what it takes counts there alone, so it shortens no one else's minute or allowance. Its reads leave the last of it
648
- * to a write. A web app opened with 30 chats whose contacts were online and 15 groups whose edges all offered at once:
649
- * the edges' offers and reads for their members spent the groups' allowance in its first second, the chats' reserve
650
- * and their offers still waiting held the rest, and its 5 communities read their beacon (who the hubs are) a minute
651
- * later, or not in 3 minutes; 2 of them were not back in 6 (bug hunt, 2026-10-14). Sized for 5 communities' way back
652
- * in the first minute on the default relays: a reading of each beacon, and a read and a write in a hub's lobby (a write
653
- * goes to every relay). A member asks it only while it has no edge up in that community.
654
- *
655
- * At worst a relay then sees, in one minute, its limit, the chats' allowance past it, the edges', this one and the edges'
656
- * answer reads' (`ANSWER_READ_ALLOWANCE`): 49 on a relay of 30 (pkarr.pubky.org allows 50 an address,
657
- * `x-ratelimit-limit`), 95 on pkarr.pubky.app's 60 (it allows 1000) and 7 on a relay of 5 (relay.pkarr.org and
658
- * pkarr.miguelmedeiros.dev allow 10). A share raised past those limits gets 429s (docs/TRANSPORTS.md, "The default list").
659
- */
660
- var WAY_BACK_SHARE = 1 / 5;
661
- /** Past the limit, a group's reads within its allowance go no more often than this on a relay. */
662
- var GROUP_OVER_PACE_MS = 5e3;
663
- /**
664
- * A group edge's read for the answer to its offer (`signal`) that the budget refused on a relay goes first there among
665
- * the groups' signaling (`GROUP_SIGNALING_ALLOWANCE_SHARE`): the edges' offers and answers, their reads back after a
666
- * restart (`resume`) and their watch reads wait this long after the refusal, while it is not read, for what it could
667
- * take then. It waits for no group write the budget refused (`WRITE_FIRST_MS`), nor for the turn of a group's key that
668
- * is not read for an answer (`GROUP_RATION_WINDOW_MS`), and the groups' other urgent reads do not spend its burst
669
- * (`GROUP_BURST_MS`): it has one of its own. Of everything on the floor it is the closest to a member back: the
670
- * offer is out, and the member has often answered already. A daemon back after a restart had its edges' offers and
671
- * reads back spend the floor in its first seconds, and read the answers to offers it had out at 0.4 s only once the
672
- * minute freed: 66 to 97 s on, and an answer read that late often found the member's attempt over (agents#971, CLI lab,
673
- * 2026-11-03).
674
- */
675
- var ANSWER_READ_FIRST_MS = 5e3;
676
- /**
677
- * A group edge's read for the answer to its offer (`signal`) that everything else holds back (the limit, the groups'
678
- * allowance, the chats' reserve, a write the budget refused) goes within an allowance of its own on that relay: this
679
- * many in a minute, never more than the groups' allowance there (`GROUP_SIGNALING_ALLOWANCE_SHARE`: none on a relay of
680
- * 5), one at a time (`ANSWER_READ_SPACING_MS`). What it takes counts there alone, as a way back's (`WAY_BACK_SHARE`),
681
- * so it shortens no one else's minute. Going first on the floor (`ANSWER_READ_FIRST_MS`) was not enough: a daemon back
682
- * after a restart had its edges' reads back and offers spend its whole minute on each relay 6 s on, before any member
683
- * had answered (7 to 19 s on), and read the answers when the minute freed: from an answer going out to the hub
684
- * reading it, 60 to 66 s at the median in each of four runs. With this allowance, 2 to 60 s (14 s over the four runs,
685
- * against 63 s), and all 18 members were back 77 to 108 s on, against 102 to 153 s (agents#971, CLI lab, 2026-11-05).
686
- *
687
- * At worst it adds 3 to a relay's minute: 49 on a relay of 30 (pkarr.pubky.org allows 50), 95 on pkarr.pubky.app's 60,
688
- * and nothing on a relay of 5.
689
- */
690
- var ANSWER_READ_ALLOWANCE = 3;
691
- /** Within that allowance, an edge's read for its answer goes no more often than this on a relay (`ANSWER_READ_ALLOWANCE`). */
692
- var ANSWER_READ_SPACING_MS = 2e4;
693
- /**
694
- * Groups' urgent reads (their edges looking fast for a signal) take at most a quarter of a relay's minute in any this
695
- * long, so that they never spend it in a burst. An app back after a restart has every edge offering and looking fast at
696
- * once; the members at the other end answer only once they notice its old sessions went (about 20 s with
697
- * node-datachannel). On the default relays the edges spent the groups' share of the minute in those seconds, and read
698
- * nothing for 40 s more: a private group's edges were live again 75 to 110 s after a restart (bug hunt r5a, 2026-09-29).
699
- */
700
- var GROUP_BURST_MS = 15e3;
701
- /** …and never fewer than one link polling fast (every 2 s) reads in that time: one edge alone is never held back. */
702
- var GROUP_BURST_ONE_LINK = 8;
703
- /**
704
- * A group's edges' reads of members that went away from a live session and have not shown themselves back (`watch`: a
705
- * link looks for them closely for two minutes, `WATCH_PEER_MS`) take at most this share of a relay's requests, whatever
706
- * their number, spread over the minute (`GROUP_RATION_WINDOW_MS`): 2 in any 10 s on a relay of 30. Under it, the key
707
- * read longest ago goes first. A member alone in a private group whose three other members left at once watched each of
708
- * them every 2 s: those reads and the admin's knock poll spent both relays' minute, the member back first had its offer
709
- * read only when the minute freed, 25 to 44 s on, and its edge came up then (bug hunt r12, measured again 2026-10-03).
710
- */
711
- var WATCH_SHARE = 1 / 3;
712
- /**
713
- * 1:1 chats' reads of contacts that went away from a live session and have not shown themselves back (`watch`) take at
714
- * most this share of a relay's requests the same way, on their own (a chat never waits behind the edges that watch the
715
- * same contact): 3 in any 10 s on a relay of 30, more than one contact's fast poll asks for. The key read longest ago
716
- * goes first. Not the few reads of a contact that just went away past the limit (`DEPARTED_READS`). Ten contacts that
717
- * left a CLI daemon at once were read every 2 s each: those reads spent both relays' minute in the 10 s after their
718
- * goodbyes, when none could be back yet, then the daemon read nobody, nor answered anyone, for 45 s, and the chats with
719
- * no HyperDHT listener at the daemon were live again 42 to 51 s after their contacts were back (CLI bug hunt, 2026-10-14).
720
- */
721
- var CHAT_WATCH_SHARE = 1 / 2;
722
- /**
723
- * A key a group reads that asked within this long and was not read since keeps its turn: while one read longer ago
724
- * waits, the others wait too (`WATCH_SHARE`, `GROUP_RATION_WINDOW_MS`). One that stops asking loses it.
725
- */
726
- var WATCH_TURN_MS = 5e3;
727
- /**
728
- * Background reads, and a 1:1 chat's at any pace, take turns per key the same way: while a key read longer ago asked
729
- * within this long and was not read since, a read of another key waits (a chat's, at a pace that is not the background
730
- * one, only for another chat's key). A saved chat that is not live reads its contact every 30 s in the
731
- * background, and one the budget refused read again only at its next poll. A request frees 60 s after the one that took
732
- * it, which is the poll after next of the chat that took it: the same chats took every request that freed. A daemon with
733
- * 30 chats and 5 groups, back after a restart while its groups signaled, read some contacts once in 10 min, and those
734
- * chats stayed down although both sides were online and offering (CLI bug hunt, 2026-10-12). A link's background read
735
- * the budget refused reads again when it frees a request (`LinkSession`), so the key whose turn it is is there to take it.
736
- * A chat not live after a restart looks fast while its offer is out, and those reads took no turn: the budget answered
737
- * them from the packet read before, every 2 to 8 s for 10 minutes, while the chats that were live already, the groups'
738
- * edges and the writes took every request that freed. A quarter of a daemon's 30 chats read their contact once in 10
739
- * minutes, their contacts online and offering, and showed them offline at 6 minutes (CLI bug hunt, 2026-10-13).
740
- */
741
- var READ_TURN_MS = 5e3;
742
- /**
743
- * The keys' turns asked and read over a minute ago are dropped at most this often: walking every key on each ask cost in
744
- * proportion to the chats, 12-14% of an idle web app's script with 200 chats.
745
- */
746
- var TURNS_PRUNE_MS = 1e3;
747
- /**
748
- * A 1:1 chat's read the budget held back this long without a break is starved: it goes before the writes that wait
749
- * (`WRITE_FIRST_MS`) and past the background share, within the minute, the key held back longest first. A daemon back
750
- * after a restart spends its whole minute on writes (each chat's and edge's offer, its packets after the attempt), which
751
- * go first, and requests free in bursts as the minute's first requests age out: every burst went to the writes that
752
- * waited, and the reads of the chats that were not in an attempt never had their turn (CLI restart lab, 2026-10-13).
753
- */
754
- var READ_STARVED_MS = 6e4;
755
- /** How long a read that let an older one go first waits before it asks again. */
756
- var TURN_WAIT_MS = 1e3;
757
- /**
758
- * Once a group's read found a relay's minute full, the groups' reads there are spread over the minute for a minute
759
- * (`GROUP_RATION_MS`): at most a sixth of it in any 10 s (5 on a relay of 30), the key read longest ago first. A sliding
760
- * minute that demand keeps full hands out its requests in bursts: the minute is spent in 25 to 35 s as requests age
761
- * out, then nothing frees for the rest of it. A private group's admin (its knock poll every 2 s while its link is new)
762
- * whose members left and came back read nothing for 18 to 42 s at a time, and the member back first waited that long
763
- * for its edge (bug hunt r12, measured again on 2026-10-03). Writes are not counted: they go first anyway.
764
- */
765
- var GROUP_RATION_WINDOW_MS = 1e4;
766
- var GROUP_RATION_MS = 6e4;
767
- /**
768
- * While a link polls fast (an `urgent` read: its peer, or the peer's offer or answer, is due any moment) within this
769
- * long, background requests (a community's periodic looks) are held to `BACKGROUND_WHILE_SIGNALING` a minute on each
770
- * relay rather than their usual share. A fast poll reads every 2 s, one relay after the other.
771
- */
772
- var SIGNALING_WINDOW_MS = 1e4;
773
- /**
774
- * Background requests a minute on each relay while a link signals: one look every 12 s. Next to a community's
775
- * lookups (20 a minute), a new group edge on one relay got 10 and read every 6 s, and its offer and answer missed each
776
- * other's fast windows (2026-09-27). Not none: fast windows can follow one another, and a hub still reads its knocks.
777
- */
778
- var BACKGROUND_WHILE_SIGNALING = 5;
779
- /**
780
- * A read of a key the relays answered this recently is answered from that answer, with no request. Several parts of
781
- * a chat read the contact's keys (the link's poll, its capabilities, DHT delivery), and each tends to read again
782
- * within a few dozen milliseconds of its last read, when a pace changes or a signal goes out: nothing new can be there
783
- * yet, and a pairing spent a sixth of its requests on those reads (2026-09-27). A publish under the key forgets it.
784
- */
785
- var FRESH_READ_MS = 500;
786
- /** A relay that missed a key's newest packet gets it (`catchUpLater`) no sooner than this, and tries again this often. */
787
- var CATCH_UP_MIN_MS = 1e3;
788
- var CATCH_UP_RETRY_MS = 5e3;
789
- /** A catch-up put waits behind every link's request: a background write. A group edge's offer or answer goes as its own (`putEverywhere`). */
790
- var CATCH_UP_ASKER = {
791
- background: true,
792
- group: false,
793
- urgent: false,
794
- door: false,
795
- write: true,
796
- signal: false,
797
- watch: false,
798
- watchWrite: false,
799
- departed: false,
800
- awaited: false,
801
- resume: false,
802
- back: false
803
- };
804
- /** Keys whose last relay is remembered for their next read (`resolve`): a profile's links and lookups, with room. */
805
- var READ_TURNS_KEPT = 512;
806
- /** A relay that fails at the network level is left alone for this long. */
807
- var NETWORK_ERROR_COOLDOWN_MS = 2e4;
808
- /**
809
- * Relays whose limit per address is far from the others': this client's share of theirs, a minute, in place of
810
- * `REQUESTS_PER_MINUTE`. relay.pkarr.org (not a default, see docs/RELAYS.md) and pkarr.miguelmedeiros.dev (a default
811
- * since 2026-10-17) allow 10 (`x-ratelimit-limit`), which a browser cannot read without CORS exposing it: half of it
812
- * leaves room for a second app behind the same address. pkarr.pubky.app allows 1000 (pkarr.pubky.org, on the same address,
813
- * 50): 60 of ours leaves room for many peers behind one address, and a page that pairs three contacts in a minute,
814
- * about ten requests a relay each, still has requests to spare there (2026-09-28). Writes go to every relay and
815
- * count once one took them; reads go to a relay with requests left.
816
- */
817
- var RELAY_REQUESTS_PER_MINUTE = {
818
- "https://relay.pkarr.org": 5,
819
- "https://pkarr.pubky.app": 60,
820
- "https://pkarr.miguelmedeiros.dev": 5
821
- };
822
- /**
823
- * A read asks the next relay too when the one it asked has not answered within this long, and takes the first good
824
- * answer. Measured on 2026-10-03 from a home connection: a relay hands over a packet it holds in 0.25 s (0.7 s on a new
825
- * connection), and one that has to fetch the packet from the DHT first takes 2.7 s. Reads used to wait for a relay's
826
- * answer before asking the next one, up to the 10 s timeout: a relay that answered slowly or not at all (pkarr.pubky.org
827
- * on 2026-10-03) made every read of a pairing that slow, and the pairing never finished.
828
- */
829
- var HEDGE_MS = 1500;
830
- /**
831
- * The hedge delay for a key whose last read found nothing (404): a relay takes 3 to 5 s to say so (it asks the DHT
832
- * every time), and a hedge at `HEDGE_MS` would double every poll of a key nobody has published yet.
833
- */
834
- var HEDGE_MISSING_MS = 6e3;
835
- /**
836
- * A packet that took longer than this to arrive, or a hedge lost to a relay that answered with the packet, is slow: it
837
- * counts against the relay's breaker like a failure (three in a row trip it, logged as "slow"), while another relay is
838
- * there to ask. A 404 says nothing either way: every relay is slow to give one.
839
- */
840
- var SLOW_MS = 3e3;
841
- /** A relay found slow goes after the others in every read for this long, unless it answers fast meanwhile. */
842
- var SLOW_DEMOTE_MS = 6e4;
843
- /** How long each source has to answer a read or a put of the turn record (WISP 06 § Publishing and reading). */
844
- var TURN_SOURCE_TIMEOUT_MS = 8e3;
845
- /** A relay's refusals of a turn put: someone else wrote (409 an older or equal packet, 412 the condition, 428 a put in flight). */
846
- var TURN_REFUSALS = [
847
- 409,
848
- 412,
849
- 428
850
- ];
851
- /** How many times a payload signed here goes again past a relay's later copy (`putRedated`): three puts at most. */
852
- var PAYLOAD_REDATES = 2;
853
- /** On a relay's 404: the sequence of an item the DHT holds under the key that is no signed packet. */
854
- var INVALID_PACKET_SEQ_HEADER = "pkarr-invalid-signed-packet-seq";
855
- /** What `answer` says, or false when it has not said within `ms`. */
856
- function answeredWithin(answer, ms) {
857
- let timer;
858
- const late = new Promise((resolve) => {
859
- timer = setTimeout(() => resolve(false), ms);
860
- });
861
- return Promise.race([answer, late]).finally(() => clearTimeout(timer));
862
- }
863
- function normalizeRelayUrl(input) {
864
- try {
865
- const url = new URL(input.trim());
866
- if (url.protocol !== "https:" && url.protocol !== "http:") return null;
867
- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
868
- } catch {
869
- return null;
870
- }
871
- }
872
- /**
873
- * Why a line of a Pkarr relay list is not a relay `normalizeRelayUrl` keeps, with the line as typed; null when it is
874
- * one. A host alone or another scheme (`relay.example.org`, `wss://…`) was meant as an https:// relay.
875
- */
876
- function relayUrlProblem(input) {
877
- const line = input.trim();
878
- if (normalizeRelayUrl(line)) return null;
879
- return looksLikeHost(line) || looksLikeHost(line.replace(/^[a-z][a-z\d+.-]*:\/\//i, "")) ? `Use an https:// relay address: ${line}` : `Not a relay address: ${line}`;
880
- }
881
- /** No space, and a dot after the first character, before the last one and before any `/` or `:`; linear, for a long pasted line. */
882
- function looksLikeHost(text) {
883
- if (/\s/.test(text)) return false;
884
- const slash = text.search(/[/:]/);
885
- const dot = text.indexOf(".", 1);
886
- return dot > 0 && dot < text.length - 1 && (slash < 0 || dot < slash);
887
- }
888
- /** A relay the breaker leaves alone for failing (`RelayBreaker`): nothing was asked of it now. */
889
- var RelayLeftAloneError = class extends Error {};
890
- /**
891
- * A relay a put did not get an answer from. `sent` false: the request never left (its network cooling down after a
892
- * failure, or a connection that could not be made, `connectFailed`); true: it may have reached the relay.
893
- */
894
- var RelayNoAnswerError = class extends Error {
895
- sent;
896
- constructor(message, sent) {
897
- super(message);
898
- this.sent = sent;
899
- }
900
- };
901
- /** What Node says of a connection it could not make: the request never left. A browser's TypeError says nothing either way. */
902
- var CONNECT_FAILURES = /* @__PURE__ */ new Set([
903
- "ECONNREFUSED",
904
- "ENOTFOUND",
905
- "EAI_AGAIN",
906
- "EHOSTUNREACH",
907
- "ENETUNREACH",
908
- "ENETDOWN",
909
- "EHOSTDOWN",
910
- "EADDRNOTAVAIL",
911
- "UND_ERR_CONNECT_TIMEOUT"
912
- ]);
913
- /** A fetch that failed before its request left this device: Node's `cause.code` (each of an AggregateError's, for several addresses). */
914
- function connectFailed(error) {
915
- const cause = error?.cause;
916
- if (!cause || typeof cause !== "object") return false;
917
- if (Array.isArray(cause.errors) && cause.errors.length) return cause.errors.every((e) => CONNECT_FAILURES.has(e?.code));
918
- return CONNECT_FAILURES.has(cause.code);
919
- }
920
- /**
921
- * The error a publish ends with after a second round dated past a relay's later copy failed too: one that may have
922
- * stored the first round's packet still may, whatever the second round's relays said.
923
- */
924
- function laterRound(first, later) {
925
- return publishedNowhere(later) && !publishedNowhere(first) ? new PublishFailedError(later.message, true) : later;
926
- }
927
- /** A packet date no further ahead of this clock than readers take (`newerPacket`): one this client may date past. */
928
- function withinSkew(timestamp) {
929
- return timestamp <= BigInt(Date.now() + PKARR_FUTURE_SKEW_MS) * 1000n;
930
- }
931
- /**
932
- * A read the relays failed (or left alone for failing before), when its caller has another path to ask
933
- * (`RelayTransport.resolve` with `keptOnFailure` false): `kept` is the newest packet the relays gave for the key before.
934
- */
935
- var RelaysFailedError = class extends Error {
936
- kept;
937
- constructor(kept) {
938
- super("No Pkarr relay reachable");
939
- this.kept = kept;
940
- }
941
- };
942
- var RelayTransport = class {
943
- relays;
944
- timeoutMs;
945
- fetchFn;
946
- timeListeners = /* @__PURE__ */ new Set();
947
- lastTimestamp = /* @__PURE__ */ new Map();
948
- newest = /* @__PURE__ */ new Map();
949
- /**
950
- * The latest time of any packet read under a key, whoever dated it: the next packet this client puts there is dated
951
- * past it (`nextTimestamp`). A key is not always one writer's with one clock: a group's lobby, beacon and knock
952
- * records are written by every member, an inviter warms its contact's key with an empty packet, and this device's
953
- * own clock may have been set back since it last wrote. A relay and the DHT keep only the packet dated latest, so
954
- * one dated by this clock alone, when it is behind, was refused (409) or silently never read, until this clock
955
- * caught up with the other one: minutes, or an hour. Only up to `PKARR_FUTURE_SKEW_MS` ahead of this clock
956
- * (`withinSkew`): a packet one holder of a shared key dated further ahead must not date every later one of this
957
- * device past it (past 64 bits, unsignable; else ahead of every reader's clock, never taken over one dated now).
958
- */
959
- seenTimestamp = /* @__PURE__ */ new Map();
960
- /**
961
- * The last packet this client put under a key that a relay took. A read the budget holds back answers the newer of
962
- * it and the last one read: a hub that wrote its own beacon entry since it last read the beacon must not see that
963
- * entry as old as the one it replaced (it would stop counting itself at its community's door until its next write).
964
- */
965
- written = /* @__PURE__ */ new Map();
966
- coolingDown = /* @__PURE__ */ new Map();
967
- networkCooldown = /* @__PURE__ */ new Map();
968
- cursor = 0;
969
- /** Per key, the relay that answered its last read: the next read of the key starts at the one after it (`resolve`). */
970
- lastReadFrom = /* @__PURE__ */ new Map();
971
- spent = /* @__PURE__ */ new Map();
972
- spentBackground = /* @__PURE__ */ new Map();
973
- /** Background writes on each relay in the last minute (`BACKGROUND_WRITES_SHARE`). */
974
- spentBackgroundWrites = /* @__PURE__ */ new Map();
975
- /** Groups' urgent reads on each relay in the last `GROUP_BURST_MS`: edges' reads for an answer apart (`ANSWER_READ_FIRST_MS`). */
976
- spentGroupUrgent = /* @__PURE__ */ new Map();
977
- spentAnswerUrgent = /* @__PURE__ */ new Map();
978
- /** Watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`WATCH_SHARE`). */
979
- spentWatch = /* @__PURE__ */ new Map();
980
- /** 1:1 chats' watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`CHAT_WATCH_SHARE`). */
981
- spentChatWatch = /* @__PURE__ */ new Map();
982
- /** Groups' reads past the limit on each relay in the last `GROUP_OVER_PACE_MS` (`GROUP_SIGNALING_ALLOWANCE_SHARE`). */
983
- spentGroupOver = /* @__PURE__ */ new Map();
984
- /** Group edges' signaling requests on each relay in the last minute: their floor (`GROUP_SIGNALING_ALLOWANCE_SHARE`). */
985
- spentGroupSignal = /* @__PURE__ */ new Map();
986
- /** Community members' ways back on each relay in the last minute: their allowance (`WAY_BACK_SHARE`). */
987
- spentWayBack = /* @__PURE__ */ new Map();
988
- /** Edges' reads for an answer that only their own allowance let through, on each relay in the last minute (`ANSWER_READ_ALLOWANCE`). */
989
- spentAnswerAllowance = /* @__PURE__ */ new Map();
990
- /** Per contact, its departed reads past the limit in the last minute, every relay together (`DEPARTED_READS`). */
991
- departedOver = /* @__PURE__ */ new Map();
992
- /** The awaited reads past the limit in the last minute, every invite and every relay together (`AWAITED_READS`). */
993
- awaitedOver = [];
994
- /** When an awaited invite's read last asked: the departed reads leave it room for a minute (`AWAITED_READS`). */
995
- awaitedAt = -Infinity;
996
- /**
997
- * Per key a group reads (not in the background), when a read of it last went out and when it last asked: whose turn
998
- * it is under the watch share (`WATCH_SHARE`) and while the groups' reads are rationed (`GROUP_RATION_WINDOW_MS`). And
999
- * per key a chat watches, whose turn it is under theirs (`CHAT_WATCH_SHARE`).
1000
- */
1001
- readTurns = /* @__PURE__ */ new Map();
1002
- /** Per key read in turn (`isTurnRead`), when a read of it last went out and when it last asked (`READ_TURN_MS`). */
1003
- keyTurns = /* @__PURE__ */ new Map();
1004
- /** When `readTurns` and `keyTurns` last dropped their stale turns (`TURNS_PRUNE_MS`). */
1005
- turnsPrunedAt = /* @__PURE__ */ new Map();
1006
- /** Groups' reads (not background ones) on each relay in the last `GROUP_RATION_WINDOW_MS`. */
1007
- spentGroupReads = /* @__PURE__ */ new Map();
1008
- /** When a group's read last found each relay's minute full: its reads there are rationed for `GROUP_RATION_MS`. */
1009
- groupsFullAt = /* @__PURE__ */ new Map();
1010
- /** When a link's write was last refused on each relay (`chat <relay>`, `group <relay>`), while it waits for the budget. */
1011
- writeWaiting = /* @__PURE__ */ new Map();
1012
- /** Per relay, the keys whose edges' reads for an answer it last refused, and when, until one is read (`ANSWER_READ_FIRST_MS`). */
1013
- answerReadWaiting = /* @__PURE__ */ new Map();
1014
- /**
1015
- * Per key a 1:1 chat asks for: when it last read urgently (for the next minute, groups leave it `CHAT_RESERVE` on
1016
- * every relay) and when the budget last refused it on each relay (the same, on that relay). A read of the key at a
1017
- * slow pace (the chat is live, or back in the background) drops it: `CHAT_RESERVE`. Per relay, the later of the two
1018
- * for each key (`chatNeed`); `chatUrgentAt` keeps the urgent ones for a relay not asked yet.
1019
- */
1020
- chatNeeds = /* @__PURE__ */ new Map();
1021
- chatUrgentAt = new RecentKeys();
1022
- /** When a link (a chat's or a group's) last asked urgently: background requests yield for `SIGNALING_WINDOW_MS`. */
1023
- urgentAt = -Infinity;
1024
- /** Timestamp of the last packet sent to each relay, per key: the compare-and-swap value for the next one. */
1025
- lastPut = /* @__PURE__ */ new Map();
1026
- /** Per relay and key, the newest packet that relay held back for its budget while another relay took it (`catchUpLater`). */
1027
- catchUp = /* @__PURE__ */ new Map();
1028
- catchUpTimer = null;
1029
- /**
1030
- * Per key whose reads the budget held back since its last read went out: when a request frees for it
1031
- * (`readHeldBackFor`), how many times in a row, and since when (`READ_STARVED_MS`).
1032
- */
1033
- heldBack = /* @__PURE__ */ new Map();
1034
- /** When the relays last answered a read of each key, for `FRESH_READ_MS`. */
1035
- readAt = /* @__PURE__ */ new Map();
1036
- freshReadMs;
1037
- perMinute;
1038
- /** `requestsPerMinute` was given: it bounds every relay, one with its own share (`RELAY_REQUESTS_PER_MINUTE`) too. */
1039
- perMinuteGiven;
1040
- backgroundPerMinute;
1041
- backgroundWhileSignaling;
1042
- breaker;
1043
- /** The relay the last read was answered by. */
1044
- lastRelay = null;
1045
- hedgeMs;
1046
- /** Until when each relay found slow (`SLOW_MS`) goes after the others in a read (`readOrder`). */
1047
- slowUntil = /* @__PURE__ */ new Map();
1048
- /** Per relay, when each of this client's requests still waiting for its answer went out (`unanswering`). */
1049
- waiting = /* @__PURE__ */ new Map();
1050
- /** When each relay last answered a request of this client, whatever it said (`unanswering`). */
1051
- answeredAt = /* @__PURE__ */ new Map();
1052
- /** Keys whose last read was answered 404: their next read hedges later (`HEDGE_MISSING_MS`). */
1053
- missing = /* @__PURE__ */ new Set();
1054
- listeners = /* @__PURE__ */ new Set();
1055
- constructor(options = {}) {
1056
- this.relays = [];
1057
- this.setRelays(options.relays ?? DEFAULT_RELAYS);
1058
- this.timeoutMs = options.timeoutMs ?? 1e4;
1059
- this.fetchFn = options.fetch ?? ((...args) => fetch(...args));
1060
- this.perMinute = options.requestsPerMinute ?? 30;
1061
- this.freshReadMs = options.freshReadMs ?? 500;
1062
- this.hedgeMs = options.hedgeMs ?? 1500;
1063
- this.perMinuteGiven = options.requestsPerMinute !== void 0;
1064
- this.backgroundPerMinute = this.perMinute === 30 ? 20 : Math.ceil(this.perMinute * 2 / 3);
1065
- this.backgroundWhileSignaling = this.perMinute === 30 ? 5 : Math.ceil(this.perMinute / 6);
1066
- const log = options.log ?? ((line) => console.info(`ghostly: ${line}`));
1067
- this.breaker = new RelayBreaker({
1068
- ...options.breaker,
1069
- onTrip: (relay, reason, forMs) => {
1070
- log(`relay ${new URL(relay).host} ${reason === "no answer" ? "did not answer" : reason === "slow" ? "answered too slowly" : `failed (${reason})`}; asked again in ${Math.round(forMs / 1e3)} s`);
1071
- options.breaker?.onTrip?.(relay, reason, forMs);
1072
- this.changed("tripped");
1073
- },
1074
- onRecover: (relay) => {
1075
- log(`relay ${new URL(relay).host} answers again`);
1076
- options.breaker?.onRecover?.(relay);
1077
- this.changed("recovered");
1078
- }
1079
- });
1080
- }
1081
- /** How reads go and how each relay is doing, for the connection panel. */
1082
- discovery() {
1083
- const relays = this.breaker.health(this.relays).map((health) => {
1084
- const limited = this.rateLimitedFor(health.relay);
1085
- return health.state === "ok" && limited > 0 ? {
1086
- ...health,
1087
- state: "throttled",
1088
- until: Date.now() + limited,
1089
- reason: "rate limited (429)"
1090
- } : health;
1091
- });
1092
- return {
1093
- path: this.lastRelay ? {
1094
- via: "relay",
1095
- relay: this.lastRelay
1096
- } : null,
1097
- relays
1098
- };
1099
- }
1100
- /** Back online on some network: relays that failed (or rate limited this address) on the old one are asked again. */
1101
- networkChanged() {
1102
- this.breaker.reset();
1103
- this.networkCooldown.clear();
1104
- this.coolingDown.clear();
1105
- this.slowUntil.clear();
1106
- this.changed("recovered");
1107
- }
1108
- /**
1109
- * `PkarrTransport.forget`: the packets and dates this client kept under these keys go, on every relay (`written`,
1110
- * `newest`, `lastTimestamp`, `seenTimestamp`, `lastPut`). A spare invite replaced unused left them here for its two keys
1111
- * for good: an idle CLI daemon gained 8 keys an hour (343 in `written` and 690 `lastPut` entries after a day). The maps
1112
- * that bound themselves (`readAt`, `lastReadFrom`, `heldBack`, `missing`, the turns) and the catch-ups, which go once
1113
- * put, are left as they are. A later put under one of these keys goes as a key's first.
1114
- */
1115
- forget(keys) {
1116
- const gone = new Set(keys);
1117
- if (gone.size === 0) return;
1118
- for (const key of gone) for (const perKey of [
1119
- this.lastTimestamp,
1120
- this.seenTimestamp,
1121
- this.newest,
1122
- this.written
1123
- ]) perKey.delete(key);
1124
- for (const slot of this.lastPut.keys()) if (gone.has(slot.slice(slot.lastIndexOf(" ") + 1))) this.lastPut.delete(slot);
1125
- }
1126
- /** Called when a relay trips or recovers. */
1127
- subscribe(listener) {
1128
- this.listeners.add(listener);
1129
- return () => this.listeners.delete(listener);
1130
- }
1131
- changed(change) {
1132
- for (const listener of this.listeners) try {
1133
- listener(change);
1134
- } catch {}
1135
- }
1136
- /** What the relay did, for its breaker. */
1137
- answered(relay, failure, method) {
1138
- if (failure) {
1139
- this.breaker.failure(relay, failure.kind, failure.reason);
1140
- return;
1141
- }
1142
- if (method) this.networkCooldown.delete(`${method} ${relay}`);
1143
- this.breaker.success(relay, this.relays);
1144
- }
1145
- setRelays(relays) {
1146
- const normalized = relays.map(normalizeRelayUrl).filter((r) => r !== null);
1147
- this.relays = [...new Set(normalized)];
1148
- }
1149
- describe() {
1150
- return {
1151
- protocol: "Pkarr relays (HTTP) → Mainline DHT (BEP44)",
1152
- relays: [...this.relays]
1153
- };
1154
- }
1155
- /**
1156
- * Publishes to every relay. Peers may be configured with different relay
1157
- * sets; writing everywhere keeps the overlap warm, the DHT covers the rest.
1158
- * Returns once one relay took the packet: the others finish in the background.
1159
- */
1160
- async publish(identity, records, options = {}) {
1161
- if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
1162
- await this.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putEverywhere(key, payload, timestamp, options, conflict), options);
1163
- }
1164
- /**
1165
- * The time the next packet under a key is dated: this clock's, and past every packet this client put or read there.
1166
- * BEP44 sequence numbers must strictly increase, and the clock that dated the last one may not be this one's.
1167
- */
1168
- nextTimestamp(pubKeyZ32) {
1169
- const now = BigInt(Date.now()) * 1000n;
1170
- const last = this.lastTimestamp.get(pubKeyZ32) ?? 0n, seen = this.seenTimestamp.get(pubKeyZ32) ?? 0n;
1171
- const floor = last > seen ? last : seen;
1172
- const timestamp = now > floor ? now : floor + 1n;
1173
- this.lastTimestamp.set(pubKeyZ32, timestamp);
1174
- return timestamp;
1175
- }
1176
- /**
1177
- * Signs the records, dated by `nextTimestamp`, and hands the payload to `put` (the relays; the CLI adds the DHT).
1178
- * When every relay's budget (or rate limit) holds this asker back, it throws that wait before signing anything
1179
- * (`publishWait`): a daemon at its budget signed about 500 packets a minute that never went out. `elsewhere`: `put`
1180
- * also takes the packet where no budget holds it back (the CLI's DHT), so it is signed whatever the relays say.
1181
- * `put` calls `conflict` for a relay that answered 409: it holds a packet under this key dated at or after this one,
1182
- * which this client has not read (an inviter's warm packet under the key it gave its contact, from a clock ahead of
1183
- * this one). That packet is read from that relay, and the records go again dated just past it, once. Without this
1184
- * the packet was refused until this device's clock passed the other one's, however long that took, and on a relay
1185
- * that did take it, readers still preferred the later-dated empty packet of another relay. `read`: how to learn the
1186
- * held packet's date where it is not a relay to ask (the CLI's DHT, whose nodes answer 302 for a later-dated packet).
1187
- */
1188
- async publishDated(identity, records, put, options = {}, again = false, elsewhere = false) {
1189
- const key = identity.pubKeyZ32;
1190
- if (!again && !elsewhere) {
1191
- const held = this.publishWait(key, asker(options, true));
1192
- if (held) throw new DiscoveryBudgetError(held.wait, `Publish held back on every relay: ${held.reasons.join("; ")}`);
1193
- const refused = this.refusedEverywhere(key, asker(options, true));
1194
- if (refused) throw refused;
1195
- }
1196
- const timestamp = this.nextTimestamp(key);
1197
- let redated;
1198
- const conflict = (relay, read) => {
1199
- if (again || redated) return;
1200
- redated = (async () => {
1201
- const held = read ? await read().catch(() => null) : await this.heldAt(relay, key, asker(options, true));
1202
- if (held === null || held < timestamp || !withinSkew(held)) return false;
1203
- traceLink(key, "publish-redated", {
1204
- aheadMs: Number((held - timestamp) / 1000n),
1205
- relay
1206
- });
1207
- if (this.lastTimestamp.get(key) !== timestamp) return true;
1208
- await this.publishDated(identity, records, put, options, true, elsewhere);
1209
- return true;
1210
- })();
1211
- redated.catch(() => {});
1212
- };
1213
- try {
1214
- await put(key, createRelayPayload(identity, records, timestamp), timestamp, conflict);
1215
- } catch (error) {
1216
- const pending = redated;
1217
- if (!pending || !await pending.catch((later) => {
1218
- throw laterRound(error, later);
1219
- })) throw error;
1220
- }
1221
- }
1222
- /** `PkarrTransport.publishHeld`: `publishDated`'s check before signing, for a payload signed elsewhere in this process. */
1223
- publishHeld(pubKeyZ32, options = {}) {
1224
- if (this.relays.length === 0) return null;
1225
- const held = this.publishWait(pubKeyZ32, asker(options, true));
1226
- return held ? new DiscoveryBudgetError(held.wait, `Publish held back on every relay: ${held.reasons.join("; ")}`) : null;
1227
- }
1228
- /**
1229
- * How long until some relay takes a publish of this asker, and why each holds it back; null when one would now. Walks the relays as `put` does,
1230
- * without asking any: a relay the budget holds back gets its refused `take` (the asker's write then waits first in
1231
- * line, as when `put` is refused), one rate limiting or throttling this address is a wait, one left alone for failing
1232
- * is none. Null too when a relay fails another way (its network cooling down): the publish then goes, and fails, as
1233
- * before, and when no relay is held back at all.
1234
- */
1235
- publishWait(pubKeyZ32, who) {
1236
- const probe = this.breaker.allDownProbe(this.relays);
1237
- let wait = Infinity;
1238
- const held = [], reasons = [];
1239
- for (const relay of this.relays) {
1240
- if (relay !== probe && this.networkCoolingDown(relay, "PUT")) return null;
1241
- const limited = this.rateLimitedFor(relay);
1242
- if (limited > 0) {
1243
- wait = Math.min(wait, limited);
1244
- reasons.push(`${relay}: Discovery relay is cooling down after a 429; retry shortly`);
1245
- continue;
1246
- }
1247
- const blocked = relay === probe ? 0 : this.breaker.blockedFor(relay);
1248
- if (blocked > 0) {
1249
- if (this.breaker.blockedKind(relay) === "throttled") {
1250
- wait = Math.min(wait, blocked);
1251
- reasons.push(`${relay}: Discovery relay is throttling this address; retry shortly`);
1252
- } else reasons.push(`${relay} is left alone after failing`);
1253
- continue;
1254
- }
1255
- if (this.heldFor(relay, who, Date.now(), pubKeyZ32) <= 0) return null;
1256
- held.push(relay);
1257
- const left = this.heldFor(relay, who);
1258
- wait = Math.min(wait, left);
1259
- reasons.push(`${relay}: discovery budget reached; retry in ${Math.ceil(left / 1e3)} s`);
1260
- }
1261
- if (wait === Infinity) return null;
1262
- for (const relay of held) this.take(relay, who, pubKeyZ32);
1263
- return {
1264
- wait,
1265
- reasons
1266
- };
1267
- }
1268
- /**
1269
- * A publish that every relay would refuse now without being asked (its network cooling down, left alone after failing,
1270
- * its rate limit or this asker's budget), and not as a wait alone (`publishWait` says those): the failure `putEverywhere`
1271
- * would end in, in the same words, said before the packet is signed and dated. Null when some relay would be asked. With
1272
- * every relay out of reach on a page that is online, each chat signed a packet every few seconds that went nowhere: ~58
1273
- * a second at 300 chats (bug hunt, 2026-11-12).
1274
- */
1275
- refusedEverywhere(pubKeyZ32, who) {
1276
- const probe = this.breaker.allDownProbe(this.relays);
1277
- const now = Date.now();
1278
- const reasons = [], held = [];
1279
- for (const relay of this.relays) {
1280
- const refused = this.refusal(relay, relay === probe);
1281
- if (refused) {
1282
- reasons.push(String(refused));
1283
- continue;
1284
- }
1285
- if (this.heldFor(relay, who, now, pubKeyZ32) <= 0) return null;
1286
- held.push(relay);
1287
- reasons.push(String(new DiscoveryBudgetError(this.heldFor(relay, who))));
1288
- }
1289
- for (const relay of held) this.take(relay, who, pubKeyZ32);
1290
- return new PublishFailedError(`Publish failed on every relay: ${reasons.join("; ")}`, false);
1291
- }
1292
- /** What `put` refuses a request to this relay with before its budget is asked; null when it gets that far. */
1293
- refusal(relay, probe) {
1294
- if (!probe && this.networkCoolingDown(relay, "PUT")) return new RelayNoAnswerError(`${relay} did not answer a moment ago; retry shortly`, false);
1295
- const limited = this.rateLimitedFor(relay);
1296
- if (limited > 0) return new DiscoveryBudgetError(limited, "Discovery relay is cooling down after a 429; retry shortly");
1297
- const blocked = probe ? 0 : this.breaker.blockedFor(relay);
1298
- if (blocked > 0) {
1299
- if (this.breaker.blockedKind(relay) === "throttled") return new DiscoveryBudgetError(blocked, "Discovery relay is throttling this address; retry shortly");
1300
- return new RelayLeftAloneError(`${relay} is left alone after failing; asked again in ${Math.max(1, Math.ceil(this.breaker.askedAgainIn(relay, this.relays) / 1e3))} s`);
1301
- }
1302
- return null;
1303
- }
1304
- /** One relay's packet for a key, read now: its time, kept for `nextTimestamp`. Null when it has none or does not answer. */
1305
- async heldAt(relay, pubKeyZ32, who) {
1306
- if (!this.take(relay, who, pubKeyZ32)) return null;
1307
- try {
1308
- let payload;
1309
- if (!(await this.request(`${relay}/${pubKeyZ32}`, { method: "GET" }, async (r, signal) => {
1310
- if (r.ok && r.status !== 404) payload = await readRelayBody(r, signal);
1311
- })).ok || !payload) return null;
1312
- const packet = parseRelayPayload(pubKeyZ32, payload);
1313
- this.sawTimestamp(pubKeyZ32, packet.timestampMicros);
1314
- return packet.timestampMicros;
1315
- } catch {
1316
- return null;
1317
- }
1318
- }
1319
- /** A packet under this key was read (on a relay, or by the CLI on the DHT): its time, for `nextTimestamp`. */
1320
- sawTimestamp(pubKeyZ32, timestamp) {
1321
- if (withinSkew(timestamp) && timestamp > (this.seenTimestamp.get(pubKeyZ32) ?? 0n)) this.seenTimestamp.set(pubKeyZ32, timestamp);
1322
- }
1323
- /**
1324
- * Puts a payload `publishDated` just signed, dated `timestamp`, on every relay. Its signature is not checked: it was
1325
- * made here (`publishPayload` checks one signed elsewhere, to read its sequence number). `conflict`: as `publishDated`
1326
- * gives it.
1327
- */
1328
- async putSigned(pubKeyZ32, payload, timestamp, options = {}, conflict) {
1329
- if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
1330
- await this.putEverywhere(pubKeyZ32, payload, timestamp, options, conflict);
1331
- }
1332
- /**
1333
- * Puts a payload signed elsewhere (a did:dht document), byte for byte, on every relay; one signed here says its date
1334
- * (`signedAt`) and is not checked again. `conflict`: as `publishDated` gives it.
1335
- */
1336
- async publishPayload(pubKeyZ32, payload, options = {}, conflict) {
1337
- if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
1338
- const seq = options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;
1339
- if (options.signedAt === void 0 || !options.redate) return this.putEverywhere(pubKeyZ32, payload, seq, options, conflict);
1340
- await this.putRedated(pubKeyZ32, payload, seq, options, PAYLOAD_REDATES);
1341
- }
1342
- /**
1343
- * A payload every relay's budget held back while another path took it (the CLI's DHT): the publish is out, and each
1344
- * relay gets it once its budget frees a request for the same asker (`catchUpLater`), unless a newer packet of the key
1345
- * goes there first. Retried by the link instead, each try was signed and put on the DHT again (1-1.6 puts a minute per
1346
- * chat at budget, not one per 4 min). `timestamp`: its date when signed here; read from the payload otherwise.
1347
- */
1348
- putLater(pubKeyZ32, payload, timestamp, options = {}) {
1349
- const at = timestamp ?? options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;
1350
- try {
1351
- this.written.set(pubKeyZ32, readOwnRelayPayload(pubKeyZ32, payload));
1352
- } catch {}
1353
- for (const relay of this.relays) this.catchUpLater(relay, pubKeyZ32, payload, at, asker(options, true));
1354
- }
1355
- /**
1356
- * A payload signed in this process (a group edge's offer or answer, `CarriedTransport`) put on every relay, past what
1357
- * a relay that answers 409 holds: that one is read, and the records go again at once, signed by `options.redate` dated
1358
- * just past it, `left` times at most. A packet put here is the key's latest too: a publish dated here next
1359
- * (`nextTimestamp`, the goodbye after the edge stops) goes past it. Before, the 409 failed the publish (or, when another
1360
- * relay took it, left the relay's copy in place), the link tried again 4 s on with its clock's date, refused as long as
1361
- * the relay's copy was later, and an edge started again in the same millisecond lost its new offer to its last one.
1362
- */
1363
- async putRedated(key, payload, timestamp, options, left) {
1364
- if (timestamp > (this.lastTimestamp.get(key) ?? 0n)) this.lastTimestamp.set(key, timestamp);
1365
- let redated;
1366
- const conflict = (relay) => {
1367
- if (left <= 0 || redated) return;
1368
- redated = (async () => {
1369
- const held = await this.heldAt(relay, key, asker(options, true));
1370
- if (held === null || held < timestamp || !withinSkew(held)) return false;
1371
- if (this.lastTimestamp.get(key) !== timestamp) return true;
1372
- const again = options.redate(held);
1373
- if (!again) return true;
1374
- traceLink(key, "publish-redated", {
1375
- aheadMs: Number((held - timestamp) / 1000n),
1376
- relay
1377
- });
1378
- await this.putRedated(key, again.payload, again.signedAt, {
1379
- ...options,
1380
- signedAt: again.signedAt
1381
- }, left - 1);
1382
- return true;
1383
- })();
1384
- redated.catch(() => {});
1385
- };
1386
- try {
1387
- await this.putEverywhere(key, payload, timestamp, options, conflict);
1388
- } catch (error) {
1389
- const pending = redated;
1390
- if (!pending || !await pending.catch((later) => {
1391
- throw laterRound(error, later);
1392
- })) throw error;
1393
- }
1394
- }
1395
- /**
1396
- * Puts the packet on every relay and settles as soon as one of them took it. A relay that is slow to
1397
- * answer (one that stores the packet and answers the PUT only at the timeout) must not hold a link's
1398
- * presence, offer or answer back: the rest finish in the background, their outcomes still counted.
1399
- * When no relay takes it, this waits for all of them to say why.
1400
- */
1401
- putEverywhere(pubKeyZ32, payload, timestamp, options, conflict) {
1402
- this.readAt.delete(pubKeyZ32);
1403
- this.missing.delete(pubKeyZ32);
1404
- for (const relay of this.relays) this.catchUp.delete(`${relay} ${pubKeyZ32}`);
1405
- const waitingBefore = new Map(this.writeWaiting);
1406
- const writer = firstWriter(asker(options, true));
1407
- const noWriteWaits = () => {
1408
- if (!writer) return;
1409
- for (const relay of this.relays) {
1410
- const key = `${writer} ${relay}`;
1411
- if (this.writeWaiting.get(key) !== waitingBefore.get(key)) this.writeWaiting.delete(key);
1412
- }
1413
- };
1414
- const probe = this.breaker.allDownProbe(this.relays);
1415
- let first;
1416
- const edgeSignal = isGroupSignal(asker(options, true));
1417
- const failed = /* @__PURE__ */ new Set();
1418
- const nowhere = this.relays.map(() => false);
1419
- const puts = this.relays.map(async (relay, i) => {
1420
- const slot = `${relay} ${pubKeyZ32}`;
1421
- const previous = this.lastPut.get(slot);
1422
- this.lastPut.set(slot, timestamp);
1423
- if (first && isChat(asker(options, true)) && this.spareHeldFor(relay, Date.now()) > 0 && await answeredWithin(first, 3e3)) {
1424
- nowhere[i] = true;
1425
- throw new DiscoveryBudgetError(Math.max(CATCH_UP_MIN_MS, this.spareHeldFor(relay, Date.now())));
1426
- }
1427
- let response;
1428
- try {
1429
- response = await this.put(relay, pubKeyZ32, payload, previous, asker(options, true), relay === probe, (ok) => {
1430
- first ??= ok;
1431
- });
1432
- if (response.status === 412) response = await this.put(relay, pubKeyZ32, payload, void 0, asker(options, true));
1433
- } catch (error) {
1434
- if (!isDiscoveryBudgetError(error) && !(error instanceof RelayLeftAloneError)) failed.add(relay);
1435
- nowhere[i] = isDiscoveryBudgetError(error) || error instanceof RelayLeftAloneError || error instanceof RelayNoAnswerError && !error.sent;
1436
- throw error;
1437
- }
1438
- nowhere[i] = response.status >= 400 && response.status < 500;
1439
- if (response.status >= 500 || response.status === 428) failed.add(relay);
1440
- if (response.status === 409) conflict?.(relay);
1441
- if (response.status === 429) throw new DiscoveryBudgetError(this.coolDown(relay, response), `${relay} responded 429; retry shortly`);
1442
- if (!response.ok) throw new Error(`${relay} responded ${response.status}`);
1443
- });
1444
- const settled = Promise.allSettled(puts);
1445
- return new Promise((resolve, reject) => {
1446
- let accepted = false;
1447
- for (const put of puts) put.then(() => {
1448
- if (accepted) return;
1449
- accepted = true;
1450
- noWriteWaits();
1451
- try {
1452
- this.written.set(pubKeyZ32, readOwnRelayPayload(pubKeyZ32, payload));
1453
- } catch {}
1454
- resolve();
1455
- }, () => {});
1456
- settled.then((results) => {
1457
- if (accepted) {
1458
- noWriteWaits();
1459
- results.forEach((r, i) => {
1460
- if (r.status !== "rejected") return;
1461
- if (isDiscoveryBudgetError(r.reason) || edgeSignal && failed.has(this.relays[i])) this.catchUpLater(this.relays[i], pubKeyZ32, payload, timestamp, edgeSignal ? asker(options, true) : CATCH_UP_ASKER);
1462
- });
1463
- return;
1464
- }
1465
- const held = results.map((r) => r.status === "rejected" && isDiscoveryBudgetError(r.reason) ? r.reason : null);
1466
- const leftAlone = (r) => r.status === "rejected" && r.reason instanceof RelayLeftAloneError;
1467
- const waits = held.filter((e) => e !== null);
1468
- const reasons = results.map((r) => r.status === "rejected" ? String(r.reason) : "").join("; ");
1469
- if (waits.length === results.length) reject(new DiscoveryBudgetError(Math.min(...waits.map((e) => e.retryInMs)), `Publish held back on every relay: ${reasons}`));
1470
- 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}`));
1471
- else reject(new PublishFailedError(`Publish failed on every relay: ${reasons}`, !nowhere.every(Boolean)));
1472
- });
1473
- });
1474
- }
1475
- /**
1476
- * Public relays rate limit by IP (120 requests a minute at the time of
1477
- * writing) and several peers may share one address, so a poll costs one
1478
- * request: one relay is asked, the next one when this one fails, or when it
1479
- * has not answered within `HEDGE_MS` (a hedge: the first good answer wins and
1480
- * the other request is dropped). The newest validly signed packet seen so far
1481
- * wins, which also covers a relay that is still serving an older cached copy.
1482
- *
1483
- * In turn per key: a key's next read starts at the relay after the one that answered its last read. A relay that
1484
- * does not have a packet yet (a publish that reached only the other relay, one rate limited there) answers a key's
1485
- * reads at most once in a row. With one turn for all keys, a link that read its peer between two other reads landed
1486
- * on the same relay every time: a restarted member's offer, only on `pkarr.pubky.app`, went unread for 12 to 60 s
1487
- * while the member at the other end read `pkarr.pubky.org` (bug hunt r5a, 2026-09-29). A relay found slow lately
1488
- * (`SLOW_DEMOTE_MS`) goes after the others, whatever the turn.
1489
- *
1490
- * A hedge spends a second request, so it goes only where the budget has requests to spare (`hedgeRoom`), never for a
1491
- * background read (nobody waits on it), and later for a key whose last read found nothing (`HEDGE_MISSING_MS`).
1492
- *
1493
- * `keptOnFailure` false: a read the relays failed throws `RelaysFailedError` with the packet they gave last, in place
1494
- * of handing that back as their answer (a CLI asks the DHT then, `RelaysAndDht`).
1495
- */
1496
- async resolve(pubKeyZ32, options = {}, keptOnFailure = true) {
1497
- if (this.relays.length === 0) throw new Error("No Pkarr relays configured");
1498
- if (options.background && !options.urgent && !options.group) this.chatNeedLapsed(pubKeyZ32);
1499
- const readAt = this.readAt.get(pubKeyZ32), age = readAt === void 0 ? Infinity : Date.now() - readAt;
1500
- if (age >= 0 && age < this.freshReadMs) return this.newest.get(pubKeyZ32) ?? null;
1501
- const order = this.readOrder(pubKeyZ32);
1502
- const probe = this.breaker.allDownProbe(this.relays);
1503
- let budgetWait = Infinity, down = false;
1504
- const who = asker(options, false);
1505
- const tried = /* @__PURE__ */ new Set();
1506
- let hedgeAfter = options.background ? Infinity : this.missing.has(pubKeyZ32) ? Math.max(this.hedgeMs, HEDGE_MISSING_MS) : this.hedgeMs;
1507
- /**
1508
- * The next relay to ask, its request taken from its budget, or null. A hedge (`hedge`) goes only to a relay with
1509
- * requests to spare; one passed over for that is still there if the relay asked fails.
1510
- */
1511
- const next = (hedge) => {
1512
- for (const relay of order) {
1513
- if (tried.has(relay)) continue;
1514
- if (relay !== probe && this.networkCoolingDown(relay, "GET")) {
1515
- tried.add(relay);
1516
- down = true;
1517
- continue;
1518
- }
1519
- const limited = this.rateLimitedFor(relay);
1520
- if (limited > 0) {
1521
- tried.add(relay);
1522
- budgetWait = Math.min(budgetWait, limited);
1523
- continue;
1524
- }
1525
- const blocked = relay === probe ? 0 : this.breaker.blockedFor(relay);
1526
- if (blocked > 0) {
1527
- tried.add(relay);
1528
- if (this.breaker.blockedKind(relay) === "throttled") budgetWait = Math.min(budgetWait, blocked);
1529
- else down = true;
1530
- continue;
1531
- }
1532
- if (hedge && (this.heldFor(relay, who, Date.now(), pubKeyZ32) > 0 || !this.hedgeRoom(relay))) continue;
1533
- tried.add(relay);
1534
- if (!this.take(relay, who, pubKeyZ32)) {
1535
- budgetWait = Math.min(budgetWait, this.heldFor(relay, who, Date.now(), pubKeyZ32));
1536
- continue;
1537
- }
1538
- if (relay === probe) this.breaker.beginAllDown(relay);
1539
- else this.breaker.begin(relay);
1540
- return relay;
1541
- }
1542
- return null;
1543
- };
1544
- const asked = /* @__PURE__ */ new Map();
1545
- let lastAsked = 0;
1546
- const ask = (hedge) => {
1547
- const relay = next(hedge);
1548
- if (!relay) return false;
1549
- asked.set(relay, this.readFromRelay(relay, pubKeyZ32));
1550
- lastAsked = Date.now();
1551
- return true;
1552
- };
1553
- ask(false);
1554
- let winner = null;
1555
- while (asked.size > 0 && !winner) {
1556
- const hedgeIn = hedgeAfter - (Date.now() - lastAsked);
1557
- if (hedgeIn <= 0) {
1558
- if (!ask(true)) hedgeAfter = Infinity;
1559
- continue;
1560
- }
1561
- let timer;
1562
- const hedgeDue = hedgeIn === Infinity ? null : new Promise((resolve) => {
1563
- timer = setTimeout(() => resolve(null), hedgeIn);
1564
- });
1565
- const settled = await Promise.race([...[...asked.values()].map((attempt) => attempt.done.then((outcome) => ({
1566
- attempt,
1567
- outcome
1568
- }))), ...hedgeDue ? [hedgeDue] : []]);
1569
- clearTimeout(timer);
1570
- if (!settled) continue;
1571
- const { attempt, outcome } = settled;
1572
- asked.delete(attempt.relay);
1573
- const relay = attempt.relay;
1574
- if (outcome.kind === "packet" || outcome.kind === "missing") {
1575
- winner = {
1576
- attempt,
1577
- outcome
1578
- };
1579
- break;
1580
- }
1581
- if (outcome.kind === "throttled") {
1582
- budgetWait = Math.min(budgetWait, this.coolDown(relay, outcome.response));
1583
- this.answered(relay, {
1584
- kind: "throttled",
1585
- reason: "rate limited (429)"
1586
- });
1587
- } else if (outcome.kind === "failed") {
1588
- this.networkCooldown.set(`GET ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
1589
- this.answered(relay, {
1590
- kind: "error",
1591
- reason: outcome.reason
1592
- });
1593
- down = true;
1594
- }
1595
- ask(false);
1596
- }
1597
- if (winner) {
1598
- const { attempt, outcome } = winner, relay = attempt.relay;
1599
- const took = Date.now() - attempt.started;
1600
- if (outcome.kind === "packet") {
1601
- this.sawTimestamp(pubKeyZ32, outcome.packet.timestampMicros);
1602
- this.newest.set(pubKeyZ32, newerPacket(this.newest.get(pubKeyZ32), outcome.packet));
1603
- this.missing.delete(pubKeyZ32);
1604
- } else {
1605
- this.missing.delete(pubKeyZ32);
1606
- this.missing.add(pubKeyZ32);
1607
- if (this.missing.size > READ_TURNS_KEPT) this.missing.delete(this.missing.values().next().value);
1608
- }
1609
- if (took <= 3e3) {
1610
- this.answered(relay, void 0, "GET");
1611
- this.slowUntil.delete(relay);
1612
- } else {
1613
- this.networkCooldown.delete(`GET ${relay}`);
1614
- if (outcome.kind === "packet") this.slow(relay);
1615
- else this.breaker.cancel(relay);
1616
- }
1617
- for (const loser of asked.values()) {
1618
- loser.controller.abort();
1619
- if (loser.started <= attempt.started && (outcome.kind === "packet" || Date.now() - loser.started >= 6e3)) this.slow(loser.relay);
1620
- else this.breaker.cancel(loser.relay);
1621
- }
1622
- this.lastRelay = relay;
1623
- this.answeredRead(pubKeyZ32);
1624
- this.readFrom(pubKeyZ32, relay);
1625
- return this.newest.get(pubKeyZ32) ?? null;
1626
- }
1627
- const resting = this.relays.every((r) => this.isCoolingDown(r, "GET") || this.breaker.blockedFor(r) > 0 || this.heldFor(r, who, Date.now(), pubKeyZ32) > 0);
1628
- const known = down ? this.newest.get(pubKeyZ32) : newerPacket(this.newest.get(pubKeyZ32), this.written.get(pubKeyZ32));
1629
- if (resting && known) {
1630
- if (down && !keptOnFailure) throw new RelaysFailedError(known);
1631
- if (!down && budgetWait < Infinity) this.heldBackUntil(pubKeyZ32, Date.now() + budgetWait);
1632
- return known;
1633
- }
1634
- if (!down && budgetWait < Infinity) {
1635
- this.heldBackUntil(pubKeyZ32, Date.now() + budgetWait);
1636
- throw new DiscoveryBudgetError(budgetWait);
1637
- }
1638
- throw new Error("No Pkarr relay reachable");
1639
- }
1640
- /**
1641
- * The order a key's read asks the relays in: in turn per key (see `resolve`), relays found slow lately or leaving a
1642
- * request unanswered (`unanswering`) last. A relay
1643
- * with a small share of its own (`RELAY_REQUESTS_PER_MINUTE` under `REQUESTS_PER_MINUTE`: pkarr.miguelmedeiros.dev's 5)
1644
- * takes no turns: it comes after the others, for when they refuse, fail or are slow, unless every relay is one. In the
1645
- * turn, it was spent in seconds and the relay after it took its turns too: pkarr.pubky.org got two reads in three and
1646
- * pkarr.pubky.app, with twice its share, one. Its few requests are then left for writes, which go to every relay.
1647
- */
1648
- readOrder(pubKeyZ32) {
1649
- const full = this.relays.filter((relay) => !((RELAY_REQUESTS_PER_MINUTE[relay] ?? Infinity) < 30));
1650
- const ring = full.length ? full : this.relays;
1651
- const last = this.lastReadFrom.get(pubKeyZ32), lastAt = last === void 0 ? -1 : this.relays.indexOf(last);
1652
- const after = lastAt < 0 ? -1 : ring.findIndex((relay) => this.relays.indexOf(relay) > lastAt);
1653
- const start = lastAt < 0 ? this.cursor++ : after < 0 ? 0 : after;
1654
- const turn = [...ring.map((_, i) => ring[(start + i) % ring.length]), ...this.relays.filter((relay) => !ring.includes(relay))];
1655
- const now = Date.now(), behind = (relay) => (this.slowUntil.get(relay) ?? 0) > now || this.unanswering(relay, now);
1656
- return [...turn.filter((relay) => !behind(relay)), ...turn.filter(behind)];
1657
- }
1658
- /**
1659
- * A request of this client has waited on the relay for `HEDGE_MS` and it has answered none since: it goes after the
1660
- * others in a read (`readOrder`), at no cost of a request. A relay that took connections and never answered held a
1661
- * fresh device's first pairing at its turn: the key's last read had found nothing (`HEDGE_MISSING_MS`), so the read
1662
- * 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).
1663
- */
1664
- unanswering(relay, now) {
1665
- const since = this.answeredAt.get(relay) ?? -Infinity;
1666
- for (const request of this.waiting.get(relay) ?? []) if (request.at > since && now - request.at >= this.hedgeMs) return true;
1667
- return false;
1668
- }
1669
- /** One GET of a key at one relay, which `controller` drops. Never rejects: what happened is the outcome. */
1670
- readFromRelay(relay, pubKeyZ32) {
1671
- const controller = new AbortController();
1672
- return {
1673
- relay,
1674
- controller,
1675
- started: Date.now(),
1676
- done: (async () => {
1677
- let status = 0;
1678
- try {
1679
- let payload;
1680
- const response = await this.request(`${relay}/${pubKeyZ32}`, { method: "GET" }, async (r, signal) => {
1681
- status = r.status;
1682
- if (r.ok && r.status !== 404) payload = await readRelayBody(r, signal);
1683
- }, controller.signal);
1684
- status = response.status;
1685
- if (response.status === 429) return {
1686
- kind: "throttled",
1687
- response
1688
- };
1689
- if (response.status === 404) return { kind: "missing" };
1690
- if (!response.ok) throw new Error(`${relay} responded ${response.status}`);
1691
- return {
1692
- kind: "packet",
1693
- packet: parseRelayPayload(pubKeyZ32, payload)
1694
- };
1695
- } catch {
1696
- if (controller.signal.aborted) return { kind: "cancelled" };
1697
- return {
1698
- kind: "failed",
1699
- reason: status >= 200 && status < 300 ? "invalid packet" : status ? `HTTP ${status}` : "no answer"
1700
- };
1701
- }
1702
- })()
1703
- };
1704
- }
1705
- /**
1706
- * The relay was slow (`SLOW_MS`): it goes after the others for a while, and counts it against its breaker while
1707
- * another relay is there to ask. With none, a slow answer beats no answer: it counts as one.
1708
- */
1709
- slow(relay) {
1710
- this.slowUntil.set(relay, Date.now() + SLOW_DEMOTE_MS);
1711
- if (this.relays.some((r) => r !== relay && this.breaker.blockedFor(r) === 0 && !this.isCoolingDown(r, "GET"))) this.breaker.failure(relay, "error", "slow");
1712
- else this.breaker.success(relay, this.relays);
1713
- }
1714
- /**
1715
- * A hedge may go to this relay: its minute has more requests left than what groups leave a chat (`reserveOf`), so
1716
- * a second request for a read that already went out never takes one a pairing needs.
1717
- */
1718
- hedgeRoom(relay) {
1719
- const now = Date.now();
1720
- return within$1(this.spent.get(relay) ?? [], now, 6e4).length < this.limitOf(relay) - this.reserveOf(relay);
1721
- }
1722
- readAnsweredAt(pubKeyZ32) {
1723
- return this.readAt.get(pubKeyZ32);
1724
- }
1725
- /** The last read of this key was answered 404 (`HEDGE_MISSING_MS`): a relay takes seconds to say so. */
1726
- lastReadMissing(pubKeyZ32) {
1727
- return this.missing.has(pubKeyZ32);
1728
- }
1729
- readHeldBackFor(pubKeyZ32) {
1730
- const held = this.heldBack.get(pubKeyZ32);
1731
- const left = held === void 0 ? 0 : held.until - Date.now();
1732
- return left > 0 ? left : void 0;
1733
- }
1734
- heldBackUntil(pubKeyZ32, until) {
1735
- const held = this.heldBack.get(pubKeyZ32), times = (held?.times ?? 0) + 1;
1736
- this.heldBack.delete(pubKeyZ32);
1737
- this.heldBack.set(pubKeyZ32, {
1738
- until,
1739
- times,
1740
- since: held?.since ?? Date.now()
1741
- });
1742
- if (this.heldBack.size > READ_TURNS_KEPT) this.heldBack.delete(this.heldBack.keys().next().value);
1743
- }
1744
- /** The relays answered a read of this key now; answers older than `FRESH_READ_MS` are dropped as the list grows. */
1745
- answeredRead(pubKeyZ32) {
1746
- const now = Date.now();
1747
- this.heldBack.delete(pubKeyZ32);
1748
- this.readAt.delete(pubKeyZ32);
1749
- this.readAt.set(pubKeyZ32, now);
1750
- if (this.readAt.size > 64) for (const [key, at] of this.readAt) {
1751
- if (now - at < this.freshReadMs) break;
1752
- this.readAt.delete(key);
1753
- }
1754
- }
1755
- /** The relay that answered a key's read, for its next one; the keys read longest ago go past `READ_TURNS_KEPT`. */
1756
- readFrom(pubKeyZ32, relay) {
1757
- this.lastReadFrom.delete(pubKeyZ32);
1758
- this.lastReadFrom.set(pubKeyZ32, relay);
1759
- if (this.lastReadFrom.size > READ_TURNS_KEPT) this.lastReadFrom.delete(this.lastReadFrom.keys().next().value);
1760
- }
1761
- /**
1762
- * A relay whose budget (this client's, or its own rate limit) held a packet back that another relay took: it gets
1763
- * that packet when it frees a request, as a background write (`who`: a group edge's offer or answer as its own, also
1764
- * after that relay failed it). Only the newest per key and relay; a newer packet put everywhere drops it. Without this,
1765
- * that relay kept the key's older packet for good, and an app that restarted and read it first found a contact's offer
1766
- * long answered, answered it again, and waited on it (bug hunt r7a).
1767
- */
1768
- catchUpLater(relay, key, payload, timestamp, who = CATCH_UP_ASKER) {
1769
- const slot = `${relay} ${key}`;
1770
- if ((this.lastPut.get(slot) ?? 0n) > timestamp) return;
1771
- const pending = this.catchUp.get(slot);
1772
- if (pending && pending.timestamp >= timestamp) return;
1773
- this.catchUp.set(slot, {
1774
- relay,
1775
- key,
1776
- payload,
1777
- timestamp,
1778
- who
1779
- });
1780
- this.scheduleCatchUp(CATCH_UP_MIN_MS);
1781
- }
1782
- scheduleCatchUp(inMs) {
1783
- if (this.catchUpTimer || this.catchUp.size === 0) return;
1784
- this.catchUpTimer = setTimeout(() => {
1785
- this.catchUpTimer = null;
1786
- this.runCatchUp();
1787
- }, inMs);
1788
- }
1789
- async runCatchUp() {
1790
- let next = Infinity;
1791
- for (const [slot, item] of [...this.catchUp]) {
1792
- if (this.catchUp.get(slot) !== item) continue;
1793
- const coolingDown = (this.networkCooldown.get(`PUT ${item.relay}`) ?? 0) - Date.now();
1794
- const wait = Math.max(this.heldFor(item.relay, item.who), this.rateLimitedFor(item.relay), this.breaker.blockedFor(item.relay), coolingDown);
1795
- if (wait > 0) {
1796
- next = Math.min(next, wait);
1797
- continue;
1798
- }
1799
- this.catchUp.delete(slot);
1800
- try {
1801
- const response = await this.put(item.relay, item.key, item.payload, void 0, item.who);
1802
- if ((response.status === 428 || response.status === 429) && !this.catchUp.has(slot)) {
1803
- this.catchUp.set(slot, item);
1804
- next = Math.min(next, CATCH_UP_RETRY_MS);
1805
- }
1806
- } catch (error) {
1807
- if (isDiscoveryBudgetError(error) && !this.catchUp.has(slot)) {
1808
- this.catchUp.set(slot, item);
1809
- next = Math.min(next, error.retryInMs);
1810
- }
1811
- }
1812
- }
1813
- if (this.catchUp.size) this.scheduleCatchUp(Math.max(CATCH_UP_MIN_MS, next === Infinity ? CATCH_UP_RETRY_MS : next));
1814
- }
1815
- /** `sent`: told, once the budget took the request, whether the relay takes the packet (a 2xx). */
1816
- async put(relay, pubKeyZ32, payload, replaces, who, probe = false, sent) {
1817
- const refused = this.refusal(relay, probe);
1818
- if (refused) throw refused;
1819
- if (!this.take(relay, who, pubKeyZ32)) throw new DiscoveryBudgetError(this.heldFor(relay, who));
1820
- if (probe) this.breaker.beginAllDown(relay);
1821
- else this.breaker.begin(relay);
1822
- const request = this.request(`${relay}/${pubKeyZ32}`, {
1823
- method: "PUT",
1824
- body: payload,
1825
- headers: replaces === void 0 ? void 0 : { "If-Match": replaces.toString() }
1826
- });
1827
- sent?.(request.then((r) => r.ok, () => false));
1828
- let response;
1829
- try {
1830
- response = await request;
1831
- } catch (error) {
1832
- this.networkCooldown.set(`PUT ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
1833
- this.answered(relay, {
1834
- kind: "error",
1835
- reason: "no answer"
1836
- });
1837
- throw new RelayNoAnswerError(`${relay} did not answer`, !connectFailed(error));
1838
- }
1839
- if (response.status === 429) this.answered(relay, {
1840
- kind: "throttled",
1841
- reason: "rate limited (429)"
1842
- });
1843
- else if (response.status >= 500) this.answered(relay, {
1844
- kind: "error",
1845
- reason: `HTTP ${response.status}`
1846
- });
1847
- else this.answered(relay, void 0, "PUT");
1848
- return response;
1849
- }
1850
- /**
1851
- * Discovery reads and writes share a bounded per-relay request budget; background requests only part of it, and
1852
- * groups leave a chat the budget refused its reserve. A link's write the budget refused goes before any read
1853
- * once a request is free again.
1854
- */
1855
- take(relay, who, key) {
1856
- const now = Date.now();
1857
- const writer = firstWriter(who);
1858
- if (who.urgent && !who.background) {
1859
- this.urgentAt = now;
1860
- if (isChat(who)) this.chatNeed(key, now);
1861
- }
1862
- if (isGroupRead(who) || isChatWatch(who)) this.readAsked(key, who, now);
1863
- if (isTurnRead(who)) this.turnAsked(key, who, now);
1864
- if (isAwaitedRead(who)) this.awaitedAt = now;
1865
- if (this.heldFor(relay, who, now, key) > 0) {
1866
- if (isGroupRead(who) && (this.spent.get(relay)?.length ?? 0) >= this.limitOf(relay)) this.groupsFullAt.set(relay, now);
1867
- if (isChat(who)) this.chatNeed(key, now, relay);
1868
- if (writer) this.writeWaiting.set(`${writer} ${relay}`, now);
1869
- if (isGroupAnswerRead(who)) {
1870
- const waiting = this.answerReadWaiting.get(relay) ?? /* @__PURE__ */ new Map();
1871
- this.answerReadWaiting.set(relay, waiting.set(key, now));
1872
- }
1873
- return false;
1874
- }
1875
- if (writer) this.writeWaiting.delete(`${writer} ${relay}`);
1876
- if (isGroupAnswerRead(who)) this.answerReadWaiting.get(relay)?.delete(key);
1877
- if (isWayBack(who) && this.heldFor(relay, {
1878
- ...who,
1879
- back: false
1880
- }, now, key, false) > 0) {
1881
- this.spentWayBack.set(relay, [...this.spentWayBack.get(relay) ?? [], now]);
1882
- if (isGroupRead(who)) this.readTurns.set(key, {
1883
- servedAt: now,
1884
- askedAt: now,
1885
- waiting: false,
1886
- watch: false,
1887
- lane: watchLane(who)
1888
- });
1889
- return true;
1890
- }
1891
- if (isGroupAnswerRead(who) && this.heldFor(relay, who, now, key, false, false) > 0) {
1892
- this.spentAnswerAllowance.set(relay, [...this.spentAnswerAllowance.get(relay) ?? [], now]);
1893
- this.readTurns.set(key, {
1894
- servedAt: now,
1895
- askedAt: now,
1896
- waiting: false,
1897
- watch: false,
1898
- lane: watchLane(who),
1899
- answer: true
1900
- });
1901
- return true;
1902
- }
1903
- if (isGroupSignal(who) && !who.write && this.spent.get(relay).length >= this.limitOf(relay)) this.spentGroupOver.get(relay).push(now);
1904
- if (isGroupSignal(who)) this.spentGroupSignal.get(relay).push(now);
1905
- const departedOver = isDepartedRead(who) && this.spent.get(relay).length >= this.limitOf(relay);
1906
- if (departedOver) this.overAdd(this.departedOver, key, now);
1907
- if (isAwaitedRead(who) && this.spent.get(relay).length >= this.limitOf(relay)) this.awaitedOver = [...within$1(this.awaitedOver, now, 6e4), now];
1908
- this.spent.get(relay).push(now);
1909
- if (who.background) this.spentBackground.get(relay).push(now);
1910
- if (who.background && who.write) this.spentBackgroundWrites.get(relay).push(now);
1911
- if (isGroupUrgentRead(who) && isGroupAnswerRead(who)) this.spentAnswerUrgent.set(relay, [...this.spentAnswerUrgent.get(relay) ?? [], now]);
1912
- else if (isGroupUrgentRead(who)) this.spentGroupUrgent.get(relay).push(now);
1913
- if (isWatch(who)) this.spentWatch.get(relay).push(now);
1914
- if (isChatWatch(who) && !departedOver) this.spentChatWatch.get(relay).push(now);
1915
- if (isGroupRead(who)) this.spentGroupReads.get(relay).push(now);
1916
- if (isGroupRead(who) || isChatWatch(who)) this.readTurns.set(key, {
1917
- servedAt: now,
1918
- askedAt: now,
1919
- waiting: false,
1920
- watch: isWatch(who) || isChatWatch(who),
1921
- lane: watchLane(who)
1922
- });
1923
- if (isTurnRead(who)) this.keyTurns.set(key, {
1924
- servedAt: now,
1925
- askedAt: now,
1926
- waiting: false,
1927
- who
1928
- });
1929
- return true;
1930
- }
1931
- /**
1932
- * How long until this relay's budget takes this request, 0 when it would now: the oldest request of the minute over
1933
- * a limit ages out, a chat's reserve lapses, or a waiting write has had its turn. Keeps the lists to the minute, oldest first.
1934
- *
1935
- * Who goes first: a chat's refused write holds back everything but chat writes; a group's refused write holds back
1936
- * group reads and background requests, never a chat's. Background requests yield to a link that signals. A chat's
1937
- * signaling goes over the limit by its allowance (`SIGNALING_ALLOWANCE_SHARE`), and so do a few of its reads of a
1938
- * 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
1939
- * without its own allowance (`ANSWER_READ_ALLOWANCE`).
1940
- */
1941
- heldFor(relay, who, now = Date.now(), key, turns = true, ownAllowance = true) {
1942
- const recent = within$1(this.spent.get(relay) ?? [], now, 6e4);
1943
- const recentBackground = within$1(this.spentBackground.get(relay) ?? [], now, 6e4);
1944
- this.spent.set(relay, recent);
1945
- this.spentBackground.set(relay, recentBackground);
1946
- const recentBackgroundWrites = within$1(this.spentBackgroundWrites.get(relay) ?? [], now, 6e4);
1947
- this.spentBackgroundWrites.set(relay, recentBackgroundWrites);
1948
- const over = (list, limit) => list.length >= limit ? list[list.length - limit] + 6e4 - now : 0;
1949
- const limit = this.limitOf(relay);
1950
- const departed = isDepartedRead(who) && key !== void 0 && recent.length >= limit && this.overReads(this.departedOver, key, now) < 6;
1951
- if (isAwaitedRead(who)) this.awaitedOver = within$1(this.awaitedOver, now, 6e4);
1952
- const awaited = isAwaitedRead(who) && key !== void 0 && recent.length >= limit && this.awaitedOver.length < 4;
1953
- const share = isChatSignal(who) || departed || awaited ? SIGNALING_ALLOWANCE_SHARE : isGroupSignal(who) ? GROUP_SIGNALING_ALLOWANCE_SHARE : 0;
1954
- let allowance = share ? Math.max(0, Math.floor(limit * share) - (who.write ? 0 : 1)) : 0;
1955
- if (departed && now - this.awaitedAt < 6e4) allowance = Math.max(0, allowance - 2);
1956
- const groupSignaled = within$1(this.spentGroupSignal.get(relay) ?? [], now, 6e4);
1957
- this.spentGroupSignal.set(relay, groupSignaled);
1958
- const groupFloor = isGroupSignal(who) && groupSignaled.length < allowance;
1959
- let wait = groupFloor ? 0 : over(recent, limit + allowance);
1960
- const starved = key !== void 0 && this.starved(key, who, now);
1961
- const groupOver = within$1(this.spentGroupOver.get(relay) ?? [], now, GROUP_OVER_PACE_MS);
1962
- this.spentGroupOver.set(relay, groupOver);
1963
- if (isGroupSignal(who) && !who.write && recent.length >= limit && groupOver.length > 0) wait = Math.max(wait, groupOver[groupOver.length - 1] + GROUP_OVER_PACE_MS - now);
1964
- if (who.background && !starved) {
1965
- const backgroundShare = Math.min(this.backgroundPerMinute, Math.ceil(limit * 2 / 3));
1966
- wait = Math.max(wait, over(recentBackground, backgroundShare));
1967
- if (who.write) wait = Math.max(wait, over(recentBackgroundWrites, Math.max(1, Math.floor(backgroundShare * BACKGROUND_WRITES_SHARE))));
1968
- const signaling = this.urgentAt + SIGNALING_WINDOW_MS - now;
1969
- if (signaling > 0 && !who.door) wait = Math.max(wait, Math.min(signaling, over(recentBackground, Math.min(this.backgroundWhileSignaling, Math.ceil(limit / 6)))));
1970
- }
1971
- const burst = within$1(this.spentGroupUrgent.get(relay) ?? [], now, GROUP_BURST_MS);
1972
- this.spentGroupUrgent.set(relay, burst);
1973
- const answerBurst = within$1(this.spentAnswerUrgent.get(relay) ?? [], now, GROUP_BURST_MS);
1974
- this.spentAnswerUrgent.set(relay, answerBurst);
1975
- if (isGroupUrgentRead(who)) {
1976
- const most = Math.max(8, Math.floor(limit * GROUP_BURST_MS / 6e4));
1977
- const spent = isGroupAnswerRead(who) ? answerBurst : burst;
1978
- if (spent.length >= most) wait = Math.max(wait, spent[spent.length - most] + GROUP_BURST_MS - now);
1979
- }
1980
- const watched = within$1(this.spentWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
1981
- this.spentWatch.set(relay, watched);
1982
- let turn = 0;
1983
- if (isWatch(who)) {
1984
- const most = Math.max(1, Math.ceil(limit * WATCH_SHARE * GROUP_RATION_WINDOW_MS / 6e4));
1985
- if (watched.length >= most) wait = Math.max(wait, watched[watched.length - most] + GROUP_RATION_WINDOW_MS - now);
1986
- if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;
1987
- }
1988
- const chatWatched = within$1(this.spentChatWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
1989
- this.spentChatWatch.set(relay, chatWatched);
1990
- if (isChatWatch(who) && !departed) {
1991
- const most = Math.max(1, Math.ceil(limit * CHAT_WATCH_SHARE * GROUP_RATION_WINDOW_MS / 6e4));
1992
- if (chatWatched.length >= most) wait = Math.max(wait, chatWatched[chatWatched.length - most] + GROUP_RATION_WINDOW_MS - now);
1993
- if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;
1994
- }
1995
- const rationed = within$1(this.spentGroupReads.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
1996
- this.spentGroupReads.set(relay, rationed);
1997
- const pastLimit = isGroupSignal(who) && recent.length >= limit;
1998
- if (isGroupRead(who) && !pastLimit && now - (this.groupsFullAt.get(relay) ?? -Infinity) < GROUP_RATION_MS) {
1999
- const most = Math.max(1, Math.ceil(limit * GROUP_RATION_WINDOW_MS / 6e4));
2000
- if (rationed.length >= most) wait = Math.max(wait, rationed[rationed.length - most] + GROUP_RATION_WINDOW_MS - now);
2001
- if (this.readsAhead(key, now, void 0, isGroupAnswerRead(who)) > 0) turn = TURN_WAIT_MS;
2002
- }
2003
- if (who.group && !groupFloor || who.background) {
2004
- const reserved = this.chatReservedFor(relay, now);
2005
- if (reserved > 0) wait = Math.max(wait, Math.min(reserved, over(recent, limit - this.chatReserveOf(relay, now))));
2006
- }
2007
- const writer = firstWriter(who);
2008
- const waiting = (lane) => {
2009
- const at = this.writeWaiting.get(`${lane} ${relay}`);
2010
- return at !== void 0 && now - at < 5e3 ? at + WRITE_FIRST_MS - now : 0;
2011
- };
2012
- const signalOver = isChatSignal(who) && !who.write && recent.length >= limit;
2013
- if (writer !== "chat" && !departed && !awaited && !signalOver && !starved) wait = Math.max(wait, waiting("chat"));
2014
- if ((writer === null && who.group && !pastLimit && !isGroupAnswerRead(who) || who.background) && !starved) wait = Math.max(wait, waiting("group"));
2015
- if (isGroupSignal(who) && !isGroupAnswerRead(who)) {
2016
- const ahead = this.answerReadAhead(relay, now);
2017
- if (ahead && this.heldFor(relay, ANSWER_READER, now, ahead.key, false, false) <= 0) wait = Math.max(wait, ahead.ms);
2018
- }
2019
- if (turns && wait <= 0 && isTurnRead(who) && this.turnAhead(relay, key, who, now)) turn = TURN_WAIT_MS;
2020
- if (wait > 0 && isWayBack(who) && this.wayBackLeft(relay, who, now) > 0) return 0;
2021
- if (wait > 0 && ownAllowance && isGroupAnswerRead(who) && this.answerAllowanceFree(relay, now)) return 0;
2022
- return Math.max(wait, turn, 0);
2023
- }
2024
- /**
2025
- * The edges' reads for their answers may take their own allowance on this relay now (`ANSWER_READ_ALLOWANCE`): fewer
2026
- * than it in the last minute, and none within `ANSWER_READ_SPACING_MS`. None where the groups have no allowance.
2027
- */
2028
- answerAllowanceFree(relay, now) {
2029
- const spent = within$1(this.spentAnswerAllowance.get(relay) ?? [], now, 6e4);
2030
- this.spentAnswerAllowance.set(relay, spent);
2031
- const most = Math.min(3, Math.floor(this.limitOf(relay) * GROUP_SIGNALING_ALLOWANCE_SHARE));
2032
- return spent.length < most && (spent.length === 0 || now - spent[spent.length - 1] >= 2e4);
2033
- }
2034
- /**
2035
- * The edges' reads for their answers the budget refused on this relay within `ANSWER_READ_FIRST_MS`, still not read:
2036
- * the key refused last, and how long the groups' other signaling waits for them there. Undefined when there is none.
2037
- */
2038
- answerReadAhead(relay, now) {
2039
- const waiting = this.answerReadWaiting.get(relay);
2040
- if (!waiting) return void 0;
2041
- let last;
2042
- for (const [key, at] of waiting) if (now - at >= 5e3) waiting.delete(key);
2043
- else if (!last || at > last.at) last = {
2044
- key,
2045
- at
2046
- };
2047
- return last && {
2048
- key: last.key,
2049
- ms: last.at + 5e3 - now
2050
- };
2051
- }
2052
- /** What is left of the community members' way back allowance on this relay (`WAY_BACK_SHARE`); its reads leave a write the last of it. */
2053
- wayBackLeft(relay, who, now) {
2054
- const spent = within$1(this.spentWayBack.get(relay) ?? [], now, 6e4);
2055
- this.spentWayBack.set(relay, spent);
2056
- return Math.floor(this.limitOf(relay) * WAY_BACK_SHARE) - (who.write ? 0 : 1) - spent.length;
2057
- }
2058
- /** A group's read of `key`, or a chat's watch read, asks: it waits for its turn from now on, unless it is taken (`readsAhead`). */
2059
- readAsked(key, who, now) {
2060
- this.pruneTurns(this.readTurns, now);
2061
- const turn = this.readTurns.get(key);
2062
- this.readTurns.set(key, {
2063
- servedAt: turn && !staleTurn(turn, now) ? turn.servedAt : -Infinity,
2064
- askedAt: now,
2065
- waiting: true,
2066
- watch: isWatch(who) || isChatWatch(who),
2067
- lane: watchLane(who),
2068
- answer: isGroupAnswerRead(who)
2069
- });
2070
- }
2071
- /**
2072
- * Keys a group reads, still asking (within `WATCH_TURN_MS`), that were read longer ago than `key`: a share keeps a
2073
- * request for each. With `watchLane`, only watched keys the same other limits hold: one the groups' burst holds back
2074
- * would keep a turn it cannot take. The chats' watched keys only in their own lane (`CHAT_WATCH_SHARE`). `answer`: an
2075
- * edge's read for its answer, which waits only for the others' (`ANSWER_READ_FIRST_MS`).
2076
- */
2077
- readsAhead(key, now, watchLane, answer = false) {
2078
- const mine = key === void 0 ? -Infinity : this.readTurns.get(key)?.servedAt ?? -Infinity;
2079
- let ahead = 0;
2080
- for (const [other, turn] of this.readTurns) {
2081
- if (other === key || !turn.waiting || now - turn.askedAt >= WATCH_TURN_MS) continue;
2082
- if (watchLane !== void 0 ? !turn.watch || turn.lane !== watchLane : turn.lane === "chat") continue;
2083
- if (answer && !turn.answer) continue;
2084
- if (turn.servedAt < mine) ahead++;
2085
- }
2086
- return ahead;
2087
- }
2088
- /** A read of `key` that takes turns asks: it waits for its turn from now on, unless it is taken (`turnAhead`). */
2089
- turnAsked(key, who, now) {
2090
- this.pruneTurns(this.keyTurns, now);
2091
- const turn = this.keyTurns.get(key);
2092
- this.keyTurns.set(key, {
2093
- servedAt: turn && !staleTurn(turn, now) ? turn.servedAt : -Infinity,
2094
- askedAt: now,
2095
- waiting: true,
2096
- who
2097
- });
2098
- }
2099
- /** Drops the turns asked and read over a minute ago, at most once in `TURNS_PRUNE_MS` (or when the clock went back). */
2100
- pruneTurns(turns, now) {
2101
- const prunedAt = this.turnsPrunedAt.get(turns) ?? -Infinity;
2102
- if (Math.abs(now - prunedAt) < TURNS_PRUNE_MS) return;
2103
- this.turnsPrunedAt.set(turns, now);
2104
- const back = now < prunedAt;
2105
- for (const [key, turn] of turns) {
2106
- if (back) {
2107
- turn.servedAt = Math.min(turn.servedAt, now);
2108
- turn.askedAt = Math.min(turn.askedAt, now);
2109
- }
2110
- if (staleTurn(turn, now)) turns.delete(key);
2111
- }
2112
- }
2113
- /**
2114
- * Whether a key read in turn longer ago than `key`, still asking, would take this relay's next request: one read in the
2115
- * background for a background read, and a chat's that is starved (`READ_STARVED_MS`) for any. One asks again after
2116
- * the budget held it back (a link's poll does, a one-off look does not), and keeps asking within `READ_TURN_MS` of its
2117
- * last ask, or of when it was told the budget frees a request for it (`readHeldBackFor`).
2118
- * One the budget holds back on its own account (a group's read, for the chats' reserve) keeps no turn: a group key
2119
- * waiting for the chats held every chat's read back (CLI lab, 2026-10-13).
2120
- */
2121
- turnAhead(relay, key, who, now) {
2122
- const mine = key === void 0 ? -Infinity : this.keyTurns.get(key)?.servedAt ?? -Infinity;
2123
- for (const [other, turn] of this.keyTurns) {
2124
- const held = this.heldBack.get(other);
2125
- if (other === key || !turn.waiting || turn.servedAt >= mine || !held || held.times < 2) continue;
2126
- if (!(who.background && turn.who.background) && !this.starved(other, turn.who, now)) continue;
2127
- if (now - Math.max(turn.askedAt, held.until) < READ_TURN_MS && this.heldFor(relay, turn.who, now, other, false) === 0) return true;
2128
- }
2129
- return false;
2130
- }
2131
- /** A 1:1 chat's read of `key` the budget has held back for `READ_STARVED_MS` without a break. */
2132
- starved(key, who, now) {
2133
- const since = this.heldBack.get(key)?.since;
2134
- return !who.group && !who.write && !who.door && since !== void 0 && now - since >= READ_STARVED_MS;
2135
- }
2136
- /** This key's departed reads past the limit in the last minute (`DEPARTED_READS`). */
2137
- overReads(over, key, now) {
2138
- const reads = within$1(over.get(key) ?? [], now, 6e4);
2139
- if (reads.length) over.set(key, reads);
2140
- else over.delete(key);
2141
- return reads.length;
2142
- }
2143
- /** One more, the keys with none in the last minute dropped. */
2144
- overAdd(over, key, now) {
2145
- for (const [other, reads] of over) if (now - reads[reads.length - 1] >= 6e4) over.delete(other);
2146
- over.set(key, [...over.get(key) ?? [], now]);
2147
- }
2148
- /** A chat's request of `key` asked urgently (it needs every relay), or the budget refused it on `relay` (it needs that one). */
2149
- chatNeed(key, now, relay) {
2150
- if (relay !== void 0) {
2151
- this.chatNeedsOn(relay, now).set(key, now);
2152
- return;
2153
- }
2154
- this.chatUrgentAt.set(key, now);
2155
- for (const needs of this.chatNeeds.values()) needs.set(key, now);
2156
- }
2157
- /** The chats that need this relay: those a request of was refused there, and the urgent ones. */
2158
- chatNeedsOn(relay, now) {
2159
- let needs = this.chatNeeds.get(relay);
2160
- if (!needs) {
2161
- this.chatNeeds.set(relay, needs = new RecentKeys());
2162
- for (const [key, at] of this.chatUrgentAt.entries(now)) needs.set(key, at);
2163
- }
2164
- return needs;
2165
- }
2166
- /** The chat reading `key` has nothing due: it needs no relay any more. */
2167
- chatNeedLapsed(key) {
2168
- this.chatUrgentAt.delete(key);
2169
- for (const needs of this.chatNeeds.values()) needs.delete(key);
2170
- }
2171
- /**
2172
- * How long groups still leave a chat its reserve on this relay (`CHAT_RESERVE`); a chat's need a minute old goes.
2173
- * Kept up to date as needs come and go (`RecentKeys`): walking them all for each request cost a daemon with 500
2174
- * contacts away 2.7 s of CPU per 10 idle minutes (bug hunt, 2026-11-01).
2175
- */
2176
- chatReservedFor(relay, now) {
2177
- return this.chatNeedsOn(relay, now).latest(now) + 6e4 - now;
2178
- }
2179
- /**
2180
- * How long a chat's packet another relay already took waits for this one: while chats need the relays, a copy takes
2181
- * none of the requests their reserve keeps (`chatReserveOf`), as a group's request does not. 0 when it goes now.
2182
- */
2183
- spareHeldFor(relay, now) {
2184
- const reserved = this.chatReservedFor(relay, now);
2185
- if (reserved <= 0) return 0;
2186
- const recent = within$1(this.spent.get(relay) ?? [], now, 6e4);
2187
- const keep = this.limitOf(relay) - this.chatReserveOf(relay, now);
2188
- return recent.length >= keep ? Math.min(reserved, recent[recent.length - keep] + 6e4 - now) : 0;
2189
- }
2190
- /** Requests allowed to this relay a minute: this client's budget, or the relay's own share (`RELAY_REQUESTS_PER_MINUTE`). */
2191
- limitOf(relay) {
2192
- const share = RELAY_REQUESTS_PER_MINUTE[relay];
2193
- if (share === void 0) return this.perMinute;
2194
- return this.perMinuteGiven ? Math.min(this.perMinute, share) : share;
2195
- }
2196
- /** What the chats that need the relays keep on this relay (`CHAT_RESERVE_PER_CHAT`), never less than `reserveOf`. */
2197
- chatReserveOf(relay, now) {
2198
- const needing = this.chatNeedsOn(relay, now).size(now);
2199
- return Math.max(this.reserveOf(relay), Math.min(needing * 3, Math.floor(this.limitOf(relay) * CHAT_RESERVE_MOST_SHARE)));
2200
- }
2201
- /** What groups leave a chat on this relay: `CHAT_RESERVE`, or a third of a smaller budget. */
2202
- reserveOf(relay) {
2203
- return Math.min(10, Math.floor(this.limitOf(relay) / 3));
2204
- }
2205
- isCoolingDown(relay, method) {
2206
- return this.rateLimitedFor(relay) > 0 || this.networkCoolingDown(relay, method);
2207
- }
2208
- /** Left alone after failing at the network level. */
2209
- networkCoolingDown(relay, method) {
2210
- return (this.networkCooldown.get(`${method} ${relay}`) ?? 0) > Date.now();
2211
- }
2212
- /** How much longer the relay asked (429) to be left alone; 0 when it did not. */
2213
- rateLimitedFor(relay) {
2214
- return Math.max(0, (this.coolingDown.get(relay) ?? 0) - Date.now());
2215
- }
2216
- /** Leaves the relay alone for as long as its 429 asks; returns that, in ms. */
2217
- coolDown(relay, response) {
2218
- const retryAfter = Number.parseInt(response.headers.get("retry-after") ?? "", 10);
2219
- const seconds = Number.isFinite(retryAfter) ? Math.min(Math.max(retryAfter, 1), 120) : 15;
2220
- this.coolingDown.set(relay, Date.now() + seconds * 1e3);
2221
- return seconds * 1e3;
2222
- }
2223
- /**
2224
- * One request under one time limit. `read` runs before the timer is cleared, so a body read there is bounded in
2225
- * time as well: a relay that sends its headers and then trickles, or never ends, is given up on like one that
2226
- * never answered.
2227
- */
2228
- /**
2229
- * The relay's own time, when its answer says it and this runtime may read it: Node and the Desktop can, a browser
2230
- * only when the relay exposes the header to other origins. Held against this device's clock (`ClockWatch`).
2231
- */
2232
- serverTime(url, response, sent) {
2233
- if (!this.timeListeners.size) return;
2234
- let date = NaN;
2235
- try {
2236
- if (Number(response.headers.get("age") ?? 0) > 0) return;
2237
- date = Date.parse(response.headers.get("date") ?? "");
2238
- } catch {}
2239
- if (!Number.isFinite(date)) return;
2240
- const time = {
2241
- source: new URL(url).origin,
2242
- date,
2243
- sent,
2244
- received: Date.now()
2245
- };
2246
- for (const listener of this.timeListeners) try {
2247
- listener(time);
2248
- } catch {}
2249
- }
2250
- onServerTime(listener) {
2251
- this.timeListeners.add(listener);
2252
- return () => this.timeListeners.delete(listener);
2253
- }
2254
- /**
2255
- * The turn record's read (WISP 06 § Publishing and reading): every relay, in parallel, `TURN_SOURCE_TIMEOUT_MS`
2256
- * each. Unlike `resolve`, it does not stop at the first relay that answers, keeps nothing, and answers nothing from
2257
- * memory. Each request counts in the relay's minute, so chats see it, but is never held back by it: a device may
2258
- * not act before it has read its turn.
2259
- */
2260
- turnRead(pubKeyZ32, options = {}) {
2261
- const timeoutMs = Math.min(options.timeoutMs ?? 8e3, TURN_SOURCE_TIMEOUT_MS);
2262
- return Promise.all(this.relays.map(async (relay) => {
2263
- try {
2264
- let payload;
2265
- const read = async (r, signal) => {
2266
- if (r.ok) payload = await readRelayBody(r, signal);
2267
- };
2268
- let response = await this.turnRequest(relay, `${pubKeyZ32}?policy=NetworkOnly`, { method: "GET" }, read, timeoutMs);
2269
- const stale = response.status === 400;
2270
- if (stale) response = await this.turnRequest(relay, pubKeyZ32, { method: "GET" }, read, timeoutMs);
2271
- const age = stale ? { stale: true } : {};
2272
- if (response.status === 404) {
2273
- const invalid = response.headers.get(INVALID_PACKET_SEQ_HEADER);
2274
- return {
2275
- source: relay,
2276
- answered: true,
2277
- payloads: [],
2278
- ...age,
2279
- ...invalid && /^\d{1,19}$/.test(invalid) ? { sequences: [invalid] } : {}
2280
- };
2281
- }
2282
- if (!response.ok || !payload) return {
2283
- source: relay,
2284
- answered: false,
2285
- payloads: [],
2286
- detail: `HTTP ${response.status}`
2287
- };
2288
- return {
2289
- source: relay,
2290
- answered: true,
2291
- payloads: [payload],
2292
- ...age
2293
- };
2294
- } catch (error) {
2295
- return {
2296
- source: relay,
2297
- answered: false,
2298
- payloads: [],
2299
- detail: error instanceof Error ? error.message : String(error)
2300
- };
2301
- }
2302
- }));
2303
- }
2304
- /**
2305
- * The turn record's put: the bytes as given, to each relay `conditions` names, with `If-Match` on the sequence that
2306
- * relay is known to hold (none where it held no record). Unlike `putEverywhere`, a relay that refuses (409, 412,
2307
- * 428) is not asked again without the condition: its refusal is the answer, and every relay's answer is reported.
2308
- */
2309
- turnPut(pubKeyZ32, payload, conditions) {
2310
- const relays = this.relays.filter((relay) => conditions[relay] !== void 0);
2311
- return Promise.all(relays.map(async (relay) => {
2312
- const replaces = conditions[relay];
2313
- try {
2314
- const response = await this.turnRequest(relay, pubKeyZ32, {
2315
- method: "PUT",
2316
- body: payload,
2317
- headers: replaces === null ? void 0 : { "If-Match": replaces }
2318
- });
2319
- if (response.ok) return {
2320
- source: relay,
2321
- outcome: "stored",
2322
- detail: `HTTP ${response.status}`
2323
- };
2324
- return {
2325
- source: relay,
2326
- outcome: TURN_REFUSALS.includes(response.status) ? "refused" : "failed",
2327
- detail: `HTTP ${response.status}`
2328
- };
2329
- } catch (error) {
2330
- return {
2331
- source: relay,
2332
- outcome: "failed",
2333
- detail: error instanceof Error ? error.message : String(error)
2334
- };
2335
- }
2336
- }));
2337
- }
2338
- async turnRequest(relay, path, init, read, timeoutMs = TURN_SOURCE_TIMEOUT_MS) {
2339
- this.spent.get(relay)?.push(Date.now());
2340
- const controller = new AbortController();
2341
- const timer = setTimeout(() => controller.abort(), timeoutMs);
2342
- try {
2343
- const response = await this.fetchFn(`${relay}/${path}`, {
2344
- ...init,
2345
- cache: "no-store",
2346
- signal: controller.signal
2347
- });
2348
- await read?.(response, controller.signal);
2349
- return response;
2350
- } finally {
2351
- clearTimeout(timer);
2352
- }
2353
- }
2354
- /** `cancel`: this client drops the request (a hedged read another relay answered first). */
2355
- async request(url, init, read, cancel) {
2356
- const controller = new AbortController();
2357
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
2358
- const drop = () => controller.abort();
2359
- cancel?.addEventListener("abort", drop, { once: true });
2360
- const relay = url.slice(0, url.lastIndexOf("/")), request = { at: Date.now() };
2361
- const waiting = this.waiting.get(relay) ?? /* @__PURE__ */ new Set();
2362
- this.waiting.set(relay, waiting.add(request));
2363
- try {
2364
- const sent = Date.now();
2365
- const response = await this.fetchFn(url, {
2366
- ...init,
2367
- cache: "no-store",
2368
- signal: controller.signal
2369
- });
2370
- this.answeredAt.set(relay, Date.now());
2371
- this.serverTime(url, response, sent);
2372
- await read?.(response, controller.signal);
2373
- return response;
2374
- } finally {
2375
- waiting.delete(request);
2376
- clearTimeout(timer);
2377
- cancel?.removeEventListener("abort", drop);
2378
- }
2379
- }
2380
- };
2381
- /**
2382
- * A relay's answer body, at most RELAY_PAYLOAD_MAX_BYTES: refused on a larger `content-length` before anything is
2383
- * read, and otherwise streamed with a running count, so a relay (a default one or one the person added, working or
2384
- * compromised) cannot fill memory with a huge or endless body. Stops when `signal` aborts.
2385
- */
2386
- async function readRelayBody(response, signal, max = RELAY_PAYLOAD_MAX_BYTES) {
2387
- const tooLarge = () => /* @__PURE__ */ new Error(`Relay answer is larger than ${max} bytes`);
2388
- if (Number(response.headers.get("content-length")) > max) {
2389
- response.body?.cancel().catch(() => {});
2390
- throw tooLarge();
2391
- }
2392
- if (!response.body) return /* @__PURE__ */ new Uint8Array(0);
2393
- const reader = response.body.getReader();
2394
- const stop = () => {
2395
- reader.cancel().catch(() => {});
2396
- };
2397
- signal.addEventListener("abort", stop, { once: true });
2398
- try {
2399
- const chunks = [];
2400
- let length = 0;
2401
- for (;;) {
2402
- if (signal.aborted) throw new Error("Relay answer timed out");
2403
- const { done, value } = await reader.read();
2404
- if (signal.aborted) throw new Error("Relay answer timed out");
2405
- if (done) break;
2406
- length += value.byteLength;
2407
- if (length > max) {
2408
- stop();
2409
- throw tooLarge();
2410
- }
2411
- chunks.push(value);
2412
- }
2413
- const body = new Uint8Array(length);
2414
- let at = 0;
2415
- for (const chunk of chunks) {
2416
- body.set(chunk, at);
2417
- at += chunk.byteLength;
2418
- }
2419
- return body;
2420
- } finally {
2421
- signal.removeEventListener("abort", stop);
2422
- }
2423
- }
2424
70
  // ../core/src/turnRecord.ts
2425
71
  /** The record's format, byte 0 of the body. */
2426
72
  var TURN_VERSION = 1;
@@ -7862,6 +5508,7 @@ var VIEWER_PERMISSIONS_POLICY = [
7862
5508
  "serial",
7863
5509
  "hid",
7864
5510
  "clipboard-read",
5511
+ "clipboard-write",
7865
5512
  "idle-detection",
7866
5513
  "local-fonts",
7867
5514
  "window-management",
@@ -8422,7 +6069,14 @@ var HttpClient = class {
8422
6069
  * refuses `javascript:` URLs (its own Trusted Types default policy: one passes every other string on as it is);
8423
6070
  * - refuses a declarative shadow root the page's script would make (`setHTMLUnsafe`, `Document.parseHTMLUnsafe`,
8424
6071
  * `document.write`, a write split in two too): its `srcdoc` frames would be out of the guard's sight;
8425
- * - listens for frames' loads again after `document.open()`, which takes every listener of the document away.
6072
+ * - listens for frames' loads again after `document.open()`, which takes every listener of the document away;
6073
+ * - starts a worker made from a `blob:` URL of the page's own (`URL.createObjectURL` in that window) from a script of its
6074
+ * own that makes a pass-through Trusted Types `default` policy there first and then runs the page's (`importScripts`;
6075
+ * for a module worker, a static `import` of the policy's module, then of the page's): such a worker takes the page's
6076
+ * policy, Trusted Types included, and no guard runs in it to make one. A `SharedWorker` made twice from one blob gets
6077
+ * 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.
6078
+ * A `data:` worker, and a blob made in another window, in a worker or already revoked, run as they were. Once per
6079
+ * window, whichever guard runs first (`ghostlyWorkerGuard`, `CLIPBOARD_GUARD_SCRIPT` does the same).
8426
6080
  * It uses nothing the page can change after it ran (the page's own code runs later, in the same realm).
8427
6081
  *
8428
6082
  * What a script put in the page cannot do, so where the viewer does not run it per document this is not a guarantee:
@@ -8545,12 +6199,71 @@ var VIEWER_GUARD_SCRIPT = `(function noWebRtc(w) {
8545
6199
  return root;
8546
6200
  };
8547
6201
  }
6202
+ if (w.trustedTypes && w.URL && w.Blob && !describe(w, "ghostlyWorkerGuard")) {
6203
+ try {
6204
+ define(w, "ghostlyWorkerGuard", { value: true });
6205
+ const construct = Reflect.construct;
6206
+ const json = JSON.stringify;
6207
+ const later = w.setTimeout;
6208
+ const Blob = w.Blob;
6209
+ const sized = describe(Blob.prototype, "size").get;
6210
+ const make = w.URL.createObjectURL;
6211
+ const revoke = w.URL.revokeObjectURL;
6212
+ const policy = "if (self.trustedTypes && !self.trustedTypes.defaultPolicy) { try { self.trustedTypes.createPolicy('default', { createHTML: (s) => s, createScript: (s) => s, createScriptURL: (s) => s }); } catch (e) {} }";
6213
+ const script = (code) => apply(make, null, [new Blob([code], { type: "text/javascript" })]);
6214
+ const known = { __proto__: null };
6215
+ let first = null;
6216
+ w.URL.createObjectURL = function createObjectURL(object) {
6217
+ const made = apply(make, this, arguments);
6218
+ try { apply(sized, object, []); known[made] = { blob: object, inner: null, classic: null, module: null }; } catch (e) {}
6219
+ return made;
6220
+ };
6221
+ w.URL.revokeObjectURL = function revokeObjectURL(url) {
6222
+ try {
6223
+ const key = text(url);
6224
+ const entry = known[key];
6225
+ if (entry) {
6226
+ delete known[key];
6227
+ const ours = [entry.inner, entry.classic, entry.module];
6228
+ apply(later, w, [() => { for (let i = 0; i < 3; i++) { if (ours[i] !== null) apply(revoke, null, [ours[i]]); } }, 60000]);
6229
+ }
6230
+ } catch (e) {}
6231
+ return apply(revoke, this, arguments);
6232
+ };
6233
+ const start = (url, options) => {
6234
+ const entry = known[text(url)];
6235
+ if (!entry) return url;
6236
+ const kind = options && typeof options === "object" && options.type === "module" ? "module" : "classic";
6237
+ if (entry[kind] === null) {
6238
+ if (entry.inner === null) entry.inner = apply(make, null, [entry.blob]);
6239
+ if (kind === "module" && first === null) first = script(policy);
6240
+ entry[kind] = script(kind === "module" ? "import " + json(first) + "; import " + json(entry.inner) + ";" : policy + " importScripts(" + json(entry.inner) + ");");
6241
+ }
6242
+ return entry[kind];
6243
+ };
6244
+ for (const name of ["Worker", "SharedWorker"]) {
6245
+ const Real = w[name];
6246
+ if (typeof Real !== "function") continue;
6247
+ const started = function (url) {
6248
+ if (new.target === undefined) return apply(Real, this, arguments);
6249
+ const args = [];
6250
+ for (let i = 0; i < arguments.length; i++) args[i] = arguments[i];
6251
+ if (args.length > 0) { try { args[0] = start(url, args[1]); } catch (e) {} }
6252
+ return construct(Real, args, new.target);
6253
+ };
6254
+ define(started, "name", { value: name });
6255
+ started.prototype = Real.prototype;
6256
+ define(Real.prototype, "constructor", { value: started, writable: true, enumerable: false, configurable: true });
6257
+ w[name] = started;
6258
+ }
6259
+ } catch (e) {}
6260
+ }
8548
6261
  apply(listen, home, ["load", sweep, true]);
8549
6262
  watch(home, w.Document.prototype.querySelectorAll);
8550
6263
  } catch (e) {}
8551
6264
  })(window)`;
8552
6265
  /** `VIEWER_GUARD_SCRIPT`'s hash, as a CSP source: a contact's own policy that would refuse it is given it (`allowingViewerGuard`). */
8553
- var VIEWER_GUARD_HASH = "'sha256-P3jYgJwfoJ/cAS31rQz7Tk99bBwsSeN2wDDqJubDMZw='";
6266
+ var VIEWER_GUARD_HASH = "'sha256-DweV0mr/eyHFWESxtsRrzk0i6VjF4GSCokjozAiXkbQ='";
8554
6267
  /**
8555
6268
  * 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
8556
6269
  * origin (a `data:` or `blob:` frame would run before the guard could), and Trusted Types, which hands each
@@ -8792,7 +6505,9 @@ async function guardViewerAnswer(headers, body, destination, guards = [WEBRTC_GU
8792
6505
  * this script first, a declarative shadow root the page's script would make is refused, and with `VIEWER_GUARD_CSP`
8793
6506
  * a `javascript:` URL is refused (its own Trusted Types default policy; one passes every other string on as it is,
8794
6507
  * or, once the page made its own `default` policy, to that one's rules: the page's `createPolicy("default")` gets the
8795
- * guard's policy back with them, and the copy of itself it puts in a `srcdoc` frame skips them).
6508
+ * guard's policy back with them, and the copy of itself it puts in a `srcdoc` frame skips them);
6509
+ * - starts a worker made from a `blob:` URL of the page's own from a script that makes a pass-through Trusted Types
6510
+ * `default` policy in it first, as the WebRTC guard does (`VIEWER_GUARD_SCRIPT`, whichever of the two runs first).
8796
6511
  * A frame's window keeps what was run in it on its first, empty page when the page it loads is of the same origin (the
8797
6512
  * bridge's guard reaches the app's frame then): there this script only watches the new document. Each document it
8798
6513
  * watches is marked (`ghostlyClipboardGuard`, fixed in place): the bridge reads that to know the guard ran in the page
@@ -8972,6 +6687,66 @@ var CLIPBOARD_GUARD_SCRIPT = `(function noClipboardWrites(w) {
8972
6687
  };
8973
6688
  } catch (e) {}
8974
6689
  }
6690
+ if (types && w.URL && w.Blob && !describe(w, "ghostlyWorkerGuard")) {
6691
+ try {
6692
+ define(w, "ghostlyWorkerGuard", { value: true });
6693
+ const construct = w.Reflect.construct;
6694
+ const json = w.JSON.stringify;
6695
+ const later = w.setTimeout;
6696
+ const Blob = w.Blob;
6697
+ const sized = describe(Blob.prototype, "size").get;
6698
+ const make = w.URL.createObjectURL;
6699
+ const revoke = w.URL.revokeObjectURL;
6700
+ const policy = "if (self.trustedTypes && !self.trustedTypes.defaultPolicy) { try { self.trustedTypes.createPolicy('default', { createHTML: (s) => s, createScript: (s) => s, createScriptURL: (s) => s }); } catch (e) {} }";
6701
+ const script = (code) => apply(make, null, [new Blob([code], { type: "text/javascript" })]);
6702
+ const known = { __proto__: null };
6703
+ let first = null;
6704
+ w.URL.createObjectURL = function createObjectURL(object) {
6705
+ const made = apply(make, this, arguments);
6706
+ try { apply(sized, object, []); known[made] = { blob: object, inner: null, classic: null, module: null }; } catch (e) {}
6707
+ return made;
6708
+ };
6709
+ w.URL.revokeObjectURL = function revokeObjectURL(url) {
6710
+ try {
6711
+ const key = text(url);
6712
+ const entry = known[key];
6713
+ if (entry) {
6714
+ delete known[key];
6715
+ const ours = [entry.inner, entry.classic, entry.module];
6716
+ apply(later, w, [() => { for (let i = 0; i < 3; i++) { if (ours[i] !== null) apply(revoke, null, [ours[i]]); } }, 60000]);
6717
+ }
6718
+ } catch (e) {}
6719
+ return apply(revoke, this, arguments);
6720
+ };
6721
+ const start = (url, options) => {
6722
+ const entry = known[text(url)];
6723
+ if (!entry) return url;
6724
+ const kind = options && typeof options === "object" && options.type === "module" ? "module" : "classic";
6725
+ if (entry[kind] === null) {
6726
+ if (entry.inner === null) entry.inner = apply(make, null, [entry.blob]);
6727
+ if (kind === "module" && first === null) first = script(policy);
6728
+ entry[kind] = script(kind === "module" ? "import " + json(first) + "; import " + json(entry.inner) + ";" : policy + " importScripts(" + json(entry.inner) + ");");
6729
+ }
6730
+ return entry[kind];
6731
+ };
6732
+ const makers = ["Worker", "SharedWorker"];
6733
+ for (let i = 0; i < makers.length; i++) {
6734
+ const Real = w[makers[i]];
6735
+ if (typeof Real !== "function") continue;
6736
+ const started = function (url) {
6737
+ if (new.target === undefined) return apply(Real, this, arguments);
6738
+ const args = [];
6739
+ for (let j = 0; j < arguments.length; j++) args[j] = arguments[j];
6740
+ if (args.length > 0) { try { args[0] = start(url, args[1]); } catch (e) {} }
6741
+ return construct(Real, args, new.target);
6742
+ };
6743
+ define(started, "name", { value: makers[i] });
6744
+ started.prototype = Real.prototype;
6745
+ define(Real.prototype, "constructor", { value: started, writable: true, enumerable: false, configurable: true });
6746
+ w[makers[i]] = started;
6747
+ }
6748
+ } catch (e) {}
6749
+ }
8975
6750
  const reopen = proto.open;
8976
6751
  proto.open = function () {
8977
6752
  const got = apply(reopen, this, arguments);
@@ -9037,7 +6812,7 @@ var CLIPBOARD_GUARD_SCRIPT = `(function noClipboardWrites(w) {
9037
6812
  } catch (e) {}
9038
6813
  })(window)`;
9039
6814
  /** `CLIPBOARD_GUARD_SCRIPT`'s hash, as a CSP source: the bridge's policy and a contact's own are given it. */
9040
- var CLIPBOARD_GUARD_HASH = "'sha256-ay9kpYD2BIflB8W9w+iAbo1krsFBwIJunUmXTACfhao='";
6815
+ var CLIPBOARD_GUARD_HASH = "'sha256-D8U3zSg1xP77RbZuV/DekRuM6nx80gIN5mh2TQAtZ40='";
9041
6816
  // ../core/src/link.ts
9042
6817
  /** What Ghostly Desktop uses against the DHT. */
9043
6818
  var DHT_POLL_INTERVALS = {
@@ -12045,6 +9820,15 @@ function removedCardText(of, title) {
12045
9820
  return `🗑 ${of === "task" ? "Task" : "Routine"} removed${title ? `: ${title}` : ""}`;
12046
9821
  }
12047
9822
  /**
9823
+ * A message's text without the line that is its app card's link (`statusCardText` puts it on a line of its own for an
9824
+ * older app): what a line quoting the message says where the card is not drawn, never the bundle's raw link. Any other
9825
+ * message's text as it is.
9826
+ */
9827
+ function withoutAppLink(text, card) {
9828
+ const url = card?.kind === "app" ? card.url : void 0;
9829
+ return url ? text.split("\n").filter((line) => line.trim() !== url).join("\n") : text;
9830
+ }
9831
+ /**
12048
9832
  * The text a card's message carries: what an app without cards shows, the DHT floor carries, the chat list previews
12049
9833
  * and search finds. Plain lines, the first naming the card, no bars or layout that would read badly elsewhere.
12050
9834
  */
@@ -13446,6 +11230,8 @@ var DhtDelivery = class DhtDelivery {
13446
11230
  * one any more), not at the next keep-alive four minutes on. Any envelope that goes out replaces it.
13447
11231
  */
13448
11232
  withdrawal;
11233
+ /** When the last withdrawal's envelope went (its `lastPublish`), for `withdrawalWaits`. */
11234
+ withdrewAt = -1;
13449
11235
  /** The sequence of the last envelope of the contact that was past its expiry (traced once). */
13450
11236
  expiredSeen = 0;
13451
11237
  controlDue = 0;
@@ -13487,6 +11273,8 @@ var DhtDelivery = class DhtDelivery {
13487
11273
  namedRev;
13488
11274
  /** A reaction of this side waits to ride on an envelope, or the contact's reactions wait to be said taken. */
13489
11275
  reactionsDue = false;
11276
+ /** The text on the floor whose envelope left the reactions no room (its id): they wait for the ones its backoff publishes. */
11277
+ crowdedBy;
13490
11278
  constructor(options) {
13491
11279
  this.options = options;
13492
11280
  const { peerRejected: _peerRejected, ...state } = structuredClone(options.state ?? emptyDhtDeliveryState());
@@ -13906,23 +11694,25 @@ var DhtDelivery = class DhtDelivery {
13906
11694
  if (edit !== void 0 && (reply !== void 0 || !ID$3.test(edit[0]) || !validEditNumber(edit[1]))) return "Invalid message.";
13907
11695
  if (utf8Encode(text).length > 256) return DHT_TEXT_TOO_LONG;
13908
11696
  if (/cashu[AB][A-Za-z0-9_-]+/i.test(text)) return "Payment tokens cannot be sent through DHT delivery.";
13909
- const now = this.clock(), pending = this.state.pending;
13910
- if (pending && pending.expires > now && pending.message[0] !== id) return "One DHT text can await a receipt at a time. Wait for its receipt or expiry before sending another.";
13911
- if (pending?.message[0] === id && pending.expires > now && pending.attempts >= MAX_ATTEMPTS) return "DHT retry budget exhausted. Wait for expiry before retrying this message.";
13912
- const next = pending?.message[0] === id && pending.expires > now ? pending : {
11697
+ const now = this.clock(), pending = this.state.pending, mine = pending?.message[0] === id && pending.expires > now ? pending : void 0;
11698
+ const next = mine ?? {
13913
11699
  message: [
13914
11700
  id,
13915
11701
  timestamp,
13916
11702
  text
13917
11703
  ],
13918
- expires: now + DHT_MESSAGE_TTL,
11704
+ expires: now + 3e5,
13919
11705
  attempts: 0,
13920
11706
  next: now,
13921
11707
  ...reply && { reply },
13922
11708
  ...edit && { edit }
13923
11709
  };
13924
11710
  const error = this.packetError(next.message, next.expires, next.reply, next.edit);
13925
- return error && next.reply ? this.packetError(next.message, next.expires) : error;
11711
+ const tooBig = error && next.reply ? this.packetError(next.message, next.expires) : error;
11712
+ if (tooBig) return tooBig;
11713
+ if (pending && pending.expires > now && !mine) return "One DHT text can await a receipt at a time. Wait for its receipt or expiry before sending another.";
11714
+ if (mine && mine.attempts >= MAX_ATTEMPTS) return "DHT retry budget exhausted. Wait for expiry before retrying this message.";
11715
+ return null;
13926
11716
  }
13927
11717
  /**
13928
11718
  * Measured, not built (`bodyFits`): the outbox asks it of every waiting text at each look, and a text that waits as no
@@ -13975,6 +11765,10 @@ var DhtDelivery = class DhtDelivery {
13975
11765
  pending: next
13976
11766
  });
13977
11767
  this.changed();
11768
+ if (this.withdrawalWaits()) {
11769
+ this.schedule();
11770
+ return null;
11771
+ }
13978
11772
  try {
13979
11773
  await this.publish(true);
13980
11774
  this.schedule();
@@ -14015,7 +11809,7 @@ var DhtDelivery = class DhtDelivery {
14015
11809
  const id = dhtFileId(file.wireId);
14016
11810
  if (reply !== void 0 && !REPLY_TO.test(reply)) reply = void 0;
14017
11811
  const error = this.validate(file.name, timestamp, id);
14018
- if (error) return error === DHT_TEXT_TOO_LONG ? DHT_FILE_TOO_LARGE : error;
11812
+ if (error) return error === "DHT text is limited to 256 UTF-8 bytes. Shorten it or choose a live connection." ? DHT_FILE_TOO_LARGE : error;
14019
11813
  const now = Date.now(), pending = this.state.pending;
14020
11814
  if (pending?.message[0] === id && pending.expires > now) return pending;
14021
11815
  const message = [
@@ -14078,6 +11872,10 @@ var DhtDelivery = class DhtDelivery {
14078
11872
  pending: next
14079
11873
  });
14080
11874
  this.changed();
11875
+ if (this.withdrawalWaits()) {
11876
+ this.schedule();
11877
+ return null;
11878
+ }
14081
11879
  try {
14082
11880
  await this.publish(true);
14083
11881
  } catch (error) {
@@ -14101,6 +11899,8 @@ var DhtDelivery = class DhtDelivery {
14101
11899
  * one's place on the relays, so a contact who looks later finds no text. Resolves once the state without it is saved;
14102
11900
  * the new envelope goes after. One that does not go (no relay reachable) is tried again within seconds (`withdrawal`):
14103
11901
  * a reader takes the withdrawn envelope until its expiry and the clock skew allowed past it (`DHT_EXPIRY_SKEW_MS`).
11902
+ * It goes at once, spacing or not: the deleted text is out of reach from then on. The text that takes the floor next
11903
+ * waits out the spacing instead (`withdrawalWaits`).
14104
11904
  */
14105
11905
  async withdraw(wireId) {
14106
11906
  const expires = await this.serialize(async () => {
@@ -14122,9 +11922,19 @@ var DhtDelivery = class DhtDelivery {
14122
11922
  try {
14123
11923
  await this.publish(true);
14124
11924
  } catch {}
11925
+ this.withdrewAt = this.lastPublish;
14125
11926
  this.schedule();
14126
11927
  });
14127
11928
  }
11929
+ /**
11930
+ * The last envelope was a withdrawal's, inside the publication spacing: the text that takes the floor now goes once
11931
+ * the spacing allows (`schedule`), not in an envelope of its own at once. Deleted then, it never went, so it costs
11932
+ * no withdrawal: deleting 10 texts queued for an away contact one after the other, each one's withdrawal and the next
11933
+ * text's envelope put 10 envelopes on every relay in under 2 s, each replaced a moment later (bug hunt, 2026-11-15).
11934
+ */
11935
+ withdrawalWaits() {
11936
+ return this.withdrewAt === this.lastPublish && this.clock() - this.lastPublish < 4e3;
11937
+ }
14128
11938
  /** The id of what awaits its receipt on the floor now, if anything does. */
14129
11939
  get pendingId() {
14130
11940
  const now = this.clock(), pending = this.state.pending;
@@ -14159,6 +11969,7 @@ var DhtDelivery = class DhtDelivery {
14159
11969
  async announceReactions() {
14160
11970
  if (!this.options.reactions?.().length) return;
14161
11971
  this.reactionsDue = true;
11972
+ this.crowdedBy = void 0;
14162
11973
  await this.serialize(async () => {
14163
11974
  try {
14164
11975
  await this.publish();
@@ -14242,7 +12053,7 @@ var DhtDelivery = class DhtDelivery {
14242
12053
  const reseal = this.resealDue;
14243
12054
  const withdrawal = this.withdrawal && this.withdrawal.until > now && this.withdrawal.attempts < MAX_ATTEMPTS ? this.withdrawal : void 0;
14244
12055
  if (!withdrawal) this.withdrawal = void 0;
14245
- const keepAlive = !force && (!pending || pending.next > now) && !receiptDue && !this.reactionsDue && !reseal && !(withdrawal && withdrawal.next <= now);
12056
+ const keepAlive = !force && (!pending || pending.next > now) && !receiptDue && !this.reactionsPress && !reseal && !(withdrawal && withdrawal.next <= now);
14246
12057
  if (keepAlive && (this.controlDue > now || this.state.inviteTaken)) return;
14247
12058
  const expires = pending?.expires ?? now - 12e4 + CONTROL_TTL;
14248
12059
  const issued = Math.min(now, Math.max(now - DHT_ISSUED_BACK_MS, expires - (pending ? DHT_MESSAGE_TTL : CONTROL_TTL), (pending?.message[1] ?? 0) - 3e4));
@@ -14257,10 +12068,16 @@ var DhtDelivery = class DhtDelivery {
14257
12068
  }, void 0, void 0);
14258
12069
  throw held;
14259
12070
  }
12071
+ if (withdrawal) this.withdrawal = {
12072
+ ...withdrawal,
12073
+ attempts: withdrawal.attempts + 1,
12074
+ next: now + backoff(withdrawal.attempts)
12075
+ };
14260
12076
  const fittedEnvelope = this.fitted(this.sequence + 1, issued, expires, pending?.message ?? null, receipt?.id ?? null, pending?.reply, pending?.edit, pending?.forwarded, pending?.file);
14261
12077
  const { body, reactions } = fittedEnvelope;
14262
12078
  const reactionsWereDue = this.reactionsDue;
14263
12079
  this.reactionsDue = !reactions && !!this.options.reactions?.().length;
12080
+ this.crowdedBy = this.reactionsDue && pending ? pending.message[0] : void 0;
14264
12081
  const sequence = body[1];
14265
12082
  await this.persist({
14266
12083
  ...this.state,
@@ -14292,11 +12109,6 @@ var DhtDelivery = class DhtDelivery {
14292
12109
  ...records[0]?.label === "_dr" && { ratchet: true }
14293
12110
  });
14294
12111
  if (pending) this.lastPublished = DhtDelivery.facts(body, records, identity.pubKeyZ32);
14295
- if (withdrawal) this.withdrawal = {
14296
- ...withdrawal,
14297
- attempts: withdrawal.attempts + 1,
14298
- next: now + backoff(withdrawal.attempts)
14299
- };
14300
12112
  try {
14301
12113
  await this.options.transport.publish(identity, records, options);
14302
12114
  } catch (error) {
@@ -14319,6 +12131,14 @@ var DhtDelivery = class DhtDelivery {
14319
12131
  return this.unsealedOut && !!this.options.credentials.peerKey;
14320
12132
  }
14321
12133
  /**
12134
+ * Reactions due (`reactionsDue`) that force an envelope of their own: not while the text that left them no room
12135
+ * (`crowdedBy`) is still retried, or each publication spends one of its attempts 4 s apart instead of at its backoff.
12136
+ */
12137
+ get reactionsPress() {
12138
+ const pending = this.state.pending, now = Date.now();
12139
+ return this.reactionsDue && !(pending && pending.message[0] === this.crowdedBy && pending.expires > now && pending.attempts < MAX_ATTEMPTS);
12140
+ }
12141
+ /**
14322
12142
  * The relays' request budget held the envelope back: nothing went out, so it was no attempt (a text keeps its eight),
14323
12143
  * and what it carried (a text, a receipt, a new mode) goes the moment the budget frees a request: the text and the
14324
12144
  * receipt as they were before, and no publication before then (`budgetUntil`) but a forced one.
@@ -14556,7 +12376,10 @@ var DhtDelivery = class DhtDelivery {
14556
12376
  const theirs = this.options.reaction ? readDhtReactions(reactions) : [];
14557
12377
  for (const reaction of theirs) await this.options.reaction?.(reaction);
14558
12378
  const newest = theirs.reduce((max, r) => Math.max(max, r.n), 0);
14559
- if (theirs.length) this.reactionsDue = true;
12379
+ if (theirs.length) {
12380
+ this.reactionsDue = true;
12381
+ this.crowdedBy = void 0;
12382
+ }
14560
12383
  const confirmed = receipt && this.state.pending?.message[0] === receipt ? receipt : this.state.confirmed;
14561
12384
  if (mode !== this.state.peerMode) traceLink(this.from, "dht-peer-mode", { peerMode: mode });
14562
12385
  if (peerPinned !== this.state.peerPinned) traceLink(this.from, "dht-peer-pinned", { peerPinned });
@@ -14776,11 +12599,13 @@ var DhtDelivery = class DhtDelivery {
14776
12599
  if (!this.running || this.ticking) return;
14777
12600
  if (this.timer) clearTimeout(this.timer);
14778
12601
  const held = this.budgetUntil - this.clock();
14779
- const due = this.reactionsDue || this.resealDue && !this.errors.publish ? Math.max(0, this.lastPublish + 4e3 - Date.now(), held) : Infinity;
12602
+ const due = this.reactionsPress || this.resealDue && !this.errors.publish ? Math.max(0, this.lastPublish + 4e3 - Date.now(), held) : Infinity;
14780
12603
  const withdrawal = this.withdrawal, now = Date.now();
14781
12604
  const retry = withdrawal && withdrawal.until > now && withdrawal.attempts < MAX_ATTEMPTS ? Math.max(0, withdrawal.next - now, this.lastPublish + 4e3 - now, held) : Infinity;
12605
+ const pending = this.state.pending;
12606
+ const waiting = pending && pending.attempts === 0 && pending.expires > now ? Math.max(0, this.lastPublish + 4e3 - now, held) : Infinity;
14782
12607
  const readHeld = this.readHeldUntil > 0 ? Math.max(1e3, this.readHeldUntil - Date.now()) : Infinity;
14783
- this.timer = setTimeout(() => void this.tick(), Math.min(held > 0 ? Math.min(this.pollMs, held) : this.pollMs, due, retry, readHeld));
12608
+ this.timer = setTimeout(() => void this.tick(), Math.min(held > 0 ? Math.min(this.pollMs, held) : this.pollMs, due, retry, waiting, readHeld));
14784
12609
  }
14785
12610
  };
14786
12611
  var DHT_TEXT_REFUSED = "Your contact's app does not accept text over the DHT. It is sent when you are live.";
@@ -19293,6 +17118,11 @@ var ChatFiles = class {
19293
17118
  /** Files that stopped sending for the chat's window alone: they go on once another's bytes are confirmed. */
19294
17119
  held = /* @__PURE__ */ new Set();
19295
17120
  /**
17121
+ * The entries not ended (`track`): what is still to come or under way is read from these, not from every file the
17122
+ * chat ever had, which it keeps for good. An offer read all of them, in every chat, at 100,000 files about 10 ms each.
17123
+ */
17124
+ unended = /* @__PURE__ */ new Set();
17125
+ /**
19296
17126
  * Files this side cancelled while no session carried the cancel (`pf-abort`), said on the next one. The session also
19297
17127
  * goes for a moment when a move swaps it (its capabilities are agreed again): unsaid, the receiver showed the file
19298
17128
  * moving, its bytes kept, until its idle nudge asked 30 s later.
@@ -19344,7 +17174,10 @@ var ChatFiles = class {
19344
17174
  checkpointed: record.confirmed,
19345
17175
  writing: Promise.resolve()
19346
17176
  };
17177
+ const replaced = this.entries.get(key(record.direction, record.id));
17178
+ if (replaced) this.unended.delete(replaced);
19347
17179
  this.entries.set(key(record.direction, record.id), entry);
17180
+ this.track(entry);
19348
17181
  }
19349
17182
  }
19350
17183
  get live() {
@@ -19357,6 +17190,23 @@ var ChatFiles = class {
19357
17190
  records() {
19358
17191
  return [...this.entries.values()].map((e) => ({ ...e.record }));
19359
17192
  }
17193
+ /** Bytes still to come of the files taken here, not ended (one still asked about is not taken yet). */
17194
+ stillToCome() {
17195
+ let due = 0;
17196
+ for (const { record } of this.unended) if (record.direction === "in" && record.state !== "asking" && !transferEnded(record)) due += Math.max(0, record.file.size - record.confirmed);
17197
+ return due;
17198
+ }
17199
+ /** A transfer under way: offered, moving, or being checked. */
17200
+ underWay() {
17201
+ for (const { record } of this.unended) if (record.state === "offered" || record.state === "active" || record.state === "verifying") return true;
17202
+ return false;
17203
+ }
17204
+ /** Bytes of the files received here that were taken without asking and are kept (or on their way). */
17205
+ takenUnasked() {
17206
+ let taken = 0;
17207
+ for (const { record } of this.entries.values()) if (record.direction === "in" && !record.consented && record.state !== "asking" && record.state !== "failed" && record.state !== "declined" && record.state !== "cancelled") taken += record.file.size;
17208
+ return taken;
17209
+ }
19360
17210
  get(direction, id) {
19361
17211
  const record = this.entries.get(key(direction, id))?.record;
19362
17212
  return record && { ...record };
@@ -19374,8 +17224,17 @@ var ChatFiles = class {
19374
17224
  return entry.in && !transferEnded(entry.record) ? Math.max(entry.in.stored, entry.record.confirmed) : entry.record.confirmed;
19375
17225
  }
19376
17226
  changed(entry, progress = false) {
17227
+ this.track(entry);
19377
17228
  this.host.changed({ ...entry.record }, this.moved(entry), progress);
19378
17229
  }
17230
+ /**
17231
+ * Keeps `unended` to the entries of this chat not ended. Each change of a record's state is reported (`changed`),
17232
+ * so that is where a file that ended leaves it, and one taken or sent again comes back.
17233
+ */
17234
+ track(entry) {
17235
+ if (!transferEnded(entry.record) && this.entries.get(key(entry.record.direction, entry.record.id)) === entry) this.unended.add(entry);
17236
+ else this.unended.delete(entry);
17237
+ }
19379
17238
  send(frame) {
19380
17239
  return this.attached && this.host.send(frame);
19381
17240
  }
@@ -20361,6 +18220,7 @@ var ChatFiles = class {
20361
18220
  const entry = this.entries.get(key("in", id));
20362
18221
  if (!entry || transferEnded(entry.record)) return;
20363
18222
  this.entries.delete(key("in", id));
18223
+ this.unended.delete(entry);
20364
18224
  const incoming = entry.in;
20365
18225
  entry.record.state = "failed";
20366
18226
  clearTimeout(incoming.timer);
@@ -20497,6 +18357,7 @@ var ChatFiles = class {
20497
18357
  if (!entry) return;
20498
18358
  if (!transferEnded(entry.record)) this.cancel(direction, id);
20499
18359
  this.entries.delete(key(direction, id));
18360
+ this.unended.delete(entry);
20500
18361
  }
20501
18362
  };
20502
18363
  // ../core/src/pairedCalls.ts
@@ -22173,6 +20034,44 @@ var MESSAGE_RECEIVE_LIMITS = {
22173
20034
  hourly: 1800,
22174
20035
  hourWindowMs: 36e5
22175
20036
  };
20037
+ /** What `sendMessage` says of a text the contact's windows have no room for yet: it did not go (`MessagePace`). */
20038
+ var MESSAGE_PACED = "Your contact takes a limited number of texts at a time. It goes by itself once they can take more.";
20039
+ /** How long a text sent with no receipt yet counts as taken past its send: one in flight is taken when it lands. */
20040
+ var PACE_UNANSWERED_MS = 6e4;
20041
+ /**
20042
+ * The texts this side sent on a paired session, counted against the contact's windows (`MESSAGE_RECEIVE_LIMITS`), so
20043
+ * none goes that the contact would refuse. A refused text went unconfirmed and came again with the outbox's backoff,
20044
+ * after texts written later that found room meanwhile: the contact read them out of order. Past the hour's total it
20045
+ * was sent until its attempts ran out, well inside the hour, and ended failed. Each counts from its receipt, the latest
20046
+ * the contact can have taken it: counted from its send, a frame that sat in a queue was taken later than counted.
20047
+ */
20048
+ var MessagePace = class {
20049
+ now;
20050
+ sent = [];
20051
+ constructor(now = Date.now) {
20052
+ this.now = now;
20053
+ }
20054
+ /** The contact's windows have room for one more text now. */
20055
+ room() {
20056
+ const now = this.now(), { burst, burstWindowMs, hourly, hourWindowMs } = MESSAGE_RECEIVE_LIMITS;
20057
+ const counts = (entry, windowMs) => entry.answered !== void 0 ? now - entry.answered < windowMs : now - entry.at < windowMs + PACE_UNANSWERED_MS;
20058
+ this.sent = this.sent.filter((entry) => counts(entry, hourWindowMs));
20059
+ return this.sent.length < hourly && this.sent.filter((entry) => counts(entry, burstWindowMs)).length < burst;
20060
+ }
20061
+ took(id) {
20062
+ this.sent.push({
20063
+ id,
20064
+ at: this.now()
20065
+ });
20066
+ }
20067
+ /** Its receipt came: the contact counted it by now. */
20068
+ answered(id) {
20069
+ for (let i = this.sent.length - 1; i >= 0; i--) if (this.sent[i].id === id && this.sent[i].answered === void 0) {
20070
+ this.sent[i].answered = this.now();
20071
+ return;
20072
+ }
20073
+ }
20074
+ };
22176
20075
  /**
22177
20076
  * A `paired-message` frame. The preview (`pv`) is left out when the frame would pass `MAX_PAIRED_MESSAGE_FRAME`
22178
20077
  * with it: the text matters, the card does not. A reply (`r`, WISP 401 § Replies) is a few hundred bytes at most
@@ -22396,6 +20295,8 @@ var GhostLink = class {
22396
20295
  editsReceived = new RateWindow(30, EDIT_RATE_WINDOW_MS);
22397
20296
  /** Text frames the contact may send per window (`MESSAGE_RECEIVE_LIMITS`); the rest go unconfirmed and come again. */
22398
20297
  messagesReceived = [new RateWindow(MESSAGE_RECEIVE_LIMITS.burst, MESSAGE_RECEIVE_LIMITS.burstWindowMs), new RateWindow(MESSAGE_RECEIVE_LIMITS.hourly, MESSAGE_RECEIVE_LIMITS.hourWindowMs)];
20298
+ /** The texts sent to the contact, against their `messagesReceived` (`MessagePace`). */
20299
+ messagesSent = new MessagePace();
22399
20300
  /** Call signals the contact may send per window; the rest are dropped. */
22400
20301
  callsReceived = new RateWindow(150, CALL_RATE_WINDOW_MS);
22401
20302
  /** WebRTC signals the contact may send on the session (`paired-rtc`) per window; the rest are dropped. */
@@ -23265,6 +21166,10 @@ var GhostLink = class {
23265
21166
  get canSendText() {
23266
21167
  return this.textDelivery !== "unavailable";
23267
21168
  }
21169
+ /** A text on the live session would find room in the contact's windows now (`MessagePace`); the DHT floor has its own pace. */
21170
+ get textRoom() {
21171
+ return this.textDelivery !== "stream" || this.messagesSent.room();
21172
+ }
23268
21173
  get dhtDelivery() {
23269
21174
  return this.dht?.view;
23270
21175
  }
@@ -24774,9 +22679,11 @@ var GhostLink = class {
24774
22679
  if (!/^[A-Za-z0-9_-]{22}$/.test(id)) return "Invalid message ID";
24775
22680
  const frame = pairedMessageFrame(id, timestamp, trimmed, preview, reply, forwarded, card);
24776
22681
  if (frame.length > 61440) return PAIRED_FRAME_TOO_LARGE;
22682
+ if (!this.messagesSent.room()) return MESSAGE_PACED;
24777
22683
  this.pairedPending.set(id, timestamp);
24778
22684
  try {
24779
22685
  this.channel.send(frame);
22686
+ this.messagesSent.took(id);
24780
22687
  return null;
24781
22688
  } catch {
24782
22689
  this.pairedPending.delete(id);
@@ -25566,6 +23473,17 @@ var GhostLink = class {
25566
23473
  if (dht && this.dht && this.textDelivery === "dht") return this.dht.send(edit.m, edit.ts, dhtEditId(edit.id, edit.e), void 0, [edit.id, edit.e]);
25567
23474
  return "Edits go when you are live";
25568
23475
  }
23476
+ /**
23477
+ * Why the DHT floor can never carry this edit, or null (WISP 403 § Edits): it goes there as a text with the edit's
23478
+ * element, which must fit the packet once sealed, as a text must (`validateText`). One past the 256 bytes never fits
23479
+ * it either, and says so with the same reason. Null off the floor, and for what only makes it wait there (a text
23480
+ * awaiting its receipt): that one goes in its turn.
23481
+ */
23482
+ dhtEditTooBig(edit) {
23483
+ if (this.isDataLinkOpen || this.textDelivery !== "dht") return null;
23484
+ const error = this.dht.validate(edit.m, edit.ts, dhtEditId(edit.id, edit.e), void 0, [edit.id, edit.e]);
23485
+ return error === "Text and authentication exceed the DHT packet budget. Shorten the message." || error === "DHT text is limited to 256 UTF-8 bytes. Shorten it or choose a live connection." ? DHT_PACKET_BUDGET : null;
23486
+ }
25569
23487
  /** Confirms an edit of the contact's that waited for its message (`onMessageEdit` returned false). */
25570
23488
  confirmEdit(id, e) {
25571
23489
  if (!this.channel || !this.supportsEdits) return;
@@ -26926,6 +24844,7 @@ var GhostLink = class {
26926
24844
  id: frame.id
26927
24845
  }));
26928
24846
  } else if (frame.t === "paired-received") {
24847
+ this.messagesSent.answered(frame.id);
26929
24848
  if (this.pairedPending.get(frame.id) !== void 0) {
26930
24849
  await this.options.events?.onMessageReceipt?.(frame.id);
26931
24850
  await this.dht?.acknowledge(frame.id);
@@ -30160,10 +28079,10 @@ var REDIRECTS = [
30160
28079
  /**
30161
28080
  * A host that is not on the public internet, as far as its name tells: this machine, a single label, `.local` and its
30162
28081
  * kin, private and reserved IP addresses. (What a public name resolves to is checked where the client resolves names
30163
- * itself, as Ghostly Desktop does.)
28082
+ * itself, as Ghostly Desktop and the CLI do.)
30164
28083
  */
30165
28084
  function isLocalHost(hostname) {
30166
- const host = hostname.toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
28085
+ const host = hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
30167
28086
  if (!host.includes(".") && !host.includes(":")) return true;
30168
28087
  if (/(^|\.)(localhost|local|internal|lan|home\.arpa)$/.test(host)) return true;
30169
28088
  const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
@@ -30171,7 +28090,7 @@ function isLocalHost(hostname) {
30171
28090
  const [a, b] = [Number(v4[1]), Number(v4[2])];
30172
28091
  return a === 0 || a === 10 || a === 127 || a >= 224 || a === 169 && b === 254 || a === 172 && b >= 16 && b < 32 || a === 192 && b === 168 || a === 100 && b >= 64 && b < 128 || a === 198 && (b === 18 || b === 19) || a === 192 && b === 0;
30173
28092
  }
30174
- if (host.includes(":")) return !/^[23][0-9a-f]{0,3}:/.test(host) || host.includes(".") || /^2001:0?db8:/.test(host);
28093
+ if (host.includes(":")) return !/^[23][0-9a-f]{3}:/.test(host) || host.includes(".") || host.startsWith("2002:") || /^2001:(0{0,4}|0{0,3}db8):/.test(host);
30175
28094
  return false;
30176
28095
  }
30177
28096
  var isLoopback = (hostname) => [
@@ -34610,7 +32529,8 @@ var GroupSession = class {
34610
32529
  adminSeen;
34611
32530
  /**
34612
32531
  * After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
34613
- * one of theirs I signed again (what I held then, until one of theirs comes). In memory only.
32532
+ * one of theirs I signed again (what I held then, until one of theirs comes). `vouched`: the latest of theirs another
32533
+ * member's sync said it holds; `held`: the latest of theirs no other member has shown it holds yet. In memory only.
34614
32534
  */
34615
32535
  takeover;
34616
32536
  /** While `handle` runs: the frames it took that a hub passes on (`handle`'s result). */
@@ -36567,6 +34487,7 @@ var GroupSession = class {
36567
34487
  if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(GROUP_LIMITS.syncAnswers, GROUP_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
36568
34488
  if (!answered.take()) return;
36569
34489
  this.hear(frame);
34490
+ await this.vouch(from, frame.mt);
36570
34491
  if (frame.e > this.epoch) {
36571
34492
  this.syncedEpoch.set(from, frame.e);
36572
34493
  if (!this.awaitsAnswer(from)) this.ask(from);
@@ -36771,7 +34692,8 @@ var GroupSession = class {
36771
34692
  const opened = openGroupMeta(frame, epochKeys(secret, this.id, frame.k).message);
36772
34693
  if (!opened) return;
36773
34694
  if (taking) {
36774
- await this.signAgainTaken(opened.meta, opened.body);
34695
+ if (this.vouches(from, s)) await this.signAgainTaken(opened.meta, opened.body);
34696
+ else this.holdTaken(from, raw, s);
36775
34697
  return;
36776
34698
  }
36777
34699
  const before = this.state.meta;
@@ -36800,6 +34722,39 @@ var GroupSession = class {
36800
34722
  return !!t && this.isAdmin && s.by === t.from && this.clock() <= t.until && groupMetaNewer(s, t.base);
36801
34723
  }
36802
34724
  /**
34725
+ * Whether a statement I would take (`takesOver`) was on its way when the role moved, as far as I can tell: a member
34726
+ * other than its signer handed it to me, or said in a sync it holds that one or a later one under the same commit.
34727
+ * The former admin alone could sign new ones after the hand-over, each taken for the whole group.
34728
+ */
34729
+ vouches(from, s) {
34730
+ const v = this.takeover?.vouched;
34731
+ return from !== s.by || !!v && v.e === s.e && v.r >= s.r;
34732
+ }
34733
+ /** The former admin's statement nobody else has shown it holds: the latest is kept until a sync does (`vouch`). */
34734
+ holdTaken(from, raw, s) {
34735
+ const t = this.takeover;
34736
+ if (!t.held || groupMetaNewer(s, t.held.s)) t.held = {
34737
+ from,
34738
+ raw,
34739
+ s
34740
+ };
34741
+ }
34742
+ /**
34743
+ * A member's sync names the statement it holds: one signed under a commit of the admin before me, by another member
34744
+ * than them, vouches for theirs up to it, and the one held is taken if it now is.
34745
+ */
34746
+ async vouch(from, tag) {
34747
+ const t = this.takeover, v = parseGroupMetaTag(tag);
34748
+ if (!t || !v || from === t.from || !this.state.chain[v.e] || rosterAdmin(this.state.chain[v.e].m) !== t.from) return;
34749
+ if (t.vouched && !groupMetaNewer(v, t.vouched)) return;
34750
+ t.vouched = v;
34751
+ const held = t.held;
34752
+ if (held && this.vouches(held.from, held.s)) {
34753
+ t.held = void 0;
34754
+ await this.receiveMeta(held.from, held.raw);
34755
+ }
34756
+ }
34757
+ /**
36803
34758
  * The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
36804
34759
  * value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
36805
34760
  */
@@ -37552,7 +35507,7 @@ var MESSAGE_BURST = {
37552
35507
  frames: COMMUNITY_LIMITS.store + COMMUNITY_LIMITS.lasting,
37553
35508
  bytes: COMMUNITY_LIMITS.storeBytes + COMMUNITY_LIMITS.lasting * COMMUNITY_LIMITS.textBytes * 2
37554
35509
  };
37555
- var MessagePace = class {
35510
+ var MessagePace$1 = class {
37556
35511
  frames = MESSAGE_BURST.frames;
37557
35512
  bytes = MESSAGE_BURST.bytes;
37558
35513
  at;
@@ -37752,7 +35707,8 @@ var CommunitySession = class CommunitySession {
37752
35707
  adminSeen;
37753
35708
  /**
37754
35709
  * After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
37755
- * one of theirs I signed again (what I held then, until one of theirs comes). In memory only.
35710
+ * one of theirs I signed again (what I held then, until one of theirs comes). `vouched`: the latest of theirs another
35711
+ * member's sync said it holds; `held`: the latest of theirs no other member has shown it holds yet. In memory only.
37756
35712
  */
37757
35713
  takeover;
37758
35714
  /** The store's frames the app holds with their messages (`storeKey` → message id): in memory here, not in what is saved. */
@@ -39809,7 +37765,7 @@ var CommunitySession = class CommunitySession {
39809
37765
  const roster = this.rosterOf(found.hash);
39810
37766
  if (!rosterHas(roster, raw.s)) return false;
39811
37767
  let pace = this.messagePace.get(raw.s);
39812
- if (!pace) this.messagePace.set(raw.s, pace = new MessagePace());
37768
+ if (!pace) this.messagePace.set(raw.s, pace = new MessagePace$1());
39813
37769
  if (!pace.take(seenKey(raw.e, raw.h), raw.n, raw.c.length, this.hooks.clock?.() ?? Date.now())) return false;
39814
37770
  this.handedInAnswer(from, raw, now);
39815
37771
  if (!rosterHas(roster, this.myKey)) {
@@ -40068,6 +38024,7 @@ var CommunitySession = class CommunitySession {
40068
38024
  let answered = this.syncsAnswered.get(from);
40069
38025
  if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(COMMUNITY_LIMITS.syncAnswers, COMMUNITY_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
40070
38026
  if (!answered.take()) return;
38027
+ if (recent) await this.vouch(from, frame.mt);
40071
38028
  if (lost) {
40072
38029
  const at = this.mainIndex.get(frame.h);
40073
38030
  let commits = this.state.chain.slice(at !== void 0 ? at + 1 : lost.fork + 1, lost.end + 1);
@@ -40361,7 +38318,8 @@ var CommunitySession = class CommunitySession {
40361
38318
  const opened = openGroupMeta(frame, epochKeys(fromBase64Url(secret), this.id, sealedUnder.e).message);
40362
38319
  if (!opened) return false;
40363
38320
  if (taking) {
40364
- await this.signAgainTaken(opened.meta, opened.body);
38321
+ if (this.vouches(from, s)) await this.signAgainTaken(opened.meta, opened.body);
38322
+ else this.holdTaken(from, raw, s);
40365
38323
  return false;
40366
38324
  }
40367
38325
  const before = this.state.meta;
@@ -40384,6 +38342,39 @@ var CommunitySession = class CommunitySession {
40384
38342
  return !!t && this.isAdmin && s.by === t.from && (this.hooks.clock?.() ?? Date.now()) <= t.until && groupMetaNewer(s, t.base);
40385
38343
  }
40386
38344
  /**
38345
+ * Whether a statement I would take (`takesOver`) was on its way when the role moved, as far as I can tell: a member
38346
+ * other than its signer handed it to me (a hub's relay included), or said in a sync it holds that one or a later one
38347
+ * under the same commit. The former admin alone could sign new ones after the hand-over, each taken for the whole group.
38348
+ */
38349
+ vouches(from, s) {
38350
+ const v = this.takeover?.vouched;
38351
+ return from !== s.by || !!v && v.e === s.e && v.r >= s.r;
38352
+ }
38353
+ /** The former admin's statement nobody else has shown it holds: the latest is kept until a sync does (`vouch`). */
38354
+ holdTaken(from, raw, s) {
38355
+ const t = this.takeover;
38356
+ if (!t.held || groupMetaNewer(s, t.held.s)) t.held = {
38357
+ from,
38358
+ raw,
38359
+ s
38360
+ };
38361
+ }
38362
+ /**
38363
+ * A member's sync names the statement it holds: one signed under a commit of the admin before me, by another member
38364
+ * than them, vouches for theirs up to it, and the one held is taken if it now is.
38365
+ */
38366
+ async vouch(from, tag) {
38367
+ const t = this.takeover, v = parseGroupMetaTag(tag), commit = v ? this.state.chain[v.e] : void 0;
38368
+ if (!t || !v || !commit || from === t.from || rosterAdmin(this.rosterAt(this.hashOf(commit)) ?? []) !== t.from) return;
38369
+ if (t.vouched && !groupMetaNewer(v, t.vouched)) return;
38370
+ t.vouched = v;
38371
+ const held = t.held;
38372
+ if (held && this.vouches(held.from, held.s)) {
38373
+ t.held = void 0;
38374
+ await this.receiveMeta(held.from, held.raw);
38375
+ }
38376
+ }
38377
+ /**
40387
38378
  * The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
40388
38379
  * value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
40389
38380
  */
@@ -40574,6 +38565,125 @@ function verifyGroupCallRequest(raw, sfu, now, seen) {
40574
38565
  }
40575
38566
  };
40576
38567
  }
38568
+ /**
38569
+ * An admin's request to act on a member in its group's call (WISP 602 · Group Calls § Moderation): what it sends to
38570
+ * `POST <sfu>/sfu/group-moderate`, signed by its group key over the node's origin as a token request is, under its own
38571
+ * tag, so neither request can stand for the other.
38572
+ *
38573
+ * {"v":1,"g":"<group>","k":"<admin key>","room":"g_<group>","act":"mute","target":"<member key>","src":["microphone"],
38574
+ * "ts":1794700800,"n":"<nonce>","sig":"…"}
38575
+ *
38576
+ * `mute` takes `src` away from `target`, `allow` gives it back, `remove` takes `target` out of the call and keeps it
38577
+ * out, `unban` lets it back in, and `state` changes nothing (the reply says who is muted and banned). Whether `k` is
38578
+ * the group's admin is the node's to say, from its roster.
38579
+ */
38580
+ /** What an admin can take from a member, in the sorted order a request lists them in. */
38581
+ var GROUP_CALL_SOURCES = [
38582
+ "camera",
38583
+ "microphone",
38584
+ "screen_share"
38585
+ ];
38586
+ var GROUP_CALL_MODERATION_ACTS = [
38587
+ "mute",
38588
+ "allow",
38589
+ "remove",
38590
+ "unban",
38591
+ "state"
38592
+ ];
38593
+ var takesSources = (act) => act === "mute" || act === "allow";
38594
+ /** Exactly the bytes an admin signs: the array form, as the token request's. */
38595
+ var groupCallModerationBytes = (sfu, g, room, k, act, target, src, ts, n) => utf8Encode(JSON.stringify([
38596
+ "ghostly-sfu/1 moderate",
38597
+ sfu,
38598
+ g,
38599
+ room,
38600
+ k,
38601
+ act,
38602
+ target,
38603
+ src,
38604
+ ts,
38605
+ n
38606
+ ]));
38607
+ /** A moderation request for `sfu`, signed by the admin's group key `seed`; `src` is listed unique and sorted. */
38608
+ function signGroupCallModeration(input, seed) {
38609
+ const k = identityFromSeed(seed).pubKeyZ32;
38610
+ const room = groupCallRoom(input.g);
38611
+ const target = input.act === "state" ? "" : input.target ?? "";
38612
+ const src = takesSources(input.act) ? [...new Set(input.src ?? [])].sort() : [];
38613
+ const ts = input.ts ?? Math.floor(Date.now() / 1e3);
38614
+ const n = input.n ?? toBase64Url(randomBytes(16));
38615
+ const sig = toBase64Url(sign(groupCallModerationBytes(input.sfu, input.g, room, k, input.act, target, src, ts, n), seed));
38616
+ return {
38617
+ v: 1,
38618
+ g: input.g,
38619
+ k,
38620
+ room,
38621
+ act: input.act,
38622
+ target,
38623
+ src,
38624
+ ts,
38625
+ n,
38626
+ sig
38627
+ };
38628
+ }
38629
+ /** `src` as an act takes it: unique known sources in sorted order, at least one, for `mute` and `allow`; none otherwise. */
38630
+ function sourcesFit(act, src) {
38631
+ if (!Array.isArray(src)) return false;
38632
+ if (!takesSources(act)) return src.length === 0;
38633
+ return src.length > 0 && src.every((s, i) => GROUP_CALL_SOURCES.includes(s) && (i === 0 || src[i - 1] < s));
38634
+ }
38635
+ /**
38636
+ * The node's checks of a moderation request but the roster, in order: the shape (a known act, a `target` that is a
38637
+ * member key other than `k`, or `""` for `state`, and `src` as the act takes it), the time within `GROUP_CALL_SKEW_S`
38638
+ * of `now` (ms), a nonce not in `seen`, and the signature over the node's own origin `sfu`. A request that passes has
38639
+ * its nonce added to `seen`; entries older than `GROUP_CALL_NONCE_S` are dropped on the way.
38640
+ */
38641
+ function verifyGroupCallModeration(raw, sfu, now, seen) {
38642
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {
38643
+ ok: false,
38644
+ reason: "malformed"
38645
+ };
38646
+ const f = raw;
38647
+ const act = f.act;
38648
+ if (f.v !== 1 || typeof f.g !== "string" || !GROUP_ID.test(f.g) || !isZ32Key(f.k) || f.room !== groupCallRoom(f.g) || !GROUP_CALL_MODERATION_ACTS.includes(act) || (act === "state" ? f.target !== "" : !isZ32Key(f.target) || f.target === f.k) || !sourcesFit(act, f.src) || !Number.isSafeInteger(f.ts) || f.ts <= 0 || typeof f.n !== "string" || !NONCE.test(f.n) || toBase64Url(fromBase64Url(f.n)) !== f.n || typeof f.sig !== "string" || !SIG.test(f.sig)) return {
38649
+ ok: false,
38650
+ reason: "malformed"
38651
+ };
38652
+ const room = groupCallRoom(f.g), target = f.target, src = f.src, ts = f.ts, nowS = Math.floor(now / 1e3);
38653
+ if (Math.abs(nowS - ts) > 60) return {
38654
+ ok: false,
38655
+ reason: "stale"
38656
+ };
38657
+ for (const [n, at] of seen) if (nowS - at > 120) seen.delete(n);
38658
+ if (seen.has(f.n)) return {
38659
+ ok: false,
38660
+ reason: "replayed"
38661
+ };
38662
+ let holds = false;
38663
+ try {
38664
+ holds = verify(fromBase64Url(f.sig), groupCallModerationBytes(sfu, f.g, room, f.k, act, target, src, ts, f.n), publicKeyFromZ32(f.k));
38665
+ } catch {}
38666
+ if (!holds) return {
38667
+ ok: false,
38668
+ reason: "signature"
38669
+ };
38670
+ seen.set(f.n, nowS);
38671
+ return {
38672
+ ok: true,
38673
+ request: {
38674
+ v: 1,
38675
+ g: f.g,
38676
+ k: f.k,
38677
+ room,
38678
+ act,
38679
+ target,
38680
+ src: [...src],
38681
+ ts,
38682
+ n: f.n,
38683
+ sig: f.sig
38684
+ }
38685
+ };
38686
+ }
40577
38687
  // ../core/src/groupTyping.ts
40578
38688
  /**
40579
38689
  * The typing indicator of a private group (WISP 902 · Group Mesh § Typing): "Ana is typing", said on the group's
@@ -41996,6 +40106,6 @@ function x401ApprovalDigest(subject) {
41996
40106
  ]);
41997
40107
  return toBase64Url(sha256(utf8Encode(canonical)));
41998
40108
  }
41999
- export { ACTIVE_DHT_POLL_MS, ACTIVE_TASK_STATUSES, ANSWERS_REFUSED_PAUSES, ANSWERS_REFUSED_PAUSE_MS, ANSWER_READ_ALLOWANCE, ANSWER_READ_FIRST_MS, ANSWER_READ_SPACING_MS, ANSWER_REFUSED_REDIALS, APPS_CAPABILITY, APP_BUNDLE_LIMITS, APP_BUNDLE_MAGIC, APP_CLIENTS, APP_CLIENT_NAME, APP_DATA_MAX_BYTES, APP_FORBIDDEN_KEYS, APP_FRAME, APP_ICON_PATH, APP_NAME, APP_PEER_OPEN_MAX, APP_PERMISSIONS, APP_PREFIXES, APP_RANGES_CAPABILITY, APP_RANGE_DATA_KIND, APP_RANGE_ERRORS, APP_RANGE_FRAMES, APP_RANGE_LIMITS, APP_RATE_LIMIT, APP_RATE_WINDOW_MS, APP_RESUME_GRACE_MS, APP_SCREENSHOTS_DIR, APP_SEND_LIMIT, APP_STATEMENT_LIMITS, APP_STORE_KINDS, APP_STORE_LIMITS, APP_VERSION_MAX, APP_VIEWS, ATPROTO_DECLARED_SCOPE, ATPROTO_FULL_SCOPE, ATPROTO_PROOF_COLLECTION, ATPROTO_PROOF_SCOPE, AUDIO_METADATA_LIMITS, AUTOMATIC_ORDER, AWAITED_READS, AWAITING_PEER_MS, AppRanges, AppSessions, AtprotoCid, AtprotoProofError, BACKGROUND_REQUESTS_PER_MINUTE, BACKGROUND_WHILE_SIGNALING, BACKGROUND_WRITES_SHARE, BIP322_REVISION, BITCOIN_NETWORKS, BLOCKED_DIAL_WAIT_MS, BOLT11_PATTERN, BREAKER_ALL_DOWN_PROBE_MS, BREAKER_BASE_MS, BREAKER_MAX_MS, BREAKER_THRESHOLD, BURST_RING_MS, BUTTONS_CAPABILITY, BUTTON_ID, BUTTON_STYLES, BitcoinAddressError, ByteReader, CALLS_CAPABILITY, CALL_RATE_WINDOW_MS, CALL_RECEIVE_LIMIT, CALL_SIGNAL_FUTURE_MS, CALL_SIGNAL_MAX_AGE_MS, CAPS_ISSUED_BACK_MS, CAPS_LABEL, CAPS_LIMITS, CAPS_PUBLISH_SPACING_MS, CAPS_REFRESH_MS, CARRIED_DEFER_MS, CATCH_UP_PAUSE_MS, CATCH_UP_SLICE, CHAT_RESERVE, CHAT_RESERVE_MOST_SHARE, CHAT_RESERVE_PER_CHAT, CHAT_WATCH_SHARE, CHUNK_FLAG_END, CHUNK_KIND, CLIPBOARD_GUARD_HASH, CLIPBOARD_GUARD_SCRIPT, CLOCK_EVIDENCE_MS, CLOCK_OFF_MS, CLOCK_PEERS, CLOCK_PEER_READ_GAP_MS, CLOCK_SERVERS, COMMUNITY_EDIT_FRAME, COMMUNITY_LIMITS, COMMUNITY_PIN_FRAME, COMMUNITY_PROFILE, COMMUNITY_REACTION_FRAME, COMMUNITY_TAKEOVER_META_MS, COMMUNITY_TOPOLOGY, CONNECT_TIMEOUT_MS, CONTACT_ASKER_FRAME, CONTACT_LINK_BYTES, CONTACT_LINK_VERSION, CONTACT_RECORD_TTL, CRON_LINE, CROSSED_FRESH_MS, CROSSED_PROBE_MS, CROSSED_WAIT_MS, CapsExchange, CapsKeys, CapsRefusedError, CarriedTransport, CatchUpAnswers, ChatFiles, ClockWatch, CommunitySession, ContactRequestError, DAEMON_WATCH_PEER_IDLE_MS, DATA_CHANNEL_ID, DATA_CHANNEL_LABEL, DATA_SETTLE_MS, DEFAULT_RELAYS, DEMOTE_AFTER_FAILURES, DEMOTE_MS, DEPARTED_READS, DEPARTED_READ_MS, DEVICES_CAPABILITY, DEVICE_CAPABILITIES, DEVICE_ECHO_FRAME, DEVICE_INVITE_BYTES, DEVICE_INVITE_LIFETIME_S, DEVICE_INVITE_OWN_DEVICE, DEVICE_INVITE_VERSION, DEVICE_KINDS, DEVICE_PING_FRAME, DEVICE_WAKE_TTL_SECONDS, DHT_FILE_CAPABILITY, DHT_FILE_REFUSED, DHT_FILE_TOO_LARGE, DHT_MESSAGE_TTL, DHT_PIN_GRACE_MS, DHT_POLL_INTERVALS, DHT_TEXT_BYTES, DHT_TEXT_CAPABILITY, DHT_TEXT_REFUSED, DIALED_IN_CONTENDERS, DID_DHT_MAX_PAYLOAD, DID_DHT_PREFIX, DID_DHT_TTL, DID_DHT_VERSION, DID_DOCUMENT_MAX_BYTES, DID_FILE_MAX_BYTES, DID_GHOSTLY_SERVICE, DID_JWS_ALGS, DID_JWS_MAX_LENGTH, DID_MAX_LENGTH, DID_METHODS, DIRECT_EVIDENCE_MS, DIRECT_OWN_ATTEMPTS, DIRECT_PEERS, DNS_LABEL, DNS_TYPE, DOMAIN_FILE_MAX_BYTES, DOMAIN_MAX_RECORDS, DOMAIN_METHODS, DOMAIN_TXT_MAX_BYTES, DataLink, DhtDelivery, DidDhtError, DidError, DirectPathWatch, DiscoveryBudgetError, EARLY_DIAL_JOIN_MS, EDITED_FRAME, EDIT_BUFFER_MAX, EDIT_BUFFER_MS, EDIT_CAPABILITY, EDIT_FRAME, EDIT_RATE_WINDOW_MS, EDIT_RECEIVE_LIMIT, EDIT_SEND_LIMIT, ENDPOINT, ENGINE_ERRORS, ENROLL_CANCEL, ENROLL_CANCEL_REASONS, ENROLL_CAPABILITY, ENROLL_DONE, ENROLL_GRANT, ENROLL_HELLO, ENROLL_PROOF, ETHEREUM_USDT, EVM_TEST_CHAINS, EXPECT_PEER_MS, EngineError, FILES_BINARY_CAPABILITY, FILES_CAPABILITY, FILE_DATA_KIND, FILE_FRAMES, FILE_LIMITS, FIRST_PAIRING_PACE_MS, FIRST_PUBLISH_MAX_MS, FLOOD_PER_DAY, FOLLOW_MS, FORWARD_LIMITS, FRESH_READ_MS, FileTransfers, FileUplink, GATHER_ATTEMPTS, GATHER_STALL_MS, GROUP_ADMIN_OFF_ERROR, GROUP_BURST_MS, GROUP_BURST_ONE_LINK, GROUP_CALL_NONCE_S, GROUP_CALL_SKEW_S, GROUP_CALL_VERSION, GROUP_EDIT_FRAME, GROUP_EDIT_TEXT_BYTES, GROUP_ENTRY_PROFILE, GROUP_FILE_LIMITS, GROUP_HAVE_FRAME, GROUP_ID, GROUP_LIMITS, GROUP_MEMBER_CAP, GROUP_META_PAST, GROUP_META_PAST_CHARS, GROUP_OVER_PACE_MS, GROUP_PIN_FRAME, GROUP_PROFILE, GROUP_RATION_WINDOW_MS, GROUP_REACTED_FRAME, GROUP_REACTION_FRAME, GROUP_READ_NOTE, GROUP_READ_NOTE_COMMUNITY, GROUP_SIGNALING_ALLOWANCE_SHARE, GROUP_SIGNAL_FRAME, GROUP_TAKEOVER_META_MS, GROUP_TYPING_FRAME, GROUP_VERSION_FILES, GROUP_VERSION_HUBS, GROUP_VERSION_LARGE, GROUP_VERSION_SIGNALS, GROUP_WAKE_FRAME, GROUP_WAKE_GROUP_LIMIT, GROUP_WAKE_GROUP_WINDOW_MS, GROUP_WAKE_MEMBER_INTERVAL_MS, GROUP_WAKE_RECEIVE_LIMIT, GROUP_WANT_FRAME, GROUP_WANT_NO_FRAME, GhostLink, GhostlyHttpError, GroupSession, GroupTypingBoard, GroupWakeLimiter, HANDLED_WAIT_MS, HANDOFF_ACK, HANDOFF_ATTEMPTS, HANDOFF_BUSY, HANDOFF_BUSY_REASONS, HANDOFF_CANCEL, HANDOFF_CANCEL_REASONS, HANDOFF_CAPABILITY, HANDOFF_DATA, HANDOFF_DONE, HANDOFF_FILE_MISSING, HANDOFF_FILE_REQUEST, HANDOFF_HAVE, HANDOFF_HELLO, HANDOFF_LATER_BYTES, HANDOFF_LIST_PER_FRAME, HANDOFF_MANIFEST, HANDOFF_OFFER, HANDOFF_PAKE, HANDOFF_PIECE_BYTES, HANDOFF_PIECE_OVERHEAD, HANDOFF_RELEASE, HANDOFF_REQUEST, HANDOFF_TIMINGS, HANDOFF_VERIFIED, HANDOFF_VERSION, HANDOFF_WINDOW, HEDGE_MISSING_MS, HEDGE_MS, HOLD_CAPABILITY, HOLD_DATED_BACK_MS, HOLD_LIMITS, HTTP_SERVICE_PROTO, HoldKeys, HoldRefusedError, HttpClient, HttpHost, IDENTITY_CHALLENGE_WINDOW, IDENTITY_CHECK_UNAVAILABLE, IDENTITY_CLOCK_SKEW, IDENTITY_FRAME_LIMIT, IDENTITY_FRAME_WINDOW_MS, IDENTITY_MAX_CHECKS_PER_HOUR, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_FRAME, IDENTITY_MAX_RECEIVED, IDENTITY_MAX_VALIDITY, IDENTITY_MEMO_IDLE_MS, IDENTITY_MEMO_MAX, IDENTITY_MEMO_SIZE, IDENTITY_PROOF_CAPABILITY, IDENTITY_PROVIDER_ID, IDENTITY_REUSE_CHECK_S, IDENTITY_REVOCATION_LABEL, IDENTITY_STATEMENT_PREFIX, IDENTITY_SUBJECT, IDENTITY_TIMELINE_MAX, IDLE_THRESHOLD, IMAGE_LIMITS, INVITER_DIAL_GRACE_MS, INVITE_HRP, INVITE_LINK_ORIGIN, INVITE_MAX_LENGTH, INVITE_TAKEN, INVITE_VERSION, ITEM_STATES, IdentityCheckUnavailable, IdentityExchange, KNOCK_SLOTS, KNOCK_SLOT_LABEL, KNOCK_TTL_MS, KNOWN_SESSION_CAPABILITIES, LABEL, LATE_ANSWER_MS, LEGACY_GROUP_MEMBERS, LEGACY_SERVICES, LIGHTNING_DESTINATION_PATTERN, LIMITS, LINK_MAX_CHARS, LINK_PREVIEW_LIMITS, LINK_RECORD_LABEL, LINK_TRAILING, LIVENESS_MISSED_PINGS, LIVENESS_PING_MS, LIVE_POLL_MS, LNURL_LIMITS, LinkSession, MAX_AVATAR_LENGTH, MAX_AVATAR_SIDE, MAX_CHUNK_PAYLOAD_BYTES, MAX_DHT_TEXT_BYTES, MAX_DNS_PACKET_BYTES, MAX_DONE, MAX_EDITS_PER_MESSAGE, MAX_GROUP_CALL_NAME, MAX_GROUP_CALL_SFU, MAX_GROUP_CHAIN, MAX_GROUP_MEMBERS, MAX_GROUP_META_BODY, MAX_GROUP_NAME_BYTES, MAX_GROUP_NAME_LENGTH, MAX_GROUP_PICTURE_LENGTH, MAX_KNOCKS, MAX_MISSED, MAX_MSGS_PAYLOAD_B64, MAX_NICK_LENGTH, MAX_PAIRED_CALL_SIGNAL, MAX_PAIRED_MESSAGE_FRAME, MAX_REMOVAL_NUMBER, MAX_SEEN, MAX_SERVICES, MAX_SHARED_APPS, MAX_SKIP, MAX_SKIPPED_KEYS, MAX_SLOT_KNOCKS, MAX_WAITING, MEMBER_KEY, MENTION_EVERYONE, MENTION_LIMITS, MESH_HUBS, MESSAGE_CLOCK_SKEW_MS, MESSAGE_RECEIVE_LIMITS, MessageRefusal, NEW_PER_HOUR, NIP05_PATH, NO_ATTEMPTS, NO_AUDIO_METADATA, NO_HUB_POLICY, NO_PICTURE_METADATA, NO_VIDEO_METADATA, OFFER_FAST_MS, OFFER_HOST_GATHER_MS, OFFER_LOOK_MS, OFFER_STEP_MAX, ONCHAIN_PROVIDER, OWN_FRAME_LIMIT, OwnInviteError, PAIRED_CALL_CANDIDATES, PAIRED_CALL_FRAME, PAIRED_FRAME_TOO_LARGE, PAIRED_PROFILE, PAIRED_REPLY_AUTHORS, PAIRING_ATTEMPT_MS, PAIRING_RETRY_MS, PICTURE_METADATA_LIMITS, PINNED_FRAME, PIN_CAPABILITY, PIN_CLOCK_SKEW_MS, PIN_FRAME, PIN_LIMITS, PKARR_FUTURE_SKEW_MS, PLAYABLE_AUDIO, PLAYABLE_VIDEO, PONG_WAIT_MS, PRESENCES, PRESENCE_HEARTBEAT, PRESENCE_WINDOW, PREVIEWABLE_IMAGE, PREVIOUS_DEFAULT_RELAYS, PROOF_ADAPTERS, PROOF_CAPABILITY, PROTOCOL_VERSION, PR_CHECKS, PR_STATES, PUBKY_PROOF_MAX_BYTES, PUBKY_PROOF_ROOT, PUSH_PAD_BYTES, PUSH_SERVICE_HOSTS, PacketTooLargeError, PairedCalls, PairedSession, PairingTracker, PaymentPreflightError, PeerProofs, PublishFailedError, QUICK_REACTIONS, QUICK_REDIAL_MS, RACE_ANSWERED_MS, RACE_DIRECT_MS, RACE_RELAYED_MS, RATCHET_CAPABILITY, RATCHET_HEADER_BYTES, RATCHET_KEEP_MS, RATCHET_OVERHEAD, REACTED_FRAME, REACTIONS_CAPABILITY, REACTION_FRAME, REACTION_LIMITS, REANSWERS, RECORDING_TYPES, RECORD_TTL, REDESCRIBED_GRACE_MS, RELAYED_FIRST_MS, RELAY_PAYLOAD_MAX_BYTES, RELAY_POLL_INTERVALS, RELAY_REQUESTS_PER_MINUTE, RELAY_URL, RELAY_WITH_SECRETS, REMOVABLE_KINDS, REMOVED_TEXT, REOPEN_BELOW, REPLY_ID, REPLY_LIMITS, REQUESTS_PER_MINUTE, REQUEST_CLOCK_SKEW_MS, REQUEST_LABEL, REQUEST_LIFETIME_MS, REQUEST_NAME_UNITS, REQUEST_PACKET_BYTES, REQUEST_TEXT_BYTES, RESUME_WAIT_MS, RING_LIFETIME, ROUTINE_STATES, RTC_CONFIG, RTC_SIGNAL_FUTURE_MS, RTC_SIGNAL_MAX_AGE_MS, RTC_SIGNAL_RATE_WINDOW_MS, RTC_SIGNAL_RECEIVE_LIMIT, RTC_UNSTARTED_MS, RUN_RESULTS, RatchetBox, RateWindow, ReactionWindow, RelayBreaker, RelayTransport, RelaysFailedError, SAID_AGAIN, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, SERVICES_CAPABILITY, SERVICES_VERSION, SESSION_CAPABILITIES_FRAME, SESSION_FRAME_MAX, SESSION_RECEIVE_PENDING, SET_ACK, SET_UPDATE, SIGNALING_ALLOWANCE_SHARE, SIGNALING_WINDOW_MS, SIGNALS_PER_MINUTE, SIGNAL_CARRIERS, SIGNAL_DUE_READS, SIGNAL_FRESH_MS, SIGNAL_HOLD_MS, SIGNAL_OUT_READS, SIGNAL_PROVEN_MS, SIGNAL_REPLY_MS, SLOW_DEMOTE_MS, SLOW_MS, SPARK_NETWORKS, SPARK_PROVIDER, SSHSIG_MAX_ARMOR, SSHSIG_NAMESPACE, SSH_KEY_TYPES, SSH_PUBLIC_KEY_MAX, STALLED_EVIDENCE_MS, STALLED_LOOK_MS, STAMP_BITS_DEFAULT, STAMP_BITS_MAX, STAMP_BITS_MIN, STATUS_AVAILABILITIES, STATUS_CAPABILITY, STATUS_CARD_CAPABILITY, STATUS_CARD_LIMITS, STATUS_FRAME, STATUS_IDLE_AFTER_MS, STATUS_RATE_LIMIT, STATUS_RATE_WINDOW_MS, STATUS_SEND_INTERVAL_MS, STATUS_TEXT_MAX, STORAGE_LIFETIME, STORAGE_ROOT, SWITCH_RETIRE_MS, SessionCapabilities, SshSigError, StatusReceiver, StatusSender, TASK_STATUSES, TEST_USDT_FAUCET_AMOUNT, TOMBSTONE_SEQUENCE, TOMBSTONE_TURN, TRANSPORTS, TRANSPORTS_GONE_MS, TURN_BODY_BYTES, TURN_LABEL, TURN_LAST_SEQUENCE, TURN_MAX, TURN_NAME_BYTES, TURN_NO_ACTIVE, TURN_PUT_WINDOW_MS, TURN_RAISE_READ_TIMEOUT_MS, TURN_REV_LIMIT, TURN_SEALED_BYTES, TURN_SETTLE_MS, TURN_SIGNED_BYTES, TURN_SLOTS, TURN_SOURCE_TIMEOUT_MS, TURN_TTL, TURN_VERSION, TURN_VISIBLE_MS, TYPING_CAPABILITY, TYPING_FRAME, TYPING_KINDS, TYPING_RATE_LIMIT, TYPING_RATE_WINDOW_MS, TYPING_REFRESH_MS, TYPING_SEND_LIMIT, TYPING_STATUS_MAX, TYPING_TIMEOUT_MS, TurnRecordError, TypingReceiver, TypingSender, UNPROVEN_AUTH_MS, UNUSED_INVITE_READS_PER_MINUTE, UNUSED_INVITE_UPKEEP_MS, UNUSED_INVITE_WAIT_MAX_MS, UPGRADE_CAPABILITY, USDT_PUBLIC_RPC, VIDEO_LIMITS, VIDEO_METADATA_LIMITS, VIEWER_DROPPED_DIRECTIVES, VIEWER_DROPPED_HEADERS, VIEWER_GUARD_CSP, VIEWER_GUARD_HASH, VIEWER_GUARD_SCRIPT, VIEWER_PERMISSIONS_POLICY, VIEWER_SERVICE_CSP, VIEWER_SERVICE_CSP_RELAY_ONLY, VIEWER_WORKER_GUARD_CSP, VOICE_LIMITS, VOICE_METER, WAKE_ANSWER_GRACE_MS, WAKE_CALL_INTERVAL_MS, WAKE_CALL_TTL_SECONDS, WAKE_CALL_WAIT_MS, WAKE_SESSION_CAPABILITY as WAKE_CAPABILITY, WAKE_SESSION_CAPABILITY, WAKE_FRAME, WAKE_INTERVAL_MS, WAKE_LOST_MS, WAKE_ONLINE_BATCH, WAKE_ONLINE_BATCH_MS, WAKE_ONLINE_DELAY_MS, WAKE_ONLINE_INTERVAL_MS, WAKE_ONLINE_TTL_SECONDS, WAKE_RETRY_MS, WAKE_SUBJECT, WAKE_TTL_SECONDS, WALLET_NETWORKS, WATCH_PEER_MS, WATCH_SHARE, WAY_BACK_SHARE, WEBRTC_GUARD, WELL_KNOWN_PATH, WRITE_FIRST_MS, WakeLimiter, WebPushError, X401_CREDENTIAL_LIMITS, X401_DCQL_LIMITS, X401_HEADERS, X401_LIMITS, X401_PROTOCOLS, X401_REQUEST_LIMITS, X401_RESPONSE_MODES, X401_SCHEME, X401_VERSION, addedAppPermissions, allowingViewerGuard, answersOffer, appCardId, appCardUrl, appCloseFrame, appDataBytes, appDataFrame, appDigest, appFingerprint, appOpenFrame, appRangeCancelFrame, appRangeChunk, appRangeDataFrame, appRangeEndFrame, appRangeErrorFrame, appRangeGetFrame, appRef, appRefPublisher, appRevocationFor, appRevocationId, appSignedBytes, appStoreDecision, appUpdateDecision, appViewOf, applyIdentityEvent, arkAddressPrefix, arrivalKey, asWritten, assembleAppBundle, assertTokenUnits, assertWholeSats, atprotoCidFor, atprotoDidMethod, atprotoProofRecord, atprotoProofRkey, audioMetadataPatches, automaticTransport, baseMime, beaconKeys, beaconRecords, bip322MessageHash, bip322ToSign, bip322ToSpend, boundIdentityDisplay, boundVerifiedIdentity, budgetRetryMs, buildAppBundle, buildDataSdp, buildLinkRecords, buildSdpFromSignal, buildX401ProofRequest, buildX401ProofResult, buildX401ResultArtifact, buildX401TokenObject, buttonLabelClash, bytesEqual, callRtcConfig, callSignalHeardAt, canonicalJson, canonicalJsonBytes, canonicalUrl, capsDescriptors, cardEditNumber, cardLine, cardLinkHost, cardTimeUtc, cardUrl, carryMentions, cashuRequestPayload, chainPieces, chatAppId, checkAppBeforeRun, checkAppListing, checkAppManifest, checkAppRevokeStatement, checkAppStoreIndex, checkAtprotoProofRecord, checkDidJws, checkDidSignature, checkPushEndpoint, checkStatusCard, checkedDescriptors, claimedTime, classifyTurnRead, clearMissed, clockOffset, commitHash, commitUntaggedHash, communityCommitHash, communityEditFrame, communityGroupId, communityHasFrame, communityMessageAuthor, communityMessageId, communityRoster, communityUntaggedHash, compactSize, compareVersions, compressSdp, concatBytes, confirmationMatches, confirmationTag, contactAskerFrame, contactAskerHolds, contactDay, contactRtcConfig, countUnusedInvite, createChatInvite, createContactLink, createDeviceInvite, createIdentity, createLink, createRelayPayload, currentRelays, decodeAnyBitcoinAddress, decodeAppRangeData, decodeAtprotoCommit, decodeBase64, decodeBitcoinAddress, decodeBolt11, decodeChunk, decodeCommunityLink, decodeControl, decodeDagCbor, decodeDidDhtPacket, decodeDnsAnswers, decodeDnsResponse, decodeFileData, decodeGroupEntryLink, decodeInviteCode, decodeServices, decodeSvcbRecords, decodeTx, decodeTxtPacket, decodeWitness, decodeX401Header, decompressSdp, decrypt, decryptPushPayload, decryptText, derivedSecret, deviceEchoFrame, deviceEchoNonce, deviceFrameCapability, deviceInviteJoinerKeyZ32, deviceInviteJoinerParams, deviceKeyZ32, deviceLinkPairing, deviceLinkParams, deviceLinkRendezvousSeed, deviceLinkSealKey, deviceLinkSecret, devicePingFrame, deviceWakeRequest, dhtEditId, dhtFileElements, dhtFileId, dialDescriptors, dialableIrohRelay, didDhtDocument, didDhtFromPublicKey, didDhtKey, didDhtRecords, didGhostlyServiceEntry, didJwsAlg, didSignedMessages, didWebDocumentUrl, didWebFile, didWebFileNames, didWebFileUrl, didWebHost, directBlocked, dnsProofName, domainTxtRecord, domainWellKnownFile, doorHubs, downsamplePeaks, dropLoneJoiners, edgeParams, editFrame, editedFrame, emptyCapsState, emptyDhtDeliveryState, emptyIdentityLedger, emptyLinkRecords, emptyProofLedger, emptyRatchetState, encodeAppRangeData, encodeChunk, encodeCommunityLink, encodeContactLink, encodeControl, encodeDagCbor, encodeDeviceInvite, encodeDidDhtDeactivated, encodeDidDhtPacket, encodeDnsQuery, encodeFileData, encodeGhostlyInvite, encodeGroupEntryLink, encodeGroupMetaBody, encodeInviteCode, encodePacketTransports, encodeServices, encodeSetSlots, encodeSvcbPacket, encodeTurnFields, encodeTx, encodeTxtPacket, encodeWitness, encodeX401Header, encrypt, encryptPushPayload, encryptText, endedRequests, engineError, engineText, enrollCancelFrame, enrollCancelReason, enrollDigits, enrollDoneFrame, enrollGrantFrame, enrollHelloFrame, enrollMessage, enrollProofFrame, entryParams, epochKeys, exifOrientation, expectedRoster, extractParamsFromSdp, extractRtcParams, fedimintRequestPayload, fetchLnurlJson, fetchesByItself, fileMessageText, filePartDigest, filePartName, findAppForbiddenKey, findBolt11, findEndpoint, findInMst, findLightningDestination, firstDeviceSetSecret, formatEnrollDigits, formatFileSize, formatLocalTarget, formatPaymentAmount, formatVideoDuration, formatVoiceDuration, forwardedAgain, forwardedMany, frameBytes, freshHubs, fromBase64, fromBase64Url, fromZ32, generateEncryptionKey, generateVapidKeys, groupCallE2ee, groupCallKey, groupCallRequestBytes, groupCallRoom, groupCallSfu, groupDisplayName, groupEntryUrl, groupFileFallback, groupMessageId, groupMetaBody, groupMetaChange, groupMetaNewer, groupMetaPicture, groupMetaTag, groupMetaToHand, groupName, groupReplyAuthor, groupSignalFrame, groupTypingEpoch, groupWakeFrame, groupWakes, guardViewerAnswer, handoffAckFrame, handoffAttemptAllowed, handoffAttemptFailed, handoffAttemptSucceeded, handoffBusyFrame, handoffCancelFrame, handoffContext, handoffContextProof, handoffDataFrame, handoffDigest, handoffDoneFrame, handoffEphemeral, handoffFileMissingFrame, handoffFileRequestFrame, handoffHaveFrames, handoffHelloFrame, handoffManifestFrames, handoffOfferFrame, handoffPakeFrame, handoffReleaseFrame, handoffRequestFrame, handoffRetryAfter, handoffStreamKey, handoffVerifiedFrame, handoffVerifiedMessage, handoffVersions, hasVisible, hash160, heardCallSignal, heardTime, heldBackError, homeserverWebEndpoint, hubRank, identityFromSeed, identityFromSeedB64, identityPresentationBytes, identityRefusal, identityRevocationValue, identityStatement, identityStatementText, imageSize, importedProof, inboxRecord, inviteLink, inviteOwnership, inviteQrSegments, inviteQrText, invoiceCallbackUrl, irohDescriptor, irohRelayUrl, isAppHash, isAppKey, isAppLicense, isAppLine, isAppPath, isAppRef, isAppSignature, isAppUrl, isAppVersion, isAsf, isAtprotoDid, isBitcoinAddress, isCandidateAddress, isChatAppId, isDiscoveryBudgetError, isEmptyLinkPacket, isFederationId, isGlobalIpv4Host, isGroupMessageId, isHandoffPartName, isHoldUrl, isIdentityBinding, isImageMime, isLegacySignature, isNewerVersion, isPlayableAudioType, isPlayableVideoType, isProofAdapter, isPubkyKey, isPubkyProofFolder, isPublicAddress, isRatcheted, isServeId, isSparkAddress, isStrippedPicture, isValidServiceId, isVideoMime, isViewerTag, isWalletNetwork, isX401Protocol, isZ32Key, jpegSize, jwkThumbprint, keepPastGroupMeta, keepsToRelays, keptAtEqualSequence, knockHolds, knockIdentity, knockRecords, knockSlotIdentity, knockSlotOf, knockSlotRecords, lastSharedWithMe, leaveStands, leaveStatement, leaveStatement3, leftStatement, legacyMessageHash, linkEnd, linkRecords, linkStop, linkTail, linksIn, liveStatus, lobbyKeys, lobbyRecords, makeStamp, makeStampPaced, matchX401Dcql, mayBeHub, mayPin, measureRecords, memberAdmissions, mentionedMembers, mentionsBytes, mentionsMember, mergeBeacon, mergeContactKnocks, mergeKnocks, mergeLobby, meshHubs, meshMessageRef, meshRendezvous, newDeviceSetSecret, newEpochSecret, newHandoffId, newMailbox as newHoldMailbox, newIdentityBinding, newInbox, newPubkyProofFolder, newWakeToken, newX401HolderKey, newerHead, newerPacket, nextGroupMetaRevision, nextPinNumber, nextReactionNumber, nextTurnPosition, nip05RootKey, normalizeAtprotoHandle, normalizeDid, normalizeDomain, normalizePubkyKey, normalizeRelayUrl, nostrProofTemplate, offerIsFresh, openDidDhtPayload, openGroupMeta, openGroupTyping, openHandoffPiece, openPair, openRelayPayload, openRequest, openSecret, openTurnValue, ownInviteRefusal, pacer, pairedEditFits, pairedMessageFits, pairedMessageFrame, pairedReplyAuthor, parseAppFrame, parseAppRangeFrame, parseAtprotoCar, parseAtprotoDidDocument, parseAtprotoDidKey, parseAtprotoVerificationKey, parseCallSignal, parseCashuRequestPayload, parseCommunityEdit, parseDid, parseDidDocument, parseDidJws, parseDidSignaturePaste, parseDomainTxt, parseEditFrame, parseEditedFrame, parseEngineError, parseFedimintRequestPayload, parseGroupCommit, parseGroupMetaBody, parseGroupMetaFrame, parseGroupMetaStatement, parseGroupMetaTag, parseGroupWakeFrame, parseHubPolicy, parseImageMeta, parseInvoiceCallback, parseLightningDestination, parseLinkPreview, parseLinkRecords, parseLocalTarget, parsePacketTransports, parsePairedCallFrame, parsePayParams, parsePaymentAmount, parsePaymentNetworks, parsePinFrame, parsePinnedFrame, parseReactedFrame, parseReactionFrame, parseRelayPayload, parseRtcSignal, parseSessionCapabilities, parseSshPublicKey, parseSshSignature, parseStatusFrame, parseTypingActivity, parseTypingFrame, parseVideoMeta, parseVoiceMeta, parseWakeFrame, pastedAgain, paymentUri, peekDhtMailbox, personStatus, pickCallCandidates, pickHubs, pickMeshHubs, pinFrame, pinIsNewer, pinNumberHolds, pinnedFrame, plainStatusLine, planAppUpdate, planKnocks, presenceSeenAt, presentX401SdJwtVc, previewImageSize, previewable, proofCapability, proofHash, proofStatement, pubkyHomeserverOf, pubkyProofCapability, pubkyProofFile, pubkyProofPath, publicKeyFromZ32, publishFailure, publishedNowhere, pushRequest, qrText, queueReaction, randomBytes, rankHubs, rankTransports, ratchetHeard, ratchetOn, ratchetOpen, ratchetRoot, ratchetSeal, ratchetSessionOf, ratchetUnknownSession, reactedFrame, reactionEmoji, reactionFrame, reactionIsNewer, readAppBundle, readAppBundleAsync, readAppFrame, readAppListing, readAppRangeFrame, readAppRevocation, readAppRevocationShape, readAppRevocations, readAppSignature, readAppStore, readAppStoreSteps, readAtprotoCid, readBeacon, readBeaconHead, readCanonicalJson, readContactLink, readDeviceInvite, readDhtFile, readDhtReactions, readDnsName, readEnrollGrant, readEnrollHello, readForwarded, readGroupFileMeta, readGroupHave, readGroupSignal, readGroupWant, readGroupWantNo, readHandoffAck, readHandoffBusy, readHandoffCancel, readHandoffData, readHandoffDone, readHandoffFileFrame, readHandoffHave, readHandoffHello, readHandoffManifest, readHandoffPake, readHandoffRelease, readHandoffTurnFrame, readHandoffVerified, readImageMeta, readInviteCode, readKnockSlot, readKnocks, readLinkRecord, readLobby, readManifest, readOwnRelayPayload, readPin, readReaction, readRelayBody, readReply, readSetUpdate, readStatusCard, readTurnBody, readTurnPacket, readWake, readWakePayload, readX401DcqlQuery, readX401OpenId4VpRequest, readX401ProofRequest, readX401ProofRequestHeader, readX401ProofResponse, readX401ProofResponseHeader, readX401ProofResult, readX401ProofResultHeader, readX401SdJwtVc, readingAhead, receivedIdentityStatus, receivedTimestamp, recordingMime, recordsFromTxt, recordsFromWellKnown, recordsName, refusalText, relativizeLocation, relayRequest, relayUrl, relayUrlProblem, relayUrlTooLong, relayedTransports, rememberAlone, removedCardText, repeatedJsonKey, replySnippet, requestLnurlInvoice, requestPlaintextBytes, requestRecords, resolveDidDht, resolveLightningDestination, resolveTargetUrl, revokesIdentity, ringAuthorization, ringClaims, ringEvidence, rosterAdmin, rosterHas, rosterHash, routedCommunityFrame, safeBlobType, sameButtonText, sameSshKey, sameStatusState, sameX401HolderJwk, sanitizeAvatar, sanitizeDisplayText, sanitizeFileName, sanitizeMime, sanitizeNick, sanitizePreviewImage, sanitizeRequestHeaders, sanitizeResponseHeaders, sanitizeStatusText, sanitizeTypingStatus, satsToBtc, sdpHasCandidates, sealGroupTyping, sealHandoffPiece, sealPair, sealSecret, sealTurnBody, sealedLength, seedSigner, seenEntry, sendBody, sentWhole, serviceIdFromName, servicesFromWire, servicesToWire, sessionCapabilitiesFrame, setAckFrame, setAppSignatureFastPath, setLinkTraceSink, setPublicKeyFastPath, setUpdateFrame, setUpdateMessage, settleRequest, sha256Hex, sha256Paced, sha256d, shortAtprotoDid, shortHash, shouldBeHub, shownTime, sign, signAppObject, signAppRevocation, signAppStore, signCommit, signCommunity, signDeviceTransports, signDidDhtPacket, signGroupCallRequest, signGroupMeta, signIdentityPresentation, signRelayPayload, signTombstone, signTurnBody, signTurnPacket, signTurnRelease, signalHasVideo, signingKeys, sortParts, sortRoster, sparkAddressKind, sparkInvoiceDetails, sparkNetworkOf, sshFingerprint, sshKeyDigestHex, sshSignCommand, stampHolds, staticDidDocument, statusCardBytes, statusCardText, statusFrame, statusState, storageProof, storageProofBody, storageProofPath, strictBase64Url, stripHidden, stripPictureMetadata, symmetricNat, takeRequest, taskProgress, toBase64, toBase64Url, toZ32, traceLink, transferEnded, transferStalled, transportOrder, trimEndOf, tryDecrypt, turnInstance, turnKeys, turnName, turnOff, turnPacket, turnPayloadSequence, turnPutSummary, turnReleaseMessage, turnSequence, turnSignedMessage, turnStatedVerifier, turnVerifierMark, txHash, txtValue, typingActivity, typingFrame, typingKindOf, u32, u64, unsignedCommitBytes, unsignedDeviceTransports, unusedInviteWait, unwrapPasted, uriEnd, usageLeft, utf8Decode, utf8Encode, validDomainRecord, validEditMessage, validEditNumber, validEditText, validExternalKey, validHead, validMentions, validReactionNumber, validRemovalNumber, validRingKey, validatePaymentTarget, vapidAuthorization, vapidKeysMatch, varBytes, verify, verifyAppRevocation, verifyAppSignature, verifyAppStatementBytes, verifyAtprotoRecordProof, verifyAtprotoSignature, verifyBip322, verifyBitcoinMessage, verifyChain, verifyCommit, verifyCommitSignature, verifyCommunityChain, verifyCommunityChainPaced, verifyCommunityCommit, verifyDeviceTransports, verifyEnrollProof, verifyGroupCallRequest, verifyGroupMetaSignature, verifyIdentityPresentation, verifyNostrProof, verifyPeerProof, verifyRingAuthorization, verifyRingEvidence, verifySetUpdate, verifySshSignature, videoMetadataPatches, viewerGuardOffset, viewerResponseHeaders, viewerServicePolicy, viewerTag, voiceDownloadName, voiceFileName, voiceLevel, voiceLevelsOf, voicePeaksOf, waitForIceGathering, wakeFrame, wakePayload, wakeRequest, walletNetworkOf, webCryptoSigner, webLocalFetch, wellKnownUrl, wireHubPolicy, wireMentions, wireReaction, wireReply, withRequestOptions, withViewerPolicy, withoutAudioMetadata, withoutPictureMetadata, withoutVideoMetadata, wrapDataChannel, wrapGroupMeta, x401AnswerableRequests, x401ApprovalDigest, x401HolderJwk, x401VpToken, yieldThread };
40109
+ export { ACTIVE_DHT_POLL_MS, ACTIVE_TASK_STATUSES, ANSWERS_REFUSED_PAUSES, ANSWERS_REFUSED_PAUSE_MS, ANSWER_READ_ALLOWANCE, ANSWER_READ_FIRST_MS, ANSWER_READ_SPACING_MS, ANSWER_REFUSED_REDIALS, APPS_CAPABILITY, APP_BUNDLE_LIMITS, APP_BUNDLE_MAGIC, APP_CLIENTS, APP_CLIENT_NAME, APP_DATA_MAX_BYTES, APP_FORBIDDEN_KEYS, APP_FRAME, APP_ICON_PATH, APP_NAME, APP_PEER_OPEN_MAX, APP_PERMISSIONS, APP_PREFIXES, APP_RANGES_CAPABILITY, APP_RANGE_DATA_KIND, APP_RANGE_ERRORS, APP_RANGE_FRAMES, APP_RANGE_LIMITS, APP_RATE_LIMIT, APP_RATE_WINDOW_MS, APP_RESUME_GRACE_MS, APP_SCREENSHOTS_DIR, APP_SEND_LIMIT, APP_STATEMENT_LIMITS, APP_STORE_KINDS, APP_STORE_LIMITS, APP_VERSION_MAX, APP_VIEWS, ATPROTO_DECLARED_SCOPE, ATPROTO_FULL_SCOPE, ATPROTO_PROOF_COLLECTION, ATPROTO_PROOF_SCOPE, AUDIO_METADATA_LIMITS, AUTOMATIC_ORDER, AWAITED_READS, AWAITING_PEER_MS, AppRanges, AppSessions, AtprotoCid, AtprotoProofError, BACKGROUND_REQUESTS_PER_MINUTE, BACKGROUND_WHILE_SIGNALING, BACKGROUND_WRITES_SHARE, BIP322_REVISION, BITCOIN_NETWORKS, BLOCKED_DIAL_WAIT_MS, BOLT11_PATTERN, BREAKER_ALL_DOWN_PROBE_MS, BREAKER_BASE_MS, BREAKER_MAX_MS, BREAKER_THRESHOLD, BURST_RING_MS, BUTTONS_CAPABILITY, BUTTON_ID, BUTTON_STYLES, BitcoinAddressError, ByteReader, CALLS_CAPABILITY, CALL_RATE_WINDOW_MS, CALL_RECEIVE_LIMIT, CALL_SIGNAL_FUTURE_MS, CALL_SIGNAL_MAX_AGE_MS, CAPS_ISSUED_BACK_MS, CAPS_LABEL, CAPS_LIMITS, CAPS_PUBLISH_SPACING_MS, CAPS_REFRESH_MS, CARRIED_DEFER_MS, CATCH_UP_PAUSE_MS, CATCH_UP_SLICE, CHAT_RESERVE, CHAT_RESERVE_MOST_SHARE, CHAT_RESERVE_PER_CHAT, CHAT_WATCH_SHARE, CHUNK_FLAG_END, CHUNK_KIND, CLIPBOARD_GUARD_HASH, CLIPBOARD_GUARD_SCRIPT, CLOCK_EVIDENCE_MS, CLOCK_OFF_MS, CLOCK_PEERS, CLOCK_PEER_READ_GAP_MS, CLOCK_SERVERS, COMMUNITY_EDIT_FRAME, COMMUNITY_LIMITS, COMMUNITY_PIN_FRAME, COMMUNITY_PROFILE, COMMUNITY_REACTION_FRAME, COMMUNITY_TAKEOVER_META_MS, COMMUNITY_TOPOLOGY, CONNECT_TIMEOUT_MS, CONTACT_ASKER_FRAME, CONTACT_LINK_BYTES, CONTACT_LINK_VERSION, CONTACT_RECORD_TTL, CRON_LINE, CROSSED_FRESH_MS, CROSSED_PROBE_MS, CROSSED_WAIT_MS, CapsExchange, CapsKeys, CapsRefusedError, CarriedTransport, CatchUpAnswers, ChatFiles, ClockWatch, CommunitySession, ContactRequestError, DAEMON_WATCH_PEER_IDLE_MS, DATA_CHANNEL_ID, DATA_CHANNEL_LABEL, DATA_SETTLE_MS, DEFAULT_RELAYS, DEMOTE_AFTER_FAILURES, DEMOTE_MS, DEPARTED_READS, DEPARTED_READ_MS, DEVICES_CAPABILITY, DEVICE_CAPABILITIES, DEVICE_ECHO_FRAME, DEVICE_INVITE_BYTES, DEVICE_INVITE_LIFETIME_S, DEVICE_INVITE_OWN_DEVICE, DEVICE_INVITE_VERSION, DEVICE_KINDS, DEVICE_PING_FRAME, DEVICE_WAKE_TTL_SECONDS, DHT_FILE_CAPABILITY, DHT_FILE_REFUSED, DHT_FILE_TOO_LARGE, DHT_MESSAGE_TTL, DHT_PACKET_BUDGET, DHT_PIN_GRACE_MS, DHT_POLL_INTERVALS, DHT_TEXT_BYTES, DHT_TEXT_CAPABILITY, DHT_TEXT_REFUSED, DIALED_IN_CONTENDERS, DID_DHT_MAX_PAYLOAD, DID_DHT_PREFIX, DID_DHT_TTL, DID_DHT_VERSION, DID_DOCUMENT_MAX_BYTES, DID_FILE_MAX_BYTES, DID_GHOSTLY_SERVICE, DID_JWS_ALGS, DID_JWS_MAX_LENGTH, DID_MAX_LENGTH, DID_METHODS, DIRECT_EVIDENCE_MS, DIRECT_OWN_ATTEMPTS, DIRECT_PEERS, DNS_LABEL, DNS_TYPE, DOMAIN_FILE_MAX_BYTES, DOMAIN_MAX_RECORDS, DOMAIN_METHODS, DOMAIN_TXT_MAX_BYTES, DataLink, DhtDelivery, DidDhtError, DidError, DirectPathWatch, DiscoveryBudgetError, EARLY_DIAL_JOIN_MS, EDITED_FRAME, EDIT_BUFFER_MAX, EDIT_BUFFER_MS, EDIT_CAPABILITY, EDIT_FRAME, EDIT_RATE_WINDOW_MS, EDIT_RECEIVE_LIMIT, EDIT_SEND_LIMIT, ENDPOINT, ENGINE_ERRORS, ENROLL_CANCEL, ENROLL_CANCEL_REASONS, ENROLL_CAPABILITY, ENROLL_DONE, ENROLL_GRANT, ENROLL_HELLO, ENROLL_PROOF, ETHEREUM_USDT, EVM_TEST_CHAINS, EXPECT_PEER_MS, EngineError, FILES_BINARY_CAPABILITY, FILES_CAPABILITY, FILE_DATA_KIND, FILE_FRAMES, FILE_LIMITS, FIRST_PAIRING_PACE_MS, FIRST_PUBLISH_MAX_MS, FLOOD_PER_DAY, FOLLOW_MS, FORWARD_LIMITS, FRESH_READ_MS, FileTransfers, FileUplink, GATHER_ATTEMPTS, GATHER_STALL_MS, GROUP_ADMIN_OFF_ERROR, GROUP_BURST_MS, GROUP_BURST_ONE_LINK, GROUP_CALL_MODERATION_ACTS, GROUP_CALL_NONCE_S, GROUP_CALL_SKEW_S, GROUP_CALL_SOURCES, GROUP_CALL_VERSION, GROUP_EDIT_FRAME, GROUP_EDIT_TEXT_BYTES, GROUP_ENTRY_PROFILE, GROUP_FILE_LIMITS, GROUP_HAVE_FRAME, GROUP_ID, GROUP_LIMITS, GROUP_MEMBER_CAP, GROUP_META_PAST, GROUP_META_PAST_CHARS, GROUP_OVER_PACE_MS, GROUP_PIN_FRAME, GROUP_PROFILE, GROUP_RATION_WINDOW_MS, GROUP_REACTED_FRAME, GROUP_REACTION_FRAME, GROUP_READ_NOTE, GROUP_READ_NOTE_COMMUNITY, GROUP_SIGNALING_ALLOWANCE_SHARE, GROUP_SIGNAL_FRAME, GROUP_TAKEOVER_META_MS, GROUP_TYPING_FRAME, GROUP_VERSION_FILES, GROUP_VERSION_HUBS, GROUP_VERSION_LARGE, GROUP_VERSION_SIGNALS, GROUP_WAKE_FRAME, GROUP_WAKE_GROUP_LIMIT, GROUP_WAKE_GROUP_WINDOW_MS, GROUP_WAKE_MEMBER_INTERVAL_MS, GROUP_WAKE_RECEIVE_LIMIT, GROUP_WANT_FRAME, GROUP_WANT_NO_FRAME, GhostLink, GhostlyHttpError, GroupSession, GroupTypingBoard, GroupWakeLimiter, HANDLED_WAIT_MS, HANDOFF_ACK, HANDOFF_ATTEMPTS, HANDOFF_BUSY, HANDOFF_BUSY_REASONS, HANDOFF_CANCEL, HANDOFF_CANCEL_REASONS, HANDOFF_CAPABILITY, HANDOFF_DATA, HANDOFF_DONE, HANDOFF_FILE_MISSING, HANDOFF_FILE_REQUEST, HANDOFF_HAVE, HANDOFF_HELLO, HANDOFF_LATER_BYTES, HANDOFF_LIST_PER_FRAME, HANDOFF_MANIFEST, HANDOFF_OFFER, HANDOFF_PAKE, HANDOFF_PIECE_BYTES, HANDOFF_PIECE_OVERHEAD, HANDOFF_RELEASE, HANDOFF_REQUEST, HANDOFF_TIMINGS, HANDOFF_VERIFIED, HANDOFF_VERSION, HANDOFF_WINDOW, HEDGE_MISSING_MS, HEDGE_MS, HOLD_CAPABILITY, HOLD_DATED_BACK_MS, HOLD_LIMITS, HTTP_SERVICE_PROTO, HoldKeys, HoldRefusedError, HttpClient, HttpHost, IDENTITY_CHALLENGE_WINDOW, IDENTITY_CHECK_UNAVAILABLE, IDENTITY_CLOCK_SKEW, IDENTITY_FRAME_LIMIT, IDENTITY_FRAME_WINDOW_MS, IDENTITY_MAX_CHECKS_PER_HOUR, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_FRAME, IDENTITY_MAX_RECEIVED, IDENTITY_MAX_VALIDITY, IDENTITY_MEMO_IDLE_MS, IDENTITY_MEMO_MAX, IDENTITY_MEMO_SIZE, IDENTITY_PROOF_CAPABILITY, IDENTITY_PROVIDER_ID, IDENTITY_REUSE_CHECK_S, IDENTITY_REVOCATION_LABEL, IDENTITY_STATEMENT_PREFIX, IDENTITY_SUBJECT, IDENTITY_TIMELINE_MAX, IDLE_THRESHOLD, IMAGE_LIMITS, INVITER_DIAL_GRACE_MS, INVITE_HRP, INVITE_LINK_ORIGIN, INVITE_MAX_LENGTH, INVITE_TAKEN, INVITE_VERSION, ITEM_STATES, IdentityCheckUnavailable, IdentityExchange, KNOCK_SLOTS, KNOCK_SLOT_LABEL, KNOCK_TTL_MS, KNOWN_SESSION_CAPABILITIES, LABEL, LATE_ANSWER_MS, LEGACY_GROUP_MEMBERS, LEGACY_SERVICES, LIGHTNING_DESTINATION_PATTERN, LIMITS, LINK_MAX_CHARS, LINK_PREVIEW_LIMITS, LINK_RECORD_LABEL, LINK_TRAILING, LIVENESS_MISSED_PINGS, LIVENESS_PING_MS, LIVE_POLL_MS, LNURL_LIMITS, LinkSession, MAX_AVATAR_LENGTH, MAX_AVATAR_SIDE, MAX_CHUNK_PAYLOAD_BYTES, MAX_DHT_TEXT_BYTES, MAX_DNS_PACKET_BYTES, MAX_DONE, MAX_EDITS_PER_MESSAGE, MAX_GROUP_CALL_NAME, MAX_GROUP_CALL_SFU, MAX_GROUP_CHAIN, MAX_GROUP_MEMBERS, MAX_GROUP_META_BODY, MAX_GROUP_NAME_BYTES, MAX_GROUP_NAME_LENGTH, MAX_GROUP_PICTURE_LENGTH, MAX_KNOCKS, MAX_MISSED, MAX_MSGS_PAYLOAD_B64, MAX_NICK_LENGTH, MAX_PAIRED_CALL_SIGNAL, MAX_PAIRED_MESSAGE_FRAME, MAX_REMOVAL_NUMBER, MAX_SEEN, MAX_SERVICES, MAX_SHARED_APPS, MAX_SKIP, MAX_SKIPPED_KEYS, MAX_SLOT_KNOCKS, MAX_WAITING, MEMBER_KEY, MENTION_EVERYONE, MENTION_LIMITS, MESH_HUBS, MESSAGE_CLOCK_SKEW_MS, MESSAGE_PACED, MESSAGE_RECEIVE_LIMITS, MessagePace, MessageRefusal, NEW_PER_HOUR, NIP05_PATH, NO_ATTEMPTS, NO_AUDIO_METADATA, NO_HUB_POLICY, NO_PICTURE_METADATA, NO_VIDEO_METADATA, OFFER_FAST_MS, OFFER_HOST_GATHER_MS, OFFER_LOOK_MS, OFFER_STEP_MAX, ONCHAIN_PROVIDER, OWN_FRAME_LIMIT, OwnInviteError, PAIRED_CALL_CANDIDATES, PAIRED_CALL_FRAME, PAIRED_FRAME_TOO_LARGE, PAIRED_PROFILE, PAIRED_REPLY_AUTHORS, PAIRING_ATTEMPT_MS, PAIRING_RETRY_MS, PICTURE_METADATA_LIMITS, PINNED_FRAME, PIN_CAPABILITY, PIN_CLOCK_SKEW_MS, PIN_FRAME, PIN_LIMITS, PKARR_FUTURE_SKEW_MS, PLAYABLE_AUDIO, PLAYABLE_VIDEO, PONG_WAIT_MS, PRESENCES, PRESENCE_HEARTBEAT, PRESENCE_WINDOW, PREVIEWABLE_IMAGE, PREVIOUS_DEFAULT_RELAYS, PROOF_ADAPTERS, PROOF_CAPABILITY, PROTOCOL_VERSION, PR_CHECKS, PR_STATES, PUBKY_PROOF_MAX_BYTES, PUBKY_PROOF_ROOT, PUSH_PAD_BYTES, PUSH_SERVICE_HOSTS, PacketTooLargeError, PairedCalls, PairedSession, PairingTracker, PaymentPreflightError, PeerProofs, PublishFailedError, QUICK_REACTIONS, QUICK_REDIAL_MS, RACE_ANSWERED_MS, RACE_DIRECT_MS, RACE_RELAYED_MS, RATCHET_CAPABILITY, RATCHET_HEADER_BYTES, RATCHET_KEEP_MS, RATCHET_OVERHEAD, REACTED_FRAME, REACTIONS_CAPABILITY, REACTION_FRAME, REACTION_LIMITS, REANSWERS, RECORDING_TYPES, RECORD_TTL, REDESCRIBED_GRACE_MS, RELAYED_FIRST_MS, RELAY_PAYLOAD_MAX_BYTES, RELAY_POLL_INTERVALS, RELAY_REQUESTS_PER_MINUTE, RELAY_URL, RELAY_WITH_SECRETS, REMOVABLE_KINDS, REMOVED_TEXT, REOPEN_BELOW, REPLY_ID, REPLY_LIMITS, REQUESTS_PER_MINUTE, REQUEST_CLOCK_SKEW_MS, REQUEST_LABEL, REQUEST_LIFETIME_MS, REQUEST_NAME_UNITS, REQUEST_PACKET_BYTES, REQUEST_TEXT_BYTES, RESUME_WAIT_MS, RING_LIFETIME, ROUTINE_STATES, RTC_CONFIG, RTC_SIGNAL_FUTURE_MS, RTC_SIGNAL_MAX_AGE_MS, RTC_SIGNAL_RATE_WINDOW_MS, RTC_SIGNAL_RECEIVE_LIMIT, RTC_UNSTARTED_MS, RUN_RESULTS, RatchetBox, RateWindow, ReactionWindow, RelayBreaker, RelayTransport, RelaysFailedError, SAID_AGAIN, SEPOLIA_TEST_USDT, SEPOLIA_TEST_USDT_FAUCET, SERVICES_CAPABILITY, SERVICES_VERSION, SESSION_CAPABILITIES_FRAME, SESSION_FRAME_MAX, SESSION_RECEIVE_PENDING, SET_ACK, SET_UPDATE, SIGNALING_ALLOWANCE_SHARE, SIGNALING_WINDOW_MS, SIGNALS_PER_MINUTE, SIGNAL_CARRIERS, SIGNAL_DUE_READS, SIGNAL_FRESH_MS, SIGNAL_HOLD_MS, SIGNAL_OUT_READS, SIGNAL_PROVEN_MS, SIGNAL_REPLY_MS, SLOW_DEMOTE_MS, SLOW_MS, SPARK_NETWORKS, SPARK_PROVIDER, SSHSIG_MAX_ARMOR, SSHSIG_NAMESPACE, SSH_KEY_TYPES, SSH_PUBLIC_KEY_MAX, STALLED_EVIDENCE_MS, STALLED_LOOK_MS, STAMP_BITS_DEFAULT, STAMP_BITS_MAX, STAMP_BITS_MIN, STATUS_AVAILABILITIES, STATUS_CAPABILITY, STATUS_CARD_CAPABILITY, STATUS_CARD_LIMITS, STATUS_FRAME, STATUS_IDLE_AFTER_MS, STATUS_RATE_LIMIT, STATUS_RATE_WINDOW_MS, STATUS_SEND_INTERVAL_MS, STATUS_TEXT_MAX, STORAGE_LIFETIME, STORAGE_ROOT, SWITCH_RETIRE_MS, SessionCapabilities, SshSigError, StatusReceiver, StatusSender, TASK_STATUSES, TEST_USDT_FAUCET_AMOUNT, TOMBSTONE_SEQUENCE, TOMBSTONE_TURN, TRANSPORTS, TRANSPORTS_GONE_MS, TURN_BODY_BYTES, TURN_LABEL, TURN_LAST_SEQUENCE, TURN_MAX, TURN_NAME_BYTES, TURN_NO_ACTIVE, TURN_PUT_WINDOW_MS, TURN_RAISE_READ_TIMEOUT_MS, TURN_REV_LIMIT, TURN_SEALED_BYTES, TURN_SETTLE_MS, TURN_SIGNED_BYTES, TURN_SLOTS, TURN_SOURCE_TIMEOUT_MS, TURN_TTL, TURN_VERSION, TURN_VISIBLE_MS, TYPING_CAPABILITY, TYPING_FRAME, TYPING_KINDS, TYPING_RATE_LIMIT, TYPING_RATE_WINDOW_MS, TYPING_REFRESH_MS, TYPING_SEND_LIMIT, TYPING_STATUS_MAX, TYPING_TIMEOUT_MS, TurnRecordError, TypingReceiver, TypingSender, UNPROVEN_AUTH_MS, UNUSED_INVITE_READS_PER_MINUTE, UNUSED_INVITE_UPKEEP_MS, UNUSED_INVITE_WAIT_MAX_MS, UPGRADE_CAPABILITY, USDT_PUBLIC_RPC, VIDEO_LIMITS, VIDEO_METADATA_LIMITS, VIEWER_DROPPED_DIRECTIVES, VIEWER_DROPPED_HEADERS, VIEWER_GUARD_CSP, VIEWER_GUARD_HASH, VIEWER_GUARD_SCRIPT, VIEWER_PERMISSIONS_POLICY, VIEWER_SERVICE_CSP, VIEWER_SERVICE_CSP_RELAY_ONLY, VIEWER_WORKER_GUARD_CSP, VOICE_LIMITS, VOICE_METER, WAKE_ANSWER_GRACE_MS, WAKE_CALL_INTERVAL_MS, WAKE_CALL_TTL_SECONDS, WAKE_CALL_WAIT_MS, WAKE_SESSION_CAPABILITY as WAKE_CAPABILITY, WAKE_SESSION_CAPABILITY, WAKE_FRAME, WAKE_INTERVAL_MS, WAKE_LOST_MS, WAKE_ONLINE_BATCH, WAKE_ONLINE_BATCH_MS, WAKE_ONLINE_DELAY_MS, WAKE_ONLINE_INTERVAL_MS, WAKE_ONLINE_TTL_SECONDS, WAKE_RETRY_MS, WAKE_SUBJECT, WAKE_TTL_SECONDS, WALLET_NETWORKS, WATCH_PEER_MS, WATCH_SHARE, WAY_BACK_SHARE, WEBRTC_GUARD, WELL_KNOWN_PATH, WRITE_FIRST_MS, WakeLimiter, WebPushError, X401_CREDENTIAL_LIMITS, X401_DCQL_LIMITS, X401_HEADERS, X401_LIMITS, X401_PROTOCOLS, X401_REQUEST_LIMITS, X401_RESPONSE_MODES, X401_SCHEME, X401_VERSION, addedAppPermissions, allowingViewerGuard, answersOffer, appCardId, appCardUrl, appCloseFrame, appDataBytes, appDataFrame, appDigest, appFingerprint, appOpenFrame, appRangeCancelFrame, appRangeChunk, appRangeDataFrame, appRangeEndFrame, appRangeErrorFrame, appRangeGetFrame, appRef, appRefPublisher, appRevocationFor, appRevocationId, appSignedBytes, appStoreDecision, appUpdateDecision, appViewOf, applyIdentityEvent, arkAddressPrefix, arrivalKey, asWritten, assembleAppBundle, assertTokenUnits, assertWholeSats, atprotoCidFor, atprotoDidMethod, atprotoProofRecord, atprotoProofRkey, audioMetadataPatches, automaticTransport, baseMime, beaconKeys, beaconRecords, bip322MessageHash, bip322ToSign, bip322ToSpend, boundIdentityDisplay, boundVerifiedIdentity, budgetRetryMs, buildAppBundle, buildDataSdp, buildLinkRecords, buildSdpFromSignal, buildX401ProofRequest, buildX401ProofResult, buildX401ResultArtifact, buildX401TokenObject, buttonLabelClash, bytesEqual, callRtcConfig, callSignalHeardAt, canonicalJson, canonicalJsonBytes, canonicalUrl, capsDescriptors, cardEditNumber, cardLine, cardLinkHost, cardTimeUtc, cardUrl, carryMentions, cashuRequestPayload, chainPieces, chatAppId, checkAppBeforeRun, checkAppListing, checkAppManifest, checkAppRevokeStatement, checkAppStoreIndex, checkAtprotoProofRecord, checkDidJws, checkDidSignature, checkPushEndpoint, checkStatusCard, checkedDescriptors, claimedTime, classifyTurnRead, clearMissed, clockOffset, commitHash, commitUntaggedHash, communityCommitHash, communityEditFrame, communityGroupId, communityHasFrame, communityMessageAuthor, communityMessageId, communityRoster, communityUntaggedHash, compactSize, compareVersions, compressSdp, concatBytes, confirmationMatches, confirmationTag, contactAskerFrame, contactAskerHolds, contactDay, contactRtcConfig, countUnusedInvite, createChatInvite, createContactLink, createDeviceInvite, createIdentity, createLink, createRelayPayload, currentRelays, decodeAnyBitcoinAddress, decodeAppRangeData, decodeAtprotoCommit, decodeBase64, decodeBitcoinAddress, decodeBolt11, decodeChunk, decodeCommunityLink, decodeControl, decodeDagCbor, decodeDidDhtPacket, decodeDnsAnswers, decodeDnsResponse, decodeFileData, decodeGroupEntryLink, decodeInviteCode, decodeServices, decodeSvcbRecords, decodeTx, decodeTxtPacket, decodeWitness, decodeX401Header, decompressSdp, decrypt, decryptPushPayload, decryptText, derivedSecret, deviceEchoFrame, deviceEchoNonce, deviceFrameCapability, deviceInviteJoinerKeyZ32, deviceInviteJoinerParams, deviceKeyZ32, deviceLinkPairing, deviceLinkParams, deviceLinkRendezvousSeed, deviceLinkSealKey, deviceLinkSecret, devicePingFrame, deviceWakeRequest, dhtEditId, dhtFileElements, dhtFileId, dialDescriptors, dialableIrohRelay, didDhtDocument, didDhtFromPublicKey, didDhtKey, didDhtRecords, didGhostlyServiceEntry, didJwsAlg, didSignedMessages, didWebDocumentUrl, didWebFile, didWebFileNames, didWebFileUrl, didWebHost, directBlocked, dnsProofName, domainTxtRecord, domainWellKnownFile, doorHubs, downsamplePeaks, dropLoneJoiners, edgeParams, editFrame, editedFrame, emptyCapsState, emptyDhtDeliveryState, emptyIdentityLedger, emptyLinkRecords, emptyProofLedger, emptyRatchetState, encodeAppRangeData, encodeChunk, encodeCommunityLink, encodeContactLink, encodeControl, encodeDagCbor, encodeDeviceInvite, encodeDidDhtDeactivated, encodeDidDhtPacket, encodeDnsQuery, encodeFileData, encodeGhostlyInvite, encodeGroupEntryLink, encodeGroupMetaBody, encodeInviteCode, encodePacketTransports, encodeServices, encodeSetSlots, encodeSvcbPacket, encodeTurnFields, encodeTx, encodeTxtPacket, encodeWitness, encodeX401Header, encrypt, encryptPushPayload, encryptText, endedRequests, engineError, engineText, enrollCancelFrame, enrollCancelReason, enrollDigits, enrollDoneFrame, enrollGrantFrame, enrollHelloFrame, enrollMessage, enrollProofFrame, entryParams, epochKeys, exifOrientation, expectedRoster, extractParamsFromSdp, extractRtcParams, fedimintRequestPayload, fetchLnurlJson, fetchesByItself, fileMessageText, filePartDigest, filePartName, findAppForbiddenKey, findBolt11, findEndpoint, findInMst, findLightningDestination, firstDeviceSetSecret, formatEnrollDigits, formatFileSize, formatLocalTarget, formatPaymentAmount, formatVideoDuration, formatVoiceDuration, forwardedAgain, forwardedMany, frameBytes, freshHubs, fromBase64, fromBase64Url, fromZ32, generateEncryptionKey, generateVapidKeys, groupCallE2ee, groupCallKey, groupCallModerationBytes, groupCallRequestBytes, groupCallRoom, groupCallSfu, groupDisplayName, groupEntryUrl, groupFileFallback, groupMessageId, groupMetaBody, groupMetaChange, groupMetaNewer, groupMetaPicture, groupMetaTag, groupMetaToHand, groupName, groupReplyAuthor, groupSignalFrame, groupTypingEpoch, groupWakeFrame, groupWakes, guardViewerAnswer, handoffAckFrame, handoffAttemptAllowed, handoffAttemptFailed, handoffAttemptSucceeded, handoffBusyFrame, handoffCancelFrame, handoffContext, handoffContextProof, handoffDataFrame, handoffDigest, handoffDoneFrame, handoffEphemeral, handoffFileMissingFrame, handoffFileRequestFrame, handoffHaveFrames, handoffHelloFrame, handoffManifestFrames, handoffOfferFrame, handoffPakeFrame, handoffReleaseFrame, handoffRequestFrame, handoffRetryAfter, handoffStreamKey, handoffVerifiedFrame, handoffVerifiedMessage, handoffVersions, hasVisible, hash160, heardCallSignal, heardTime, heldBackError, homeserverWebEndpoint, hubRank, identityFromSeed, identityFromSeedB64, identityPresentationBytes, identityRefusal, identityRevocationValue, identityStatement, identityStatementText, imageSize, importedProof, inboxRecord, inviteLink, inviteOwnership, inviteQrSegments, inviteQrText, invoiceCallbackUrl, irohDescriptor, irohRelayUrl, isAppHash, isAppKey, isAppLicense, isAppLine, isAppPath, isAppRef, isAppSignature, isAppUrl, isAppVersion, isAsf, isAtprotoDid, isBitcoinAddress, isCandidateAddress, isChatAppId, isDiscoveryBudgetError, isEmptyLinkPacket, isFederationId, isGlobalIpv4Host, isGroupMessageId, isHandoffPartName, isHoldUrl, isIdentityBinding, isImageMime, isLegacySignature, isNewerVersion, isPlayableAudioType, isPlayableVideoType, isProofAdapter, isPubkyKey, isPubkyProofFolder, isPublicAddress, isRatcheted, isServeId, isSparkAddress, isStrippedPicture, isValidServiceId, isVideoMime, isViewerTag, isWalletNetwork, isX401Protocol, isZ32Key, jpegSize, jwkThumbprint, keepPastGroupMeta, keepsToRelays, keptAtEqualSequence, knockHolds, knockIdentity, knockRecords, knockSlotIdentity, knockSlotOf, knockSlotRecords, lastSharedWithMe, leaveStands, leaveStatement, leaveStatement3, leftStatement, legacyMessageHash, linkEnd, linkRecords, linkStop, linkTail, linksIn, liveStatus, lobbyKeys, lobbyRecords, makeStamp, makeStampPaced, matchX401Dcql, mayBeHub, mayPin, measureRecords, memberAdmissions, mentionedMembers, mentionsBytes, mentionsMember, mergeBeacon, mergeContactKnocks, mergeKnocks, mergeLobby, meshHubs, meshMessageRef, meshRendezvous, newDeviceSetSecret, newEpochSecret, newHandoffId, newMailbox as newHoldMailbox, newIdentityBinding, newInbox, newPubkyProofFolder, newWakeToken, newX401HolderKey, newerHead, newerPacket, nextGroupMetaRevision, nextPinNumber, nextReactionNumber, nextTurnPosition, nip05RootKey, normalizeAtprotoHandle, normalizeDid, normalizeDomain, normalizePubkyKey, normalizeRelayUrl, nostrProofTemplate, offerIsFresh, openDidDhtPayload, openGroupMeta, openGroupTyping, openHandoffPiece, openPair, openRelayPayload, openRequest, openSecret, openTurnValue, ownInviteRefusal, pacer, pairedEditFits, pairedMessageFits, pairedMessageFrame, pairedReplyAuthor, parseAppFrame, parseAppRangeFrame, parseAtprotoCar, parseAtprotoDidDocument, parseAtprotoDidKey, parseAtprotoVerificationKey, parseCallSignal, parseCashuRequestPayload, parseCommunityEdit, parseDid, parseDidDocument, parseDidJws, parseDidSignaturePaste, parseDomainTxt, parseEditFrame, parseEditedFrame, parseEngineError, parseFedimintRequestPayload, parseGroupCommit, parseGroupMetaBody, parseGroupMetaFrame, parseGroupMetaStatement, parseGroupMetaTag, parseGroupWakeFrame, parseHubPolicy, parseImageMeta, parseInvoiceCallback, parseLightningDestination, parseLinkPreview, parseLinkRecords, parseLocalTarget, parsePacketTransports, parsePairedCallFrame, parsePayParams, parsePaymentAmount, parsePaymentNetworks, parsePinFrame, parsePinnedFrame, parseReactedFrame, parseReactionFrame, parseRelayPayload, parseRtcSignal, parseSessionCapabilities, parseSshPublicKey, parseSshSignature, parseStatusFrame, parseTypingActivity, parseTypingFrame, parseVideoMeta, parseVoiceMeta, parseWakeFrame, pastedAgain, paymentUri, peekDhtMailbox, personStatus, pickCallCandidates, pickHubs, pickMeshHubs, pinFrame, pinIsNewer, pinNumberHolds, pinnedFrame, plainStatusLine, planAppUpdate, planKnocks, presenceSeenAt, presentX401SdJwtVc, previewImageSize, previewable, proofCapability, proofHash, proofStatement, pubkyHomeserverOf, pubkyProofCapability, pubkyProofFile, pubkyProofPath, publicKeyFromZ32, publishFailure, publishedNowhere, pushRequest, qrText, queueReaction, randomBytes, rankHubs, rankTransports, ratchetHeard, ratchetOn, ratchetOpen, ratchetRoot, ratchetSeal, ratchetSessionOf, ratchetUnknownSession, reactedFrame, reactionEmoji, reactionFrame, reactionIsNewer, readAppBundle, readAppBundleAsync, readAppFrame, readAppListing, readAppRangeFrame, readAppRevocation, readAppRevocationShape, readAppRevocations, readAppSignature, readAppStore, readAppStoreSteps, readAtprotoCid, readBeacon, readBeaconHead, readCanonicalJson, readContactLink, readDeviceInvite, readDhtFile, readDhtReactions, readDnsName, readEnrollGrant, readEnrollHello, readForwarded, readGroupFileMeta, readGroupHave, readGroupSignal, readGroupWant, readGroupWantNo, readHandoffAck, readHandoffBusy, readHandoffCancel, readHandoffData, readHandoffDone, readHandoffFileFrame, readHandoffHave, readHandoffHello, readHandoffManifest, readHandoffPake, readHandoffRelease, readHandoffTurnFrame, readHandoffVerified, readImageMeta, readInviteCode, readKnockSlot, readKnocks, readLinkRecord, readLobby, readManifest, readOwnRelayPayload, readPin, readReaction, readRelayBody, readReply, readSetUpdate, readStatusCard, readTurnBody, readTurnPacket, readWake, readWakePayload, readX401DcqlQuery, readX401OpenId4VpRequest, readX401ProofRequest, readX401ProofRequestHeader, readX401ProofResponse, readX401ProofResponseHeader, readX401ProofResult, readX401ProofResultHeader, readX401SdJwtVc, readingAhead, receivedIdentityStatus, receivedTimestamp, recordingMime, recordsFromTxt, recordsFromWellKnown, recordsName, refusalText, relativizeLocation, relayRequest, relayUrl, relayUrlProblem, relayUrlTooLong, relayedTransports, rememberAlone, removedCardText, repeatedJsonKey, replySnippet, requestLnurlInvoice, requestPlaintextBytes, requestRecords, resolveDidDht, resolveLightningDestination, resolveTargetUrl, revokesIdentity, ringAuthorization, ringClaims, ringEvidence, rosterAdmin, rosterHas, rosterHash, routedCommunityFrame, safeBlobType, sameButtonText, sameSshKey, sameStatusState, sameX401HolderJwk, sanitizeAvatar, sanitizeDisplayText, sanitizeFileName, sanitizeMime, sanitizeNick, sanitizePreviewImage, sanitizeRequestHeaders, sanitizeResponseHeaders, sanitizeStatusText, sanitizeTypingStatus, satsToBtc, sdpHasCandidates, sealGroupTyping, sealHandoffPiece, sealPair, sealSecret, sealTurnBody, sealedLength, seedSigner, seenEntry, sendBody, sentWhole, serviceIdFromName, servicesFromWire, servicesToWire, sessionCapabilitiesFrame, setAckFrame, setAppSignatureFastPath, setLinkTraceSink, setPublicKeyFastPath, setUpdateFrame, setUpdateMessage, settleRequest, sha256Hex, sha256Paced, sha256d, shortAtprotoDid, shortHash, shouldBeHub, shownTime, sign, signAppObject, signAppRevocation, signAppStore, signCommit, signCommunity, signDeviceTransports, signDidDhtPacket, signGroupCallModeration, signGroupCallRequest, signGroupMeta, signIdentityPresentation, signRelayPayload, signTombstone, signTurnBody, signTurnPacket, signTurnRelease, signalHasVideo, signingKeys, sortParts, sortRoster, sparkAddressKind, sparkInvoiceDetails, sparkNetworkOf, sshFingerprint, sshKeyDigestHex, sshSignCommand, stampHolds, staticDidDocument, statusCardBytes, statusCardText, statusFrame, statusState, storageProof, storageProofBody, storageProofPath, strictBase64Url, stripHidden, stripPictureMetadata, symmetricNat, takeRequest, taskProgress, toBase64, toBase64Url, toZ32, traceLink, transferEnded, transferStalled, transportOrder, trimEndOf, tryDecrypt, turnInstance, turnKeys, turnName, turnOff, turnPacket, turnPayloadSequence, turnPutSummary, turnReleaseMessage, turnSequence, turnSignedMessage, turnStatedVerifier, turnVerifierMark, txHash, txtValue, typingActivity, typingFrame, typingKindOf, u32, u64, unsignedCommitBytes, unsignedDeviceTransports, unusedInviteWait, unwrapPasted, uriEnd, usageLeft, utf8Decode, utf8Encode, validDomainRecord, validEditMessage, validEditNumber, validEditText, validExternalKey, validHead, validMentions, validReactionNumber, validRemovalNumber, validRingKey, validatePaymentTarget, vapidAuthorization, vapidKeysMatch, varBytes, verify, verifyAppRevocation, verifyAppSignature, verifyAppStatementBytes, verifyAtprotoRecordProof, verifyAtprotoSignature, verifyBip322, verifyBitcoinMessage, verifyChain, verifyCommit, verifyCommitSignature, verifyCommunityChain, verifyCommunityChainPaced, verifyCommunityCommit, verifyDeviceTransports, verifyEnrollProof, verifyGroupCallModeration, verifyGroupCallRequest, verifyGroupMetaSignature, verifyIdentityPresentation, verifyNostrProof, verifyPeerProof, verifyRingAuthorization, verifyRingEvidence, verifySetUpdate, verifySshSignature, videoMetadataPatches, viewerGuardOffset, viewerResponseHeaders, viewerServicePolicy, viewerTag, voiceDownloadName, voiceFileName, voiceLevel, voiceLevelsOf, voicePeaksOf, waitForIceGathering, wakeFrame, wakePayload, wakeRequest, walletNetworkOf, webCryptoSigner, webLocalFetch, wellKnownUrl, wireHubPolicy, wireMentions, wireReaction, wireReply, withRequestOptions, withViewerPolicy, withoutAppLink, withoutAudioMetadata, withoutPictureMetadata, withoutVideoMetadata, wrapDataChannel, wrapGroupMeta, x401AnswerableRequests, x401ApprovalDigest, x401HolderJwk, x401VpToken, yieldThread };
42000
40110
 
42001
40111
  //# sourceMappingURL=core.js.map