@ghostlytools/sdk 1.13.0 → 1.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bitcoinAddress-BIW3tpJG.js +4133 -0
- package/dist/bitcoinAddress-BIW3tpJG.js.map +1 -0
- package/dist/core.js +433 -2489
- package/dist/core.js.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/{pairedTransports-CkYMAoYN.js → pairedTransports-BcTRg3tp.js} +28 -304
- package/dist/pairedTransports-BcTRg3tp.js.map +1 -0
- package/dist/testing.js +2 -2
- package/dist/types/browser/src/proofs/contract.d.ts +5 -0
- package/dist/types/browser/src/proofs/pkarrRelays.d.ts +4 -0
- package/dist/types/browser/src/proofs/verify.d.ts +3 -0
- package/dist/types/core/src/appStatements.d.ts +16 -0
- package/dist/types/core/src/canonicalJson.d.ts +9 -0
- package/dist/types/core/src/chatFiles.d.ts +7 -0
- package/dist/types/core/src/deviceInvite.d.ts +16 -2
- package/dist/types/core/src/dhtDelivery.d.ts +2 -0
- package/dist/types/core/src/domainProofs.d.ts +2 -1
- package/dist/types/core/src/engineErrors.d.ts +6 -0
- package/dist/types/core/src/ghostlink.d.ts +30 -0
- package/dist/types/core/src/groupCommunity.d.ts +25 -1
- package/dist/types/core/src/groupSession.d.ts +22 -2
- package/dist/types/core/src/identityProofs.d.ts +39 -2
- package/dist/types/core/src/index.d.ts +1 -1
- package/dist/types/core/src/link.d.ts +1 -1
- package/dist/types/core/src/linkPreview.d.ts +13 -1
- package/dist/types/core/src/linkTrace.d.ts +2 -0
- package/dist/types/core/src/localNames.d.ts +7 -0
- package/dist/types/core/src/relay.d.ts +27 -1
- package/dist/types/core/src/statusCards.d.ts +6 -0
- package/dist/types/core/src/transportSwitch.d.ts +7 -3
- package/dist/{verify-CSo7-43-.js → verify-DGJJAFTs.js} +24 -5
- package/dist/verify-DGJJAFTs.js.map +1 -0
- package/package.json +1 -1
- package/dist/bitcoinAddress-C2MAmcDT.js +0 -1225
- package/dist/bitcoinAddress-C2MAmcDT.js.map +0 -1
- package/dist/pairedTransports-CkYMAoYN.js.map +0 -1
- 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
|
|
3
|
+
import { $ as DEFAULT_RELAYS, $t as decodeTxtPacket, A as identityRevocationValue, At as BREAKER_BASE_MS, B as applyIdentityEvent, Bt as withRequestOptions, C as IdentityCheckUnavailable, Ct as currentRelays, D as emptyIdentityLedger, Dt as setLinkTraceSink, E as boundVerifiedIdentity, Et as relayUrlProblem, F as receivedIdentityStatus, Ft as PublishFailedError, G as AWAITED_READS, Gt as createRelayPayload, H as ANSWER_READ_ALLOWANCE, Ht as PKARR_FUTURE_SKEW_MS, I as revokesIdentity, It as budgetRetryMs, J as BACKGROUND_WRITES_SHARE, Jt as openRelayPayload, K as BACKGROUND_REQUESTS_PER_MINUTE, Kt as measureRecords, L as signIdentityPresentation, Lt as heldBackError, M as identityStatementText, Mt as BREAKER_THRESHOLD, N as isIdentityBinding, Nt as RelayBreaker, O as identityPresentationBytes, Ot as traceLink, P as newIdentityBinding, Pt as DiscoveryBudgetError, Q as CHAT_WATCH_SHARE, Qt as decodeDnsAnswers, R as verifyIdentityPresentation, Rt as isDiscoveryBudgetError, S as IDENTITY_SUBJECT, St as WRITE_FIRST_MS, T as boundIdentityDisplay, Tt as readRelayBody, U as ANSWER_READ_FIRST_MS, Ut as PacketTooLargeError, V as lastSharedWithMe, Vt as MAX_DNS_PACKET_BYTES, W as ANSWER_READ_SPACING_MS, Wt as RELAY_PAYLOAD_MAX_BYTES, X as CHAT_RESERVE_MOST_SHARE, Xt as readOwnRelayPayload, Y as CHAT_RESERVE, Yt as parseRelayPayload, Z as CHAT_RESERVE_PER_CHAT, Zt as signRelayPayload, _ as IDENTITY_REUSE_CHECK_S, _n as stripHidden, _t as SLOW_DEMOTE_MS, a as IDENTITY_CLOCK_SKEW, an as createIdentity, at as GROUP_OVER_PACE_MS, b as IDENTITY_SEND_WINDOW_MS, bt as WATCH_SHARE, c as IDENTITY_MAX_CHECKS_PER_HOUR, cn as publicKeyFromZ32, ct as HEDGE_MISSING_MS, d as IDENTITY_MAX_RECEIVED, dn as verify, dt as RELAY_REQUESTS_PER_MINUTE, en as encodeTxtPacket, et as DEPARTED_READS, f as IDENTITY_MAX_VALIDITY, fn as MAX_NICK_LENGTH, ft as REQUESTS_PER_MINUTE, g as IDENTITY_RESEND_MS, gn as sanitizeNick, gt as SIGNALING_WINDOW_MS, h as IDENTITY_RESENDS, hn as sanitizeDisplayText, ht as SIGNALING_ALLOWANCE_SHARE, i as IDENTITY_CHECK_UNAVAILABLE, in as IDENTITY_MEMO_SIZE, it as GROUP_BURST_ONE_LINK, j as identityStatement, jt as BREAKER_MAX_MS, k as identityRefusal, kt as BREAKER_ALL_DOWN_PROBE_MS, l as IDENTITY_MAX_EVIDENCE, ln as setPublicKeyFastPath, lt as HEDGE_MS, m as IDENTITY_PROVIDER_ID, mn as hasVisible, mt as RelaysFailedError, n as isBitcoinAddress, nn as IDENTITY_MEMO_IDLE_MS, nt as FRESH_READ_MS, o as IDENTITY_FRAME_LIMIT, on as identityFromSeed, ot as GROUP_RATION_WINDOW_MS, p as IDENTITY_PROOF_CAPABILITY, pn as dropLoneJoiners, pt as RelayTransport, q as BACKGROUND_WHILE_SIGNALING, qt as newerPacket, r as IDENTITY_CHALLENGE_WINDOW, rn as IDENTITY_MEMO_MAX, rt as GROUP_BURST_MS, s as IDENTITY_FRAME_WINDOW_MS, sn as identityFromSeedB64, st as GROUP_SIGNALING_ALLOWANCE_SHARE, t as BITCOIN_NETWORKS, tn as readDnsName, tt as DOOR_FIRST_MS, u as IDENTITY_MAX_FRAME, un as sign, ut as PREVIOUS_DEFAULT_RELAYS, v as IDENTITY_REVOCATION_LABEL, vn as trimEndOf, vt as SLOW_MS, w as IdentityExchange, wt as normalizeRelayUrl, x as IDENTITY_STATEMENT_PREFIX, xt as WAY_BACK_SHARE, y as IDENTITY_SEND_LIMIT, yn as unwrapPasted, yt as TURN_SOURCE_TIMEOUT_MS, z as IDENTITY_TIMELINE_MAX, zt as publishedNowhere } from "./bitcoinAddress-BIW3tpJG.js";
|
|
4
|
+
import { A as NIP05_PATH, B as parseDomainTxt, C as underLocalSuffix, D as DOMAIN_MAX_RECORDS, E as DOMAIN_FILE_MAX_BYTES, F as domainWellKnownFile, G as validDomainRecord, H as recordsFromWellKnown, I as encodeDnsQuery, J as encrypt, K as wellKnownUrl, L as isPublicAddress, M as decodeDnsResponse, N as dnsProofName, O as DOMAIN_METHODS, P as domainTxtRecord, R as nip05RootKey, S as readManifest, T as DNS_TYPE, U as recordsName, V as recordsFromTxt, W as txtValue, X as sealedLength, Y as generateEncryptionKey, Z as tryDecrypt, _ as HOLD_LIMITS, a as automaticTransport, b as isHoldUrl, c as irohDescriptor, d as relayUrl, f as relayUrlTooLong, g as HOLD_DATED_BACK_MS, h as HOLD_CAPABILITY, i as TRANSPORTS, j as WELL_KNOWN_PATH, k as DOMAIN_TXT_MAX_BYTES, l as irohRelayUrl, m as transportOrder, n as RELAY_URL, o as checkedDescriptors, p as relayedTransports, q as decrypt, r as RELAY_WITH_SECRETS, s as dialableIrohRelay, t as AUTOMATIC_ORDER, u as rankTransports, v as HoldKeys, w as DNS_LABEL, x as newMailbox, y as HoldRefusedError, z as normalizeDomain } from "./pairedTransports-BcTRg3tp.js";
|
|
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,2422 +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
|
-
* A background read the budget held back far down the turns asks again no later than this (`backgroundTurnIn`). The
|
|
759
|
-
* requests past the background share go to a read held back long (`READ_STARVED_MS`) that is there when one frees: asked
|
|
760
|
-
* only at its estimated turn, a web app with 200 chats away read each contact every 7 to 8 minutes, not every 6, and
|
|
761
|
-
* one with 100 left half the writes' share unused at 20 s.
|
|
762
|
-
*/
|
|
763
|
-
var BACKGROUND_TURN_MAX_MS = 15e3;
|
|
764
|
-
/**
|
|
765
|
-
* Once a group's read found a relay's minute full, the groups' reads there are spread over the minute for a minute
|
|
766
|
-
* (`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
|
|
767
|
-
* minute that demand keeps full hands out its requests in bursts: the minute is spent in 25 to 35 s as requests age
|
|
768
|
-
* 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)
|
|
769
|
-
* whose members left and came back read nothing for 18 to 42 s at a time, and the member back first waited that long
|
|
770
|
-
* for its edge (bug hunt r12, measured again on 2026-10-03). Writes are not counted: they go first anyway.
|
|
771
|
-
*/
|
|
772
|
-
var GROUP_RATION_WINDOW_MS = 1e4;
|
|
773
|
-
var GROUP_RATION_MS = 6e4;
|
|
774
|
-
/**
|
|
775
|
-
* While a link polls fast (an `urgent` read: its peer, or the peer's offer or answer, is due any moment) within this
|
|
776
|
-
* long, background requests (a community's periodic looks) are held to `BACKGROUND_WHILE_SIGNALING` a minute on each
|
|
777
|
-
* relay rather than their usual share. A fast poll reads every 2 s, one relay after the other.
|
|
778
|
-
*/
|
|
779
|
-
var SIGNALING_WINDOW_MS = 1e4;
|
|
780
|
-
/**
|
|
781
|
-
* Background requests a minute on each relay while a link signals: one look every 12 s. Next to a community's
|
|
782
|
-
* 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
|
|
783
|
-
* other's fast windows (2026-09-27). Not none: fast windows can follow one another, and a hub still reads its knocks.
|
|
784
|
-
*/
|
|
785
|
-
var BACKGROUND_WHILE_SIGNALING = 5;
|
|
786
|
-
/**
|
|
787
|
-
* A read of a key the relays answered this recently is answered from that answer, with no request. Several parts of
|
|
788
|
-
* a chat read the contact's keys (the link's poll, its capabilities, DHT delivery), and each tends to read again
|
|
789
|
-
* within a few dozen milliseconds of its last read, when a pace changes or a signal goes out: nothing new can be there
|
|
790
|
-
* yet, and a pairing spent a sixth of its requests on those reads (2026-09-27). A publish under the key forgets it.
|
|
791
|
-
*/
|
|
792
|
-
var FRESH_READ_MS = 500;
|
|
793
|
-
/** A relay that missed a key's newest packet gets it (`catchUpLater`) no sooner than this, and tries again this often. */
|
|
794
|
-
var CATCH_UP_MIN_MS = 1e3;
|
|
795
|
-
var CATCH_UP_RETRY_MS = 5e3;
|
|
796
|
-
/**
|
|
797
|
-
* The longest another background write is told to wait behind the packets queued for a relay (`catchUpLater`): the
|
|
798
|
-
* link and the DHT floor try again within a minute anyway, and longer kept a chat's upkeep off a relay with a long queue
|
|
799
|
-
* for most of the presence window.
|
|
800
|
-
*/
|
|
801
|
-
var CATCH_UP_BEHIND_MAX_MS = 6e4;
|
|
802
|
-
/** 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`). */
|
|
803
|
-
var CATCH_UP_ASKER = {
|
|
804
|
-
background: true,
|
|
805
|
-
group: false,
|
|
806
|
-
urgent: false,
|
|
807
|
-
door: false,
|
|
808
|
-
write: true,
|
|
809
|
-
signal: false,
|
|
810
|
-
watch: false,
|
|
811
|
-
watchWrite: false,
|
|
812
|
-
departed: false,
|
|
813
|
-
awaited: false,
|
|
814
|
-
resume: false,
|
|
815
|
-
back: false
|
|
816
|
-
};
|
|
817
|
-
/** Keys whose last relay is remembered for their next read (`resolve`): a profile's links and lookups, with room. */
|
|
818
|
-
var READ_TURNS_KEPT = 512;
|
|
819
|
-
/** A relay that fails at the network level is left alone for this long. */
|
|
820
|
-
var NETWORK_ERROR_COOLDOWN_MS = 2e4;
|
|
821
|
-
/**
|
|
822
|
-
* Relays whose limit per address is far from the others': this client's share of theirs, a minute, in place of
|
|
823
|
-
* `REQUESTS_PER_MINUTE`. relay.pkarr.org (not a default, see docs/RELAYS.md) and pkarr.miguelmedeiros.dev (a default
|
|
824
|
-
* since 2026-10-17) allow 10 (`x-ratelimit-limit`), which a browser cannot read without CORS exposing it: half of it
|
|
825
|
-
* leaves room for a second app behind the same address. pkarr.pubky.app allows 1000 (pkarr.pubky.org, on the same address,
|
|
826
|
-
* 50): 60 of ours leaves room for many peers behind one address, and a page that pairs three contacts in a minute,
|
|
827
|
-
* about ten requests a relay each, still has requests to spare there (2026-09-28). Writes go to every relay and
|
|
828
|
-
* count once one took them; reads go to a relay with requests left.
|
|
829
|
-
*/
|
|
830
|
-
var RELAY_REQUESTS_PER_MINUTE = {
|
|
831
|
-
"https://relay.pkarr.org": 5,
|
|
832
|
-
"https://pkarr.pubky.app": 60,
|
|
833
|
-
"https://pkarr.miguelmedeiros.dev": 5
|
|
834
|
-
};
|
|
835
|
-
/**
|
|
836
|
-
* A read asks the next relay too when the one it asked has not answered within this long, and takes the first good
|
|
837
|
-
* 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
|
|
838
|
-
* 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
|
|
839
|
-
* answer before asking the next one, up to the 10 s timeout: a relay that answered slowly or not at all (pkarr.pubky.org
|
|
840
|
-
* on 2026-10-03) made every read of a pairing that slow, and the pairing never finished.
|
|
841
|
-
*/
|
|
842
|
-
var HEDGE_MS = 1500;
|
|
843
|
-
/**
|
|
844
|
-
* 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
|
|
845
|
-
* every time), and a hedge at `HEDGE_MS` would double every poll of a key nobody has published yet.
|
|
846
|
-
*/
|
|
847
|
-
var HEDGE_MISSING_MS = 6e3;
|
|
848
|
-
/**
|
|
849
|
-
* A packet that took longer than this to arrive, or a hedge lost to a relay that answered with the packet, is slow: it
|
|
850
|
-
* counts against the relay's breaker like a failure (three in a row trip it, logged as "slow"), while another relay is
|
|
851
|
-
* there to ask. A 404 says nothing either way: every relay is slow to give one.
|
|
852
|
-
*/
|
|
853
|
-
var SLOW_MS = 3e3;
|
|
854
|
-
/** A relay found slow goes after the others in every read for this long, unless it answers fast meanwhile. */
|
|
855
|
-
var SLOW_DEMOTE_MS = 6e4;
|
|
856
|
-
/** How long each source has to answer a read or a put of the turn record (WISP 06 § Publishing and reading). */
|
|
857
|
-
var TURN_SOURCE_TIMEOUT_MS = 8e3;
|
|
858
|
-
/** 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). */
|
|
859
|
-
var TURN_REFUSALS = [
|
|
860
|
-
409,
|
|
861
|
-
412,
|
|
862
|
-
428
|
|
863
|
-
];
|
|
864
|
-
/** How many times a payload signed here goes again past a relay's later copy (`putRedated`): three puts at most. */
|
|
865
|
-
var PAYLOAD_REDATES = 2;
|
|
866
|
-
/** On a relay's 404: the sequence of an item the DHT holds under the key that is no signed packet. */
|
|
867
|
-
var INVALID_PACKET_SEQ_HEADER = "pkarr-invalid-signed-packet-seq";
|
|
868
|
-
/** What `answer` says, or false when it has not said within `ms`. */
|
|
869
|
-
function answeredWithin(answer, ms) {
|
|
870
|
-
let timer;
|
|
871
|
-
const late = new Promise((resolve) => {
|
|
872
|
-
timer = setTimeout(() => resolve(false), ms);
|
|
873
|
-
});
|
|
874
|
-
return Promise.race([answer, late]).finally(() => clearTimeout(timer));
|
|
875
|
-
}
|
|
876
|
-
function normalizeRelayUrl(input) {
|
|
877
|
-
try {
|
|
878
|
-
const url = new URL(input.trim());
|
|
879
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
|
880
|
-
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
881
|
-
} catch {
|
|
882
|
-
return null;
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
/**
|
|
886
|
-
* Why a line of a Pkarr relay list is not a relay `normalizeRelayUrl` keeps, with the line as typed; null when it is
|
|
887
|
-
* one. A host alone or another scheme (`relay.example.org`, `wss://…`) was meant as an https:// relay.
|
|
888
|
-
*/
|
|
889
|
-
function relayUrlProblem(input) {
|
|
890
|
-
const line = input.trim();
|
|
891
|
-
if (normalizeRelayUrl(line)) return null;
|
|
892
|
-
return looksLikeHost(line) || looksLikeHost(line.replace(/^[a-z][a-z\d+.-]*:\/\//i, "")) ? `Use an https:// relay address: ${line}` : `Not a relay address: ${line}`;
|
|
893
|
-
}
|
|
894
|
-
/** No space, and a dot after the first character, before the last one and before any `/` or `:`; linear, for a long pasted line. */
|
|
895
|
-
function looksLikeHost(text) {
|
|
896
|
-
if (/\s/.test(text)) return false;
|
|
897
|
-
const slash = text.search(/[/:]/);
|
|
898
|
-
const dot = text.indexOf(".", 1);
|
|
899
|
-
return dot > 0 && dot < text.length - 1 && (slash < 0 || dot < slash);
|
|
900
|
-
}
|
|
901
|
-
/** A relay the breaker leaves alone for failing (`RelayBreaker`): nothing was asked of it now. */
|
|
902
|
-
var RelayLeftAloneError = class extends Error {};
|
|
903
|
-
/**
|
|
904
|
-
* A relay a put did not get an answer from. `sent` false: the request never left (its network cooling down after a
|
|
905
|
-
* failure, or a connection that could not be made, `connectFailed`); true: it may have reached the relay.
|
|
906
|
-
*/
|
|
907
|
-
var RelayNoAnswerError = class extends Error {
|
|
908
|
-
sent;
|
|
909
|
-
constructor(message, sent) {
|
|
910
|
-
super(message);
|
|
911
|
-
this.sent = sent;
|
|
912
|
-
}
|
|
913
|
-
};
|
|
914
|
-
/** What Node says of a connection it could not make: the request never left. A browser's TypeError says nothing either way. */
|
|
915
|
-
var CONNECT_FAILURES = /* @__PURE__ */ new Set([
|
|
916
|
-
"ECONNREFUSED",
|
|
917
|
-
"ENOTFOUND",
|
|
918
|
-
"EAI_AGAIN",
|
|
919
|
-
"EHOSTUNREACH",
|
|
920
|
-
"ENETUNREACH",
|
|
921
|
-
"ENETDOWN",
|
|
922
|
-
"EHOSTDOWN",
|
|
923
|
-
"EADDRNOTAVAIL",
|
|
924
|
-
"UND_ERR_CONNECT_TIMEOUT"
|
|
925
|
-
]);
|
|
926
|
-
/** A fetch that failed before its request left this device: Node's `cause.code` (each of an AggregateError's, for several addresses). */
|
|
927
|
-
function connectFailed(error) {
|
|
928
|
-
const cause = error?.cause;
|
|
929
|
-
if (!cause || typeof cause !== "object") return false;
|
|
930
|
-
if (Array.isArray(cause.errors) && cause.errors.length) return cause.errors.every((e) => CONNECT_FAILURES.has(e?.code));
|
|
931
|
-
return CONNECT_FAILURES.has(cause.code);
|
|
932
|
-
}
|
|
933
|
-
/**
|
|
934
|
-
* The error a publish ends with after a second round dated past a relay's later copy failed too: one that may have
|
|
935
|
-
* stored the first round's packet still may, whatever the second round's relays said.
|
|
936
|
-
*/
|
|
937
|
-
function laterRound(first, later) {
|
|
938
|
-
return publishedNowhere(later) && !publishedNowhere(first) ? new PublishFailedError(later.message, true) : later;
|
|
939
|
-
}
|
|
940
|
-
/** A packet date no further ahead of this clock than readers take (`newerPacket`): one this client may date past. */
|
|
941
|
-
function withinSkew(timestamp) {
|
|
942
|
-
return timestamp <= BigInt(Date.now() + PKARR_FUTURE_SKEW_MS) * 1000n;
|
|
943
|
-
}
|
|
944
|
-
/**
|
|
945
|
-
* A read the relays failed (or left alone for failing before), when its caller has another path to ask
|
|
946
|
-
* (`RelayTransport.resolve` with `keptOnFailure` false): `kept` is the newest packet the relays gave for the key before.
|
|
947
|
-
*/
|
|
948
|
-
var RelaysFailedError = class extends Error {
|
|
949
|
-
kept;
|
|
950
|
-
constructor(kept) {
|
|
951
|
-
super("No Pkarr relay reachable");
|
|
952
|
-
this.kept = kept;
|
|
953
|
-
}
|
|
954
|
-
};
|
|
955
|
-
var RelayTransport = class {
|
|
956
|
-
relays;
|
|
957
|
-
timeoutMs;
|
|
958
|
-
fetchFn;
|
|
959
|
-
timeListeners = /* @__PURE__ */ new Set();
|
|
960
|
-
lastTimestamp = /* @__PURE__ */ new Map();
|
|
961
|
-
newest = /* @__PURE__ */ new Map();
|
|
962
|
-
/**
|
|
963
|
-
* The latest time of any packet read under a key, whoever dated it: the next packet this client puts there is dated
|
|
964
|
-
* past it (`nextTimestamp`). A key is not always one writer's with one clock: a group's lobby, beacon and knock
|
|
965
|
-
* records are written by every member, an inviter warms its contact's key with an empty packet, and this device's
|
|
966
|
-
* own clock may have been set back since it last wrote. A relay and the DHT keep only the packet dated latest, so
|
|
967
|
-
* one dated by this clock alone, when it is behind, was refused (409) or silently never read, until this clock
|
|
968
|
-
* caught up with the other one: minutes, or an hour. Only up to `PKARR_FUTURE_SKEW_MS` ahead of this clock
|
|
969
|
-
* (`withinSkew`): a packet one holder of a shared key dated further ahead must not date every later one of this
|
|
970
|
-
* device past it (past 64 bits, unsignable; else ahead of every reader's clock, never taken over one dated now).
|
|
971
|
-
*/
|
|
972
|
-
seenTimestamp = /* @__PURE__ */ new Map();
|
|
973
|
-
/**
|
|
974
|
-
* The last packet this client put under a key that a relay took. A read the budget holds back answers the newer of
|
|
975
|
-
* it and the last one read: a hub that wrote its own beacon entry since it last read the beacon must not see that
|
|
976
|
-
* entry as old as the one it replaced (it would stop counting itself at its community's door until its next write).
|
|
977
|
-
*/
|
|
978
|
-
written = /* @__PURE__ */ new Map();
|
|
979
|
-
coolingDown = /* @__PURE__ */ new Map();
|
|
980
|
-
networkCooldown = /* @__PURE__ */ new Map();
|
|
981
|
-
cursor = 0;
|
|
982
|
-
/** Per key, the relay that answered its last read: the next read of the key starts at the one after it (`resolve`). */
|
|
983
|
-
lastReadFrom = /* @__PURE__ */ new Map();
|
|
984
|
-
spent = /* @__PURE__ */ new Map();
|
|
985
|
-
spentBackground = /* @__PURE__ */ new Map();
|
|
986
|
-
/** Background writes on each relay in the last minute (`BACKGROUND_WRITES_SHARE`). */
|
|
987
|
-
spentBackgroundWrites = /* @__PURE__ */ new Map();
|
|
988
|
-
/** Groups' urgent reads on each relay in the last `GROUP_BURST_MS`: edges' reads for an answer apart (`ANSWER_READ_FIRST_MS`). */
|
|
989
|
-
spentGroupUrgent = /* @__PURE__ */ new Map();
|
|
990
|
-
spentAnswerUrgent = /* @__PURE__ */ new Map();
|
|
991
|
-
/** Watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`WATCH_SHARE`). */
|
|
992
|
-
spentWatch = /* @__PURE__ */ new Map();
|
|
993
|
-
/** 1:1 chats' watch reads on each relay in the last `GROUP_RATION_WINDOW_MS` (`CHAT_WATCH_SHARE`). */
|
|
994
|
-
spentChatWatch = /* @__PURE__ */ new Map();
|
|
995
|
-
/** Groups' reads past the limit on each relay in the last `GROUP_OVER_PACE_MS` (`GROUP_SIGNALING_ALLOWANCE_SHARE`). */
|
|
996
|
-
spentGroupOver = /* @__PURE__ */ new Map();
|
|
997
|
-
/** Group edges' signaling requests on each relay in the last minute: their floor (`GROUP_SIGNALING_ALLOWANCE_SHARE`). */
|
|
998
|
-
spentGroupSignal = /* @__PURE__ */ new Map();
|
|
999
|
-
/** Community members' ways back on each relay in the last minute: their allowance (`WAY_BACK_SHARE`). */
|
|
1000
|
-
spentWayBack = /* @__PURE__ */ new Map();
|
|
1001
|
-
/** Edges' reads for an answer that only their own allowance let through, on each relay in the last minute (`ANSWER_READ_ALLOWANCE`). */
|
|
1002
|
-
spentAnswerAllowance = /* @__PURE__ */ new Map();
|
|
1003
|
-
/** Per contact, its departed reads past the limit in the last minute, every relay together (`DEPARTED_READS`). */
|
|
1004
|
-
departedOver = /* @__PURE__ */ new Map();
|
|
1005
|
-
/** The awaited reads past the limit in the last minute, every invite and every relay together (`AWAITED_READS`). */
|
|
1006
|
-
awaitedOver = [];
|
|
1007
|
-
/** When an awaited invite's read last asked: the departed reads leave it room for a minute (`AWAITED_READS`). */
|
|
1008
|
-
awaitedAt = -Infinity;
|
|
1009
|
-
/**
|
|
1010
|
-
* Per key a group reads (not in the background), when a read of it last went out and when it last asked: whose turn
|
|
1011
|
-
* it is under the watch share (`WATCH_SHARE`) and while the groups' reads are rationed (`GROUP_RATION_WINDOW_MS`). And
|
|
1012
|
-
* per key a chat watches, whose turn it is under theirs (`CHAT_WATCH_SHARE`).
|
|
1013
|
-
*/
|
|
1014
|
-
readTurns = /* @__PURE__ */ new Map();
|
|
1015
|
-
/** Per key read in turn (`isTurnRead`), when a read of it last went out and when it last asked (`READ_TURN_MS`). */
|
|
1016
|
-
keyTurns = /* @__PURE__ */ new Map();
|
|
1017
|
-
/** When `readTurns` and `keyTurns` last dropped their stale turns (`TURNS_PRUNE_MS`). */
|
|
1018
|
-
turnsPrunedAt = /* @__PURE__ */ new Map();
|
|
1019
|
-
/** Groups' reads (not background ones) on each relay in the last `GROUP_RATION_WINDOW_MS`. */
|
|
1020
|
-
spentGroupReads = /* @__PURE__ */ new Map();
|
|
1021
|
-
/** When a group's read last found each relay's minute full: its reads there are rationed for `GROUP_RATION_MS`. */
|
|
1022
|
-
groupsFullAt = /* @__PURE__ */ new Map();
|
|
1023
|
-
/** When a link's write was last refused on each relay (`chat <relay>`, `group <relay>`), while it waits for the budget. */
|
|
1024
|
-
writeWaiting = /* @__PURE__ */ new Map();
|
|
1025
|
-
/** Per relay, the keys whose edges' reads for an answer it last refused, and when, until one is read (`ANSWER_READ_FIRST_MS`). */
|
|
1026
|
-
answerReadWaiting = /* @__PURE__ */ new Map();
|
|
1027
|
-
/**
|
|
1028
|
-
* Per key a 1:1 chat asks for: when it last read urgently (for the next minute, groups leave it `CHAT_RESERVE` on
|
|
1029
|
-
* every relay) and when the budget last refused it on each relay (the same, on that relay). A read of the key at a
|
|
1030
|
-
* slow pace (the chat is live, or back in the background) drops it: `CHAT_RESERVE`. Per relay, the later of the two
|
|
1031
|
-
* for each key (`chatNeed`); `chatUrgentAt` keeps the urgent ones for a relay not asked yet.
|
|
1032
|
-
*/
|
|
1033
|
-
chatNeeds = /* @__PURE__ */ new Map();
|
|
1034
|
-
chatUrgentAt = new RecentKeys();
|
|
1035
|
-
/** When a link (a chat's or a group's) last asked urgently: background requests yield for `SIGNALING_WINDOW_MS`. */
|
|
1036
|
-
urgentAt = -Infinity;
|
|
1037
|
-
/** Timestamp of the last packet sent to each relay, per key: the compare-and-swap value for the next one. */
|
|
1038
|
-
lastPut = /* @__PURE__ */ new Map();
|
|
1039
|
-
/** Per relay and key, the newest packet that relay held back for its budget while another relay took it (`catchUpLater`). */
|
|
1040
|
-
catchUp = /* @__PURE__ */ new Map();
|
|
1041
|
-
/** Per relay, how many packets wait in `catchUp` for it: background reads leave them their share (`heldFor`). */
|
|
1042
|
-
catchUpWaiting = /* @__PURE__ */ new Map();
|
|
1043
|
-
catchUpTimer = null;
|
|
1044
|
-
/**
|
|
1045
|
-
* Per key whose reads the budget held back since its last read went out: when a request frees for it
|
|
1046
|
-
* (`readHeldBackFor`), how many times in a row, and since when (`READ_STARVED_MS`).
|
|
1047
|
-
*/
|
|
1048
|
-
heldBack = /* @__PURE__ */ new Map();
|
|
1049
|
-
/** When the relays last answered a read of each key, for `FRESH_READ_MS`. */
|
|
1050
|
-
readAt = /* @__PURE__ */ new Map();
|
|
1051
|
-
freshReadMs;
|
|
1052
|
-
perMinute;
|
|
1053
|
-
/** `requestsPerMinute` was given: it bounds every relay, one with its own share (`RELAY_REQUESTS_PER_MINUTE`) too. */
|
|
1054
|
-
perMinuteGiven;
|
|
1055
|
-
backgroundPerMinute;
|
|
1056
|
-
backgroundWhileSignaling;
|
|
1057
|
-
breaker;
|
|
1058
|
-
/** The relay the last read was answered by. */
|
|
1059
|
-
lastRelay = null;
|
|
1060
|
-
hedgeMs;
|
|
1061
|
-
/** Until when each relay found slow (`SLOW_MS`) goes after the others in a read (`readOrder`). */
|
|
1062
|
-
slowUntil = /* @__PURE__ */ new Map();
|
|
1063
|
-
/** Per relay, when each of this client's requests still waiting for its answer went out (`unanswering`). */
|
|
1064
|
-
waiting = /* @__PURE__ */ new Map();
|
|
1065
|
-
/** When each relay last answered a request of this client, whatever it said (`unanswering`). */
|
|
1066
|
-
answeredAt = /* @__PURE__ */ new Map();
|
|
1067
|
-
/** Keys whose last read was answered 404: their next read hedges later (`HEDGE_MISSING_MS`). */
|
|
1068
|
-
missing = /* @__PURE__ */ new Set();
|
|
1069
|
-
listeners = /* @__PURE__ */ new Set();
|
|
1070
|
-
constructor(options = {}) {
|
|
1071
|
-
this.relays = [];
|
|
1072
|
-
this.setRelays(options.relays ?? DEFAULT_RELAYS);
|
|
1073
|
-
this.timeoutMs = options.timeoutMs ?? 1e4;
|
|
1074
|
-
this.fetchFn = options.fetch ?? ((...args) => fetch(...args));
|
|
1075
|
-
this.perMinute = options.requestsPerMinute ?? 30;
|
|
1076
|
-
this.freshReadMs = options.freshReadMs ?? 500;
|
|
1077
|
-
this.hedgeMs = options.hedgeMs ?? 1500;
|
|
1078
|
-
this.perMinuteGiven = options.requestsPerMinute !== void 0;
|
|
1079
|
-
this.backgroundPerMinute = this.perMinute === 30 ? 20 : Math.ceil(this.perMinute * 2 / 3);
|
|
1080
|
-
this.backgroundWhileSignaling = this.perMinute === 30 ? 5 : Math.ceil(this.perMinute / 6);
|
|
1081
|
-
const log = options.log ?? ((line) => console.info(`ghostly: ${line}`));
|
|
1082
|
-
this.breaker = new RelayBreaker({
|
|
1083
|
-
...options.breaker,
|
|
1084
|
-
onTrip: (relay, reason, forMs) => {
|
|
1085
|
-
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`);
|
|
1086
|
-
options.breaker?.onTrip?.(relay, reason, forMs);
|
|
1087
|
-
this.changed("tripped");
|
|
1088
|
-
},
|
|
1089
|
-
onRecover: (relay) => {
|
|
1090
|
-
log(`relay ${new URL(relay).host} answers again`);
|
|
1091
|
-
options.breaker?.onRecover?.(relay);
|
|
1092
|
-
this.changed("recovered");
|
|
1093
|
-
}
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
/** How reads go and how each relay is doing, for the connection panel. */
|
|
1097
|
-
discovery() {
|
|
1098
|
-
const relays = this.breaker.health(this.relays).map((health) => {
|
|
1099
|
-
const limited = this.rateLimitedFor(health.relay);
|
|
1100
|
-
return health.state === "ok" && limited > 0 ? {
|
|
1101
|
-
...health,
|
|
1102
|
-
state: "throttled",
|
|
1103
|
-
until: Date.now() + limited,
|
|
1104
|
-
reason: "rate limited (429)"
|
|
1105
|
-
} : health;
|
|
1106
|
-
});
|
|
1107
|
-
return {
|
|
1108
|
-
path: this.lastRelay ? {
|
|
1109
|
-
via: "relay",
|
|
1110
|
-
relay: this.lastRelay
|
|
1111
|
-
} : null,
|
|
1112
|
-
relays
|
|
1113
|
-
};
|
|
1114
|
-
}
|
|
1115
|
-
/** Back online on some network: relays that failed (or rate limited this address) on the old one are asked again. */
|
|
1116
|
-
networkChanged() {
|
|
1117
|
-
this.breaker.reset();
|
|
1118
|
-
this.networkCooldown.clear();
|
|
1119
|
-
this.coolingDown.clear();
|
|
1120
|
-
this.slowUntil.clear();
|
|
1121
|
-
this.changed("recovered");
|
|
1122
|
-
}
|
|
1123
|
-
/**
|
|
1124
|
-
* `PkarrTransport.forget`: the packets and dates this client kept under these keys go, on every relay (`written`,
|
|
1125
|
-
* `newest`, `lastTimestamp`, `seenTimestamp`, `lastPut`). A spare invite replaced unused left them here for its two keys
|
|
1126
|
-
* for good: an idle CLI daemon gained 8 keys an hour (343 in `written` and 690 `lastPut` entries after a day). The maps
|
|
1127
|
-
* that bound themselves (`readAt`, `lastReadFrom`, `heldBack`, `missing`, the turns) and the catch-ups, which go once
|
|
1128
|
-
* put, are left as they are. A later put under one of these keys goes as a key's first.
|
|
1129
|
-
*/
|
|
1130
|
-
forget(keys) {
|
|
1131
|
-
const gone = new Set(keys);
|
|
1132
|
-
if (gone.size === 0) return;
|
|
1133
|
-
for (const key of gone) for (const perKey of [
|
|
1134
|
-
this.lastTimestamp,
|
|
1135
|
-
this.seenTimestamp,
|
|
1136
|
-
this.newest,
|
|
1137
|
-
this.written
|
|
1138
|
-
]) perKey.delete(key);
|
|
1139
|
-
for (const slot of this.lastPut.keys()) if (gone.has(slot.slice(slot.lastIndexOf(" ") + 1))) this.lastPut.delete(slot);
|
|
1140
|
-
}
|
|
1141
|
-
/** Called when a relay trips or recovers. */
|
|
1142
|
-
subscribe(listener) {
|
|
1143
|
-
this.listeners.add(listener);
|
|
1144
|
-
return () => this.listeners.delete(listener);
|
|
1145
|
-
}
|
|
1146
|
-
changed(change) {
|
|
1147
|
-
for (const listener of this.listeners) try {
|
|
1148
|
-
listener(change);
|
|
1149
|
-
} catch {}
|
|
1150
|
-
}
|
|
1151
|
-
/** What the relay did, for its breaker. */
|
|
1152
|
-
answered(relay, failure, method) {
|
|
1153
|
-
if (failure) {
|
|
1154
|
-
this.breaker.failure(relay, failure.kind, failure.reason);
|
|
1155
|
-
return;
|
|
1156
|
-
}
|
|
1157
|
-
if (method) this.networkCooldown.delete(`${method} ${relay}`);
|
|
1158
|
-
this.breaker.success(relay, this.relays);
|
|
1159
|
-
}
|
|
1160
|
-
setRelays(relays) {
|
|
1161
|
-
const normalized = relays.map(normalizeRelayUrl).filter((r) => r !== null);
|
|
1162
|
-
this.relays = [...new Set(normalized)];
|
|
1163
|
-
}
|
|
1164
|
-
describe() {
|
|
1165
|
-
return {
|
|
1166
|
-
protocol: "Pkarr relays (HTTP) → Mainline DHT (BEP44)",
|
|
1167
|
-
relays: [...this.relays]
|
|
1168
|
-
};
|
|
1169
|
-
}
|
|
1170
|
-
/**
|
|
1171
|
-
* Publishes to every relay. Peers may be configured with different relay
|
|
1172
|
-
* sets; writing everywhere keeps the overlap warm, the DHT covers the rest.
|
|
1173
|
-
* Returns once one relay took the packet: the others finish in the background.
|
|
1174
|
-
*/
|
|
1175
|
-
async publish(identity, records, options = {}) {
|
|
1176
|
-
if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
|
|
1177
|
-
await this.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putEverywhere(key, payload, timestamp, options, conflict), options);
|
|
1178
|
-
}
|
|
1179
|
-
/**
|
|
1180
|
-
* The time the next packet under a key is dated: this clock's, and past every packet this client put or read there.
|
|
1181
|
-
* BEP44 sequence numbers must strictly increase, and the clock that dated the last one may not be this one's.
|
|
1182
|
-
*/
|
|
1183
|
-
nextTimestamp(pubKeyZ32) {
|
|
1184
|
-
const now = BigInt(Date.now()) * 1000n;
|
|
1185
|
-
const last = this.lastTimestamp.get(pubKeyZ32) ?? 0n, seen = this.seenTimestamp.get(pubKeyZ32) ?? 0n;
|
|
1186
|
-
const floor = last > seen ? last : seen;
|
|
1187
|
-
const timestamp = now > floor ? now : floor + 1n;
|
|
1188
|
-
this.lastTimestamp.set(pubKeyZ32, timestamp);
|
|
1189
|
-
return timestamp;
|
|
1190
|
-
}
|
|
1191
|
-
/**
|
|
1192
|
-
* Signs the records, dated by `nextTimestamp`, and hands the payload to `put` (the relays; the CLI adds the DHT).
|
|
1193
|
-
* When every relay's budget (or rate limit) holds this asker back, it throws that wait before signing anything
|
|
1194
|
-
* (`publishWait`): a daemon at its budget signed about 500 packets a minute that never went out. `elsewhere`: `put`
|
|
1195
|
-
* also takes the packet where no budget holds it back (the CLI's DHT), so it is signed whatever the relays say.
|
|
1196
|
-
* `put` calls `conflict` for a relay that answered 409: it holds a packet under this key dated at or after this one,
|
|
1197
|
-
* which this client has not read (an inviter's warm packet under the key it gave its contact, from a clock ahead of
|
|
1198
|
-
* this one). That packet is read from that relay, and the records go again dated just past it, once. Without this
|
|
1199
|
-
* the packet was refused until this device's clock passed the other one's, however long that took, and on a relay
|
|
1200
|
-
* that did take it, readers still preferred the later-dated empty packet of another relay. `read`: how to learn the
|
|
1201
|
-
* 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).
|
|
1202
|
-
*/
|
|
1203
|
-
async publishDated(identity, records, put, options = {}, again = false, elsewhere = false) {
|
|
1204
|
-
const key = identity.pubKeyZ32;
|
|
1205
|
-
if (!again && !elsewhere) {
|
|
1206
|
-
const held = this.publishWait(key, asker(options, true));
|
|
1207
|
-
if (held) throw new DiscoveryBudgetError(held.wait, `Publish held back on every relay: ${held.reasons.join("; ")}`);
|
|
1208
|
-
const refused = this.refusedEverywhere(key, asker(options, true));
|
|
1209
|
-
if (refused) throw refused;
|
|
1210
|
-
}
|
|
1211
|
-
const timestamp = this.nextTimestamp(key);
|
|
1212
|
-
let redated;
|
|
1213
|
-
const conflict = (relay, read) => {
|
|
1214
|
-
if (again || redated) return;
|
|
1215
|
-
redated = (async () => {
|
|
1216
|
-
const held = read ? await read().catch(() => null) : await this.heldAt(relay, key, asker(options, true));
|
|
1217
|
-
if (held === null || held < timestamp || !withinSkew(held)) return false;
|
|
1218
|
-
traceLink(key, "publish-redated", {
|
|
1219
|
-
aheadMs: Number((held - timestamp) / 1000n),
|
|
1220
|
-
relay
|
|
1221
|
-
});
|
|
1222
|
-
if (this.lastTimestamp.get(key) !== timestamp) return true;
|
|
1223
|
-
await this.publishDated(identity, records, put, options, true, elsewhere);
|
|
1224
|
-
return true;
|
|
1225
|
-
})();
|
|
1226
|
-
redated.catch(() => {});
|
|
1227
|
-
};
|
|
1228
|
-
try {
|
|
1229
|
-
await put(key, createRelayPayload(identity, records, timestamp), timestamp, conflict);
|
|
1230
|
-
} catch (error) {
|
|
1231
|
-
const pending = redated;
|
|
1232
|
-
if (!pending || !await pending.catch((later) => {
|
|
1233
|
-
throw laterRound(error, later);
|
|
1234
|
-
})) throw error;
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
/** `PkarrTransport.publishHeld`: `publishDated`'s check before signing, for a payload signed elsewhere in this process. */
|
|
1238
|
-
publishHeld(pubKeyZ32, options = {}) {
|
|
1239
|
-
if (this.relays.length === 0) return null;
|
|
1240
|
-
const held = this.publishWait(pubKeyZ32, asker(options, true));
|
|
1241
|
-
return held ? new DiscoveryBudgetError(held.wait, `Publish held back on every relay: ${held.reasons.join("; ")}`) : null;
|
|
1242
|
-
}
|
|
1243
|
-
/**
|
|
1244
|
-
* 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,
|
|
1245
|
-
* without asking any: a relay the budget holds back gets its refused `take` (the asker's write then waits first in
|
|
1246
|
-
* line, as when `put` is refused), one rate limiting or throttling this address is a wait, one left alone for failing
|
|
1247
|
-
* is none. Null too when a relay fails another way (its network cooling down): the publish then goes, and fails, as
|
|
1248
|
-
* before, and when no relay is held back at all.
|
|
1249
|
-
*/
|
|
1250
|
-
publishWait(pubKeyZ32, who) {
|
|
1251
|
-
const probe = this.breaker.allDownProbe(this.relays);
|
|
1252
|
-
let wait = Infinity;
|
|
1253
|
-
const held = [], reasons = [];
|
|
1254
|
-
for (const relay of this.relays) {
|
|
1255
|
-
if (relay !== probe && this.networkCoolingDown(relay, "PUT")) return null;
|
|
1256
|
-
const limited = this.rateLimitedFor(relay);
|
|
1257
|
-
if (limited > 0) {
|
|
1258
|
-
wait = Math.min(wait, limited);
|
|
1259
|
-
reasons.push(`${relay}: Discovery relay is cooling down after a 429; retry shortly`);
|
|
1260
|
-
continue;
|
|
1261
|
-
}
|
|
1262
|
-
const blocked = relay === probe ? 0 : this.breaker.blockedFor(relay);
|
|
1263
|
-
if (blocked > 0) {
|
|
1264
|
-
if (this.breaker.blockedKind(relay) === "throttled") {
|
|
1265
|
-
wait = Math.min(wait, blocked);
|
|
1266
|
-
reasons.push(`${relay}: Discovery relay is throttling this address; retry shortly`);
|
|
1267
|
-
} else reasons.push(`${relay} is left alone after failing`);
|
|
1268
|
-
continue;
|
|
1269
|
-
}
|
|
1270
|
-
if (this.heldFor(relay, who, Date.now(), pubKeyZ32) <= 0) return null;
|
|
1271
|
-
held.push(relay);
|
|
1272
|
-
const left = this.heldFor(relay, who);
|
|
1273
|
-
wait = Math.min(wait, left);
|
|
1274
|
-
reasons.push(`${relay}: discovery budget reached; retry in ${Math.ceil(left / 1e3)} s`);
|
|
1275
|
-
}
|
|
1276
|
-
if (wait === Infinity) return null;
|
|
1277
|
-
for (const relay of held) this.take(relay, who, pubKeyZ32);
|
|
1278
|
-
return {
|
|
1279
|
-
wait,
|
|
1280
|
-
reasons
|
|
1281
|
-
};
|
|
1282
|
-
}
|
|
1283
|
-
/**
|
|
1284
|
-
* A publish that every relay would refuse now without being asked (its network cooling down, left alone after failing,
|
|
1285
|
-
* its rate limit or this asker's budget), and not as a wait alone (`publishWait` says those): the failure `putEverywhere`
|
|
1286
|
-
* would end in, in the same words, said before the packet is signed and dated. Null when some relay would be asked. With
|
|
1287
|
-
* every relay out of reach on a page that is online, each chat signed a packet every few seconds that went nowhere: ~58
|
|
1288
|
-
* a second at 300 chats (bug hunt, 2026-11-12).
|
|
1289
|
-
*/
|
|
1290
|
-
refusedEverywhere(pubKeyZ32, who) {
|
|
1291
|
-
const probe = this.breaker.allDownProbe(this.relays);
|
|
1292
|
-
const now = Date.now();
|
|
1293
|
-
const reasons = [], held = [];
|
|
1294
|
-
for (const relay of this.relays) {
|
|
1295
|
-
const refused = this.refusal(relay, relay === probe);
|
|
1296
|
-
if (refused) {
|
|
1297
|
-
reasons.push(String(refused));
|
|
1298
|
-
continue;
|
|
1299
|
-
}
|
|
1300
|
-
if (this.heldFor(relay, who, now, pubKeyZ32) <= 0) return null;
|
|
1301
|
-
held.push(relay);
|
|
1302
|
-
reasons.push(String(new DiscoveryBudgetError(this.heldFor(relay, who))));
|
|
1303
|
-
}
|
|
1304
|
-
for (const relay of held) this.take(relay, who, pubKeyZ32);
|
|
1305
|
-
return new PublishFailedError(`Publish failed on every relay: ${reasons.join("; ")}`, false);
|
|
1306
|
-
}
|
|
1307
|
-
/** What `put` refuses a request to this relay with before its budget is asked; null when it gets that far. */
|
|
1308
|
-
refusal(relay, probe) {
|
|
1309
|
-
if (!probe && this.networkCoolingDown(relay, "PUT")) return new RelayNoAnswerError(`${relay} did not answer a moment ago; retry shortly`, false);
|
|
1310
|
-
const limited = this.rateLimitedFor(relay);
|
|
1311
|
-
if (limited > 0) return new DiscoveryBudgetError(limited, "Discovery relay is cooling down after a 429; retry shortly");
|
|
1312
|
-
const blocked = probe ? 0 : this.breaker.blockedFor(relay);
|
|
1313
|
-
if (blocked > 0) {
|
|
1314
|
-
if (this.breaker.blockedKind(relay) === "throttled") return new DiscoveryBudgetError(blocked, "Discovery relay is throttling this address; retry shortly");
|
|
1315
|
-
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`);
|
|
1316
|
-
}
|
|
1317
|
-
return null;
|
|
1318
|
-
}
|
|
1319
|
-
/** One relay's packet for a key, read now: its time, kept for `nextTimestamp`. Null when it has none or does not answer. */
|
|
1320
|
-
async heldAt(relay, pubKeyZ32, who) {
|
|
1321
|
-
if (!this.take(relay, who, pubKeyZ32)) return null;
|
|
1322
|
-
try {
|
|
1323
|
-
let payload;
|
|
1324
|
-
if (!(await this.request(`${relay}/${pubKeyZ32}`, { method: "GET" }, async (r, signal) => {
|
|
1325
|
-
if (r.ok && r.status !== 404) payload = await readRelayBody(r, signal);
|
|
1326
|
-
})).ok || !payload) return null;
|
|
1327
|
-
const packet = parseRelayPayload(pubKeyZ32, payload);
|
|
1328
|
-
this.sawTimestamp(pubKeyZ32, packet.timestampMicros);
|
|
1329
|
-
return packet.timestampMicros;
|
|
1330
|
-
} catch {
|
|
1331
|
-
return null;
|
|
1332
|
-
}
|
|
1333
|
-
}
|
|
1334
|
-
/** A packet under this key was read (on a relay, or by the CLI on the DHT): its time, for `nextTimestamp`. */
|
|
1335
|
-
sawTimestamp(pubKeyZ32, timestamp) {
|
|
1336
|
-
if (withinSkew(timestamp) && timestamp > (this.seenTimestamp.get(pubKeyZ32) ?? 0n)) this.seenTimestamp.set(pubKeyZ32, timestamp);
|
|
1337
|
-
}
|
|
1338
|
-
/**
|
|
1339
|
-
* Puts a payload `publishDated` just signed, dated `timestamp`, on every relay. Its signature is not checked: it was
|
|
1340
|
-
* made here (`publishPayload` checks one signed elsewhere, to read its sequence number). `conflict`: as `publishDated`
|
|
1341
|
-
* gives it.
|
|
1342
|
-
*/
|
|
1343
|
-
async putSigned(pubKeyZ32, payload, timestamp, options = {}, conflict) {
|
|
1344
|
-
if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
|
|
1345
|
-
await this.putEverywhere(pubKeyZ32, payload, timestamp, options, conflict);
|
|
1346
|
-
}
|
|
1347
|
-
/**
|
|
1348
|
-
* Puts a payload signed elsewhere (a did:dht document), byte for byte, on every relay; one signed here says its date
|
|
1349
|
-
* (`signedAt`) and is not checked again. `conflict`: as `publishDated` gives it.
|
|
1350
|
-
*/
|
|
1351
|
-
async publishPayload(pubKeyZ32, payload, options = {}, conflict) {
|
|
1352
|
-
if (this.relays.length === 0) throw new PublishFailedError("No Pkarr relays configured", false);
|
|
1353
|
-
const seq = options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;
|
|
1354
|
-
if (options.signedAt === void 0 || !options.redate) return this.putEverywhere(pubKeyZ32, payload, seq, options, conflict);
|
|
1355
|
-
await this.putRedated(pubKeyZ32, payload, seq, options, PAYLOAD_REDATES);
|
|
1356
|
-
}
|
|
1357
|
-
/**
|
|
1358
|
-
* A payload every relay's budget held back while another path took it (the CLI's DHT): the publish is out, and each
|
|
1359
|
-
* relay gets it once its budget frees a request for the same asker (`catchUpLater`), unless a newer packet of the key
|
|
1360
|
-
* 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
|
|
1361
|
-
* chat at budget, not one per 4 min). `timestamp`: its date when signed here; read from the payload otherwise.
|
|
1362
|
-
*/
|
|
1363
|
-
putLater(pubKeyZ32, payload, timestamp, options = {}) {
|
|
1364
|
-
const at = timestamp ?? options.signedAt ?? openRelayPayload(pubKeyZ32, payload).seq;
|
|
1365
|
-
try {
|
|
1366
|
-
this.written.set(pubKeyZ32, readOwnRelayPayload(pubKeyZ32, payload));
|
|
1367
|
-
} catch {}
|
|
1368
|
-
for (const relay of this.relays) this.catchUpLater(relay, pubKeyZ32, payload, at, asker(options, true));
|
|
1369
|
-
}
|
|
1370
|
-
/**
|
|
1371
|
-
* A payload signed in this process (a group edge's offer or answer, `CarriedTransport`) put on every relay, past what
|
|
1372
|
-
* a relay that answers 409 holds: that one is read, and the records go again at once, signed by `options.redate` dated
|
|
1373
|
-
* just past it, `left` times at most. A packet put here is the key's latest too: a publish dated here next
|
|
1374
|
-
* (`nextTimestamp`, the goodbye after the edge stops) goes past it. Before, the 409 failed the publish (or, when another
|
|
1375
|
-
* 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
|
|
1376
|
-
* the relay's copy was later, and an edge started again in the same millisecond lost its new offer to its last one.
|
|
1377
|
-
*/
|
|
1378
|
-
async putRedated(key, payload, timestamp, options, left) {
|
|
1379
|
-
if (timestamp > (this.lastTimestamp.get(key) ?? 0n)) this.lastTimestamp.set(key, timestamp);
|
|
1380
|
-
let redated;
|
|
1381
|
-
const conflict = (relay) => {
|
|
1382
|
-
if (left <= 0 || redated) return;
|
|
1383
|
-
redated = (async () => {
|
|
1384
|
-
const held = await this.heldAt(relay, key, asker(options, true));
|
|
1385
|
-
if (held === null || held < timestamp || !withinSkew(held)) return false;
|
|
1386
|
-
if (this.lastTimestamp.get(key) !== timestamp) return true;
|
|
1387
|
-
const again = options.redate(held);
|
|
1388
|
-
if (!again) return true;
|
|
1389
|
-
traceLink(key, "publish-redated", {
|
|
1390
|
-
aheadMs: Number((held - timestamp) / 1000n),
|
|
1391
|
-
relay
|
|
1392
|
-
});
|
|
1393
|
-
await this.putRedated(key, again.payload, again.signedAt, {
|
|
1394
|
-
...options,
|
|
1395
|
-
signedAt: again.signedAt
|
|
1396
|
-
}, left - 1);
|
|
1397
|
-
return true;
|
|
1398
|
-
})();
|
|
1399
|
-
redated.catch(() => {});
|
|
1400
|
-
};
|
|
1401
|
-
try {
|
|
1402
|
-
await this.putEverywhere(key, payload, timestamp, options, conflict);
|
|
1403
|
-
} catch (error) {
|
|
1404
|
-
const pending = redated;
|
|
1405
|
-
if (!pending || !await pending.catch((later) => {
|
|
1406
|
-
throw laterRound(error, later);
|
|
1407
|
-
})) throw error;
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
/**
|
|
1411
|
-
* Puts the packet on every relay and settles as soon as one of them took it. A relay that is slow to
|
|
1412
|
-
* answer (one that stores the packet and answers the PUT only at the timeout) must not hold a link's
|
|
1413
|
-
* presence, offer or answer back: the rest finish in the background, their outcomes still counted.
|
|
1414
|
-
* When no relay takes it, this waits for all of them to say why.
|
|
1415
|
-
*/
|
|
1416
|
-
putEverywhere(pubKeyZ32, payload, timestamp, options, conflict) {
|
|
1417
|
-
this.readAt.delete(pubKeyZ32);
|
|
1418
|
-
this.missing.delete(pubKeyZ32);
|
|
1419
|
-
const waitingBefore = new Map(this.writeWaiting);
|
|
1420
|
-
const writer = firstWriter(asker(options, true));
|
|
1421
|
-
const noWriteWaits = () => {
|
|
1422
|
-
if (!writer) return;
|
|
1423
|
-
for (const relay of this.relays) {
|
|
1424
|
-
const key = `${writer} ${relay}`;
|
|
1425
|
-
if (this.writeWaiting.get(key) !== waitingBefore.get(key)) this.writeWaiting.delete(key);
|
|
1426
|
-
}
|
|
1427
|
-
};
|
|
1428
|
-
const probe = this.breaker.allDownProbe(this.relays);
|
|
1429
|
-
let first;
|
|
1430
|
-
const edgeSignal = isGroupSignal(asker(options, true));
|
|
1431
|
-
const failed = /* @__PURE__ */ new Set();
|
|
1432
|
-
const nowhere = this.relays.map(() => false);
|
|
1433
|
-
const puts = this.relays.map(async (relay, i) => {
|
|
1434
|
-
const slot = `${relay} ${pubKeyZ32}`;
|
|
1435
|
-
const previous = this.lastPut.get(slot);
|
|
1436
|
-
this.lastPut.set(slot, timestamp);
|
|
1437
|
-
if (first && isChat(asker(options, true)) && this.spareHeldFor(relay, Date.now()) > 0 && await answeredWithin(first, 3e3)) {
|
|
1438
|
-
nowhere[i] = true;
|
|
1439
|
-
throw new DiscoveryBudgetError(Math.max(CATCH_UP_MIN_MS, this.spareHeldFor(relay, Date.now())));
|
|
1440
|
-
}
|
|
1441
|
-
let response;
|
|
1442
|
-
try {
|
|
1443
|
-
response = await this.put(relay, pubKeyZ32, payload, previous, asker(options, true), relay === probe, (ok) => {
|
|
1444
|
-
first ??= ok;
|
|
1445
|
-
});
|
|
1446
|
-
if (response.status === 412) response = await this.put(relay, pubKeyZ32, payload, void 0, asker(options, true));
|
|
1447
|
-
} catch (error) {
|
|
1448
|
-
if (!isDiscoveryBudgetError(error) && !(error instanceof RelayLeftAloneError)) failed.add(relay);
|
|
1449
|
-
nowhere[i] = isDiscoveryBudgetError(error) || error instanceof RelayLeftAloneError || error instanceof RelayNoAnswerError && !error.sent;
|
|
1450
|
-
if (this.catchUp.has(slot) && isDiscoveryBudgetError(error)) this.catchUpLater(relay, pubKeyZ32, payload, timestamp, asker(options, true));
|
|
1451
|
-
throw error;
|
|
1452
|
-
}
|
|
1453
|
-
if (response.ok && (this.catchUp.get(slot)?.timestamp ?? 0n) <= timestamp) this.dropCatchUp(relay, pubKeyZ32);
|
|
1454
|
-
nowhere[i] = response.status >= 400 && response.status < 500;
|
|
1455
|
-
if (response.status >= 500 || response.status === 428) failed.add(relay);
|
|
1456
|
-
if (response.status === 409) conflict?.(relay);
|
|
1457
|
-
if (response.status === 429) throw new DiscoveryBudgetError(this.coolDown(relay, response), `${relay} responded 429; retry shortly`);
|
|
1458
|
-
if (!response.ok) throw new Error(`${relay} responded ${response.status}`);
|
|
1459
|
-
});
|
|
1460
|
-
const settled = Promise.allSettled(puts);
|
|
1461
|
-
return new Promise((resolve, reject) => {
|
|
1462
|
-
let accepted = false;
|
|
1463
|
-
for (const put of puts) put.then(() => {
|
|
1464
|
-
if (accepted) return;
|
|
1465
|
-
accepted = true;
|
|
1466
|
-
noWriteWaits();
|
|
1467
|
-
try {
|
|
1468
|
-
this.written.set(pubKeyZ32, readOwnRelayPayload(pubKeyZ32, payload));
|
|
1469
|
-
} catch {}
|
|
1470
|
-
resolve();
|
|
1471
|
-
}, () => {});
|
|
1472
|
-
settled.then((results) => {
|
|
1473
|
-
if (accepted) {
|
|
1474
|
-
noWriteWaits();
|
|
1475
|
-
results.forEach((r, i) => {
|
|
1476
|
-
if (r.status !== "rejected") return;
|
|
1477
|
-
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);
|
|
1478
|
-
});
|
|
1479
|
-
return;
|
|
1480
|
-
}
|
|
1481
|
-
const held = results.map((r) => r.status === "rejected" && isDiscoveryBudgetError(r.reason) ? r.reason : null);
|
|
1482
|
-
const leftAlone = (r) => r.status === "rejected" && r.reason instanceof RelayLeftAloneError;
|
|
1483
|
-
const waits = held.filter((e) => e !== null);
|
|
1484
|
-
const reasons = results.map((r) => r.status === "rejected" ? String(r.reason) : "").join("; ");
|
|
1485
|
-
if (waits.length === results.length) reject(new DiscoveryBudgetError(Math.min(...waits.map((e) => e.retryInMs)), `Publish held back on every relay: ${reasons}`));
|
|
1486
|
-
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}`));
|
|
1487
|
-
else reject(new PublishFailedError(`Publish failed on every relay: ${reasons}`, !nowhere.every(Boolean)));
|
|
1488
|
-
});
|
|
1489
|
-
});
|
|
1490
|
-
}
|
|
1491
|
-
/**
|
|
1492
|
-
* Public relays rate limit by IP (120 requests a minute at the time of
|
|
1493
|
-
* writing) and several peers may share one address, so a poll costs one
|
|
1494
|
-
* request: one relay is asked, the next one when this one fails, or when it
|
|
1495
|
-
* has not answered within `HEDGE_MS` (a hedge: the first good answer wins and
|
|
1496
|
-
* the other request is dropped). The newest validly signed packet seen so far
|
|
1497
|
-
* wins, which also covers a relay that is still serving an older cached copy.
|
|
1498
|
-
*
|
|
1499
|
-
* In turn per key: a key's next read starts at the relay after the one that answered its last read. A relay that
|
|
1500
|
-
* does not have a packet yet (a publish that reached only the other relay, one rate limited there) answers a key's
|
|
1501
|
-
* reads at most once in a row. With one turn for all keys, a link that read its peer between two other reads landed
|
|
1502
|
-
* on the same relay every time: a restarted member's offer, only on `pkarr.pubky.app`, went unread for 12 to 60 s
|
|
1503
|
-
* while the member at the other end read `pkarr.pubky.org` (bug hunt r5a, 2026-09-29). A relay found slow lately
|
|
1504
|
-
* (`SLOW_DEMOTE_MS`) goes after the others, whatever the turn.
|
|
1505
|
-
*
|
|
1506
|
-
* A hedge spends a second request, so it goes only where the budget has requests to spare (`hedgeRoom`), never for a
|
|
1507
|
-
* background read (nobody waits on it), and later for a key whose last read found nothing (`HEDGE_MISSING_MS`).
|
|
1508
|
-
*
|
|
1509
|
-
* `keptOnFailure` false: a read the relays failed throws `RelaysFailedError` with the packet they gave last, in place
|
|
1510
|
-
* of handing that back as their answer (a CLI asks the DHT then, `RelaysAndDht`).
|
|
1511
|
-
*/
|
|
1512
|
-
async resolve(pubKeyZ32, options = {}, keptOnFailure = true) {
|
|
1513
|
-
if (this.relays.length === 0) throw new Error("No Pkarr relays configured");
|
|
1514
|
-
if (options.background && !options.urgent && !options.group) this.chatNeedLapsed(pubKeyZ32);
|
|
1515
|
-
const readAt = this.readAt.get(pubKeyZ32), age = readAt === void 0 ? Infinity : Date.now() - readAt;
|
|
1516
|
-
if (age >= 0 && age < this.freshReadMs) return this.newest.get(pubKeyZ32) ?? null;
|
|
1517
|
-
const order = this.readOrder(pubKeyZ32);
|
|
1518
|
-
const probe = this.breaker.allDownProbe(this.relays);
|
|
1519
|
-
let budgetWait = Infinity, down = false;
|
|
1520
|
-
const who = asker(options, false);
|
|
1521
|
-
const tried = /* @__PURE__ */ new Set();
|
|
1522
|
-
let hedgeAfter = options.background ? Infinity : this.missing.has(pubKeyZ32) ? Math.max(this.hedgeMs, HEDGE_MISSING_MS) : this.hedgeMs;
|
|
1523
|
-
/**
|
|
1524
|
-
* The next relay to ask, its request taken from its budget, or null. A hedge (`hedge`) goes only to a relay with
|
|
1525
|
-
* requests to spare; one passed over for that is still there if the relay asked fails.
|
|
1526
|
-
*/
|
|
1527
|
-
const next = (hedge) => {
|
|
1528
|
-
for (const relay of order) {
|
|
1529
|
-
if (tried.has(relay)) continue;
|
|
1530
|
-
if (relay !== probe && this.networkCoolingDown(relay, "GET")) {
|
|
1531
|
-
tried.add(relay);
|
|
1532
|
-
down = true;
|
|
1533
|
-
continue;
|
|
1534
|
-
}
|
|
1535
|
-
const limited = this.rateLimitedFor(relay);
|
|
1536
|
-
if (limited > 0) {
|
|
1537
|
-
tried.add(relay);
|
|
1538
|
-
budgetWait = Math.min(budgetWait, limited);
|
|
1539
|
-
continue;
|
|
1540
|
-
}
|
|
1541
|
-
const blocked = relay === probe ? 0 : this.breaker.blockedFor(relay);
|
|
1542
|
-
if (blocked > 0) {
|
|
1543
|
-
tried.add(relay);
|
|
1544
|
-
if (this.breaker.blockedKind(relay) === "throttled") budgetWait = Math.min(budgetWait, blocked);
|
|
1545
|
-
else down = true;
|
|
1546
|
-
continue;
|
|
1547
|
-
}
|
|
1548
|
-
if (hedge && (this.heldFor(relay, who, Date.now(), pubKeyZ32) > 0 || !this.hedgeRoom(relay))) continue;
|
|
1549
|
-
tried.add(relay);
|
|
1550
|
-
if (!this.take(relay, who, pubKeyZ32)) {
|
|
1551
|
-
budgetWait = Math.min(budgetWait, this.heldFor(relay, who, Date.now(), pubKeyZ32));
|
|
1552
|
-
continue;
|
|
1553
|
-
}
|
|
1554
|
-
if (relay === probe) this.breaker.beginAllDown(relay);
|
|
1555
|
-
else this.breaker.begin(relay);
|
|
1556
|
-
return relay;
|
|
1557
|
-
}
|
|
1558
|
-
return null;
|
|
1559
|
-
};
|
|
1560
|
-
const asked = /* @__PURE__ */ new Map();
|
|
1561
|
-
let lastAsked = 0;
|
|
1562
|
-
const ask = (hedge) => {
|
|
1563
|
-
const relay = next(hedge);
|
|
1564
|
-
if (!relay) return false;
|
|
1565
|
-
asked.set(relay, this.readFromRelay(relay, pubKeyZ32));
|
|
1566
|
-
lastAsked = Date.now();
|
|
1567
|
-
return true;
|
|
1568
|
-
};
|
|
1569
|
-
ask(false);
|
|
1570
|
-
let winner = null;
|
|
1571
|
-
while (asked.size > 0 && !winner) {
|
|
1572
|
-
const hedgeIn = hedgeAfter - (Date.now() - lastAsked);
|
|
1573
|
-
if (hedgeIn <= 0) {
|
|
1574
|
-
if (!ask(true)) hedgeAfter = Infinity;
|
|
1575
|
-
continue;
|
|
1576
|
-
}
|
|
1577
|
-
let timer;
|
|
1578
|
-
const hedgeDue = hedgeIn === Infinity ? null : new Promise((resolve) => {
|
|
1579
|
-
timer = setTimeout(() => resolve(null), hedgeIn);
|
|
1580
|
-
});
|
|
1581
|
-
const settled = await Promise.race([...[...asked.values()].map((attempt) => attempt.done.then((outcome) => ({
|
|
1582
|
-
attempt,
|
|
1583
|
-
outcome
|
|
1584
|
-
}))), ...hedgeDue ? [hedgeDue] : []]);
|
|
1585
|
-
clearTimeout(timer);
|
|
1586
|
-
if (!settled) continue;
|
|
1587
|
-
const { attempt, outcome } = settled;
|
|
1588
|
-
asked.delete(attempt.relay);
|
|
1589
|
-
const relay = attempt.relay;
|
|
1590
|
-
if (outcome.kind === "packet" || outcome.kind === "missing") {
|
|
1591
|
-
winner = {
|
|
1592
|
-
attempt,
|
|
1593
|
-
outcome
|
|
1594
|
-
};
|
|
1595
|
-
break;
|
|
1596
|
-
}
|
|
1597
|
-
if (outcome.kind === "throttled") {
|
|
1598
|
-
budgetWait = Math.min(budgetWait, this.coolDown(relay, outcome.response));
|
|
1599
|
-
this.answered(relay, {
|
|
1600
|
-
kind: "throttled",
|
|
1601
|
-
reason: "rate limited (429)"
|
|
1602
|
-
});
|
|
1603
|
-
} else if (outcome.kind === "failed") {
|
|
1604
|
-
this.networkCooldown.set(`GET ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
|
|
1605
|
-
this.answered(relay, {
|
|
1606
|
-
kind: "error",
|
|
1607
|
-
reason: outcome.reason
|
|
1608
|
-
});
|
|
1609
|
-
down = true;
|
|
1610
|
-
}
|
|
1611
|
-
ask(false);
|
|
1612
|
-
}
|
|
1613
|
-
if (winner) {
|
|
1614
|
-
const { attempt, outcome } = winner, relay = attempt.relay;
|
|
1615
|
-
const took = Date.now() - attempt.started;
|
|
1616
|
-
if (outcome.kind === "packet") {
|
|
1617
|
-
this.sawTimestamp(pubKeyZ32, outcome.packet.timestampMicros);
|
|
1618
|
-
this.newest.set(pubKeyZ32, newerPacket(this.newest.get(pubKeyZ32), outcome.packet));
|
|
1619
|
-
this.missing.delete(pubKeyZ32);
|
|
1620
|
-
} else {
|
|
1621
|
-
this.missing.delete(pubKeyZ32);
|
|
1622
|
-
this.missing.add(pubKeyZ32);
|
|
1623
|
-
if (this.missing.size > READ_TURNS_KEPT) this.missing.delete(this.missing.values().next().value);
|
|
1624
|
-
}
|
|
1625
|
-
if (took <= 3e3) {
|
|
1626
|
-
this.answered(relay, void 0, "GET");
|
|
1627
|
-
this.slowUntil.delete(relay);
|
|
1628
|
-
} else {
|
|
1629
|
-
this.networkCooldown.delete(`GET ${relay}`);
|
|
1630
|
-
if (outcome.kind === "packet") this.slow(relay);
|
|
1631
|
-
else this.breaker.cancel(relay);
|
|
1632
|
-
}
|
|
1633
|
-
for (const loser of asked.values()) {
|
|
1634
|
-
loser.controller.abort();
|
|
1635
|
-
if (loser.started <= attempt.started && (outcome.kind === "packet" || Date.now() - loser.started >= 6e3)) this.slow(loser.relay);
|
|
1636
|
-
else this.breaker.cancel(loser.relay);
|
|
1637
|
-
}
|
|
1638
|
-
this.lastRelay = relay;
|
|
1639
|
-
this.answeredRead(pubKeyZ32);
|
|
1640
|
-
this.readFrom(pubKeyZ32, relay);
|
|
1641
|
-
return this.newest.get(pubKeyZ32) ?? null;
|
|
1642
|
-
}
|
|
1643
|
-
const resting = this.relays.every((r) => this.isCoolingDown(r, "GET") || this.breaker.blockedFor(r) > 0 || this.heldFor(r, who, Date.now(), pubKeyZ32) > 0);
|
|
1644
|
-
const known = down ? this.newest.get(pubKeyZ32) : newerPacket(this.newest.get(pubKeyZ32), this.written.get(pubKeyZ32));
|
|
1645
|
-
if (!down && budgetWait < Infinity) budgetWait = Math.max(budgetWait, this.backgroundTurnIn(pubKeyZ32, who, Date.now()));
|
|
1646
|
-
if (resting && known) {
|
|
1647
|
-
if (down && !keptOnFailure) throw new RelaysFailedError(known);
|
|
1648
|
-
if (!down && budgetWait < Infinity) this.heldBackUntil(pubKeyZ32, Date.now() + budgetWait);
|
|
1649
|
-
return known;
|
|
1650
|
-
}
|
|
1651
|
-
if (!down && budgetWait < Infinity) {
|
|
1652
|
-
this.heldBackUntil(pubKeyZ32, Date.now() + budgetWait);
|
|
1653
|
-
throw new DiscoveryBudgetError(budgetWait);
|
|
1654
|
-
}
|
|
1655
|
-
throw new Error("No Pkarr relay reachable");
|
|
1656
|
-
}
|
|
1657
|
-
/**
|
|
1658
|
-
* The order a key's read asks the relays in: in turn per key (see `resolve`), relays found slow lately or leaving a
|
|
1659
|
-
* request unanswered (`unanswering`) last. A relay
|
|
1660
|
-
* with a small share of its own (`RELAY_REQUESTS_PER_MINUTE` under `REQUESTS_PER_MINUTE`: pkarr.miguelmedeiros.dev's 5)
|
|
1661
|
-
* takes no turns: it comes after the others, for when they refuse, fail or are slow, unless every relay is one. In the
|
|
1662
|
-
* turn, it was spent in seconds and the relay after it took its turns too: pkarr.pubky.org got two reads in three and
|
|
1663
|
-
* pkarr.pubky.app, with twice its share, one. Its few requests are then left for writes, which go to every relay.
|
|
1664
|
-
*/
|
|
1665
|
-
readOrder(pubKeyZ32) {
|
|
1666
|
-
const full = this.relays.filter((relay) => !((RELAY_REQUESTS_PER_MINUTE[relay] ?? Infinity) < 30));
|
|
1667
|
-
const ring = full.length ? full : this.relays;
|
|
1668
|
-
const last = this.lastReadFrom.get(pubKeyZ32), lastAt = last === void 0 ? -1 : this.relays.indexOf(last);
|
|
1669
|
-
const after = lastAt < 0 ? -1 : ring.findIndex((relay) => this.relays.indexOf(relay) > lastAt);
|
|
1670
|
-
const start = lastAt < 0 ? this.cursor++ : after < 0 ? 0 : after;
|
|
1671
|
-
const turn = [...ring.map((_, i) => ring[(start + i) % ring.length]), ...this.relays.filter((relay) => !ring.includes(relay))];
|
|
1672
|
-
const now = Date.now(), behind = (relay) => (this.slowUntil.get(relay) ?? 0) > now || this.unanswering(relay, now);
|
|
1673
|
-
return [...turn.filter((relay) => !behind(relay)), ...turn.filter(behind)];
|
|
1674
|
-
}
|
|
1675
|
-
/**
|
|
1676
|
-
* A request of this client has waited on the relay for `HEDGE_MS` and it has answered none since: it goes after the
|
|
1677
|
-
* others in a read (`readOrder`), at no cost of a request. A relay that took connections and never answered held a
|
|
1678
|
-
* fresh device's first pairing at its turn: the key's last read had found nothing (`HEDGE_MISSING_MS`), so the read
|
|
1679
|
-
* 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).
|
|
1680
|
-
*/
|
|
1681
|
-
unanswering(relay, now) {
|
|
1682
|
-
const since = this.answeredAt.get(relay) ?? -Infinity;
|
|
1683
|
-
for (const request of this.waiting.get(relay) ?? []) if (request.at > since && now - request.at >= this.hedgeMs) return true;
|
|
1684
|
-
return false;
|
|
1685
|
-
}
|
|
1686
|
-
/** One GET of a key at one relay, which `controller` drops. Never rejects: what happened is the outcome. */
|
|
1687
|
-
readFromRelay(relay, pubKeyZ32) {
|
|
1688
|
-
const controller = new AbortController();
|
|
1689
|
-
return {
|
|
1690
|
-
relay,
|
|
1691
|
-
controller,
|
|
1692
|
-
started: Date.now(),
|
|
1693
|
-
done: (async () => {
|
|
1694
|
-
let status = 0;
|
|
1695
|
-
try {
|
|
1696
|
-
let payload;
|
|
1697
|
-
const response = await this.request(`${relay}/${pubKeyZ32}`, { method: "GET" }, async (r, signal) => {
|
|
1698
|
-
status = r.status;
|
|
1699
|
-
if (r.ok && r.status !== 404) payload = await readRelayBody(r, signal);
|
|
1700
|
-
}, controller.signal);
|
|
1701
|
-
status = response.status;
|
|
1702
|
-
if (response.status === 429) return {
|
|
1703
|
-
kind: "throttled",
|
|
1704
|
-
response
|
|
1705
|
-
};
|
|
1706
|
-
if (response.status === 404) return { kind: "missing" };
|
|
1707
|
-
if (!response.ok) throw new Error(`${relay} responded ${response.status}`);
|
|
1708
|
-
return {
|
|
1709
|
-
kind: "packet",
|
|
1710
|
-
packet: parseRelayPayload(pubKeyZ32, payload)
|
|
1711
|
-
};
|
|
1712
|
-
} catch {
|
|
1713
|
-
if (controller.signal.aborted) return { kind: "cancelled" };
|
|
1714
|
-
return {
|
|
1715
|
-
kind: "failed",
|
|
1716
|
-
reason: status >= 200 && status < 300 ? "invalid packet" : status ? `HTTP ${status}` : "no answer"
|
|
1717
|
-
};
|
|
1718
|
-
}
|
|
1719
|
-
})()
|
|
1720
|
-
};
|
|
1721
|
-
}
|
|
1722
|
-
/**
|
|
1723
|
-
* The relay was slow (`SLOW_MS`): it goes after the others for a while, and counts it against its breaker while
|
|
1724
|
-
* another relay is there to ask. With none, a slow answer beats no answer: it counts as one.
|
|
1725
|
-
*/
|
|
1726
|
-
slow(relay) {
|
|
1727
|
-
this.slowUntil.set(relay, Date.now() + SLOW_DEMOTE_MS);
|
|
1728
|
-
if (this.relays.some((r) => r !== relay && this.breaker.blockedFor(r) === 0 && !this.isCoolingDown(r, "GET"))) this.breaker.failure(relay, "error", "slow");
|
|
1729
|
-
else this.breaker.success(relay, this.relays);
|
|
1730
|
-
}
|
|
1731
|
-
/**
|
|
1732
|
-
* A hedge may go to this relay: its minute has more requests left than what groups leave a chat (`reserveOf`), so
|
|
1733
|
-
* a second request for a read that already went out never takes one a pairing needs.
|
|
1734
|
-
*/
|
|
1735
|
-
hedgeRoom(relay) {
|
|
1736
|
-
const now = Date.now();
|
|
1737
|
-
return within$1(this.spent.get(relay) ?? [], now, 6e4).length < this.limitOf(relay) - this.reserveOf(relay);
|
|
1738
|
-
}
|
|
1739
|
-
readAnsweredAt(pubKeyZ32) {
|
|
1740
|
-
return this.readAt.get(pubKeyZ32);
|
|
1741
|
-
}
|
|
1742
|
-
/** The last read of this key was answered 404 (`HEDGE_MISSING_MS`): a relay takes seconds to say so. */
|
|
1743
|
-
lastReadMissing(pubKeyZ32) {
|
|
1744
|
-
return this.missing.has(pubKeyZ32);
|
|
1745
|
-
}
|
|
1746
|
-
readHeldBackFor(pubKeyZ32) {
|
|
1747
|
-
const held = this.heldBack.get(pubKeyZ32);
|
|
1748
|
-
const left = held === void 0 ? 0 : held.until - Date.now();
|
|
1749
|
-
return left > 0 ? left : void 0;
|
|
1750
|
-
}
|
|
1751
|
-
heldBackUntil(pubKeyZ32, until) {
|
|
1752
|
-
const held = this.heldBack.get(pubKeyZ32), times = (held?.times ?? 0) + 1;
|
|
1753
|
-
this.heldBack.delete(pubKeyZ32);
|
|
1754
|
-
this.heldBack.set(pubKeyZ32, {
|
|
1755
|
-
until,
|
|
1756
|
-
times,
|
|
1757
|
-
since: held?.since ?? Date.now()
|
|
1758
|
-
});
|
|
1759
|
-
if (this.heldBack.size > READ_TURNS_KEPT) this.heldBack.delete(this.heldBack.keys().next().value);
|
|
1760
|
-
}
|
|
1761
|
-
/** The relays answered a read of this key now; answers older than `FRESH_READ_MS` are dropped as the list grows. */
|
|
1762
|
-
answeredRead(pubKeyZ32) {
|
|
1763
|
-
const now = Date.now();
|
|
1764
|
-
this.heldBack.delete(pubKeyZ32);
|
|
1765
|
-
this.readAt.delete(pubKeyZ32);
|
|
1766
|
-
this.readAt.set(pubKeyZ32, now);
|
|
1767
|
-
if (this.readAt.size > 64) for (const [key, at] of this.readAt) {
|
|
1768
|
-
if (now - at < this.freshReadMs) break;
|
|
1769
|
-
this.readAt.delete(key);
|
|
1770
|
-
}
|
|
1771
|
-
}
|
|
1772
|
-
/** The relay that answered a key's read, for its next one; the keys read longest ago go past `READ_TURNS_KEPT`. */
|
|
1773
|
-
readFrom(pubKeyZ32, relay) {
|
|
1774
|
-
this.lastReadFrom.delete(pubKeyZ32);
|
|
1775
|
-
this.lastReadFrom.set(pubKeyZ32, relay);
|
|
1776
|
-
if (this.lastReadFrom.size > READ_TURNS_KEPT) this.lastReadFrom.delete(this.lastReadFrom.keys().next().value);
|
|
1777
|
-
}
|
|
1778
|
-
/**
|
|
1779
|
-
* A relay whose budget (this client's, or its own rate limit) held a packet back that another relay took: it gets
|
|
1780
|
-
* that packet when it frees a request, as a background write (`who`: a group edge's offer or answer as its own, also
|
|
1781
|
-
* after that relay failed it). Only the newest per key and relay, until that relay takes this packet or a newer one (one
|
|
1782
|
-
* the budget holds there takes its place). Without this,
|
|
1783
|
-
* that relay kept the key's older packet for good, and an app that restarted and read it first found a contact's offer
|
|
1784
|
-
* long answered, answered it again, and waited on it (bug hunt r7a).
|
|
1785
|
-
*/
|
|
1786
|
-
catchUpLater(relay, key, payload, timestamp, who = CATCH_UP_ASKER) {
|
|
1787
|
-
const slot = `${relay} ${key}`;
|
|
1788
|
-
if ((this.lastPut.get(slot) ?? 0n) > timestamp) return;
|
|
1789
|
-
const pending = this.catchUp.get(slot);
|
|
1790
|
-
if (pending && pending.timestamp >= timestamp) return;
|
|
1791
|
-
this.keepCatchUp(slot, {
|
|
1792
|
-
relay,
|
|
1793
|
-
key,
|
|
1794
|
-
payload,
|
|
1795
|
-
timestamp,
|
|
1796
|
-
who
|
|
1797
|
-
});
|
|
1798
|
-
this.scheduleCatchUp(CATCH_UP_MIN_MS);
|
|
1799
|
-
}
|
|
1800
|
-
keepCatchUp(slot, item) {
|
|
1801
|
-
if (!this.catchUp.has(slot)) this.catchUpWaiting.set(item.relay, (this.catchUpWaiting.get(item.relay) ?? 0) + 1);
|
|
1802
|
-
this.catchUp.set(slot, item);
|
|
1803
|
-
}
|
|
1804
|
-
dropCatchUp(relay, key) {
|
|
1805
|
-
if (!this.catchUp.delete(`${relay} ${key}`)) return;
|
|
1806
|
-
const left = (this.catchUpWaiting.get(relay) ?? 1) - 1;
|
|
1807
|
-
if (left > 0) this.catchUpWaiting.set(relay, left);
|
|
1808
|
-
else this.catchUpWaiting.delete(relay);
|
|
1809
|
-
}
|
|
1810
|
-
scheduleCatchUp(inMs) {
|
|
1811
|
-
if (this.catchUpTimer || this.catchUp.size === 0) return;
|
|
1812
|
-
this.catchUpTimer = setTimeout(() => {
|
|
1813
|
-
this.catchUpTimer = null;
|
|
1814
|
-
this.runCatchUp();
|
|
1815
|
-
}, inMs);
|
|
1816
|
-
}
|
|
1817
|
-
async runCatchUp() {
|
|
1818
|
-
let next = Infinity;
|
|
1819
|
-
for (const [slot, item] of [...this.catchUp]) {
|
|
1820
|
-
if (this.catchUp.get(slot) !== item) continue;
|
|
1821
|
-
const coolingDown = (this.networkCooldown.get(`PUT ${item.relay}`) ?? 0) - Date.now();
|
|
1822
|
-
const who = {
|
|
1823
|
-
...item.who,
|
|
1824
|
-
catchUp: true
|
|
1825
|
-
};
|
|
1826
|
-
const wait = Math.max(this.heldFor(item.relay, who), this.rateLimitedFor(item.relay), this.breaker.blockedFor(item.relay), coolingDown);
|
|
1827
|
-
if (wait > 0) {
|
|
1828
|
-
next = Math.min(next, wait);
|
|
1829
|
-
continue;
|
|
1830
|
-
}
|
|
1831
|
-
this.dropCatchUp(item.relay, item.key);
|
|
1832
|
-
try {
|
|
1833
|
-
const response = await this.put(item.relay, item.key, item.payload, void 0, who);
|
|
1834
|
-
if ((response.status === 428 || response.status === 429) && !this.catchUp.has(slot)) {
|
|
1835
|
-
this.keepCatchUp(slot, item);
|
|
1836
|
-
next = Math.min(next, CATCH_UP_RETRY_MS);
|
|
1837
|
-
}
|
|
1838
|
-
} catch (error) {
|
|
1839
|
-
if (isDiscoveryBudgetError(error) && !this.catchUp.has(slot)) {
|
|
1840
|
-
this.keepCatchUp(slot, item);
|
|
1841
|
-
next = Math.min(next, error.retryInMs);
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
}
|
|
1845
|
-
if (this.catchUp.size) this.scheduleCatchUp(Math.max(CATCH_UP_MIN_MS, next === Infinity ? CATCH_UP_RETRY_MS : next));
|
|
1846
|
-
}
|
|
1847
|
-
/** `sent`: told, once the budget took the request, whether the relay takes the packet (a 2xx). */
|
|
1848
|
-
async put(relay, pubKeyZ32, payload, replaces, who, probe = false, sent) {
|
|
1849
|
-
const refused = this.refusal(relay, probe);
|
|
1850
|
-
if (refused) throw refused;
|
|
1851
|
-
if (!this.take(relay, who, pubKeyZ32)) throw new DiscoveryBudgetError(this.heldFor(relay, who));
|
|
1852
|
-
if (probe) this.breaker.beginAllDown(relay);
|
|
1853
|
-
else this.breaker.begin(relay);
|
|
1854
|
-
const request = this.request(`${relay}/${pubKeyZ32}`, {
|
|
1855
|
-
method: "PUT",
|
|
1856
|
-
body: payload,
|
|
1857
|
-
headers: replaces === void 0 ? void 0 : { "If-Match": replaces.toString() }
|
|
1858
|
-
});
|
|
1859
|
-
sent?.(request.then((r) => r.ok, () => false));
|
|
1860
|
-
let response;
|
|
1861
|
-
try {
|
|
1862
|
-
response = await request;
|
|
1863
|
-
} catch (error) {
|
|
1864
|
-
this.networkCooldown.set(`PUT ${relay}`, Date.now() + NETWORK_ERROR_COOLDOWN_MS);
|
|
1865
|
-
this.answered(relay, {
|
|
1866
|
-
kind: "error",
|
|
1867
|
-
reason: "no answer"
|
|
1868
|
-
});
|
|
1869
|
-
throw new RelayNoAnswerError(`${relay} did not answer`, !connectFailed(error));
|
|
1870
|
-
}
|
|
1871
|
-
if (response.status === 429) this.answered(relay, {
|
|
1872
|
-
kind: "throttled",
|
|
1873
|
-
reason: "rate limited (429)"
|
|
1874
|
-
});
|
|
1875
|
-
else if (response.status >= 500) this.answered(relay, {
|
|
1876
|
-
kind: "error",
|
|
1877
|
-
reason: `HTTP ${response.status}`
|
|
1878
|
-
});
|
|
1879
|
-
else this.answered(relay, void 0, "PUT");
|
|
1880
|
-
return response;
|
|
1881
|
-
}
|
|
1882
|
-
/**
|
|
1883
|
-
* Discovery reads and writes share a bounded per-relay request budget; background requests only part of it, and
|
|
1884
|
-
* groups leave a chat the budget refused its reserve. A link's write the budget refused goes before any read
|
|
1885
|
-
* once a request is free again.
|
|
1886
|
-
*/
|
|
1887
|
-
take(relay, who, key) {
|
|
1888
|
-
const now = Date.now();
|
|
1889
|
-
const writer = firstWriter(who);
|
|
1890
|
-
if (who.urgent && !who.background) {
|
|
1891
|
-
this.urgentAt = now;
|
|
1892
|
-
if (isChat(who)) this.chatNeed(key, now);
|
|
1893
|
-
}
|
|
1894
|
-
if (isGroupRead(who) || isChatWatch(who)) this.readAsked(key, who, now);
|
|
1895
|
-
if (isTurnRead(who)) this.turnAsked(key, who, now);
|
|
1896
|
-
if (isAwaitedRead(who)) this.awaitedAt = now;
|
|
1897
|
-
if (this.heldFor(relay, who, now, key) > 0) {
|
|
1898
|
-
if (isGroupRead(who) && (this.spent.get(relay)?.length ?? 0) >= this.limitOf(relay)) this.groupsFullAt.set(relay, now);
|
|
1899
|
-
if (isChat(who)) this.chatNeed(key, now, relay);
|
|
1900
|
-
if (writer) this.writeWaiting.set(`${writer} ${relay}`, now);
|
|
1901
|
-
if (isGroupAnswerRead(who)) {
|
|
1902
|
-
const waiting = this.answerReadWaiting.get(relay) ?? /* @__PURE__ */ new Map();
|
|
1903
|
-
this.answerReadWaiting.set(relay, waiting.set(key, now));
|
|
1904
|
-
}
|
|
1905
|
-
return false;
|
|
1906
|
-
}
|
|
1907
|
-
if (writer) this.writeWaiting.delete(`${writer} ${relay}`);
|
|
1908
|
-
if (isGroupAnswerRead(who)) this.answerReadWaiting.get(relay)?.delete(key);
|
|
1909
|
-
if (isWayBack(who) && this.heldFor(relay, {
|
|
1910
|
-
...who,
|
|
1911
|
-
back: false
|
|
1912
|
-
}, now, key, false) > 0) {
|
|
1913
|
-
this.spentWayBack.set(relay, [...this.spentWayBack.get(relay) ?? [], now]);
|
|
1914
|
-
if (isGroupRead(who)) this.readTurns.set(key, {
|
|
1915
|
-
servedAt: now,
|
|
1916
|
-
askedAt: now,
|
|
1917
|
-
waiting: false,
|
|
1918
|
-
watch: false,
|
|
1919
|
-
lane: watchLane(who)
|
|
1920
|
-
});
|
|
1921
|
-
return true;
|
|
1922
|
-
}
|
|
1923
|
-
if (isGroupAnswerRead(who) && this.heldFor(relay, who, now, key, false, false) > 0) {
|
|
1924
|
-
this.spentAnswerAllowance.set(relay, [...this.spentAnswerAllowance.get(relay) ?? [], now]);
|
|
1925
|
-
this.readTurns.set(key, {
|
|
1926
|
-
servedAt: now,
|
|
1927
|
-
askedAt: now,
|
|
1928
|
-
waiting: false,
|
|
1929
|
-
watch: false,
|
|
1930
|
-
lane: watchLane(who),
|
|
1931
|
-
answer: true
|
|
1932
|
-
});
|
|
1933
|
-
return true;
|
|
1934
|
-
}
|
|
1935
|
-
if (isGroupSignal(who) && !who.write && this.spent.get(relay).length >= this.limitOf(relay)) this.spentGroupOver.get(relay).push(now);
|
|
1936
|
-
if (isGroupSignal(who)) this.spentGroupSignal.get(relay).push(now);
|
|
1937
|
-
const departedOver = isDepartedRead(who) && this.spent.get(relay).length >= this.limitOf(relay);
|
|
1938
|
-
if (departedOver) this.overAdd(this.departedOver, key, now);
|
|
1939
|
-
if (isAwaitedRead(who) && this.spent.get(relay).length >= this.limitOf(relay)) this.awaitedOver = [...within$1(this.awaitedOver, now, 6e4), now];
|
|
1940
|
-
this.spent.get(relay).push(now);
|
|
1941
|
-
if (who.background) this.spentBackground.get(relay).push(now);
|
|
1942
|
-
if (who.background && who.write) this.spentBackgroundWrites.get(relay).push(now);
|
|
1943
|
-
if (isGroupUrgentRead(who) && isGroupAnswerRead(who)) this.spentAnswerUrgent.set(relay, [...this.spentAnswerUrgent.get(relay) ?? [], now]);
|
|
1944
|
-
else if (isGroupUrgentRead(who)) this.spentGroupUrgent.get(relay).push(now);
|
|
1945
|
-
if (isWatch(who)) this.spentWatch.get(relay).push(now);
|
|
1946
|
-
if (isChatWatch(who) && !departedOver) this.spentChatWatch.get(relay).push(now);
|
|
1947
|
-
if (isGroupRead(who)) this.spentGroupReads.get(relay).push(now);
|
|
1948
|
-
if (isGroupRead(who) || isChatWatch(who)) this.readTurns.set(key, {
|
|
1949
|
-
servedAt: now,
|
|
1950
|
-
askedAt: now,
|
|
1951
|
-
waiting: false,
|
|
1952
|
-
watch: isWatch(who) || isChatWatch(who),
|
|
1953
|
-
lane: watchLane(who)
|
|
1954
|
-
});
|
|
1955
|
-
if (isTurnRead(who)) this.keyTurns.set(key, {
|
|
1956
|
-
servedAt: now,
|
|
1957
|
-
askedAt: now,
|
|
1958
|
-
waiting: false,
|
|
1959
|
-
who
|
|
1960
|
-
});
|
|
1961
|
-
return true;
|
|
1962
|
-
}
|
|
1963
|
-
/**
|
|
1964
|
-
* How long until this relay's budget takes this request, 0 when it would now: the oldest request of the minute over
|
|
1965
|
-
* 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.
|
|
1966
|
-
*
|
|
1967
|
-
* Who goes first: a chat's refused write holds back everything but chat writes; a group's refused write holds back
|
|
1968
|
-
* group reads and background requests, never a chat's. Background requests yield to a link that signals. A chat's
|
|
1969
|
-
* signaling goes over the limit by its allowance (`SIGNALING_ALLOWANCE_SHARE`), and so do a few of its reads of a
|
|
1970
|
-
* 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
|
|
1971
|
-
* without its own allowance (`ANSWER_READ_ALLOWANCE`).
|
|
1972
|
-
*/
|
|
1973
|
-
heldFor(relay, who, now = Date.now(), key, turns = true, ownAllowance = true) {
|
|
1974
|
-
const recent = within$1(this.spent.get(relay) ?? [], now, 6e4);
|
|
1975
|
-
const recentBackground = within$1(this.spentBackground.get(relay) ?? [], now, 6e4);
|
|
1976
|
-
this.spent.set(relay, recent);
|
|
1977
|
-
this.spentBackground.set(relay, recentBackground);
|
|
1978
|
-
const recentBackgroundWrites = within$1(this.spentBackgroundWrites.get(relay) ?? [], now, 6e4);
|
|
1979
|
-
this.spentBackgroundWrites.set(relay, recentBackgroundWrites);
|
|
1980
|
-
const over = (list, limit) => list.length >= limit ? list[list.length - limit] + 6e4 - now : 0;
|
|
1981
|
-
const limit = this.limitOf(relay);
|
|
1982
|
-
const departed = isDepartedRead(who) && key !== void 0 && recent.length >= limit && this.overReads(this.departedOver, key, now) < 6;
|
|
1983
|
-
if (isAwaitedRead(who)) this.awaitedOver = within$1(this.awaitedOver, now, 6e4);
|
|
1984
|
-
const awaited = isAwaitedRead(who) && key !== void 0 && recent.length >= limit && this.awaitedOver.length < 4;
|
|
1985
|
-
const share = isChatSignal(who) || departed || awaited ? SIGNALING_ALLOWANCE_SHARE : isGroupSignal(who) ? GROUP_SIGNALING_ALLOWANCE_SHARE : 0;
|
|
1986
|
-
let allowance = share ? Math.max(0, Math.floor(limit * share) - (who.write ? 0 : 1)) : 0;
|
|
1987
|
-
if (departed && now - this.awaitedAt < 6e4) allowance = Math.max(0, allowance - 2);
|
|
1988
|
-
const groupSignaled = within$1(this.spentGroupSignal.get(relay) ?? [], now, 6e4);
|
|
1989
|
-
this.spentGroupSignal.set(relay, groupSignaled);
|
|
1990
|
-
const groupFloor = isGroupSignal(who) && groupSignaled.length < allowance;
|
|
1991
|
-
let wait = groupFloor ? 0 : over(recent, limit + allowance);
|
|
1992
|
-
const starved = key !== void 0 && this.starved(key, who, now);
|
|
1993
|
-
const groupOver = within$1(this.spentGroupOver.get(relay) ?? [], now, GROUP_OVER_PACE_MS);
|
|
1994
|
-
this.spentGroupOver.set(relay, groupOver);
|
|
1995
|
-
if (isGroupSignal(who) && !who.write && recent.length >= limit && groupOver.length > 0) wait = Math.max(wait, groupOver[groupOver.length - 1] + GROUP_OVER_PACE_MS - now);
|
|
1996
|
-
const backgroundShare = Math.min(this.backgroundPerMinute, Math.ceil(limit * 2 / 3));
|
|
1997
|
-
const writesShare = Math.max(1, Math.floor(backgroundShare * BACKGROUND_WRITES_SHARE));
|
|
1998
|
-
const caughtUp = this.catchUpWaiting.get(relay) ?? 0;
|
|
1999
|
-
if (who.background && !who.write && caughtUp) {
|
|
2000
|
-
const writesLeft = writesShare - recentBackgroundWrites.length;
|
|
2001
|
-
if (writesLeft > 0) wait = Math.max(wait, over(recent, Math.max(1, limit - writesLeft)), over(recentBackground, Math.max(1, backgroundShare - writesLeft)));
|
|
2002
|
-
}
|
|
2003
|
-
if (who.background && who.write && !who.catchUp && caughtUp) wait = Math.max(wait, Math.min(CATCH_UP_BEHIND_MAX_MS, Math.ceil(caughtUp * 6e4 / writesShare)));
|
|
2004
|
-
if (who.background && !starved) {
|
|
2005
|
-
wait = Math.max(wait, over(recentBackground, backgroundShare));
|
|
2006
|
-
if (who.write) wait = Math.max(wait, over(recentBackgroundWrites, writesShare));
|
|
2007
|
-
const signaling = this.urgentAt + SIGNALING_WINDOW_MS - now;
|
|
2008
|
-
if (signaling > 0 && !who.door) wait = Math.max(wait, Math.min(signaling, over(recentBackground, Math.min(this.backgroundWhileSignaling, Math.ceil(limit / 6)))));
|
|
2009
|
-
}
|
|
2010
|
-
const burst = within$1(this.spentGroupUrgent.get(relay) ?? [], now, GROUP_BURST_MS);
|
|
2011
|
-
this.spentGroupUrgent.set(relay, burst);
|
|
2012
|
-
const answerBurst = within$1(this.spentAnswerUrgent.get(relay) ?? [], now, GROUP_BURST_MS);
|
|
2013
|
-
this.spentAnswerUrgent.set(relay, answerBurst);
|
|
2014
|
-
if (isGroupUrgentRead(who)) {
|
|
2015
|
-
const most = Math.max(8, Math.floor(limit * GROUP_BURST_MS / 6e4));
|
|
2016
|
-
const spent = isGroupAnswerRead(who) ? answerBurst : burst;
|
|
2017
|
-
if (spent.length >= most) wait = Math.max(wait, spent[spent.length - most] + GROUP_BURST_MS - now);
|
|
2018
|
-
}
|
|
2019
|
-
const watched = within$1(this.spentWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
|
|
2020
|
-
this.spentWatch.set(relay, watched);
|
|
2021
|
-
let turn = 0;
|
|
2022
|
-
if (isWatch(who)) {
|
|
2023
|
-
const most = Math.max(1, Math.ceil(limit * WATCH_SHARE * GROUP_RATION_WINDOW_MS / 6e4));
|
|
2024
|
-
if (watched.length >= most) wait = Math.max(wait, watched[watched.length - most] + GROUP_RATION_WINDOW_MS - now);
|
|
2025
|
-
if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;
|
|
2026
|
-
}
|
|
2027
|
-
const chatWatched = within$1(this.spentChatWatch.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
|
|
2028
|
-
this.spentChatWatch.set(relay, chatWatched);
|
|
2029
|
-
if (isChatWatch(who) && !departed) {
|
|
2030
|
-
const most = Math.max(1, Math.ceil(limit * CHAT_WATCH_SHARE * GROUP_RATION_WINDOW_MS / 6e4));
|
|
2031
|
-
if (chatWatched.length >= most) wait = Math.max(wait, chatWatched[chatWatched.length - most] + GROUP_RATION_WINDOW_MS - now);
|
|
2032
|
-
if (this.readsAhead(key, now, watchLane(who)) > 0) turn = TURN_WAIT_MS;
|
|
2033
|
-
}
|
|
2034
|
-
const rationed = within$1(this.spentGroupReads.get(relay) ?? [], now, GROUP_RATION_WINDOW_MS);
|
|
2035
|
-
this.spentGroupReads.set(relay, rationed);
|
|
2036
|
-
const pastLimit = isGroupSignal(who) && recent.length >= limit;
|
|
2037
|
-
if (isGroupRead(who) && !pastLimit && now - (this.groupsFullAt.get(relay) ?? -Infinity) < GROUP_RATION_MS) {
|
|
2038
|
-
const most = Math.max(1, Math.ceil(limit * GROUP_RATION_WINDOW_MS / 6e4));
|
|
2039
|
-
if (rationed.length >= most) wait = Math.max(wait, rationed[rationed.length - most] + GROUP_RATION_WINDOW_MS - now);
|
|
2040
|
-
if (this.readsAhead(key, now, void 0, isGroupAnswerRead(who)) > 0) turn = TURN_WAIT_MS;
|
|
2041
|
-
}
|
|
2042
|
-
if (who.group && !groupFloor || who.background) {
|
|
2043
|
-
const reserved = this.chatReservedFor(relay, now);
|
|
2044
|
-
if (reserved > 0) wait = Math.max(wait, Math.min(reserved, over(recent, limit - this.chatReserveOf(relay, now))));
|
|
2045
|
-
}
|
|
2046
|
-
const writer = firstWriter(who);
|
|
2047
|
-
const waiting = (lane) => {
|
|
2048
|
-
const at = this.writeWaiting.get(`${lane} ${relay}`);
|
|
2049
|
-
return at !== void 0 && now - at < 5e3 ? at + WRITE_FIRST_MS - now : 0;
|
|
2050
|
-
};
|
|
2051
|
-
const signalOver = isChatSignal(who) && !who.write && recent.length >= limit;
|
|
2052
|
-
if (writer !== "chat" && !departed && !awaited && !signalOver && !starved) wait = Math.max(wait, waiting("chat"));
|
|
2053
|
-
if ((writer === null && who.group && !pastLimit && !isGroupAnswerRead(who) || who.background) && !starved) wait = Math.max(wait, waiting("group"));
|
|
2054
|
-
if (isGroupSignal(who) && !isGroupAnswerRead(who)) {
|
|
2055
|
-
const ahead = this.answerReadAhead(relay, now);
|
|
2056
|
-
if (ahead && this.heldFor(relay, ANSWER_READER, now, ahead.key, false, false) <= 0) wait = Math.max(wait, ahead.ms);
|
|
2057
|
-
}
|
|
2058
|
-
if (turns && wait <= 0 && isTurnRead(who) && this.turnAhead(relay, key, who, now)) turn = TURN_WAIT_MS;
|
|
2059
|
-
if (wait > 0 && isWayBack(who) && this.wayBackLeft(relay, who, now) > 0) return 0;
|
|
2060
|
-
if (wait > 0 && ownAllowance && isGroupAnswerRead(who) && this.answerAllowanceFree(relay, now)) return 0;
|
|
2061
|
-
return Math.max(wait, turn, 0);
|
|
2062
|
-
}
|
|
2063
|
-
/**
|
|
2064
|
-
* The edges' reads for their answers may take their own allowance on this relay now (`ANSWER_READ_ALLOWANCE`): fewer
|
|
2065
|
-
* than it in the last minute, and none within `ANSWER_READ_SPACING_MS`. None where the groups have no allowance.
|
|
2066
|
-
*/
|
|
2067
|
-
answerAllowanceFree(relay, now) {
|
|
2068
|
-
const spent = within$1(this.spentAnswerAllowance.get(relay) ?? [], now, 6e4);
|
|
2069
|
-
this.spentAnswerAllowance.set(relay, spent);
|
|
2070
|
-
const most = Math.min(3, Math.floor(this.limitOf(relay) * GROUP_SIGNALING_ALLOWANCE_SHARE));
|
|
2071
|
-
return spent.length < most && (spent.length === 0 || now - spent[spent.length - 1] >= 2e4);
|
|
2072
|
-
}
|
|
2073
|
-
/**
|
|
2074
|
-
* The edges' reads for their answers the budget refused on this relay within `ANSWER_READ_FIRST_MS`, still not read:
|
|
2075
|
-
* the key refused last, and how long the groups' other signaling waits for them there. Undefined when there is none.
|
|
2076
|
-
*/
|
|
2077
|
-
answerReadAhead(relay, now) {
|
|
2078
|
-
const waiting = this.answerReadWaiting.get(relay);
|
|
2079
|
-
if (!waiting) return void 0;
|
|
2080
|
-
let last;
|
|
2081
|
-
for (const [key, at] of waiting) if (now - at >= 5e3) waiting.delete(key);
|
|
2082
|
-
else if (!last || at > last.at) last = {
|
|
2083
|
-
key,
|
|
2084
|
-
at
|
|
2085
|
-
};
|
|
2086
|
-
return last && {
|
|
2087
|
-
key: last.key,
|
|
2088
|
-
ms: last.at + 5e3 - now
|
|
2089
|
-
};
|
|
2090
|
-
}
|
|
2091
|
-
/** 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. */
|
|
2092
|
-
wayBackLeft(relay, who, now) {
|
|
2093
|
-
const spent = within$1(this.spentWayBack.get(relay) ?? [], now, 6e4);
|
|
2094
|
-
this.spentWayBack.set(relay, spent);
|
|
2095
|
-
return Math.floor(this.limitOf(relay) * WAY_BACK_SHARE) - (who.write ? 0 : 1) - spent.length;
|
|
2096
|
-
}
|
|
2097
|
-
/** 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`). */
|
|
2098
|
-
readAsked(key, who, now) {
|
|
2099
|
-
this.pruneTurns(this.readTurns, now);
|
|
2100
|
-
const turn = this.readTurns.get(key);
|
|
2101
|
-
this.readTurns.set(key, {
|
|
2102
|
-
servedAt: turn && !staleTurn(turn, now) ? turn.servedAt : -Infinity,
|
|
2103
|
-
askedAt: now,
|
|
2104
|
-
waiting: true,
|
|
2105
|
-
watch: isWatch(who) || isChatWatch(who),
|
|
2106
|
-
lane: watchLane(who),
|
|
2107
|
-
answer: isGroupAnswerRead(who)
|
|
2108
|
-
});
|
|
2109
|
-
}
|
|
2110
|
-
/**
|
|
2111
|
-
* Keys a group reads, still asking (within `WATCH_TURN_MS`), that were read longer ago than `key`: a share keeps a
|
|
2112
|
-
* request for each. With `watchLane`, only watched keys the same other limits hold: one the groups' burst holds back
|
|
2113
|
-
* would keep a turn it cannot take. The chats' watched keys only in their own lane (`CHAT_WATCH_SHARE`). `answer`: an
|
|
2114
|
-
* edge's read for its answer, which waits only for the others' (`ANSWER_READ_FIRST_MS`).
|
|
2115
|
-
*/
|
|
2116
|
-
readsAhead(key, now, watchLane, answer = false) {
|
|
2117
|
-
const mine = key === void 0 ? -Infinity : this.readTurns.get(key)?.servedAt ?? -Infinity;
|
|
2118
|
-
let ahead = 0;
|
|
2119
|
-
for (const [other, turn] of this.readTurns) {
|
|
2120
|
-
if (other === key || !turn.waiting || now - turn.askedAt >= WATCH_TURN_MS) continue;
|
|
2121
|
-
if (watchLane !== void 0 ? !turn.watch || turn.lane !== watchLane : turn.lane === "chat") continue;
|
|
2122
|
-
if (answer && !turn.answer) continue;
|
|
2123
|
-
if (turn.servedAt < mine) ahead++;
|
|
2124
|
-
}
|
|
2125
|
-
return ahead;
|
|
2126
|
-
}
|
|
2127
|
-
/** A read of `key` that takes turns asks: it waits for its turn from now on, unless it is taken (`turnAhead`). */
|
|
2128
|
-
turnAsked(key, who, now) {
|
|
2129
|
-
this.pruneTurns(this.keyTurns, now);
|
|
2130
|
-
const turn = this.keyTurns.get(key);
|
|
2131
|
-
this.keyTurns.set(key, {
|
|
2132
|
-
servedAt: turn && !staleTurn(turn, now) ? turn.servedAt : -Infinity,
|
|
2133
|
-
askedAt: now,
|
|
2134
|
-
waiting: true,
|
|
2135
|
-
who
|
|
2136
|
-
});
|
|
2137
|
-
}
|
|
2138
|
-
/** Drops the turns asked and read over a minute ago, at most once in `TURNS_PRUNE_MS` (or when the clock went back). */
|
|
2139
|
-
pruneTurns(turns, now) {
|
|
2140
|
-
const prunedAt = this.turnsPrunedAt.get(turns) ?? -Infinity;
|
|
2141
|
-
if (Math.abs(now - prunedAt) < TURNS_PRUNE_MS) return;
|
|
2142
|
-
this.turnsPrunedAt.set(turns, now);
|
|
2143
|
-
const back = now < prunedAt;
|
|
2144
|
-
for (const [key, turn] of turns) {
|
|
2145
|
-
if (back) {
|
|
2146
|
-
turn.servedAt = Math.min(turn.servedAt, now);
|
|
2147
|
-
turn.askedAt = Math.min(turn.askedAt, now);
|
|
2148
|
-
}
|
|
2149
|
-
if (staleTurn(turn, now)) turns.delete(key);
|
|
2150
|
-
}
|
|
2151
|
-
}
|
|
2152
|
-
/**
|
|
2153
|
-
* Whether a key read in turn longer ago than `key`, still asking, would take this relay's next request: one read in the
|
|
2154
|
-
* background for a background read, and a chat's that is starved (`READ_STARVED_MS`) for any. One asks again after
|
|
2155
|
-
* 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
|
|
2156
|
-
* last ask, or of when it was told the budget frees a request for it (`readHeldBackFor`).
|
|
2157
|
-
* One the budget holds back on its own account (a group's read, for the chats' reserve) keeps no turn: a group key
|
|
2158
|
-
* waiting for the chats held every chat's read back (CLI lab, 2026-10-13).
|
|
2159
|
-
*/
|
|
2160
|
-
turnAhead(relay, key, who, now) {
|
|
2161
|
-
const mine = key === void 0 ? -Infinity : this.keyTurns.get(key)?.servedAt ?? -Infinity;
|
|
2162
|
-
for (const [other, turn] of this.keyTurns) {
|
|
2163
|
-
const held = this.heldBack.get(other);
|
|
2164
|
-
if (other === key || !turn.waiting || turn.servedAt >= mine || !held || held.times < 2) continue;
|
|
2165
|
-
if (!(who.background && turn.who.background) && !this.starved(other, turn.who, now)) continue;
|
|
2166
|
-
if (now - Math.max(turn.askedAt, held.until) < READ_TURN_MS && this.heldFor(relay, turn.who, now, other, false) === 0) return true;
|
|
2167
|
-
}
|
|
2168
|
-
return false;
|
|
2169
|
-
}
|
|
2170
|
-
/**
|
|
2171
|
-
* How long until a background read of `key` the budget held back is likely to have its turn: the background reads of
|
|
2172
|
-
* keys ahead of it in turn (read longer ago, still asking; `turnAhead`), one after the other at the relays' background
|
|
2173
|
-
* share. Told only when the budget frees the next request, every held key asked again then, and lost it to the key
|
|
2174
|
-
* whose turn it was: a daemon whose 50 contacts were away asked about 600 times a minute for some 50 reads, and one
|
|
2175
|
-
* with 200 three times as often after four hours as after 15 minutes (bug hunts, 2026-11-06 and 2026-11-14).
|
|
2176
|
-
*/
|
|
2177
|
-
backgroundTurnIn(key, who, now) {
|
|
2178
|
-
if (!who.background || !isTurnRead(who)) return 0;
|
|
2179
|
-
const mine = this.keyTurns.get(key);
|
|
2180
|
-
if (!mine) return 0;
|
|
2181
|
-
const since = (k) => this.heldBack.get(k)?.since ?? now;
|
|
2182
|
-
const mineSince = since(key);
|
|
2183
|
-
let ahead = 0, read = 0;
|
|
2184
|
-
for (const [other, turn] of this.keyTurns) {
|
|
2185
|
-
if (other !== key && turn.who.background && now - turn.servedAt < 6e4) read++;
|
|
2186
|
-
if (other === key || !turn.waiting || !turn.who.background || staleTurn(turn, now)) continue;
|
|
2187
|
-
if (turn.servedAt < mine.servedAt || turn.servedAt === mine.servedAt && (since(other) < mineSince || since(other) === mineSince && other < key)) ahead++;
|
|
2188
|
-
}
|
|
2189
|
-
if (ahead === 0) return 0;
|
|
2190
|
-
const perMinute = this.relays.reduce((sum, relay) => sum + Math.min(this.backgroundPerMinute, Math.ceil(this.limitOf(relay) * 2 / 3)), 0);
|
|
2191
|
-
return Math.min(BACKGROUND_TURN_MAX_MS, Math.ceil(ahead * 6e4 / Math.max(1, perMinute, read)));
|
|
2192
|
-
}
|
|
2193
|
-
/** A 1:1 chat's read of `key` the budget has held back for `READ_STARVED_MS` without a break. */
|
|
2194
|
-
starved(key, who, now) {
|
|
2195
|
-
const since = this.heldBack.get(key)?.since;
|
|
2196
|
-
return !who.group && !who.write && !who.door && since !== void 0 && now - since >= READ_STARVED_MS;
|
|
2197
|
-
}
|
|
2198
|
-
/** This key's departed reads past the limit in the last minute (`DEPARTED_READS`). */
|
|
2199
|
-
overReads(over, key, now) {
|
|
2200
|
-
const reads = within$1(over.get(key) ?? [], now, 6e4);
|
|
2201
|
-
if (reads.length) over.set(key, reads);
|
|
2202
|
-
else over.delete(key);
|
|
2203
|
-
return reads.length;
|
|
2204
|
-
}
|
|
2205
|
-
/** One more, the keys with none in the last minute dropped. */
|
|
2206
|
-
overAdd(over, key, now) {
|
|
2207
|
-
for (const [other, reads] of over) if (now - reads[reads.length - 1] >= 6e4) over.delete(other);
|
|
2208
|
-
over.set(key, [...over.get(key) ?? [], now]);
|
|
2209
|
-
}
|
|
2210
|
-
/** A chat's request of `key` asked urgently (it needs every relay), or the budget refused it on `relay` (it needs that one). */
|
|
2211
|
-
chatNeed(key, now, relay) {
|
|
2212
|
-
if (relay !== void 0) {
|
|
2213
|
-
this.chatNeedsOn(relay, now).set(key, now);
|
|
2214
|
-
return;
|
|
2215
|
-
}
|
|
2216
|
-
this.chatUrgentAt.set(key, now);
|
|
2217
|
-
for (const needs of this.chatNeeds.values()) needs.set(key, now);
|
|
2218
|
-
}
|
|
2219
|
-
/** The chats that need this relay: those a request of was refused there, and the urgent ones. */
|
|
2220
|
-
chatNeedsOn(relay, now) {
|
|
2221
|
-
let needs = this.chatNeeds.get(relay);
|
|
2222
|
-
if (!needs) {
|
|
2223
|
-
this.chatNeeds.set(relay, needs = new RecentKeys());
|
|
2224
|
-
for (const [key, at] of this.chatUrgentAt.entries(now)) needs.set(key, at);
|
|
2225
|
-
}
|
|
2226
|
-
return needs;
|
|
2227
|
-
}
|
|
2228
|
-
/** The chat reading `key` has nothing due: it needs no relay any more. */
|
|
2229
|
-
chatNeedLapsed(key) {
|
|
2230
|
-
this.chatUrgentAt.delete(key);
|
|
2231
|
-
for (const needs of this.chatNeeds.values()) needs.delete(key);
|
|
2232
|
-
}
|
|
2233
|
-
/**
|
|
2234
|
-
* How long groups still leave a chat its reserve on this relay (`CHAT_RESERVE`); a chat's need a minute old goes.
|
|
2235
|
-
* Kept up to date as needs come and go (`RecentKeys`): walking them all for each request cost a daemon with 500
|
|
2236
|
-
* contacts away 2.7 s of CPU per 10 idle minutes (bug hunt, 2026-11-01).
|
|
2237
|
-
*/
|
|
2238
|
-
chatReservedFor(relay, now) {
|
|
2239
|
-
return this.chatNeedsOn(relay, now).latest(now) + 6e4 - now;
|
|
2240
|
-
}
|
|
2241
|
-
/**
|
|
2242
|
-
* How long a chat's packet another relay already took waits for this one: while chats need the relays, a copy takes
|
|
2243
|
-
* none of the requests their reserve keeps (`chatReserveOf`), as a group's request does not. 0 when it goes now.
|
|
2244
|
-
*/
|
|
2245
|
-
spareHeldFor(relay, now) {
|
|
2246
|
-
const reserved = this.chatReservedFor(relay, now);
|
|
2247
|
-
if (reserved <= 0) return 0;
|
|
2248
|
-
const recent = within$1(this.spent.get(relay) ?? [], now, 6e4);
|
|
2249
|
-
const keep = this.limitOf(relay) - this.chatReserveOf(relay, now);
|
|
2250
|
-
return recent.length >= keep ? Math.min(reserved, recent[recent.length - keep] + 6e4 - now) : 0;
|
|
2251
|
-
}
|
|
2252
|
-
/** Requests allowed to this relay a minute: this client's budget, or the relay's own share (`RELAY_REQUESTS_PER_MINUTE`). */
|
|
2253
|
-
limitOf(relay) {
|
|
2254
|
-
const share = RELAY_REQUESTS_PER_MINUTE[relay];
|
|
2255
|
-
if (share === void 0) return this.perMinute;
|
|
2256
|
-
return this.perMinuteGiven ? Math.min(this.perMinute, share) : share;
|
|
2257
|
-
}
|
|
2258
|
-
/** What the chats that need the relays keep on this relay (`CHAT_RESERVE_PER_CHAT`), never less than `reserveOf`. */
|
|
2259
|
-
chatReserveOf(relay, now) {
|
|
2260
|
-
const needing = this.chatNeedsOn(relay, now).size(now);
|
|
2261
|
-
return Math.max(this.reserveOf(relay), Math.min(needing * 3, Math.floor(this.limitOf(relay) * CHAT_RESERVE_MOST_SHARE)));
|
|
2262
|
-
}
|
|
2263
|
-
/** What groups leave a chat on this relay: `CHAT_RESERVE`, or a third of a smaller budget. */
|
|
2264
|
-
reserveOf(relay) {
|
|
2265
|
-
return Math.min(10, Math.floor(this.limitOf(relay) / 3));
|
|
2266
|
-
}
|
|
2267
|
-
isCoolingDown(relay, method) {
|
|
2268
|
-
return this.rateLimitedFor(relay) > 0 || this.networkCoolingDown(relay, method);
|
|
2269
|
-
}
|
|
2270
|
-
/** Left alone after failing at the network level. */
|
|
2271
|
-
networkCoolingDown(relay, method) {
|
|
2272
|
-
return (this.networkCooldown.get(`${method} ${relay}`) ?? 0) > Date.now();
|
|
2273
|
-
}
|
|
2274
|
-
/** How much longer the relay asked (429) to be left alone; 0 when it did not. */
|
|
2275
|
-
rateLimitedFor(relay) {
|
|
2276
|
-
return Math.max(0, (this.coolingDown.get(relay) ?? 0) - Date.now());
|
|
2277
|
-
}
|
|
2278
|
-
/** Leaves the relay alone for as long as its 429 asks; returns that, in ms. */
|
|
2279
|
-
coolDown(relay, response) {
|
|
2280
|
-
const retryAfter = Number.parseInt(response.headers.get("retry-after") ?? "", 10);
|
|
2281
|
-
const seconds = Number.isFinite(retryAfter) ? Math.min(Math.max(retryAfter, 1), 120) : 15;
|
|
2282
|
-
this.coolingDown.set(relay, Date.now() + seconds * 1e3);
|
|
2283
|
-
return seconds * 1e3;
|
|
2284
|
-
}
|
|
2285
|
-
/**
|
|
2286
|
-
* One request under one time limit. `read` runs before the timer is cleared, so a body read there is bounded in
|
|
2287
|
-
* time as well: a relay that sends its headers and then trickles, or never ends, is given up on like one that
|
|
2288
|
-
* never answered.
|
|
2289
|
-
*/
|
|
2290
|
-
/**
|
|
2291
|
-
* The relay's own time, when its answer says it and this runtime may read it: Node and the Desktop can, a browser
|
|
2292
|
-
* only when the relay exposes the header to other origins. Held against this device's clock (`ClockWatch`).
|
|
2293
|
-
*/
|
|
2294
|
-
serverTime(url, response, sent) {
|
|
2295
|
-
if (!this.timeListeners.size) return;
|
|
2296
|
-
let date = NaN;
|
|
2297
|
-
try {
|
|
2298
|
-
if (Number(response.headers.get("age") ?? 0) > 0) return;
|
|
2299
|
-
date = Date.parse(response.headers.get("date") ?? "");
|
|
2300
|
-
} catch {}
|
|
2301
|
-
if (!Number.isFinite(date)) return;
|
|
2302
|
-
const time = {
|
|
2303
|
-
source: new URL(url).origin,
|
|
2304
|
-
date,
|
|
2305
|
-
sent,
|
|
2306
|
-
received: Date.now()
|
|
2307
|
-
};
|
|
2308
|
-
for (const listener of this.timeListeners) try {
|
|
2309
|
-
listener(time);
|
|
2310
|
-
} catch {}
|
|
2311
|
-
}
|
|
2312
|
-
onServerTime(listener) {
|
|
2313
|
-
this.timeListeners.add(listener);
|
|
2314
|
-
return () => this.timeListeners.delete(listener);
|
|
2315
|
-
}
|
|
2316
|
-
/**
|
|
2317
|
-
* The turn record's read (WISP 06 § Publishing and reading): every relay, in parallel, `TURN_SOURCE_TIMEOUT_MS`
|
|
2318
|
-
* each. Unlike `resolve`, it does not stop at the first relay that answers, keeps nothing, and answers nothing from
|
|
2319
|
-
* memory. Each request counts in the relay's minute, so chats see it, but is never held back by it: a device may
|
|
2320
|
-
* not act before it has read its turn.
|
|
2321
|
-
*/
|
|
2322
|
-
turnRead(pubKeyZ32, options = {}) {
|
|
2323
|
-
const timeoutMs = Math.min(options.timeoutMs ?? 8e3, TURN_SOURCE_TIMEOUT_MS);
|
|
2324
|
-
return Promise.all(this.relays.map(async (relay) => {
|
|
2325
|
-
try {
|
|
2326
|
-
let payload;
|
|
2327
|
-
const read = async (r, signal) => {
|
|
2328
|
-
if (r.ok) payload = await readRelayBody(r, signal);
|
|
2329
|
-
};
|
|
2330
|
-
let response = await this.turnRequest(relay, `${pubKeyZ32}?policy=NetworkOnly`, { method: "GET" }, read, timeoutMs);
|
|
2331
|
-
const stale = response.status === 400;
|
|
2332
|
-
if (stale) response = await this.turnRequest(relay, pubKeyZ32, { method: "GET" }, read, timeoutMs);
|
|
2333
|
-
const age = stale ? { stale: true } : {};
|
|
2334
|
-
if (response.status === 404) {
|
|
2335
|
-
const invalid = response.headers.get(INVALID_PACKET_SEQ_HEADER);
|
|
2336
|
-
return {
|
|
2337
|
-
source: relay,
|
|
2338
|
-
answered: true,
|
|
2339
|
-
payloads: [],
|
|
2340
|
-
...age,
|
|
2341
|
-
...invalid && /^\d{1,19}$/.test(invalid) ? { sequences: [invalid] } : {}
|
|
2342
|
-
};
|
|
2343
|
-
}
|
|
2344
|
-
if (!response.ok || !payload) return {
|
|
2345
|
-
source: relay,
|
|
2346
|
-
answered: false,
|
|
2347
|
-
payloads: [],
|
|
2348
|
-
detail: `HTTP ${response.status}`
|
|
2349
|
-
};
|
|
2350
|
-
return {
|
|
2351
|
-
source: relay,
|
|
2352
|
-
answered: true,
|
|
2353
|
-
payloads: [payload],
|
|
2354
|
-
...age
|
|
2355
|
-
};
|
|
2356
|
-
} catch (error) {
|
|
2357
|
-
return {
|
|
2358
|
-
source: relay,
|
|
2359
|
-
answered: false,
|
|
2360
|
-
payloads: [],
|
|
2361
|
-
detail: error instanceof Error ? error.message : String(error)
|
|
2362
|
-
};
|
|
2363
|
-
}
|
|
2364
|
-
}));
|
|
2365
|
-
}
|
|
2366
|
-
/**
|
|
2367
|
-
* The turn record's put: the bytes as given, to each relay `conditions` names, with `If-Match` on the sequence that
|
|
2368
|
-
* relay is known to hold (none where it held no record). Unlike `putEverywhere`, a relay that refuses (409, 412,
|
|
2369
|
-
* 428) is not asked again without the condition: its refusal is the answer, and every relay's answer is reported.
|
|
2370
|
-
*/
|
|
2371
|
-
turnPut(pubKeyZ32, payload, conditions) {
|
|
2372
|
-
const relays = this.relays.filter((relay) => conditions[relay] !== void 0);
|
|
2373
|
-
return Promise.all(relays.map(async (relay) => {
|
|
2374
|
-
const replaces = conditions[relay];
|
|
2375
|
-
try {
|
|
2376
|
-
const response = await this.turnRequest(relay, pubKeyZ32, {
|
|
2377
|
-
method: "PUT",
|
|
2378
|
-
body: payload,
|
|
2379
|
-
headers: replaces === null ? void 0 : { "If-Match": replaces }
|
|
2380
|
-
});
|
|
2381
|
-
if (response.ok) return {
|
|
2382
|
-
source: relay,
|
|
2383
|
-
outcome: "stored",
|
|
2384
|
-
detail: `HTTP ${response.status}`
|
|
2385
|
-
};
|
|
2386
|
-
return {
|
|
2387
|
-
source: relay,
|
|
2388
|
-
outcome: TURN_REFUSALS.includes(response.status) ? "refused" : "failed",
|
|
2389
|
-
detail: `HTTP ${response.status}`
|
|
2390
|
-
};
|
|
2391
|
-
} catch (error) {
|
|
2392
|
-
return {
|
|
2393
|
-
source: relay,
|
|
2394
|
-
outcome: "failed",
|
|
2395
|
-
detail: error instanceof Error ? error.message : String(error)
|
|
2396
|
-
};
|
|
2397
|
-
}
|
|
2398
|
-
}));
|
|
2399
|
-
}
|
|
2400
|
-
async turnRequest(relay, path, init, read, timeoutMs = TURN_SOURCE_TIMEOUT_MS) {
|
|
2401
|
-
this.spent.get(relay)?.push(Date.now());
|
|
2402
|
-
const controller = new AbortController();
|
|
2403
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
2404
|
-
try {
|
|
2405
|
-
const response = await this.fetchFn(`${relay}/${path}`, {
|
|
2406
|
-
...init,
|
|
2407
|
-
cache: "no-store",
|
|
2408
|
-
signal: controller.signal
|
|
2409
|
-
});
|
|
2410
|
-
await read?.(response, controller.signal);
|
|
2411
|
-
return response;
|
|
2412
|
-
} finally {
|
|
2413
|
-
clearTimeout(timer);
|
|
2414
|
-
}
|
|
2415
|
-
}
|
|
2416
|
-
/** `cancel`: this client drops the request (a hedged read another relay answered first). */
|
|
2417
|
-
async request(url, init, read, cancel) {
|
|
2418
|
-
const controller = new AbortController();
|
|
2419
|
-
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
2420
|
-
const drop = () => controller.abort();
|
|
2421
|
-
cancel?.addEventListener("abort", drop, { once: true });
|
|
2422
|
-
const relay = url.slice(0, url.lastIndexOf("/")), request = { at: Date.now() };
|
|
2423
|
-
const waiting = this.waiting.get(relay) ?? /* @__PURE__ */ new Set();
|
|
2424
|
-
this.waiting.set(relay, waiting.add(request));
|
|
2425
|
-
try {
|
|
2426
|
-
const sent = Date.now();
|
|
2427
|
-
const response = await this.fetchFn(url, {
|
|
2428
|
-
...init,
|
|
2429
|
-
cache: "no-store",
|
|
2430
|
-
signal: controller.signal
|
|
2431
|
-
});
|
|
2432
|
-
this.answeredAt.set(relay, Date.now());
|
|
2433
|
-
this.serverTime(url, response, sent);
|
|
2434
|
-
await read?.(response, controller.signal);
|
|
2435
|
-
return response;
|
|
2436
|
-
} finally {
|
|
2437
|
-
waiting.delete(request);
|
|
2438
|
-
clearTimeout(timer);
|
|
2439
|
-
cancel?.removeEventListener("abort", drop);
|
|
2440
|
-
}
|
|
2441
|
-
}
|
|
2442
|
-
};
|
|
2443
|
-
/**
|
|
2444
|
-
* A relay's answer body, at most RELAY_PAYLOAD_MAX_BYTES: refused on a larger `content-length` before anything is
|
|
2445
|
-
* read, and otherwise streamed with a running count, so a relay (a default one or one the person added, working or
|
|
2446
|
-
* compromised) cannot fill memory with a huge or endless body. Stops when `signal` aborts.
|
|
2447
|
-
*/
|
|
2448
|
-
async function readRelayBody(response, signal, max = RELAY_PAYLOAD_MAX_BYTES) {
|
|
2449
|
-
const tooLarge = () => /* @__PURE__ */ new Error(`Relay answer is larger than ${max} bytes`);
|
|
2450
|
-
if (Number(response.headers.get("content-length")) > max) {
|
|
2451
|
-
response.body?.cancel().catch(() => {});
|
|
2452
|
-
throw tooLarge();
|
|
2453
|
-
}
|
|
2454
|
-
if (!response.body) return /* @__PURE__ */ new Uint8Array(0);
|
|
2455
|
-
const reader = response.body.getReader();
|
|
2456
|
-
const stop = () => {
|
|
2457
|
-
reader.cancel().catch(() => {});
|
|
2458
|
-
};
|
|
2459
|
-
signal.addEventListener("abort", stop, { once: true });
|
|
2460
|
-
try {
|
|
2461
|
-
const chunks = [];
|
|
2462
|
-
let length = 0;
|
|
2463
|
-
for (;;) {
|
|
2464
|
-
if (signal.aborted) throw new Error("Relay answer timed out");
|
|
2465
|
-
const { done, value } = await reader.read();
|
|
2466
|
-
if (signal.aborted) throw new Error("Relay answer timed out");
|
|
2467
|
-
if (done) break;
|
|
2468
|
-
length += value.byteLength;
|
|
2469
|
-
if (length > max) {
|
|
2470
|
-
stop();
|
|
2471
|
-
throw tooLarge();
|
|
2472
|
-
}
|
|
2473
|
-
chunks.push(value);
|
|
2474
|
-
}
|
|
2475
|
-
const body = new Uint8Array(length);
|
|
2476
|
-
let at = 0;
|
|
2477
|
-
for (const chunk of chunks) {
|
|
2478
|
-
body.set(chunk, at);
|
|
2479
|
-
at += chunk.byteLength;
|
|
2480
|
-
}
|
|
2481
|
-
return body;
|
|
2482
|
-
} finally {
|
|
2483
|
-
signal.removeEventListener("abort", stop);
|
|
2484
|
-
}
|
|
2485
|
-
}
|
|
2486
70
|
// ../core/src/turnRecord.ts
|
|
2487
71
|
/** The record's format, byte 0 of the body. */
|
|
2488
72
|
var TURN_VERSION = 1;
|
|
@@ -3562,6 +1146,19 @@ var DEVICE_INVITE_BYTES = 133;
|
|
|
3562
1146
|
var DEVICE_INVITE_OWN_DEVICE = 1;
|
|
3563
1147
|
/** How long a code is good for (WISP 06: the inviter enforces the 10 minutes). */
|
|
3564
1148
|
var DEVICE_INVITE_LIFETIME_S = 600;
|
|
1149
|
+
/**
|
|
1150
|
+
* How far past its expiry, by the reading device's own clock, a code is still taken: a day. The expiry is in the
|
|
1151
|
+
* inviter's clock, and the reader's may run ahead of it by minutes (no time sync), by hours (a wrong time zone set as
|
|
1152
|
+
* local time) or more; only the inviter's word counts, and the inviter refuses a code past its ten minutes. A code a
|
|
1153
|
+
* day past its expiry here is old by any likely clock.
|
|
1154
|
+
*/
|
|
1155
|
+
var DEVICE_INVITE_READ_SLACK_S = 86400;
|
|
1156
|
+
/**
|
|
1157
|
+
* Whether the device reading a code takes it as expired: `expires` is the code's (the inviter's clock), `now` this
|
|
1158
|
+
* device's, both UNIX seconds. The one rule for every reader (the enrollment and the join dialogs), so none refuses a
|
|
1159
|
+
* fresh code from an inviter whose clock is behind this one.
|
|
1160
|
+
*/
|
|
1161
|
+
var deviceInviteExpired = (expires, now) => expires + DEVICE_INVITE_READ_SLACK_S <= now;
|
|
3565
1162
|
/** The `ghostly1z…` code of a device invite. */
|
|
3566
1163
|
function encodeDeviceInvite(invite) {
|
|
3567
1164
|
const fields = [
|
|
@@ -3585,7 +1182,8 @@ function encodeDeviceInvite(invite) {
|
|
|
3585
1182
|
var body$1 = (input) => unwrapPasted(input).replace(/^.*#/, "");
|
|
3586
1183
|
/**
|
|
3587
1184
|
* Reads a device code, pasted or scanned (bare, in capitals from a QR code, or after a `#`). `now` is in UNIX
|
|
3588
|
-
* seconds: a code past its expiry is refused here
|
|
1185
|
+
* seconds, this device's clock: only a code a day past its expiry by it is refused here (`deviceInviteExpired`), since
|
|
1186
|
+
* only the inviter's word counts.
|
|
3589
1187
|
*/
|
|
3590
1188
|
function readDeviceInvite(input, now = Math.floor(Date.now() / 1e3)) {
|
|
3591
1189
|
const code = body$1(input).toLowerCase();
|
|
@@ -3647,7 +1245,7 @@ function readDeviceInvite(input, now = Math.floor(Date.now() / 1e3)) {
|
|
|
3647
1245
|
detail: `Flags ${flags}`
|
|
3648
1246
|
};
|
|
3649
1247
|
const expires = new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getUint32(129);
|
|
3650
|
-
if (expires
|
|
1248
|
+
if (deviceInviteExpired(expires, now)) return {
|
|
3651
1249
|
ok: false,
|
|
3652
1250
|
reason: "expired"
|
|
3653
1251
|
};
|
|
@@ -3871,6 +1469,42 @@ function readCanonicalJson(bytes) {
|
|
|
3871
1469
|
value
|
|
3872
1470
|
};
|
|
3873
1471
|
}
|
|
1472
|
+
/**
|
|
1473
|
+
* The entries of bytes that must be a canonical JSON list, each as its own bytes, one at a time: a scan that builds no
|
|
1474
|
+
* value and goes no further than the entry it yields, so a caller reads (and may refuse) each before the next is
|
|
1475
|
+
* found. It ends with null at the closing `]`; `not-list` past `maxEntries` entries, at an entry over `maxEntryBytes`,
|
|
1476
|
+
* or when the bytes are not within `[` and `]`; `not-json` when brackets or quotes do not close. A canonical list is
|
|
1477
|
+
* `[`, its entries' canonical texts joined by `,`, then `]`, so the bytes are canonical exactly when the scan ends with
|
|
1478
|
+
* null and each entry read alone with `readCanonicalJson` is.
|
|
1479
|
+
*/
|
|
1480
|
+
function* canonicalJsonListEntries(bytes, maxEntries, maxEntryBytes) {
|
|
1481
|
+
const end = bytes.length - 1;
|
|
1482
|
+
if (end < 1 || bytes[0] !== 91 || bytes[end] !== 93) return "not-list";
|
|
1483
|
+
if (end === 1) return null;
|
|
1484
|
+
let depth = 0;
|
|
1485
|
+
let inString = false;
|
|
1486
|
+
let start = 1;
|
|
1487
|
+
let count = 0;
|
|
1488
|
+
for (let i = 1; i <= end; i++) {
|
|
1489
|
+
const b = bytes[i];
|
|
1490
|
+
if (i === end || b === 44 && depth === 0 && !inString) {
|
|
1491
|
+
if (i === end && (depth !== 0 || inString)) return "not-json";
|
|
1492
|
+
if (count === maxEntries || i - start > maxEntryBytes) return "not-list";
|
|
1493
|
+
count++;
|
|
1494
|
+
yield bytes.subarray(start, i);
|
|
1495
|
+
start = i + 1;
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
if (i - start >= maxEntryBytes) return "not-list";
|
|
1499
|
+
if (inString) {
|
|
1500
|
+
if (b === 92) i++;
|
|
1501
|
+
else if (b === 34) inString = false;
|
|
1502
|
+
} else if (b === 34) inString = true;
|
|
1503
|
+
else if (b === 91 || b === 123) depth++;
|
|
1504
|
+
else if ((b === 93 || b === 125) && --depth < 0) return "not-json";
|
|
1505
|
+
}
|
|
1506
|
+
return start === end + 1 ? null : "not-json";
|
|
1507
|
+
}
|
|
3874
1508
|
// ../core/src/image.ts
|
|
3875
1509
|
var IMAGE_LIMITS = {
|
|
3876
1510
|
/** Pixels on either side: the most a JPEG can say, well past what anyone sends as a picture. */
|
|
@@ -4057,7 +1691,12 @@ var APP_STATEMENT_LIMITS = {
|
|
|
4057
1691
|
/** A revocation's reason, in characters. */
|
|
4058
1692
|
reason: 200,
|
|
4059
1693
|
/** Revocations in one `ghostly-revoke.json`. */
|
|
4060
|
-
revocations: 4096
|
|
1694
|
+
revocations: 4096,
|
|
1695
|
+
/**
|
|
1696
|
+
* One signed revocation's canonical bytes: twice the largest a valid one can be (64 digests, a 32-character name and
|
|
1697
|
+
* a 200-character reason of 4-byte characters: about 4.1 KB), so a reader refuses a larger entry before parsing it.
|
|
1698
|
+
*/
|
|
1699
|
+
revocationBytes: 8192
|
|
4061
1700
|
};
|
|
4062
1701
|
/** A z-base32 Ed25519 public key: 52 characters that decode to 32 bytes and encode back to the same text. */
|
|
4063
1702
|
function isAppKey(value) {
|
|
@@ -4349,24 +1988,39 @@ function verifyAppRevocation(revocation, checked) {
|
|
|
4349
1988
|
* file, as a store index's `revoked` does. With `checked`, a revocation it holds is not checked again.
|
|
4350
1989
|
*/
|
|
4351
1990
|
function readAppRevocations(bytes, checked) {
|
|
4352
|
-
const read = readCanonicalJson(bytes);
|
|
4353
|
-
if (!read.ok) return read;
|
|
4354
|
-
if (!Array.isArray(read.value) || read.value.length > APP_STATEMENT_LIMITS.revocations) return {
|
|
4355
|
-
ok: false,
|
|
4356
|
-
reason: "bad-revocation",
|
|
4357
|
-
detail: "Not a list of at most 4096 revocations"
|
|
4358
|
-
};
|
|
4359
1991
|
const revocations = [];
|
|
4360
|
-
|
|
4361
|
-
|
|
1992
|
+
const entries = appRevocationsFileEntries(bytes);
|
|
1993
|
+
let next = entries.next();
|
|
1994
|
+
for (; !next.done; next = entries.next()) {
|
|
1995
|
+
const read = readCanonicalJson(next.value);
|
|
1996
|
+
if (!read.ok) return read;
|
|
1997
|
+
const one = readAppRevocation(read.value, checked);
|
|
4362
1998
|
if (!one.ok) return one;
|
|
4363
1999
|
revocations.push(one.revocation);
|
|
4364
2000
|
}
|
|
4365
|
-
return {
|
|
2001
|
+
return next.value ?? {
|
|
4366
2002
|
ok: true,
|
|
4367
2003
|
revocations
|
|
4368
2004
|
};
|
|
4369
2005
|
}
|
|
2006
|
+
/**
|
|
2007
|
+
* The entries of a `ghostly-revoke.json`, each as its own bytes, one at a time and with nothing parsed: a file past
|
|
2008
|
+
* 4096 entries, or with one larger than any revocation can be, is refused there, however large it is. It ends with null
|
|
2009
|
+
* when the list closed. Each entry read alone (`readCanonicalJson`, then `readAppRevocation`) refuses exactly the files
|
|
2010
|
+
* reading the file whole refuses.
|
|
2011
|
+
*/
|
|
2012
|
+
function* appRevocationsFileEntries(bytes) {
|
|
2013
|
+
const end = yield* canonicalJsonListEntries(bytes, APP_STATEMENT_LIMITS.revocations, APP_STATEMENT_LIMITS.revocationBytes);
|
|
2014
|
+
if (end === "not-list") return {
|
|
2015
|
+
ok: false,
|
|
2016
|
+
reason: "bad-revocation",
|
|
2017
|
+
detail: "Not a list of at most 4096 revocations"
|
|
2018
|
+
};
|
|
2019
|
+
return end && {
|
|
2020
|
+
ok: false,
|
|
2021
|
+
reason: end
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
4370
2024
|
// ../core/src/appBundle.ts
|
|
4371
2025
|
var APP_BUNDLE_MAGIC = "GHOSTLYAPP1";
|
|
4372
2026
|
var MAGIC$1 = utf8Encode(APP_BUNDLE_MAGIC);
|
|
@@ -7924,6 +5578,7 @@ var VIEWER_PERMISSIONS_POLICY = [
|
|
|
7924
5578
|
"serial",
|
|
7925
5579
|
"hid",
|
|
7926
5580
|
"clipboard-read",
|
|
5581
|
+
"clipboard-write",
|
|
7927
5582
|
"idle-detection",
|
|
7928
5583
|
"local-fonts",
|
|
7929
5584
|
"window-management",
|
|
@@ -9572,9 +7227,9 @@ var LinkSession = class {
|
|
|
9572
7227
|
if (publish) this.publish().catch(() => {});
|
|
9573
7228
|
if (read) this.pollNow();
|
|
9574
7229
|
}
|
|
9575
|
-
/** This side's packet goes out now, unless one already did. */
|
|
7230
|
+
/** This side's packet goes out now, unless one already did (in this run, once it left DHT only: `presenceDue`). */
|
|
9576
7231
|
ensureAdvertised() {
|
|
9577
|
-
if (!this.running || this.lastPublishedAt > 0 || this.publishing) return;
|
|
7232
|
+
if (!this.running || this.lastPublishedAt > 0 && !this.presenceDueOut || this.publishing) return;
|
|
9578
7233
|
this.publish().catch(() => {});
|
|
9579
7234
|
}
|
|
9580
7235
|
/** This side's packet goes out again as it is: another writer of its key (a second device on a device code) may have replaced it. */
|
|
@@ -12235,6 +9890,15 @@ function removedCardText(of, title) {
|
|
|
12235
9890
|
return `🗑 ${of === "task" ? "Task" : "Routine"} removed${title ? `: ${title}` : ""}`;
|
|
12236
9891
|
}
|
|
12237
9892
|
/**
|
|
9893
|
+
* 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
|
|
9894
|
+
* older app): what a line quoting the message says where the card is not drawn, never the bundle's raw link. Any other
|
|
9895
|
+
* message's text as it is.
|
|
9896
|
+
*/
|
|
9897
|
+
function withoutAppLink(text, card) {
|
|
9898
|
+
const url = card?.kind === "app" ? card.url : void 0;
|
|
9899
|
+
return url ? text.split("\n").filter((line) => line.trim() !== url).join("\n") : text;
|
|
9900
|
+
}
|
|
9901
|
+
/**
|
|
12238
9902
|
* The text a card's message carries: what an app without cards shows, the DHT floor carries, the chat list previews
|
|
12239
9903
|
* and search finds. Plain lines, the first naming the card, no bars or layout that would read badly elsewhere.
|
|
12240
9904
|
*/
|
|
@@ -12650,20 +10314,27 @@ var LINK_CLOSERS = {
|
|
|
12650
10314
|
* and full stop, the full-width ! , : ; ? and brackets, the corner quotes, the Arabic comma, semicolon and question
|
|
12651
10315
|
* mark, the Urdu full stop. No address holds one as typed, so a link stops at the first.
|
|
12652
10316
|
*/
|
|
12653
|
-
var
|
|
10317
|
+
var LINK_STOP_CHARS = "、。〈-】!(),:;?،؛؟۔";
|
|
10318
|
+
var LINK_STOP = new RegExp(`[${LINK_STOP_CHARS}]`);
|
|
12654
10319
|
/** What a link leaves out at its end: a sentence's punctuation ("…", "»", "”" too), never a path's "/". */
|
|
12655
10320
|
var LINK_TRAILING = /[.,;:!?'"*_>…»’”]/;
|
|
12656
10321
|
/**
|
|
12657
10322
|
* What a chat puts right after a link with no space and no address ends with: an emoji ("https://x.example/a🔥", with
|
|
12658
|
-
* its skin tone, presentation selector, joiners and flag tags) and characters that draw as nothing
|
|
12659
|
-
*
|
|
10323
|
+
* its skin tone, presentation selector, joiners and flag tags) and characters that draw as nothing, the direction marks
|
|
10324
|
+
* and isolates a right-to-left sentence puts around a link among them. Read one code point at a time from the end, so
|
|
10325
|
+
* an emoji inside an address stays in it.
|
|
12660
10326
|
*/
|
|
12661
|
-
var LINK_TAIL = /^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|[\u200b\u200c\u2060\ufeff\u{e0020}-\u{e007f}]|\u200d|\ufe0e|\ufe0f)$/u;
|
|
10327
|
+
var LINK_TAIL = /^(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|[\u200b\u200c\u2060\ufeff\u{e0020}-\u{e007f}]|[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]|\u200d|\ufe0e|\ufe0f)$/u;
|
|
10328
|
+
/** The direction marks and isolates alone: a payment link, which keeps an emoji at its end, still ends before these. */
|
|
10329
|
+
var DIRECTION_TAIL = /^[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]$/;
|
|
12662
10330
|
/** How many UTF-16 units of `url` before `end` are an emoji's or an invisible character's last code point (0: none). */
|
|
12663
10331
|
function linkTail(url, end) {
|
|
12664
10332
|
const units = end > 1 && /[\udc00-\udfff]/.test(url[end - 1]) && /[\ud800-\udbff]/.test(url[end - 2]) ? 2 : 1;
|
|
12665
10333
|
return end > 0 && LINK_TAIL.test(url.slice(end - units, end)) ? units : 0;
|
|
12666
10334
|
}
|
|
10335
|
+
function directionTail(url, end) {
|
|
10336
|
+
return end > 0 && DIRECTION_TAIL.test(url[end - 1]) ? 1 : 0;
|
|
10337
|
+
}
|
|
12667
10338
|
/** A link up to the first `LINK_STOP`: "https://x.example/a。" opens /a, not /a%E3%80%82. */
|
|
12668
10339
|
function linkStop(url) {
|
|
12669
10340
|
const at = url.search(LINK_STOP);
|
|
@@ -12679,7 +10350,8 @@ function linkEnd(whole) {
|
|
|
12679
10350
|
}
|
|
12680
10351
|
/**
|
|
12681
10352
|
* A payment link (`bitcoin:`, `monero:`…) ends as a web link does, but keeps an emoji at its end: its label or message
|
|
12682
|
-
* is text written as it is ("…&label=Pizza 🍕"), cut at 140 characters wherever that falls.
|
|
10353
|
+
* is text written as it is ("…&label=Pizza 🍕"), cut at 140 characters wherever that falls. A direction mark or
|
|
10354
|
+
* isolate typed after it is still left out, so "bitcoin:bc1q…\u200f." pays bc1q….
|
|
12683
10355
|
*/
|
|
12684
10356
|
function uriEnd(whole) {
|
|
12685
10357
|
return trimEnd(whole, false);
|
|
@@ -12699,7 +10371,7 @@ function trimEnd(whole, tails) {
|
|
|
12699
10371
|
while (end > 0) {
|
|
12700
10372
|
const last = url[end - 1];
|
|
12701
10373
|
const opener = LINK_CLOSERS[last];
|
|
12702
|
-
const tail = tails ? linkTail(url, end) :
|
|
10374
|
+
const tail = tails ? linkTail(url, end) : directionTail(url, end);
|
|
12703
10375
|
if (tail) {
|
|
12704
10376
|
end -= tail;
|
|
12705
10377
|
continue;
|
|
@@ -12712,9 +10384,14 @@ function trimEnd(whole, tails) {
|
|
|
12712
10384
|
}
|
|
12713
10385
|
/** Characters of a link worth reading: a longer one is no address anyone shares, and is left as text. */
|
|
12714
10386
|
var LINK_MAX_CHARS = 4096;
|
|
10387
|
+
/**
|
|
10388
|
+
* An http(s) link's run in a text, as a `RegExp` source: up to a space or a `LINK_STOP_CHARS` character, as the bubble
|
|
10389
|
+
* reads it. A link written right after another one's "。" or "،", with no space, is a run of its own.
|
|
10390
|
+
*/
|
|
10391
|
+
var LINK_RUN = String.raw`https?:\/\/[^\s${LINK_STOP_CHARS}]+`;
|
|
12715
10392
|
/** The http(s) links of a text, in order, each ending as the bubble ends it. */
|
|
12716
10393
|
function linksIn(text) {
|
|
12717
|
-
return [...text.matchAll(
|
|
10394
|
+
return [...text.matchAll(new RegExp(LINK_RUN, "gi"))].filter((match) => match[0].length <= LINK_MAX_CHARS).map((match) => linkEnd(match[0])).filter((url) => url.length > 8);
|
|
12718
10395
|
}
|
|
12719
10396
|
/**
|
|
12720
10397
|
* The link as a preview names it: parsed, http(s) only, without tracking parameters (`utm_*`, `fbclid`, …). The
|
|
@@ -14215,7 +11892,7 @@ var DhtDelivery = class DhtDelivery {
|
|
|
14215
11892
|
const id = dhtFileId(file.wireId);
|
|
14216
11893
|
if (reply !== void 0 && !REPLY_TO.test(reply)) reply = void 0;
|
|
14217
11894
|
const error = this.validate(file.name, timestamp, id);
|
|
14218
|
-
if (error) return error ===
|
|
11895
|
+
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;
|
|
14219
11896
|
const now = Date.now(), pending = this.state.pending;
|
|
14220
11897
|
if (pending?.message[0] === id && pending.expires > now) return pending;
|
|
14221
11898
|
const message = [
|
|
@@ -15369,7 +13046,7 @@ var TransportSwitch = class {
|
|
|
15369
13046
|
remoteReplaces = false;
|
|
15370
13047
|
/** This side chose while no session was open: the next one begins with it as a choice. */
|
|
15371
13048
|
apart = false;
|
|
15372
|
-
policiesRead = new RateWindow(
|
|
13049
|
+
policiesRead = new RateWindow(30, POLICY_RECEIVE_WINDOW_MS);
|
|
15373
13050
|
/** The session on which the contact's policy, the one read already, was said again and read for free (`handle`). */
|
|
15374
13051
|
repeatRead = "";
|
|
15375
13052
|
policyHeld = null;
|
|
@@ -19483,6 +17160,19 @@ function storeFailure(error) {
|
|
|
19483
17160
|
const message = (error instanceof Error ? error.message : String(error)).trim();
|
|
19484
17161
|
return `Could not store the file: ${error?.name === "QuotaExceededError" && !message.startsWith("QuotaExceededError") ? `QuotaExceededError${message ? `: ${message}` : ""}` : message}`;
|
|
19485
17162
|
}
|
|
17163
|
+
/**
|
|
17164
|
+
* The room this device tells a contact (`pf-room`, a `no-room` refusal): its free space rounded down to a power of two or
|
|
17165
|
+
* one and a half of one. The exact bytes would be the same from every profile on the device, and move with whatever it
|
|
17166
|
+
* stores, so a contact could tell one device from another, or watch it, by asking. Never more than the room itself.
|
|
17167
|
+
*/
|
|
17168
|
+
function coarseRoom(room) {
|
|
17169
|
+
if (!Number.isSafeInteger(room)) return null;
|
|
17170
|
+
if (room <= 0) return 0;
|
|
17171
|
+
let step = 2 ** Math.floor(Math.log2(room));
|
|
17172
|
+
while (step > room) step /= 2;
|
|
17173
|
+
while (step * 2 <= room) step *= 2;
|
|
17174
|
+
return room >= step * 1.5 ? step * 1.5 : step;
|
|
17175
|
+
}
|
|
19486
17176
|
/** What a refusal means to the sender's person. */
|
|
19487
17177
|
function refusalText(why, room) {
|
|
19488
17178
|
switch (why) {
|
|
@@ -19736,9 +17426,19 @@ var ChatFiles = class {
|
|
|
19736
17426
|
}
|
|
19737
17427
|
async sayRoom() {
|
|
19738
17428
|
const room = await this.host.room?.().catch(() => null);
|
|
19739
|
-
|
|
17429
|
+
const max = typeof room === "number" ? coarseRoom(room) : null;
|
|
17430
|
+
if (max !== null) this.send({
|
|
19740
17431
|
t: "pf-room",
|
|
19741
|
-
max
|
|
17432
|
+
max
|
|
17433
|
+
});
|
|
17434
|
+
}
|
|
17435
|
+
refuseOffer(id, decision) {
|
|
17436
|
+
const room = decision.room !== void 0 ? coarseRoom(decision.room) : null;
|
|
17437
|
+
this.send({
|
|
17438
|
+
t: "pf-refuse",
|
|
17439
|
+
id,
|
|
17440
|
+
why: decision.refuse,
|
|
17441
|
+
...room !== null && { room }
|
|
19742
17442
|
});
|
|
19743
17443
|
}
|
|
19744
17444
|
/** A new file to send: offered now if a session is open, or on the next one. */
|
|
@@ -20162,12 +17862,7 @@ var ChatFiles = class {
|
|
|
20162
17862
|
}
|
|
20163
17863
|
if (this.entries.has(key("in", id))) return;
|
|
20164
17864
|
if (typeof decision === "object") {
|
|
20165
|
-
this.
|
|
20166
|
-
t: "pf-refuse",
|
|
20167
|
-
id,
|
|
20168
|
-
why: decision.refuse,
|
|
20169
|
-
...decision.room !== void 0 && { room: decision.room }
|
|
20170
|
-
});
|
|
17865
|
+
this.refuseOffer(id, decision);
|
|
20171
17866
|
return;
|
|
20172
17867
|
}
|
|
20173
17868
|
const entry = {
|
|
@@ -20221,12 +17916,7 @@ var ChatFiles = class {
|
|
|
20221
17916
|
decision = { refuse: "invalid" };
|
|
20222
17917
|
}
|
|
20223
17918
|
if (typeof decision === "object") {
|
|
20224
|
-
this.
|
|
20225
|
-
t: "pf-refuse",
|
|
20226
|
-
id: record.id,
|
|
20227
|
-
why: decision.refuse,
|
|
20228
|
-
...decision.room !== void 0 && { room: decision.room }
|
|
20229
|
-
});
|
|
17919
|
+
this.refuseOffer(record.id, decision);
|
|
20230
17920
|
return false;
|
|
20231
17921
|
}
|
|
20232
17922
|
if (decision === "ask") {
|
|
@@ -22025,6 +19715,7 @@ var ENGINE_ERRORS = {
|
|
|
22025
19715
|
ecashBeingReceived: "This ecash is already being received",
|
|
22026
19716
|
ecashFeeTakesAll: "The mint keeps all {amount} sats of this ecash as its fee to take it in: nothing was redeemed, and its sender can still take it back",
|
|
22027
19717
|
ecashOtherUnit: "This ecash is in {unit}: only sat ecash can be redeemed here",
|
|
19718
|
+
ecashUnnamedUnit: "This ecash is in another unit: only sat ecash can be redeemed here",
|
|
22028
19719
|
reviewedEcashSpent: "The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.",
|
|
22029
19720
|
reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.",
|
|
22030
19721
|
mintFailedQuote: "{host} could not take this payment right now, and no sats left your wallet: try again later. The mint said: {reason}",
|
|
@@ -22100,12 +19791,19 @@ function engineText(code, values = {}) {
|
|
|
22100
19791
|
return ENGINE_ERRORS[code].replace(/\{(\w+)\}/g, (_, name) => name in values ? String(values[name]) : `{${name}}`);
|
|
22101
19792
|
}
|
|
22102
19793
|
var engineError = (code, values) => new EngineError(code, values);
|
|
19794
|
+
/** A unit as the app names it: a unit's shape (`frames.ts` `isUnit`, in any case), never a token sender's other text. */
|
|
19795
|
+
var NAMED_UNIT = "[A-Za-z0-9]{1,12}";
|
|
19796
|
+
/**
|
|
19797
|
+
* Why ecash of `unit` is not redeemed here. The unit is named only when it looks like one: a token's unit is whatever
|
|
19798
|
+
* its sender wrote, and the line is the app's own (a contact's payment's refusal row, the CLI's answer).
|
|
19799
|
+
*/
|
|
19800
|
+
var ecashUnitError = (unit) => new RegExp(`^${NAMED_UNIT}$`).test(unit) ? engineError("ecashOtherUnit", { unit }) : engineError("ecashUnnamedUnit");
|
|
22103
19801
|
/** What each kind of value looks like in a text: never a space in a host, a network by its name, an amount as digits. */
|
|
22104
19802
|
var VALUE = {
|
|
22105
19803
|
host: "(\\S+)",
|
|
22106
19804
|
domain: "(\\S+)",
|
|
22107
19805
|
chain: "(\\S+)",
|
|
22108
|
-
unit:
|
|
19806
|
+
unit: `(${NAMED_UNIT})`,
|
|
22109
19807
|
network: "(Mainnet|Testnet)",
|
|
22110
19808
|
amount: "(\\d[\\d.,\\u00a0\\u202f' ]*?)",
|
|
22111
19809
|
fee: "(\\d[\\d.,\\u00a0\\u202f' ]*?)",
|
|
@@ -22440,6 +20138,44 @@ var MESSAGE_RECEIVE_LIMITS = {
|
|
|
22440
20138
|
hourly: 1800,
|
|
22441
20139
|
hourWindowMs: 36e5
|
|
22442
20140
|
};
|
|
20141
|
+
/** What `sendMessage` says of a text the contact's windows have no room for yet: it did not go (`MessagePace`). */
|
|
20142
|
+
var MESSAGE_PACED = "Your contact takes a limited number of texts at a time. It goes by itself once they can take more.";
|
|
20143
|
+
/** How long a text sent with no receipt yet counts as taken past its send: one in flight is taken when it lands. */
|
|
20144
|
+
var PACE_UNANSWERED_MS = 6e4;
|
|
20145
|
+
/**
|
|
20146
|
+
* The texts this side sent on a paired session, counted against the contact's windows (`MESSAGE_RECEIVE_LIMITS`), so
|
|
20147
|
+
* none goes that the contact would refuse. A refused text went unconfirmed and came again with the outbox's backoff,
|
|
20148
|
+
* after texts written later that found room meanwhile: the contact read them out of order. Past the hour's total it
|
|
20149
|
+
* was sent until its attempts ran out, well inside the hour, and ended failed. Each counts from its receipt, the latest
|
|
20150
|
+
* the contact can have taken it: counted from its send, a frame that sat in a queue was taken later than counted.
|
|
20151
|
+
*/
|
|
20152
|
+
var MessagePace = class {
|
|
20153
|
+
now;
|
|
20154
|
+
sent = [];
|
|
20155
|
+
constructor(now = Date.now) {
|
|
20156
|
+
this.now = now;
|
|
20157
|
+
}
|
|
20158
|
+
/** The contact's windows have room for one more text now. */
|
|
20159
|
+
room() {
|
|
20160
|
+
const now = this.now(), { burst, burstWindowMs, hourly, hourWindowMs } = MESSAGE_RECEIVE_LIMITS;
|
|
20161
|
+
const counts = (entry, windowMs) => entry.answered !== void 0 ? now - entry.answered < windowMs : now - entry.at < windowMs + PACE_UNANSWERED_MS;
|
|
20162
|
+
this.sent = this.sent.filter((entry) => counts(entry, hourWindowMs));
|
|
20163
|
+
return this.sent.length < hourly && this.sent.filter((entry) => counts(entry, burstWindowMs)).length < burst;
|
|
20164
|
+
}
|
|
20165
|
+
took(id) {
|
|
20166
|
+
this.sent.push({
|
|
20167
|
+
id,
|
|
20168
|
+
at: this.now()
|
|
20169
|
+
});
|
|
20170
|
+
}
|
|
20171
|
+
/** Its receipt came: the contact counted it by now. */
|
|
20172
|
+
answered(id) {
|
|
20173
|
+
for (let i = this.sent.length - 1; i >= 0; i--) if (this.sent[i].id === id && this.sent[i].answered === void 0) {
|
|
20174
|
+
this.sent[i].answered = this.now();
|
|
20175
|
+
return;
|
|
20176
|
+
}
|
|
20177
|
+
}
|
|
20178
|
+
};
|
|
22443
20179
|
/**
|
|
22444
20180
|
* A `paired-message` frame. The preview (`pv`) is left out when the frame would pass `MAX_PAIRED_MESSAGE_FRAME`
|
|
22445
20181
|
* with it: the text matters, the card does not. A reply (`r`, WISP 401 § Replies) is a few hundred bytes at most
|
|
@@ -22663,6 +20399,8 @@ var GhostLink = class {
|
|
|
22663
20399
|
editsReceived = new RateWindow(30, EDIT_RATE_WINDOW_MS);
|
|
22664
20400
|
/** Text frames the contact may send per window (`MESSAGE_RECEIVE_LIMITS`); the rest go unconfirmed and come again. */
|
|
22665
20401
|
messagesReceived = [new RateWindow(MESSAGE_RECEIVE_LIMITS.burst, MESSAGE_RECEIVE_LIMITS.burstWindowMs), new RateWindow(MESSAGE_RECEIVE_LIMITS.hourly, MESSAGE_RECEIVE_LIMITS.hourWindowMs)];
|
|
20402
|
+
/** The texts sent to the contact, against their `messagesReceived` (`MessagePace`). */
|
|
20403
|
+
messagesSent = new MessagePace();
|
|
22666
20404
|
/** Call signals the contact may send per window; the rest are dropped. */
|
|
22667
20405
|
callsReceived = new RateWindow(150, CALL_RATE_WINDOW_MS);
|
|
22668
20406
|
/** WebRTC signals the contact may send on the session (`paired-rtc`) per window; the rest are dropped. */
|
|
@@ -23532,6 +21270,10 @@ var GhostLink = class {
|
|
|
23532
21270
|
get canSendText() {
|
|
23533
21271
|
return this.textDelivery !== "unavailable";
|
|
23534
21272
|
}
|
|
21273
|
+
/** A text on the live session would find room in the contact's windows now (`MessagePace`); the DHT floor has its own pace. */
|
|
21274
|
+
get textRoom() {
|
|
21275
|
+
return this.textDelivery !== "stream" || this.messagesSent.room();
|
|
21276
|
+
}
|
|
23535
21277
|
get dhtDelivery() {
|
|
23536
21278
|
return this.dht?.view;
|
|
23537
21279
|
}
|
|
@@ -23588,11 +21330,11 @@ var GhostLink = class {
|
|
|
23588
21330
|
if (this.myPubKeyZ32 > this.options.params.peerPubKeyZ32) this.session.presenceDue();
|
|
23589
21331
|
this.session.start();
|
|
23590
21332
|
}
|
|
23591
|
-
await this.dht.setMode(mode);
|
|
23592
21333
|
if (mode === "dht") {
|
|
23593
21334
|
await this.session.stop(false);
|
|
23594
21335
|
await Promise.allSettled([...this.endpoints.keys()].map((t) => this.releaseEndpoint(t)));
|
|
23595
21336
|
}
|
|
21337
|
+
await this.dht.setMode(mode);
|
|
23596
21338
|
this.streamBlockChanged();
|
|
23597
21339
|
this.emitDeliveryState();
|
|
23598
21340
|
}
|
|
@@ -25041,9 +22783,11 @@ var GhostLink = class {
|
|
|
25041
22783
|
if (!/^[A-Za-z0-9_-]{22}$/.test(id)) return "Invalid message ID";
|
|
25042
22784
|
const frame = pairedMessageFrame(id, timestamp, trimmed, preview, reply, forwarded, card);
|
|
25043
22785
|
if (frame.length > 61440) return PAIRED_FRAME_TOO_LARGE;
|
|
22786
|
+
if (!this.messagesSent.room()) return MESSAGE_PACED;
|
|
25044
22787
|
this.pairedPending.set(id, timestamp);
|
|
25045
22788
|
try {
|
|
25046
22789
|
this.channel.send(frame);
|
|
22790
|
+
this.messagesSent.took(id);
|
|
25047
22791
|
return null;
|
|
25048
22792
|
} catch {
|
|
25049
22793
|
this.pairedPending.delete(id);
|
|
@@ -25833,6 +23577,17 @@ var GhostLink = class {
|
|
|
25833
23577
|
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]);
|
|
25834
23578
|
return "Edits go when you are live";
|
|
25835
23579
|
}
|
|
23580
|
+
/**
|
|
23581
|
+
* Why the DHT floor can never carry this edit, or null (WISP 403 § Edits): it goes there as a text with the edit's
|
|
23582
|
+
* element, which must fit the packet once sealed, as a text must (`validateText`). One past the 256 bytes never fits
|
|
23583
|
+
* it either, and says so with the same reason. Null off the floor, and for what only makes it wait there (a text
|
|
23584
|
+
* awaiting its receipt): that one goes in its turn.
|
|
23585
|
+
*/
|
|
23586
|
+
dhtEditTooBig(edit) {
|
|
23587
|
+
if (this.isDataLinkOpen || this.textDelivery !== "dht") return null;
|
|
23588
|
+
const error = this.dht.validate(edit.m, edit.ts, dhtEditId(edit.id, edit.e), void 0, [edit.id, edit.e]);
|
|
23589
|
+
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;
|
|
23590
|
+
}
|
|
25836
23591
|
/** Confirms an edit of the contact's that waited for its message (`onMessageEdit` returned false). */
|
|
25837
23592
|
confirmEdit(id, e) {
|
|
25838
23593
|
if (!this.channel || !this.supportsEdits) return;
|
|
@@ -27193,6 +24948,7 @@ var GhostLink = class {
|
|
|
27193
24948
|
id: frame.id
|
|
27194
24949
|
}));
|
|
27195
24950
|
} else if (frame.t === "paired-received") {
|
|
24951
|
+
this.messagesSent.answered(frame.id);
|
|
27196
24952
|
if (this.pairedPending.get(frame.id) !== void 0) {
|
|
27197
24953
|
await this.options.events?.onMessageReceipt?.(frame.id);
|
|
27198
24954
|
await this.dht?.acknowledge(frame.id);
|
|
@@ -30425,20 +28181,20 @@ var REDIRECTS = [
|
|
|
30425
28181
|
308
|
|
30426
28182
|
];
|
|
30427
28183
|
/**
|
|
30428
|
-
* A host that is not on the public internet, as far as its name tells: this machine, a single label,
|
|
30429
|
-
*
|
|
30430
|
-
* itself, as Ghostly Desktop
|
|
28184
|
+
* A host that is not on the public internet, as far as its name tells: this machine, a single label, a name under a
|
|
28185
|
+
* local suffix (`localNames.ts`), private and reserved IP addresses. (What a public name resolves to is checked where
|
|
28186
|
+
* the client resolves names itself, as Ghostly Desktop and the CLI do, for every request.)
|
|
30431
28187
|
*/
|
|
30432
28188
|
function isLocalHost(hostname) {
|
|
30433
|
-
const host = hostname.toLowerCase().replace(
|
|
28189
|
+
const host = hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
|
|
30434
28190
|
if (!host.includes(".") && !host.includes(":")) return true;
|
|
30435
|
-
if (
|
|
28191
|
+
if (underLocalSuffix(host)) return true;
|
|
30436
28192
|
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
30437
28193
|
if (v4) {
|
|
30438
28194
|
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
30439
28195
|
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;
|
|
30440
28196
|
}
|
|
30441
|
-
if (host.includes(":")) return !/^[23][0-9a-f]{
|
|
28197
|
+
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);
|
|
30442
28198
|
return false;
|
|
30443
28199
|
}
|
|
30444
28200
|
var isLoopback = (hostname) => [
|
|
@@ -30558,6 +28314,7 @@ async function readBounded(response, maxBytes) {
|
|
|
30558
28314
|
/** One GET to an LNURL service (and to each checked redirect of it): bounded in time and size, no credentials, no referrer, and the answer must be JSON. */
|
|
30559
28315
|
async function fetchLnurlJson(url, options = {}) {
|
|
30560
28316
|
const target = acceptUrl(url);
|
|
28317
|
+
if (!isLoopback(target.hostname) && isLocalHost(target.hostname)) throw new Error(`${target.host} is a local address`);
|
|
30561
28318
|
const doFetch = options.fetch ?? globalThis.fetch;
|
|
30562
28319
|
if (!doFetch) throw new Error("No way to reach the network here");
|
|
30563
28320
|
const controller = new AbortController();
|
|
@@ -34877,7 +32634,8 @@ var GroupSession = class {
|
|
|
34877
32634
|
adminSeen;
|
|
34878
32635
|
/**
|
|
34879
32636
|
* After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
|
|
34880
|
-
* one of theirs I signed again (what I held then, until one of theirs comes).
|
|
32637
|
+
* one of theirs I signed again (what I held then, until one of theirs comes). `vouched`: the latest of theirs another
|
|
32638
|
+
* member's sync said it holds; `held`: the latest of theirs no other member has shown it holds yet. In memory only.
|
|
34881
32639
|
*/
|
|
34882
32640
|
takeover;
|
|
34883
32641
|
/** While `handle` runs: the frames it took that a hub passes on (`handle`'s result). */
|
|
@@ -35803,11 +33561,12 @@ var GroupSession = class {
|
|
|
35803
33561
|
* My message `id` was deleted for everyone: its frame, and each copy said again, keep their place in my log (`nextSeq`,
|
|
35804
33562
|
* `couldRead`, the removal's copies) and lose what they said. The log is in the saved state beside the epochs' secrets,
|
|
35805
33563
|
* so the text stayed readable from the profile until 32 later sends pushed it out (`message delete --purge` promises
|
|
35806
|
-
* it leaves the folder).
|
|
33564
|
+
* it leaves the folder). A reply of mine that quotes it keeps its place and its reply, its line sealed again empty
|
|
33565
|
+
* and signed whole again (`sig` does not cover the box). A member's frame of it, or quoting it, I kept to hand on goes:
|
|
33566
|
+
* I cannot sign theirs, and its author hands it on. Saved soon, as a community's `forget`; `flush` writes it now.
|
|
35807
33567
|
*/
|
|
35808
33568
|
forget(id) {
|
|
35809
|
-
|
|
35810
|
-
this.state.sent = this.state.sent.map((f) => !f.c || this.messageIdOf(f) !== id ? f : {
|
|
33569
|
+
const sent = this.state.sent.map((f) => !f.c ? f : this.messageIdOf(f) === id ? {
|
|
35811
33570
|
t: f.t,
|
|
35812
33571
|
g: f.g,
|
|
35813
33572
|
e: f.e,
|
|
@@ -35818,9 +33577,37 @@ var GroupSession = class {
|
|
|
35818
33577
|
c: "",
|
|
35819
33578
|
sig: "",
|
|
35820
33579
|
...f.o ? { o: f.o } : {}
|
|
35821
|
-
});
|
|
33580
|
+
} : this.unquoted(f, id));
|
|
33581
|
+
const gone = (f) => this.messageIdOf(f) === id || !!this.quoting(f, id);
|
|
33582
|
+
const relay = this.state.relay?.filter((f) => !gone(f)), rows = this.onRows?.filter((f) => !gone(f));
|
|
33583
|
+
if (sent.every((f, i) => f === this.state.sent[i]) && relay?.length === this.state.relay?.length && rows?.length === this.onRows?.length) return;
|
|
33584
|
+
this.state.sent = sent;
|
|
33585
|
+
if (relay) this.state.relay = relay;
|
|
33586
|
+
if (rows) this.onRows = rows;
|
|
35822
33587
|
this.persistSoon();
|
|
35823
33588
|
}
|
|
33589
|
+
/** The reply a frame's box holds, when it quotes `id` with a line of it. */
|
|
33590
|
+
quoting(f, id) {
|
|
33591
|
+
const secret = f.r && this.secret(f.e), reply = secret ? this.openReply(epochKeys(secret, this.id, f.e).message, f) : void 0;
|
|
33592
|
+
return reply?.i === id && reply.s ? reply : void 0;
|
|
33593
|
+
}
|
|
33594
|
+
/** My frame `f` without the line of `id` it quotes (`forget`); `f` itself when it quotes none. */
|
|
33595
|
+
unquoted(f, id) {
|
|
33596
|
+
const reply = this.quoting(f, id);
|
|
33597
|
+
if (!reply) return f;
|
|
33598
|
+
const r = encryptText(epochKeys(this.secret(f.e), this.id, f.e).message, replyAad(f), JSON.stringify({
|
|
33599
|
+
...reply,
|
|
33600
|
+
s: ""
|
|
33601
|
+
}));
|
|
33602
|
+
return {
|
|
33603
|
+
...f,
|
|
33604
|
+
r,
|
|
33605
|
+
xs: toBase64Url(sign(messageSignedWhole({
|
|
33606
|
+
...f,
|
|
33607
|
+
r
|
|
33608
|
+
}), this.identity.seed))
|
|
33609
|
+
};
|
|
33610
|
+
}
|
|
35824
33611
|
/**
|
|
35825
33612
|
* Saves, then sends my frame to every other member of its epoch still in the group (`saved`: the caller saved it). One no edge took (none was up:
|
|
35826
33613
|
* my app just opened) is remembered (`alone`): I may be behind on the chain without knowing, and members let in
|
|
@@ -36834,6 +34621,7 @@ var GroupSession = class {
|
|
|
36834
34621
|
if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(GROUP_LIMITS.syncAnswers, GROUP_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
|
|
36835
34622
|
if (!answered.take()) return;
|
|
36836
34623
|
this.hear(frame);
|
|
34624
|
+
await this.vouch(from, frame.mt);
|
|
36837
34625
|
if (frame.e > this.epoch) {
|
|
36838
34626
|
this.syncedEpoch.set(from, frame.e);
|
|
36839
34627
|
if (!this.awaitsAnswer(from)) this.ask(from);
|
|
@@ -37038,7 +34826,8 @@ var GroupSession = class {
|
|
|
37038
34826
|
const opened = openGroupMeta(frame, epochKeys(secret, this.id, frame.k).message);
|
|
37039
34827
|
if (!opened) return;
|
|
37040
34828
|
if (taking) {
|
|
37041
|
-
await this.signAgainTaken(opened.meta, opened.body);
|
|
34829
|
+
if (this.vouches(from, s)) await this.signAgainTaken(opened.meta, opened.body);
|
|
34830
|
+
else this.holdTaken(from, raw, s);
|
|
37042
34831
|
return;
|
|
37043
34832
|
}
|
|
37044
34833
|
const before = this.state.meta;
|
|
@@ -37067,6 +34856,39 @@ var GroupSession = class {
|
|
|
37067
34856
|
return !!t && this.isAdmin && s.by === t.from && this.clock() <= t.until && groupMetaNewer(s, t.base);
|
|
37068
34857
|
}
|
|
37069
34858
|
/**
|
|
34859
|
+
* Whether a statement I would take (`takesOver`) was on its way when the role moved, as far as I can tell: a member
|
|
34860
|
+
* 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.
|
|
34861
|
+
* The former admin alone could sign new ones after the hand-over, each taken for the whole group.
|
|
34862
|
+
*/
|
|
34863
|
+
vouches(from, s) {
|
|
34864
|
+
const v = this.takeover?.vouched;
|
|
34865
|
+
return from !== s.by || !!v && v.e === s.e && v.r >= s.r;
|
|
34866
|
+
}
|
|
34867
|
+
/** The former admin's statement nobody else has shown it holds: the latest is kept until a sync does (`vouch`). */
|
|
34868
|
+
holdTaken(from, raw, s) {
|
|
34869
|
+
const t = this.takeover;
|
|
34870
|
+
if (!t.held || groupMetaNewer(s, t.held.s)) t.held = {
|
|
34871
|
+
from,
|
|
34872
|
+
raw,
|
|
34873
|
+
s
|
|
34874
|
+
};
|
|
34875
|
+
}
|
|
34876
|
+
/**
|
|
34877
|
+
* A member's sync names the statement it holds: one signed under a commit of the admin before me, by another member
|
|
34878
|
+
* than them, vouches for theirs up to it, and the one held is taken if it now is.
|
|
34879
|
+
*/
|
|
34880
|
+
async vouch(from, tag) {
|
|
34881
|
+
const t = this.takeover, v = parseGroupMetaTag(tag);
|
|
34882
|
+
if (!t || !v || from === t.from || !this.state.chain[v.e] || rosterAdmin(this.state.chain[v.e].m) !== t.from) return;
|
|
34883
|
+
if (t.vouched && !groupMetaNewer(v, t.vouched)) return;
|
|
34884
|
+
t.vouched = v;
|
|
34885
|
+
const held = t.held;
|
|
34886
|
+
if (held && this.vouches(held.from, held.s)) {
|
|
34887
|
+
t.held = void 0;
|
|
34888
|
+
await this.receiveMeta(held.from, held.raw);
|
|
34889
|
+
}
|
|
34890
|
+
}
|
|
34891
|
+
/**
|
|
37070
34892
|
* The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
|
|
37071
34893
|
* value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
|
|
37072
34894
|
*/
|
|
@@ -37819,7 +35641,7 @@ var MESSAGE_BURST = {
|
|
|
37819
35641
|
frames: COMMUNITY_LIMITS.store + COMMUNITY_LIMITS.lasting,
|
|
37820
35642
|
bytes: COMMUNITY_LIMITS.storeBytes + COMMUNITY_LIMITS.lasting * COMMUNITY_LIMITS.textBytes * 2
|
|
37821
35643
|
};
|
|
37822
|
-
var MessagePace = class {
|
|
35644
|
+
var MessagePace$1 = class {
|
|
37823
35645
|
frames = MESSAGE_BURST.frames;
|
|
37824
35646
|
bytes = MESSAGE_BURST.bytes;
|
|
37825
35647
|
at;
|
|
@@ -37959,6 +35781,23 @@ function isMessageFrame(v) {
|
|
|
37959
35781
|
const f = v;
|
|
37960
35782
|
return f.t === "group-msg" && f.v === 2 && typeof f.g === "string" && GROUP_ID.test(f.g) && Number.isSafeInteger(f.e) && f.e >= 0 && typeof f.h === "string" && /^[a-f0-9]{16}$/.test(f.h) && typeof f.s === "string" && MEMBER_KEY.test(f.s) && Number.isSafeInteger(f.n) && f.n >= 0 && Number.isSafeInteger(f.ts) && f.ts > 0 && typeof f.nn === "string" && f.nn.length === 32 && B64.test(f.nn) && typeof f.c === "string" && f.c.length <= MAX_TEXT_BOX && B64.test(f.c) && typeof f.sig === "string" && f.sig.length === 86 && B64.test(f.sig);
|
|
37961
35783
|
}
|
|
35784
|
+
/** A message frame's own fields alone: whatever else came beside them is outside its author's signature, so no member's word, and is neither kept nor handed on. */
|
|
35785
|
+
function messageFields(f) {
|
|
35786
|
+
const { t, v, g, e, h, s, n, ts, nn, c, sig } = f;
|
|
35787
|
+
return {
|
|
35788
|
+
t,
|
|
35789
|
+
v,
|
|
35790
|
+
g,
|
|
35791
|
+
e,
|
|
35792
|
+
h,
|
|
35793
|
+
s,
|
|
35794
|
+
n,
|
|
35795
|
+
ts,
|
|
35796
|
+
nn,
|
|
35797
|
+
c,
|
|
35798
|
+
sig
|
|
35799
|
+
};
|
|
35800
|
+
}
|
|
37962
35801
|
/**
|
|
37963
35802
|
* One member's view of a community group: the branch it follows and the ones it knows, the
|
|
37964
35803
|
* secrets it holds, what it has seen, and the recent frames it keeps for others.
|
|
@@ -38019,7 +35858,8 @@ var CommunitySession = class CommunitySession {
|
|
|
38019
35858
|
adminSeen;
|
|
38020
35859
|
/**
|
|
38021
35860
|
* After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
|
|
38022
|
-
* one of theirs I signed again (what I held then, until one of theirs comes).
|
|
35861
|
+
* one of theirs I signed again (what I held then, until one of theirs comes). `vouched`: the latest of theirs another
|
|
35862
|
+
* member's sync said it holds; `held`: the latest of theirs no other member has shown it holds yet. In memory only.
|
|
38023
35863
|
*/
|
|
38024
35864
|
takeover;
|
|
38025
35865
|
/** The store's frames the app holds with their messages (`storeKey` → message id): in memory here, not in what is saved. */
|
|
@@ -38045,6 +35885,7 @@ var CommunitySession = class CommunitySession {
|
|
|
38045
35885
|
});
|
|
38046
35886
|
this.rebuild();
|
|
38047
35887
|
this.pruneSeen();
|
|
35888
|
+
if (hooks.removed && this.unquote((id) => hooks.removed(id))) this.persistSoon();
|
|
38048
35889
|
this.adminSeen = this.admin;
|
|
38049
35890
|
if ((state.status === "active" || state.status === "lost") && this.bestBranch().tip !== this.topHash) this.serialize(() => this.chooseBranch());
|
|
38050
35891
|
}
|
|
@@ -39706,11 +37547,74 @@ var CommunitySession = class CommunitySession {
|
|
|
39706
37547
|
forget(id) {
|
|
39707
37548
|
const author = id.slice(0, id.indexOf(":"));
|
|
39708
37549
|
const kept = this.state.store.filter((f) => f.s !== author || this.storedId(f) !== id);
|
|
39709
|
-
|
|
39710
|
-
|
|
39711
|
-
|
|
39712
|
-
|
|
39713
|
-
|
|
37550
|
+
const dropped = kept.length !== this.state.store.length;
|
|
37551
|
+
if (dropped) {
|
|
37552
|
+
const left = new Set(kept.map(storeKey));
|
|
37553
|
+
for (const f of this.state.store) if (!left.has(storeKey(f))) this.onRows.delete(storeKey(f));
|
|
37554
|
+
this.state.store = kept;
|
|
37555
|
+
}
|
|
37556
|
+
if (this.unquote((quoted) => quoted === id) || dropped) this.persistSoon();
|
|
37557
|
+
}
|
|
37558
|
+
/**
|
|
37559
|
+
* The frames whose reply quotes a message deleted for everyone (`gone`): the line of it (`r.s`) is sealed with them,
|
|
37560
|
+
* and opens with the epoch secret this profile keeps. Mine is sealed again with an empty line, in its place, time and
|
|
37561
|
+
* reply, and signed again: a member who holds the first drops it as seen, one who missed it gets the reply without
|
|
37562
|
+
* the line. A member's I cannot sign again: it goes, and its author hands it on. Either way the row that held the
|
|
37563
|
+
* first gives it up; mine is saved with the state from then on.
|
|
37564
|
+
*/
|
|
37565
|
+
unquote(gone) {
|
|
37566
|
+
let changed = false;
|
|
37567
|
+
const store = [];
|
|
37568
|
+
for (const f of this.state.store) {
|
|
37569
|
+
const key = this.messageKey(f);
|
|
37570
|
+
const plain = key ? decryptText(key, messageAad(f), f.nn, f.c) : null;
|
|
37571
|
+
let parsed = null;
|
|
37572
|
+
try {
|
|
37573
|
+
parsed = plain === null ? null : JSON.parse(plain);
|
|
37574
|
+
} catch {}
|
|
37575
|
+
const r = isObject$5(parsed) ? parsed.r : void 0;
|
|
37576
|
+
if (!isObject$5(r) || typeof r.i !== "string" || r.s === "" || !gone(r.i)) {
|
|
37577
|
+
store.push(f);
|
|
37578
|
+
continue;
|
|
37579
|
+
}
|
|
37580
|
+
changed = true;
|
|
37581
|
+
const row = this.onRows.get(storeKey(f));
|
|
37582
|
+
if (row !== void 0) {
|
|
37583
|
+
this.onRows.delete(storeKey(f));
|
|
37584
|
+
this.hooks.forgetFrame?.(row);
|
|
37585
|
+
}
|
|
37586
|
+
if (f.s !== this.myKey) continue;
|
|
37587
|
+
const { n: nn, c } = encryptText(key, messageAad(f), JSON.stringify({
|
|
37588
|
+
...parsed,
|
|
37589
|
+
r: {
|
|
37590
|
+
...r,
|
|
37591
|
+
s: ""
|
|
37592
|
+
}
|
|
37593
|
+
}));
|
|
37594
|
+
const unsigned = {
|
|
37595
|
+
g: f.g,
|
|
37596
|
+
e: f.e,
|
|
37597
|
+
h: f.h,
|
|
37598
|
+
s: f.s,
|
|
37599
|
+
n: f.n,
|
|
37600
|
+
ts: f.ts,
|
|
37601
|
+
nn,
|
|
37602
|
+
c
|
|
37603
|
+
};
|
|
37604
|
+
store.push({
|
|
37605
|
+
t: "group-msg",
|
|
37606
|
+
v: 2,
|
|
37607
|
+
...unsigned,
|
|
37608
|
+
sig: toBase64Url(sign(messageSigned(unsigned), this.identity.seed))
|
|
37609
|
+
});
|
|
37610
|
+
}
|
|
37611
|
+
if (changed) this.state.store = store;
|
|
37612
|
+
return changed;
|
|
37613
|
+
}
|
|
37614
|
+
/** The key a stored frame is sealed with, when I hold its epoch's secret. */
|
|
37615
|
+
messageKey(f) {
|
|
37616
|
+
const found = this.commitByShort(f.e, f.h), secret = found && this.state.secrets[found.hash];
|
|
37617
|
+
return secret ? epochKeys(fromBase64Url(secret), this.id, f.e).message : void 0;
|
|
39714
37618
|
}
|
|
39715
37619
|
/** The id of the message a stored frame is, by its first place when it was said again (and I can open it). */
|
|
39716
37620
|
storedId(f) {
|
|
@@ -39742,11 +37646,16 @@ var CommunitySession = class CommunitySession {
|
|
|
39742
37646
|
/** The frames the app's rows hold, into the store: oldest first by when they were written, with what the record kept from before. */
|
|
39743
37647
|
takeRows(rows) {
|
|
39744
37648
|
if (!rows.length) return;
|
|
39745
|
-
const inRecord = new
|
|
37649
|
+
const inRecord = new Map(this.state.store.map((f) => [storeKey(f), f]));
|
|
39746
37650
|
for (const { id, frame } of rows) {
|
|
39747
|
-
this.onRows.set(storeKey(frame), id);
|
|
39748
|
-
if (!inRecord.has(storeKey(frame))) this.state.store.push(frame);
|
|
39749
37651
|
if (frame.s === this.myKey && frame.h === shortHash(this.state.seqH) && frame.n >= this.state.seq && frame.n < OWN_FRAME_LIMIT) this.state.seq = frame.n + 1;
|
|
37652
|
+
const recorded = inRecord.get(storeKey(frame));
|
|
37653
|
+
if (recorded && frame.s === this.myKey && recorded.sig !== frame.sig) {
|
|
37654
|
+
this.hooks.forgetFrame?.(id);
|
|
37655
|
+
continue;
|
|
37656
|
+
}
|
|
37657
|
+
this.onRows.set(storeKey(frame), id);
|
|
37658
|
+
if (!recorded) this.state.store.push(messageFields(frame));
|
|
39750
37659
|
}
|
|
39751
37660
|
this.state.store.sort((a, b) => a.ts - b.ts);
|
|
39752
37661
|
this.trimStore();
|
|
@@ -40043,18 +37952,18 @@ var CommunitySession = class CommunitySession {
|
|
|
40043
37952
|
* once: the mark says it is passed on as it came.
|
|
40044
37953
|
*/
|
|
40045
37954
|
passOn(frame) {
|
|
40046
|
-
if (frame
|
|
40047
|
-
const
|
|
37955
|
+
if (!isMessageFrame(frame)) return frame;
|
|
37956
|
+
const fields = messageFields(frame);
|
|
40048
37957
|
return this.cameLive.has(frame) ? {
|
|
40049
|
-
...
|
|
37958
|
+
...fields,
|
|
40050
37959
|
lv: this.myKey
|
|
40051
|
-
} :
|
|
37960
|
+
} : fields;
|
|
40052
37961
|
}
|
|
40053
37962
|
/** `waited`: it waited for a commit or a secret (`replayWaiting`), so it is not live. */
|
|
40054
37963
|
async receiveMessage(from, input, waited = false) {
|
|
40055
37964
|
if (!isMessageFrame(input)) return false;
|
|
40056
|
-
const
|
|
40057
|
-
const raw =
|
|
37965
|
+
const mark = input.lv;
|
|
37966
|
+
const raw = messageFields(input);
|
|
40058
37967
|
if (raw.s === this.myKey) {
|
|
40059
37968
|
this.ownFrame(raw);
|
|
40060
37969
|
return false;
|
|
@@ -40076,7 +37985,7 @@ var CommunitySession = class CommunitySession {
|
|
|
40076
37985
|
const roster = this.rosterOf(found.hash);
|
|
40077
37986
|
if (!rosterHas(roster, raw.s)) return false;
|
|
40078
37987
|
let pace = this.messagePace.get(raw.s);
|
|
40079
|
-
if (!pace) this.messagePace.set(raw.s, pace = new MessagePace());
|
|
37988
|
+
if (!pace) this.messagePace.set(raw.s, pace = new MessagePace$1());
|
|
40080
37989
|
if (!pace.take(seenKey(raw.e, raw.h), raw.n, raw.c.length, this.hooks.clock?.() ?? Date.now())) return false;
|
|
40081
37990
|
this.handedInAnswer(from, raw, now);
|
|
40082
37991
|
if (!rosterHas(roster, this.myKey)) {
|
|
@@ -40335,6 +38244,7 @@ var CommunitySession = class CommunitySession {
|
|
|
40335
38244
|
let answered = this.syncsAnswered.get(from);
|
|
40336
38245
|
if (!answered) this.syncsAnswered.set(from, answered = new RateWindow(COMMUNITY_LIMITS.syncAnswers, COMMUNITY_LIMITS.syncWindowMs, () => this.hooks.clock?.() ?? Date.now()));
|
|
40337
38246
|
if (!answered.take()) return;
|
|
38247
|
+
if (recent) await this.vouch(from, frame.mt);
|
|
40338
38248
|
if (lost) {
|
|
40339
38249
|
const at = this.mainIndex.get(frame.h);
|
|
40340
38250
|
let commits = this.state.chain.slice(at !== void 0 ? at + 1 : lost.fork + 1, lost.end + 1);
|
|
@@ -40628,7 +38538,8 @@ var CommunitySession = class CommunitySession {
|
|
|
40628
38538
|
const opened = openGroupMeta(frame, epochKeys(fromBase64Url(secret), this.id, sealedUnder.e).message);
|
|
40629
38539
|
if (!opened) return false;
|
|
40630
38540
|
if (taking) {
|
|
40631
|
-
await this.signAgainTaken(opened.meta, opened.body);
|
|
38541
|
+
if (this.vouches(from, s)) await this.signAgainTaken(opened.meta, opened.body);
|
|
38542
|
+
else this.holdTaken(from, raw, s);
|
|
40632
38543
|
return false;
|
|
40633
38544
|
}
|
|
40634
38545
|
const before = this.state.meta;
|
|
@@ -40651,6 +38562,39 @@ var CommunitySession = class CommunitySession {
|
|
|
40651
38562
|
return !!t && this.isAdmin && s.by === t.from && (this.hooks.clock?.() ?? Date.now()) <= t.until && groupMetaNewer(s, t.base);
|
|
40652
38563
|
}
|
|
40653
38564
|
/**
|
|
38565
|
+
* Whether a statement I would take (`takesOver`) was on its way when the role moved, as far as I can tell: a member
|
|
38566
|
+
* 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
|
|
38567
|
+
* under the same commit. The former admin alone could sign new ones after the hand-over, each taken for the whole group.
|
|
38568
|
+
*/
|
|
38569
|
+
vouches(from, s) {
|
|
38570
|
+
const v = this.takeover?.vouched;
|
|
38571
|
+
return from !== s.by || !!v && v.e === s.e && v.r >= s.r;
|
|
38572
|
+
}
|
|
38573
|
+
/** The former admin's statement nobody else has shown it holds: the latest is kept until a sync does (`vouch`). */
|
|
38574
|
+
holdTaken(from, raw, s) {
|
|
38575
|
+
const t = this.takeover;
|
|
38576
|
+
if (!t.held || groupMetaNewer(s, t.held.s)) t.held = {
|
|
38577
|
+
from,
|
|
38578
|
+
raw,
|
|
38579
|
+
s
|
|
38580
|
+
};
|
|
38581
|
+
}
|
|
38582
|
+
/**
|
|
38583
|
+
* A member's sync names the statement it holds: one signed under a commit of the admin before me, by another member
|
|
38584
|
+
* than them, vouches for theirs up to it, and the one held is taken if it now is.
|
|
38585
|
+
*/
|
|
38586
|
+
async vouch(from, tag) {
|
|
38587
|
+
const t = this.takeover, v = parseGroupMetaTag(tag), commit = v ? this.state.chain[v.e] : void 0;
|
|
38588
|
+
if (!t || !v || !commit || from === t.from || rosterAdmin(this.rosterAt(this.hashOf(commit)) ?? []) !== t.from) return;
|
|
38589
|
+
if (t.vouched && !groupMetaNewer(v, t.vouched)) return;
|
|
38590
|
+
t.vouched = v;
|
|
38591
|
+
const held = t.held;
|
|
38592
|
+
if (held && this.vouches(held.from, held.s)) {
|
|
38593
|
+
t.held = void 0;
|
|
38594
|
+
await this.receiveMeta(held.from, held.raw);
|
|
38595
|
+
}
|
|
38596
|
+
}
|
|
38597
|
+
/**
|
|
40654
38598
|
* The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
|
|
40655
38599
|
* value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
|
|
40656
38600
|
*/
|
|
@@ -42382,6 +40326,6 @@ function x401ApprovalDigest(subject) {
|
|
|
42382
40326
|
]);
|
|
42383
40327
|
return toBase64Url(sha256(utf8Encode(canonical)));
|
|
42384
40328
|
}
|
|
42385
|
-
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_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_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, 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, withoutAudioMetadata, withoutPictureMetadata, withoutVideoMetadata, wrapDataChannel, wrapGroupMeta, x401AnswerableRequests, x401ApprovalDigest, x401HolderJwk, x401VpToken, yieldThread };
|
|
40329
|
+
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_READ_SLACK_S, 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, DOOR_FIRST_MS, 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_RESENDS, IDENTITY_RESEND_MS, IDENTITY_REUSE_CHECK_S, IDENTITY_REVOCATION_LABEL, IDENTITY_SEND_LIMIT, IDENTITY_SEND_WINDOW_MS, 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_RUN, LINK_STOP_CHARS, 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, appRevocationsFileEntries, 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, canonicalJsonListEntries, 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, coarseRoom, 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, deviceInviteExpired, 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, ecashUnitError, 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 };
|
|
42386
40330
|
|
|
42387
40331
|
//# sourceMappingURL=core.js.map
|