@ghostlytools/cli 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +5 -5
  2. package/dist/assets/{api-DYMKyb1k.js → api-CVtg7MpI.js} +2 -2
  3. package/dist/assets/{api-DLzCtePC.js → api-CjOaoG-v.js} +53 -27
  4. package/dist/assets/api-CjOaoG-v.js.map +1 -0
  5. package/dist/assets/{apiKit-CVaEzKWQ.js → apiKit-BAGvlQtm.js} +2 -2
  6. package/dist/assets/{apiKit-CVaEzKWQ.js.map → apiKit-BAGvlQtm.js.map} +1 -1
  7. package/dist/assets/{appFetch-D56GsYuq.js → appFetch-BwJd-kNq.js} +2 -2
  8. package/dist/assets/{appFetch-D56GsYuq.js.map → appFetch-BwJd-kNq.js.map} +1 -1
  9. package/dist/assets/{apps-XnZ8VEuj.js → apps-Cuk45sz5.js} +6 -6
  10. package/dist/assets/{apps-XnZ8VEuj.js.map → apps-Cuk45sz5.js.map} +1 -1
  11. package/dist/assets/{apps-BPFW19Wc.js → apps-DjY095Af.js} +1 -1
  12. package/dist/assets/{backup-COX6j1_W.js → backup-B56sQqoQ.js} +1 -1
  13. package/dist/assets/{backup-DpyvT9Z6.js → backup-DekVCDWv.js} +47 -8
  14. package/dist/assets/backup-DekVCDWv.js.map +1 -0
  15. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
  16. package/dist/assets/{bitcoind-DTsrd7TF.js → bitcoind-B2bbVSzh.js} +2 -2
  17. package/dist/assets/{bitcoind-DTsrd7TF.js.map → bitcoind-B2bbVSzh.js.map} +1 -1
  18. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
  19. package/dist/assets/{buttons-BvWqHJeh.js → buttons-BGxzOtrq.js} +27 -6
  20. package/dist/assets/buttons-BGxzOtrq.js.map +1 -0
  21. package/dist/assets/buttons-CsN2WJOf.js +1 -0
  22. package/dist/assets/{client-kGZ3ZdUW.js → client-DcQAfc3h.js} +2 -2
  23. package/dist/assets/{client-kGZ3ZdUW.js.map → client-DcQAfc3h.js.map} +1 -1
  24. package/dist/assets/{endpoint-B0vE5ojY.js → endpoint-Cvu-taMs.js} +42 -5
  25. package/dist/assets/{endpoint-B0vE5ojY.js.map → endpoint-Cvu-taMs.js.map} +1 -1
  26. package/dist/assets/{fixedHosts-CPSsGOI2.js → fixedHosts-C3hBliM9.js} +2 -2
  27. package/dist/assets/{fixedHosts-CPSsGOI2.js.map → fixedHosts-C3hBliM9.js.map} +1 -1
  28. package/dist/assets/{groupMeta-DTQAJG50.js → groupMeta-goASqzOt.js} +135 -37
  29. package/dist/assets/groupMeta-goASqzOt.js.map +1 -0
  30. package/dist/assets/{host-z0FAHP9Z.js → host-C2WRKj3g.js} +105 -32
  31. package/dist/assets/host-C2WRKj3g.js.map +1 -0
  32. package/dist/assets/{hyperdhtRelay-CvsAfQRQ.js → hyperdhtRelay-DLUiwfnt.js} +32 -4
  33. package/dist/assets/hyperdhtRelay-DLUiwfnt.js.map +1 -0
  34. package/dist/assets/{irohWeb-CLBx5MIv.js → irohWeb-NfthOL98.js} +178 -9
  35. package/dist/assets/irohWeb-NfthOL98.js.map +1 -0
  36. package/dist/assets/{main-CVqkvuIo.js → main-Dh7fePd8.js} +49 -32
  37. package/dist/assets/main-Dh7fePd8.js.map +1 -0
  38. package/dist/assets/{mainline-CVrd0C1n.js → mainline-DY95WbuK.js} +2 -2
  39. package/dist/assets/{mainline-CVrd0C1n.js.map → mainline-DY95WbuK.js.map} +1 -1
  40. package/dist/assets/{ownDid-DY3rYqDI.js → ownDid-BErplN7N.js} +2 -2
  41. package/dist/assets/{ownDid-DY3rYqDI.js.map → ownDid-BErplN7N.js.map} +1 -1
  42. package/dist/assets/{ownStatus-DMEhrpkd.js → ownStatus-ClrFjd7h.js} +5 -3
  43. package/dist/assets/ownStatus-ClrFjd7h.js.map +1 -0
  44. package/dist/assets/{profiles-BFSGqDFC.js → profiles-B8xO8-oj.js} +2 -2
  45. package/dist/assets/{profiles-BFSGqDFC.js.map → profiles-B8xO8-oj.js.map} +1 -1
  46. package/dist/assets/{registry-B15Yg_1C.js → registry--Rg2YvOH.js} +1 -1
  47. package/dist/assets/{registry-rXgaZeNn.js → registry-CU8PevhI.js} +38 -30
  48. package/dist/assets/registry-CU8PevhI.js.map +1 -0
  49. package/dist/assets/{relay-Cjfmdec0.js → relay-CHWg5hpZ.js} +73 -11
  50. package/dist/assets/relay-CHWg5hpZ.js.map +1 -0
  51. package/dist/assets/{resolve-CIc3KZMV.js → resolve-B1upovPM.js} +2 -2
  52. package/dist/assets/{resolve-CIc3KZMV.js.map → resolve-B1upovPM.js.map} +1 -1
  53. package/dist/assets/secretGuard-Bm6nci0I.js +1 -0
  54. package/dist/assets/{secretGuard-B4-LlMjv.js → secretGuard-BrATm_gl.js} +33 -9
  55. package/dist/assets/{secretGuard-B4-LlMjv.js.map → secretGuard-BrATm_gl.js.map} +1 -1
  56. package/dist/assets/{server-CQR7NLCz.js → server-Dgxx_DaN.js} +473 -60
  57. package/dist/assets/server-Dgxx_DaN.js.map +1 -0
  58. package/dist/assets/{waitNotice-BGM0QOS2.js → waitNotice-ylU3XwjO.js} +2 -2
  59. package/dist/assets/{waitNotice-BGM0QOS2.js.map → waitNotice-ylU3XwjO.js.map} +1 -1
  60. package/dist/ghostly.mjs +1 -1
  61. package/npm-shrinkwrap.json +2 -2
  62. package/package.json +1 -1
  63. package/dist/assets/api-DLzCtePC.js.map +0 -1
  64. package/dist/assets/backup-DpyvT9Z6.js.map +0 -1
  65. package/dist/assets/buttons-Bq7pTXqF.js +0 -1
  66. package/dist/assets/buttons-BvWqHJeh.js.map +0 -1
  67. package/dist/assets/groupMeta-DTQAJG50.js.map +0 -1
  68. package/dist/assets/host-z0FAHP9Z.js.map +0 -1
  69. package/dist/assets/hyperdhtRelay-CvsAfQRQ.js.map +0 -1
  70. package/dist/assets/irohWeb-CLBx5MIv.js.map +0 -1
  71. package/dist/assets/main-CVqkvuIo.js.map +0 -1
  72. package/dist/assets/ownStatus-DMEhrpkd.js.map +0 -1
  73. package/dist/assets/registry-rXgaZeNn.js.map +0 -1
  74. package/dist/assets/relay-Cjfmdec0.js.map +0 -1
  75. package/dist/assets/secretGuard-BmmnEbYf.js +0 -1
  76. package/dist/assets/server-CQR7NLCz.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { a as RelaysFailedError, f as DiscoveryBudgetError, i as RelayTransport, m as isDiscoveryBudgetError, n as HEDGE_MISSING_MS, o as SLOW_MS, r as HEDGE_MS } from "./relay-Cjfmdec0.js";
1
+ import { a as RelaysFailedError, f as DiscoveryBudgetError, i as RelayTransport, m as isDiscoveryBudgetError, n as HEDGE_MISSING_MS, o as SLOW_MS, r as HEDGE_MS } from "./relay-CHWg5hpZ.js";
2
2
  import { l as parseRelayPayload, s as newerPacket, y as publicKeyFromZ32 } from "./pkarr-BQo4PcCg.js";
3
3
  import { ed25519 } from "@noble/curves/ed25519.js";
4
4
  import { createHash } from "node:crypto";
@@ -577,4 +577,4 @@ var RelaysAndDht = class {
577
577
  };
578
578
  export { Mainline, RelaysAndDht };
579
579
 
580
- //# sourceMappingURL=mainline-CVrd0C1n.js.map
580
+ //# sourceMappingURL=mainline-DY95WbuK.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mainline-CVrd0C1n.js","names":["verify"],"sources":["../../src/runtime/mainline.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport DHT from \"bittorrent-dht\";\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\nimport {\n BACKGROUND_REQUESTS_PER_MINUTE, DiscoveryBudgetError, HEDGE_MISSING_MS, HEDGE_MS, RelayTransport, RelaysFailedError, SLOW_MS, isDiscoveryBudgetError, newerPacket, parseRelayPayload, publicKeyFromZ32,\n type DiscoveryStatus, type GhostRecord, type Identity, type PkarrRequestOptions, type PkarrTransport, type RelayTransportOptions, type SignedPacket,\n} from \"@ghostly/core\";\n\n/**\n * Pkarr over the Mainline DHT (BEP44), from Node, as the Desktop reaches it from Rust: the relays are HTTP bridges to\n * this same DHT, so a headless Ghostly that speaks it directly keeps finding its contacts while the relays fail (they\n * answered HTTP 500 for more than ten minutes on 2026-09-27, and a group's edges stayed down all that while).\n *\n * A Pkarr packet is a BEP44 mutable item: the key is the Ed25519 public key, the value the DNS packet, the sequence\n * number its timestamp in microseconds, and the signature the one the relay payload already carries (over\n * `3:seqi<seq>e1:v<len>:<v>`). So one signed payload goes to the relays and to the DHT unchanged.\n */\n\nexport interface MainlineOptions {\n /** `host:port` nodes to start from; the public routers when absent; none with `false` (a testnet's first node). */\n bootstrap?: string[] | false;\n /** Address to bind (a loopback testnet binds 127.0.0.1). */\n host?: string;\n /** How long a lookup may take before it is given up, in ms. */\n timeoutMs?: number;\n}\n\nconst SIGNATURE = 64, TIMESTAMP = 8;\nconst verify = (sig: Uint8Array, message: Uint8Array, key: Uint8Array) => { try { return ed25519.verify(sig, message, key); } catch { return false; } };\n/**\n * What a `get` takes from the nodes that answer: a record signed without salt (Pkarr has none). bittorrent-dht reads a\n * reply's `salt` (`Buffer.concat` with the key) only once it is verified, and a number there threw in its socket handler:\n * any node a lookup asked, signing with its own key, raised an error nobody caught. Signed data is `4:salt…` with a salt.\n */\nconst SALTED = Buffer.from(\"4:salt\");\nconst verifyUnsalted = (sig: Uint8Array, message: Uint8Array, key: Uint8Array) =>\n !Buffer.from(message.buffer, message.byteOffset, Math.min(message.length, SALTED.length)).equals(SALTED) && verify(sig, message, key);\n\n/** Queries the node answers, a second: from each address (as libtorrent's default), and from all of them together. */\nconst QUERY_LIMITS = { perAddress: 5, perAddressBurst: 20, total: 50, totalBurst: 200 };\n/** Addresses `DhtQueryLimit` remembers: forged source addresses must not grow it without end. */\nconst ADDRESSES_KEPT = 4_096;\n/** Mutable items others put on the node: as many as bittorrent-dht keeps, each for the two hours BEP44 suggests. */\nconst VALUES_KEPT = { max: 1_000, maxAge: 2 * 60 * 60_000 };\n\n/**\n * The queries a DHT node answers, as token buckets: a burst then a rate per source address, and a total for all. UDP\n * has no handshake, so a query's address can be someone else's: answered without a limit, a stranger who parked a\n * 1000-byte item on the node had it send ~12.5x the bytes of each forged `get` (5-6x with nothing parked) to that\n * address, as fast as they came. Queries past either limit go unanswered, as an overloaded node's do. This node's own\n * lookups (answers to its queries, not queries) are not counted.\n */\nexport class DhtQueryLimit {\n private readonly addresses = new Map<string, { tokens: number; at: number }>();\n private all: { tokens: number; at: number } | null = null;\n\n constructor(private readonly limits: typeof QUERY_LIMITS = QUERY_LIMITS) {}\n\n /** Addresses remembered (`ADDRESSES_KEPT` at most). */\n get size(): number { return this.addresses.size; }\n\n /** Whether a query from `host` is answered now (counted if so). */\n take(host: string, now = Date.now()): boolean {\n const refill = (bucket: { tokens: number; at: number } | null | undefined, rate: number, burst: number) => {\n if (!bucket) return { tokens: burst, at: now };\n // A clock that went back refills nothing, and counts from now on.\n bucket.tokens = Math.min(burst, bucket.tokens + Math.max(0, now - bucket.at) * rate / 1_000);\n bucket.at = now;\n return bucket;\n };\n const all = this.all = refill(this.all, this.limits.total, this.limits.totalBurst);\n const own = refill(this.addresses.get(host), this.limits.perAddress, this.limits.perAddressBurst);\n // Kept in the order last asked: the address not heard from the longest goes first.\n this.addresses.delete(host);\n this.addresses.set(host, own);\n if (this.addresses.size > ADDRESSES_KEPT) this.addresses.delete(this.addresses.keys().next().value!);\n if (own.tokens < 1 || all.tokens < 1) return false;\n own.tokens -= 1; all.tokens -= 1;\n return true;\n }\n}\n\ntype Query = { q?: Buffer | string; a?: { k?: unknown; v?: unknown; seq?: unknown; sig?: unknown; salt?: unknown; target?: unknown; info_hash?: unknown } };\ntype QueryPeer = { address: string; port: number };\n/** The parts of bittorrent-dht's node (no API for them) through which it answers queries. */\ninterface DhtInternals { _onquery(query: Query, peer: QueryPeer): void; _rpc: { error(peer: QueryPeer, query: Query, error: [number, string]): void } }\n\n/**\n * A source on loopback is this machine, never a forged address from outside (a packet from the network claiming one is\n * dropped before it gets here): each of its ports is a node of its own (a loopback testnet's nodes all share the host),\n * counted apart. Any other address is counted whatever its port, as a forged source's port is the sender's choice.\n */\nconst LOOPBACK = /^(127\\.|::1$|::ffff:127\\.)/;\nconst bytes = (value: unknown, length: number): boolean => Buffer.isBuffer(value) && value.length === length;\n/** BEP44's bound on an item's value, which bittorrent-dht checks only on what has a `length` (not a dictionary). */\nconst VALUE_MAX = 1_000;\n\n/**\n * What the node answers strangers: queries at `DhtQueryLimit`'s rate, ping, find_node and get/get_peers as BEP5/BEP44\n * say, and puts of signed mutable items only, which is what Pkarr packets are (the testnet's nodes and the public DHT\n * keep each other's that way). It refuses what the app has no use for and bittorrent-dht kept for anyone and served to\n * anyone: immutable items and peers announced for torrents. A put's value is a string of at most 1000 bytes and its seq\n * a non-negative integer, as every Pkarr packet's: bittorrent-dht bounds only a value with a `length`, so a dictionary\n * of 60 KB was kept and served whole to every get. A query whose hash, key, signature or salt is not the string\n * BEP5/BEP44 say (a put signed without a key, a number for a target) threw out of the socket handler: an error nobody\n * caught, one per datagram. It is refused before bittorrent-dht reads it.\n */\nfunction answerBounded(dht: DHT, limit = new DhtQueryLimit()): void {\n const node = dht as unknown as DhtInternals;\n const answer = node._onquery.bind(dht);\n node._onquery = (query, peer) => {\n if (!query || !peer || !limit.take(LOOPBACK.test(peer.address) ? `${peer.address}:${peer.port}` : peer.address)) return;\n const q = query.q?.toString(), a = query.a ?? {};\n if (q === \"announce_peer\") return node._rpc.error(peer, query, [204, \"announce_peer is not served here\"]);\n if (q === \"put\" && (!bytes(a.k, 32) || !bytes(a.sig, SIGNATURE))) return node._rpc.error(peer, query, [203, \"only signed mutable items are stored here\"]);\n if (q === \"put\" && !(Buffer.isBuffer(a.v) && a.v.length <= VALUE_MAX)) return node._rpc.error(peer, query, [205, \"only values of at most 1000 bytes are stored here\"]);\n const malformed = ((q === \"get\" || q === \"find_node\") && !bytes(a.target, 20)) || (q === \"get_peers\" && !bytes(a.info_hash, 20))\n || (q === \"put\" && !(Number.isSafeInteger(a.seq) && (a.seq as number) >= 0))\n || (q === \"put\" && a.salt !== undefined && !(Buffer.isBuffer(a.salt) && a.salt.length <= 64));\n if (malformed) return node._rpc.error(peer, query, [203, \"malformed query\"]);\n try { answer(query, peer); } catch { /* a query bittorrent-dht could not read goes unanswered */ }\n };\n}\n\n/**\n * Every DHT node asked refused a put for holding a later-dated packet of the key (BEP44 error 302, \"sequence number less\n * than current\"): one put by this key's earlier clock, ahead of this one, before a restart forgot its date.\n */\nexport class DhtRefusedError extends Error {\n constructor(reason: string) {\n super(`The DHT holds a later-dated packet of this key (${reason})`);\n this.name = \"DhtRefusedError\";\n }\n}\n\n/**\n * A DHT node of this process: puts and gets Pkarr packets. The node starts at the first thing asked of it: a command\n * that reads only the profile (`chat list`, `settings get`) or a profile set offline asks nothing, and before, every\n * command bound a UDP port and bootstrapped from the public routers all the same, sending them this machine's address.\n */\nexport class Mainline {\n private node: { dht: DHT; listening: Promise<void> } | null = null;\n private closed = false;\n private readonly timeoutMs: number;\n\n constructor(private readonly options: MainlineOptions = {}) {\n this.timeoutMs = options.timeoutMs ?? 20_000;\n }\n\n private get dht(): DHT { return this.started().dht; }\n\n private started(): { dht: DHT; listening: Promise<void> } {\n if (this.closed) throw new Error(\"The DHT node is closed\");\n if (this.node) return this.node;\n const { host } = this.options;\n const bootstrap = this.options.bootstrap === false ? false : this.options.bootstrap?.length ? this.options.bootstrap : undefined;\n // `maxValues` reaches the `lru` that holds others' items, which takes `{ max, maxAge }` as well as a number.\n const dht = new DHT({ verify, maxValues: VALUES_KEPT, ...(bootstrap !== undefined ? { bootstrap } : {}), ...(host ? { host } : {}) });\n // A node of the table that errors must not end the process.\n dht.on(\"error\", () => {});\n answerBounded(dht);\n this.node = { dht, listening: new Promise((resolve) => dht.listen(0, host, () => resolve())) };\n return this.node;\n }\n\n /** Whether the node started (something was put, got or added). */\n get running(): boolean { return this.node !== null; }\n /** Its UDP socket is bound (starts the node). */\n get listening(): Promise<void> { return this.started().listening; }\n\n /** Adds a node (a testnet's peers). */\n addNode(host: string, port: number): void { this.dht.addNode({ host, port }); }\n address(): { port: number } { return this.dht.address() as { port: number }; }\n\n /** Puts a relay payload (`<signature><timestamp><DNS packet>`) as the mutable item of `pubKeyZ32`; resolves with the nodes that took it. */\n put(pubKeyZ32: string, payload: Uint8Array): Promise<number> {\n const k = Buffer.from(publicKeyFromZ32(pubKeyZ32));\n const sig = Buffer.from(payload.subarray(0, SIGNATURE));\n const seq = Number(new DataView(payload.buffer, payload.byteOffset + SIGNATURE, TIMESTAMP).getBigUint64(0));\n const v = Buffer.from(payload.subarray(SIGNATURE + TIMESTAMP));\n return this.bounded(new Promise((resolve, reject) => {\n this.dht.put({ k, v, seq, sig }, (error, _hash, nodes) => {\n if (error) reject((error as Error & { code?: unknown }).code === 302 ? new DhtRefusedError(error.message) : error);\n else if (!nodes) reject(new Error(\"No DHT node took the packet\")); else resolve(nodes);\n });\n }));\n }\n\n /** The newest packet of `pubKeyZ32` the DHT holds, checked; null when nobody has one. */\n get(pubKeyZ32: string): Promise<SignedPacket | null> {\n const k = Buffer.from(publicKeyFromZ32(pubKeyZ32));\n // A mutable item without salt is found under the SHA-1 of its public key (BEP44).\n const target = createHash(\"sha1\").update(k).digest();\n return this.bounded(new Promise((resolve, reject) => {\n this.dht.get(target, { cache: false, verify: verifyUnsalted }, (error, found) => {\n if (error) return reject(error);\n // A record is what its node sent, checked only by its signature: one signed with no `seq` (bittorrent-dht signs\n // `seq || 0`) or with a dictionary for `v` threw here, out of the socket's handler.\n if (!found || !Buffer.isBuffer(found.v) || !Buffer.isBuffer(found.sig) || !Number.isSafeInteger(found.seq) || found.seq < 0) return resolve(null);\n try {\n const timestamp = new Uint8Array(TIMESTAMP);\n new DataView(timestamp.buffer).setBigUint64(0, BigInt(found.seq));\n const payload = new Uint8Array(SIGNATURE + TIMESTAMP + found.v.length);\n payload.set(found.sig, 0); payload.set(timestamp, SIGNATURE); payload.set(found.v, SIGNATURE + TIMESTAMP);\n resolve(parseRelayPayload(pubKeyZ32, payload));\n } catch { resolve(null); }\n });\n }));\n }\n\n private bounded<T>(work: Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(\"DHT lookup timed out\")), this.timeoutMs);\n work.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error); });\n });\n }\n\n /** Closes the node and its socket, if it started; the next thing asked of it starts it again. */\n stop(): Promise<void> {\n const node = this.node;\n this.node = null;\n return node ? new Promise((resolve) => node.dht.destroy(() => resolve())) : Promise.resolve();\n }\n\n destroy(): Promise<void> {\n this.closed = true;\n return this.stop();\n }\n}\n\n/** Keys a `RelaysAndDht` remembers as found nowhere (`missing`). */\nconst MISSING_KEPT = 256;\n\n/** How long a key that asked for a background DHT read counts among those that share the budget (`DhtBackgroundBudget`). */\nconst ASKERS_WINDOW_MS = 2 * 60_000;\n/** The same for a background DHT write: past a chat's 4-minute upkeep, with room for its turn (a control envelope's life). */\nconst WRITERS_WINDOW_MS = 10 * 60_000;\nconst MINUTE_MS = 60_000;\n\n/**\n * Background reads that go to the DHT in the relays' place (every relay failing, or failing this read), within the share\n * the relays would have given them (`BACKGROUND_REQUESTS_PER_MINUTE` a minute on each relay): a minute's lookups at\n * most, and each key in its turn, no sooner than the keys asking share that minute (`n` keys at `perMinute` a minute:\n * once every `n / perMinute` minutes). Without it, a daemon looked up every contact away on the DHT four times a minute\n * for as long as the relays failed (200 lookups a minute at 50 contacts, 1,200 at 300), where with the relays up it\n * made 26-54 relay reads a minute in all; each lookup on the real DHT is dozens of UDP queries.\n * Reads someone waits on (not `background`, or `urgent`, `signal`, `door`, `resume`) never wait for it, nor count.\n */\nexport class DhtBackgroundBudget {\n private readonly spent: number[] = [];\n /** Per key, when it last asked (oldest first) and when its last lookup went. */\n private readonly askedAt = new Map<string, number>();\n private readonly lookedAt = new Map<string, number>();\n /** The time of the last `take`: none of the above is dated after it. */\n private latest = -Infinity;\n\n /** `askersWindowMs`: how long a key counts among those sharing the budget since it last asked (`ASKERS_WINDOW_MS`). */\n constructor(private readonly perMinute: () => number, private readonly askersWindowMs = ASKERS_WINDOW_MS) {}\n\n /** 0: the lookup goes now (counted). Otherwise how long until this key's turn, in ms; nothing is counted. */\n take(pubKeyZ32: string, now = Date.now()): number {\n // The clock went back (an NTP step, a clock that ran ahead fixed by hand): what is dated after now counts as of now,\n // as just spent. Counted as it was, an hour's step back held every key's lookup for 56 minutes (bug hunt, 2026-11-07).\n if (now < this.latest) {\n this.spent.forEach((at, i) => { this.spent[i] = Math.min(at, now); });\n for (const times of [this.askedAt, this.lookedAt]) for (const [key, at] of times) if (at > now) times.set(key, now);\n }\n this.latest = now;\n this.askedAt.delete(pubKeyZ32);\n this.askedAt.set(pubKeyZ32, now);\n for (const [key, at] of this.askedAt) {\n if (now - at < this.askersWindowMs) break;\n this.askedAt.delete(key);\n this.lookedAt.delete(key);\n }\n while (this.spent.length && now - this.spent[0]! >= MINUTE_MS) this.spent.shift();\n const limit = Math.max(1, this.perMinute());\n const turn = Math.ceil(this.askedAt.size * MINUTE_MS / limit);\n const last = this.lookedAt.get(pubKeyZ32);\n const ownTurn = last === undefined ? 0 : last + turn - now;\n // The minute's lookups are spent (keys new to it, all at once): this key's turn, or the minute's next free one if later.\n const minute = this.spent.length >= limit ? this.spent[0]! + MINUTE_MS - now : 0;\n if (ownTurn > 0 || minute > 0) return Math.max(ownTurn, minute, last === undefined ? turn : 0);\n this.spent.push(now);\n this.lookedAt.set(pubKeyZ32, now);\n return 0;\n }\n}\n\n/** A read nobody waits on: what the relays' budget calls background, and what the DHT's (`DhtBackgroundBudget`) holds. */\nconst waitable = (options: PkarrRequestOptions): boolean =>\n !!options.background && !options.urgent && !options.signal && !options.door && !options.resume;\n\n/**\n * The relays first, as the web app reaches Pkarr (its contacts read only the relays), and the DHT beside them: every\n * packet also goes to the DHT, and a read goes there when every relay is failing, the read failed, or this app's own\n * request budget held it back (the DHT has no budget), or every relay rate limits this address (429). A background read\n * this app's budget holds waits for it. Background reads the DHT answers in the relays' place keep to the relays'\n * background share (`DhtBackgroundBudget`), and so do background writes on the DHT: one past it goes to the relays alone.\n *\n * `pinned`: the relays given are the only ones (`GHOSTLY_PKARR_RELAYS`, a private network): the profile's `relays`\n * setting does not replace them. With no DHT (`dht` null), the relays alone carry every packet.\n */\nexport class RelaysAndDht implements PkarrTransport {\n readonly relays: RelayTransport;\n private lastVia: \"relay\" | \"dht\" = \"relay\";\n /**\n * Keys a hedged read found nowhere: the DHT said so before the relays' slow 404 came, so the next poll of the key\n * hedges late too (`HEDGE_MISSING_MS`), not only once that 404 lands. The newest `MISSING_KEPT`.\n */\n private readonly missing = new Set<string>();\n /** Background reads on the DHT in the relays' place, at their background share (`DhtBackgroundBudget`). */\n private readonly dhtBackground = new DhtBackgroundBudget(() => BACKGROUND_REQUESTS_PER_MINUTE * this.relays.describe().relays.length);\n /**\n * Background writes on the DHT (upkeep nobody waits on: a chat's heartbeat and keep-alive while its contact is away)\n * at the same share. Without it, every chat put two packets there every 4 minutes for as long as the daemon ran,\n * whatever the relays' budget held of the same: ~104 puts a minute at 200 chats, each a whole iterative lookup.\n * A key counts among those sharing it for longer than a read's (`WRITERS_WINDOW_MS`): one that went asks again only\n * at the next upkeep, 4 minutes on, and forgotten by then it came back as new, without its turn: some chats were put\n * every 4 minutes and others not once in 25.\n * `writeTurns`: keys whose write `publishHeld` let go, not counted again when the publish comes.\n */\n private readonly dhtBackgroundWrites = new DhtBackgroundBudget(() => BACKGROUND_REQUESTS_PER_MINUTE * this.relays.describe().relays.length, WRITERS_WINDOW_MS);\n private readonly writeTurns = new Set<string>();\n\n /** Off while the profile keeps to the relays (Hide my IP from contacts, `configure`'s `dhtDirect: false`). */\n private direct = true;\n\n constructor(private readonly mainline: Mainline | null, relays: RelayTransportOptions = {}, private readonly pinned = false) {\n this.relays = new RelayTransport(relays);\n }\n\n /** The DHT this transport reaches now: none while the profile keeps to the relays. */\n private get dht(): Mainline | null { return this.direct ? this.mainline : null; }\n\n async publish(identity: Identity, records: GhostRecord[], options: PkarrRequestOptions = {}): Promise<void> {\n // BEP44 sequence numbers must strictly increase, on the relays and on the DHT alike: one payload for both, dated\n // past every packet put or read under the key (`RelayTransport.publishDated`), whichever clock dated those.\n // With the DHT, the packet goes there whatever the relays' budgets say: signed every time. Without it (a private\n // network's relays only), a publish none of them takes now is not signed at all. A background write the DHT's\n // share holds goes to the relays alone, as without the DHT, or waits its turn there while every relay fails.\n const toDht = this.dht !== null && this.dhtWriteTurn(identity.pubKeyZ32, options);\n await this.relays.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putBoth(key, payload, options, conflict, timestamp, toDht), options, false, toDht);\n }\n\n async publishPayload(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions = {}): Promise<void> {\n return this.putBoth(pubKeyZ32, payload, options, undefined, undefined, this.dhtWriteTurn(pubKeyZ32, options));\n }\n\n /** Every relay is left alone for failing: what goes to them alone goes nowhere. */\n private relaysDown(): boolean {\n return this.relays.discovery().relays.every((relay) => relay.state === \"failing\");\n }\n\n /**\n * Whether this write goes to the DHT too (`dhtWriteWait`). One the DHT's share holds while every relay fails is held\n * back until its turn there (a `DiscoveryBudgetError`), as a background read is: tried on the relays alone, it failed,\n * and the link tried it again every 4 s until that turn came, 15 packets built a minute per chat whose contact was\n * away (~2,300 a minute at 200 chats, twice the CPU of the daemon before the share, bug hunt 2026-11-14).\n */\n private dhtWriteTurn(pubKeyZ32: string, options: PkarrRequestOptions): boolean {\n const wait = this.dhtWriteWait(pubKeyZ32, options);\n if (wait > 0 && this.relaysDown()) throw new DiscoveryBudgetError(wait, \"Background DHT writes in the relays' place are at their share; retry shortly\");\n return wait === 0;\n }\n\n /**\n * 0: this write goes to the DHT now (a background one counted in its share, unless `publishHeld` already let it go).\n * Otherwise how long until its turn there. Writes someone waits on never wait for it, nor count; with no relay set at\n * all the DHT is the only way.\n */\n private dhtWriteWait(pubKeyZ32: string, options: PkarrRequestOptions, ahead = false): number {\n if (!this.dht || !waitable(options) || this.relays.describe().relays.length === 0) return 0;\n if (this.writeTurns.delete(pubKeyZ32)) return 0;\n const wait = this.dhtBackgroundWrites.take(pubKeyZ32);\n if (ahead && wait === 0) this.writeTurns.add(pubKeyZ32);\n return wait;\n }\n\n /**\n * `timestamp`: the payload was just signed here (`publish`), dated so; its signature is not checked again on the way\n * to the relays. Without it (`publishPayload`, signed elsewhere) the relays' side checks it to read its date.\n * `toDht` false: the relays alone (a background write the DHT's share holds).\n */\n private async putBoth(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions, conflict?: (relay: string, read?: () => Promise<bigint | null>) => void, timestamp?: bigint, toDht = true): Promise<void> {\n const toRelays = () => timestamp === undefined\n ? this.relays.publishPayload(pubKeyZ32, payload, options, conflict)\n : this.relays.putSigned(pubKeyZ32, payload, timestamp, options, conflict);\n if (!this.dht || !toDht) return toRelays();\n const onDht = this.dht.put(pubKeyZ32, payload);\n onDht.catch(() => {});\n const onRelays = toRelays();\n onRelays.catch(() => {});\n // Out on the DHT is out (a Pkarr relay reads the DHT for a key it has not got): a relay that takes the request and\n // never answers held each publish for its 10 s timeout, an invite's first among them, while the DHT took it in\n // milliseconds. The relays' copy finishes in the background. A budget's hold is said before any request goes, so\n // it wins this race: once the DHT took the packet, that is out too, and the relays get it when their budget frees\n // (`putLater`; browser contacts read only them). Said held back, the link signed it and put it on the DHT again in\n // 0.25-4 s, at budget 1.5-2.2x the DHT puts of a DHT-only daemon.\n let refused: unknown;\n const tookIt = onDht.then(() => true, (error: unknown) => {\n refused = error;\n // The DHT holds a later-dated packet of this key, as a relay that answers 409 does: its date is read there, and\n // the records go again dated just past it (`publishDated`). After a clock that ran ahead was set right, a\n // restarted CLI had every put refused, tried again every 4 s until the clock caught up (15 a minute per chat), and\n // texts to a contact away stayed queued.\n if (error instanceof DhtRefusedError) conflict?.(\"dht\", () => this.fromDht(pubKeyZ32).then((packet) => packet?.timestampMicros ?? null));\n return false;\n });\n if (await Promise.race([onRelays.then(() => false, () => false), tookIt])) return;\n try {\n await onRelays;\n } catch (error) {\n if (isDiscoveryBudgetError(error)) {\n if (!(await tookIt)) throw error;\n this.relays.putLater(pubKeyZ32, payload, timestamp, options);\n return;\n }\n // The relays failed: the DHT's answer is the publish's, and its refusal is said with theirs.\n if (!(await tookIt)) throw refused instanceof Error ? new Error(`${error instanceof Error ? error.message : String(error)}; ${refused.message}`, { cause: error }) : error;\n }\n }\n\n async resolve(pubKeyZ32: string, options: PkarrRequestOptions = {}, keptOnFailure = true): Promise<SignedPacket | null> {\n if (!this.dht) return this.relays.resolve(pubKeyZ32, options, keptOnFailure);\n let fromRelays: SignedPacket | null = null, failed: unknown = null;\n // Every relay left alone for failing: the relays answer from what they last saw, if anything; the DHT is asked.\n const down = () => this.relays.discovery().relays.every((relay) => relay.state === \"failing\");\n if (!down()) {\n const started = Date.now();\n // A read the relays failed asks the DHT at once, their last copy kept to weigh against its packet. Handed back\n // as their answer, it stood for each 20 s cooldown until the breaker opened: about 40 s of a contact's old packet\n // with the newer one on the DHT (bug hunt, 2026-10-17).\n const relays = this.relays.resolve(pubKeyZ32, options, false).then((packet) => ({ packet, failed: null as unknown }), (error: unknown) => ({ packet: null, failed: error }));\n let timer: ReturnType<typeof setTimeout> | undefined;\n // A key whose last read found nothing: the relays take 3-5 s to say a key is not there\n // (they ask the DHT themselves), and a hedge at HEDGE_MS made every poll of an unused invite's key a DHT lookup\n // of its own (+47 in 10 min: agents#1595). Their own hedge waits as long (`RelayTransport`, `HEDGE_MISSING_MS`).\n const hedgeAfter = this.relays.lastReadMissing(pubKeyZ32) || this.missing.has(pubKeyZ32) ? HEDGE_MISSING_MS : HEDGE_MS;\n const answered = await Promise.race([relays, new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), hedgeAfter); })]);\n clearTimeout(timer);\n // The relays have not answered within a hedge's time (one that takes requests and never answers held each read\n // for its 10 s timeout): the DHT is asked too.\n if (!answered) {\n const found = await this.hedged(pubKeyZ32, relays, started);\n this.missing.delete(pubKeyZ32);\n if (!found) { this.missing.add(pubKeyZ32); if (this.missing.size > MISSING_KEPT) this.missing.delete(this.missing.values().next().value!); }\n return found;\n }\n ({ packet: fromRelays, failed } = answered);\n // No relay is asked now: each one rate limits this address (429) for as long as it said, or fails. Their answer is\n // what they last saw, or a wait, and the DHT is asked in their place, as when they all fail (a background read\n // at their share). Taken as their answer, a daemon whose relays answered 429 for 10 minutes read none of its 50\n // contacts in that time, and looked none up on the DHT (bug hunt, 2026-11-11).\n const refusing = this.relays.discovery().relays.every((relay) => relay.state !== \"ok\");\n // The relays' budget held the read back: the DHT, which has no budget and already has a contact's first\n // envelope, is asked instead. Waiting for the relays' minute made each pairing past ~10 chats on working relays\n // take 3-18 s (13-37 s on one relay), where DHT-only pairings take 0.1-2.8 s (agents#1715). Found nowhere there,\n // or a background read, it is still a wait.\n if (isDiscoveryBudgetError(failed) && !(refusing && options.background)) return this.heldBack(pubKeyZ32, failed, options);\n if (failed instanceof RelaysFailedError) fromRelays = failed.kept;\n if (!failed) this.lastVia = \"relay\";\n if (!failed && !down() && !refusing) return fromRelays;\n }\n try {\n // A background read the DHT answers instead of the relays waits its turn there (`DhtBackgroundBudget`), as it did\n // on them: held back, as their budget holds one. With no relay set at all the DHT is the only way, not a stand-in.\n if (waitable(options) && this.relays.describe().relays.length > 0) {\n const wait = this.dhtBackground.take(pubKeyZ32);\n if (wait > 0) throw new DiscoveryBudgetError(wait, \"Background DHT reads in the relays' place are at their share; retry shortly\");\n }\n const fromDht = await this.fromDht(pubKeyZ32);\n this.lastVia = \"dht\";\n return newerPacket(fromRelays, fromDht);\n } catch (error) {\n // Nothing answered, the DHT neither: the relays' last copy is the answer, or, for a caller that asks, the failure\n // that carries it (`keptOnFailure`).\n if (fromRelays && (keptOnFailure || !(failed instanceof RelaysFailedError))) return fromRelays;\n throw failed ?? error;\n }\n }\n\n private async heldBack(pubKeyZ32: string, held: unknown, options: PkarrRequestOptions): Promise<SignedPacket> {\n if (options.background) throw held;\n const fromDht = await this.fromDht(pubKeyZ32).catch(() => null);\n if (!fromDht) throw held;\n this.lastVia = \"dht\";\n return fromDht;\n }\n\n private async fromDht(pubKeyZ32: string): Promise<SignedPacket | null> {\n // The switch turned while a read was on its way to the DHT: it does not go.\n if (!this.dht) throw new Error(\"The DHT is not reached while the profile keeps to the relays\");\n const packet = await this.dht.get(pubKeyZ32);\n if (packet) this.relays.sawTimestamp(pubKeyZ32, packet.timestampMicros);\n return packet;\n }\n\n /**\n * A read the relays are slow to answer, the DHT asked beside them. The relays' packet first is the answer, as without\n * the hedge. The DHT's first waits for the relays until a slow relay would have had its say (`SLOW_MS`, a relay\n * fetching the packet from the DHT itself), or until they answer, and the newer of the two is the answer: taken at\n * once, the DHT's older copy won every read over a relay that took 2 s with the newer one (agents#1594). The DHT\n * finding none is the answer once that time is up too, or once the relays answered. Both failing: the relays' reason.\n */\n private async hedged(pubKeyZ32: string, relays: Promise<{ packet: SignedPacket | null; failed: unknown }>, started: number): Promise<SignedPacket | null> {\n const dht = this.fromDht(pubKeyZ32).then((packet) => ({ packet, failed: null as unknown, via: \"dht\" as const }), (error: unknown) => ({ packet: null, failed: error, via: \"dht\" as const }));\n const viaRelays = relays.then((r) => ({ ...r, via: \"relay\" as const }));\n const first = await Promise.race([viaRelays, dht]);\n if (first.packet && first.via === \"relay\") { this.lastVia = \"relay\"; return first.packet; }\n const fromDht = await dht;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const slowAfter = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), Math.max(0, SLOW_MS - (Date.now() - started))); });\n const fromRelays = await Promise.race([viaRelays, slowAfter]);\n clearTimeout(timer);\n if (fromDht.packet) {\n const newer = newerPacket(fromRelays?.packet, fromDht.packet);\n this.lastVia = newer === fromDht.packet ? \"dht\" : \"relay\";\n return newer;\n }\n if (fromRelays?.packet) { this.lastVia = \"relay\"; return fromRelays.packet; }\n if (!fromDht.failed) { this.lastVia = \"dht\"; return null; }\n if (!fromRelays) throw fromDht.failed;\n if (!fromRelays.failed) return null;\n throw fromRelays.failed;\n }\n\n describe(): { protocol: string; relays: string[] } {\n return { protocol: this.dht ? \"Pkarr relays (HTTP), and the Mainline DHT (BEP44) directly\" : \"Pkarr relays (HTTP)\", relays: this.relays.describe().relays };\n }\n discovery(): DiscoveryStatus {\n const status = this.relays.discovery();\n return this.lastVia === \"dht\" ? { ...status, path: { via: \"dht\" } } : status;\n }\n subscribe(listener: Parameters<RelayTransport[\"subscribe\"]>[0]): () => void { return this.relays.subscribe(listener); }\n /** A relay's answer only: a packet the DHT hands back when the relays are down may be older than one already read. */\n readAnsweredAt(pubKeyZ32: string): number | undefined { return this.relays.readAnsweredAt(pubKeyZ32); }\n readHeldBackFor(pubKeyZ32: string): number | undefined { return this.relays.readHeldBackFor(pubKeyZ32); }\n /**\n * With the DHT a packet goes there too, whatever the relays' budgets say: nothing is held, but a background write past\n * the DHT's share (`dhtBackgroundWrites`), which goes to the relays alone and is held as they say, or until its turn\n * on the DHT while every relay fails (`dhtWriteTurn`).\n */\n publishHeld(pubKeyZ32: string, options: PkarrRequestOptions = {}): DiscoveryBudgetError | null {\n if (!this.dht) return this.relays.publishHeld(pubKeyZ32, options);\n const wait = this.dhtWriteWait(pubKeyZ32, options, true);\n if (wait === 0) return null;\n return this.relaysDown() ? new DiscoveryBudgetError(wait, \"Background DHT writes in the relays' place are at their share; retry shortly\") : this.relays.publishHeld(pubKeyZ32, options);\n }\n onServerTime(listener: Parameters<RelayTransport[\"onServerTime\"]>[0]): () => void { return this.relays.onServerTime(listener); }\n /**\n * `dhtDirect: false` (Hide my IP from contacts): no packet is put on or read from the DHT, and its node is closed, so\n * no UDP goes from this machine to a DHT node; true again starts it at the next put or read. Absent leaves it as it is.\n */\n configure({ relays, dhtDirect }: { relays: string[]; readRelays: boolean; dhtDirect?: boolean }): void {\n if (!this.pinned) this.relays.setRelays(relays);\n if (dhtDirect === undefined) return;\n this.direct = dhtDirect;\n if (!dhtDirect) this.mainline?.stop().catch(() => {});\n }\n /**\n * The relays' side, and a write's turn `publishHeld` gave that no publish took (`writeTurns`). What the DHT side keeps\n * per key otherwise is bounded (`missing`, `MISSING_KEPT`; the background budgets' windows).\n */\n forget(keys: Iterable<string>): void {\n const gone = [...keys];\n for (const key of gone) this.writeTurns.delete(key);\n this.relays.forget(gone);\n }\n}\n"],"mappings":";;;;;;AA2BA,IAAM,YAAY;AAAI,IAAA,YAAY;AAClC,IAAMA,YAAU,KAAiB,SAAqB,QAAoB;CAAE,IAAI;EAAE,OAAO,QAAQ,OAAO,KAAK,SAAS,GAAG;CAAG,QAAQ;EAAE,OAAO;CAAO;AAAE;;;;;;AAMtJ,IAAM,SAAS,OAAO,KAAK,QAAQ;AACnC,IAAM,kBAAkB,KAAiB,SAAqB,QAC5D,CAAC,OAAO,KAAK,QAAQ,QAAQ,QAAQ,YAAY,KAAK,IAAI,QAAQ,QAAQ,OAAO,MAAM,CAAC,CAAC,CAAC,OAAO,MAAM,KAAKA,SAAO,KAAK,SAAS,GAAG;;AAGtI,IAAM,eAAe;CAAE,YAAY;CAAG,iBAAiB;CAAI,OAAO;CAAI,YAAY;AAAI;;AAEtF,IAAM,iBAAiB;;AAEvB,IAAM,cAAc;CAAE,KAAK;CAAO,QAAQ;AAAgB;;;;;;;;AAS1D,IAAa,gBAAb,MAA2B;CAII;CAH7B,4BAA6B,IAAI,IAA4C;CAC7E,MAAqD;CAErD,YAAY,SAA+C,cAAc;EAA5C,KAAA,SAAA;CAA6C;;CAG1E,IAAI,OAAe;EAAE,OAAO,KAAK,UAAU;CAAM;;CAGjD,KAAK,MAAc,MAAM,KAAK,IAAI,GAAY;EAC5C,MAAM,UAAU,QAA2D,MAAc,UAAkB;GACzG,IAAI,CAAC,QAAQ,OAAO;IAAE,QAAQ;IAAO,IAAI;GAAI;GAE7C,OAAO,SAAS,KAAK,IAAI,OAAO,OAAO,SAAS,KAAK,IAAI,GAAG,MAAM,OAAO,EAAE,IAAI,O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AO,MAAM,KAAK,WAAW,OAAO,GAAG;EAClD,KAAK,OAAO,OAAO,IAAI;CACzB;AACF"}
1
+ {"version":3,"file":"mainline-DY95WbuK.js","names":["verify"],"sources":["../../src/runtime/mainline.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport DHT from \"bittorrent-dht\";\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\nimport {\n BACKGROUND_REQUESTS_PER_MINUTE, DiscoveryBudgetError, HEDGE_MISSING_MS, HEDGE_MS, RelayTransport, RelaysFailedError, SLOW_MS, isDiscoveryBudgetError, newerPacket, parseRelayPayload, publicKeyFromZ32,\n type DiscoveryStatus, type GhostRecord, type Identity, type PkarrRequestOptions, type PkarrTransport, type RelayTransportOptions, type SignedPacket,\n} from \"@ghostly/core\";\n\n/**\n * Pkarr over the Mainline DHT (BEP44), from Node, as the Desktop reaches it from Rust: the relays are HTTP bridges to\n * this same DHT, so a headless Ghostly that speaks it directly keeps finding its contacts while the relays fail (they\n * answered HTTP 500 for more than ten minutes on 2026-09-27, and a group's edges stayed down all that while).\n *\n * A Pkarr packet is a BEP44 mutable item: the key is the Ed25519 public key, the value the DNS packet, the sequence\n * number its timestamp in microseconds, and the signature the one the relay payload already carries (over\n * `3:seqi<seq>e1:v<len>:<v>`). So one signed payload goes to the relays and to the DHT unchanged.\n */\n\nexport interface MainlineOptions {\n /** `host:port` nodes to start from; the public routers when absent; none with `false` (a testnet's first node). */\n bootstrap?: string[] | false;\n /** Address to bind (a loopback testnet binds 127.0.0.1). */\n host?: string;\n /** How long a lookup may take before it is given up, in ms. */\n timeoutMs?: number;\n}\n\nconst SIGNATURE = 64, TIMESTAMP = 8;\nconst verify = (sig: Uint8Array, message: Uint8Array, key: Uint8Array) => { try { return ed25519.verify(sig, message, key); } catch { return false; } };\n/**\n * What a `get` takes from the nodes that answer: a record signed without salt (Pkarr has none). bittorrent-dht reads a\n * reply's `salt` (`Buffer.concat` with the key) only once it is verified, and a number there threw in its socket handler:\n * any node a lookup asked, signing with its own key, raised an error nobody caught. Signed data is `4:salt…` with a salt.\n */\nconst SALTED = Buffer.from(\"4:salt\");\nconst verifyUnsalted = (sig: Uint8Array, message: Uint8Array, key: Uint8Array) =>\n !Buffer.from(message.buffer, message.byteOffset, Math.min(message.length, SALTED.length)).equals(SALTED) && verify(sig, message, key);\n\n/** Queries the node answers, a second: from each address (as libtorrent's default), and from all of them together. */\nconst QUERY_LIMITS = { perAddress: 5, perAddressBurst: 20, total: 50, totalBurst: 200 };\n/** Addresses `DhtQueryLimit` remembers: forged source addresses must not grow it without end. */\nconst ADDRESSES_KEPT = 4_096;\n/** Mutable items others put on the node: as many as bittorrent-dht keeps, each for the two hours BEP44 suggests. */\nconst VALUES_KEPT = { max: 1_000, maxAge: 2 * 60 * 60_000 };\n\n/**\n * The queries a DHT node answers, as token buckets: a burst then a rate per source address, and a total for all. UDP\n * has no handshake, so a query's address can be someone else's: answered without a limit, a stranger who parked a\n * 1000-byte item on the node had it send ~12.5x the bytes of each forged `get` (5-6x with nothing parked) to that\n * address, as fast as they came. Queries past either limit go unanswered, as an overloaded node's do. This node's own\n * lookups (answers to its queries, not queries) are not counted.\n */\nexport class DhtQueryLimit {\n private readonly addresses = new Map<string, { tokens: number; at: number }>();\n private all: { tokens: number; at: number } | null = null;\n\n constructor(private readonly limits: typeof QUERY_LIMITS = QUERY_LIMITS) {}\n\n /** Addresses remembered (`ADDRESSES_KEPT` at most). */\n get size(): number { return this.addresses.size; }\n\n /** Whether a query from `host` is answered now (counted if so). */\n take(host: string, now = Date.now()): boolean {\n const refill = (bucket: { tokens: number; at: number } | null | undefined, rate: number, burst: number) => {\n if (!bucket) return { tokens: burst, at: now };\n // A clock that went back refills nothing, and counts from now on.\n bucket.tokens = Math.min(burst, bucket.tokens + Math.max(0, now - bucket.at) * rate / 1_000);\n bucket.at = now;\n return bucket;\n };\n const all = this.all = refill(this.all, this.limits.total, this.limits.totalBurst);\n const own = refill(this.addresses.get(host), this.limits.perAddress, this.limits.perAddressBurst);\n // Kept in the order last asked: the address not heard from the longest goes first.\n this.addresses.delete(host);\n this.addresses.set(host, own);\n if (this.addresses.size > ADDRESSES_KEPT) this.addresses.delete(this.addresses.keys().next().value!);\n if (own.tokens < 1 || all.tokens < 1) return false;\n own.tokens -= 1; all.tokens -= 1;\n return true;\n }\n}\n\ntype Query = { q?: Buffer | string; a?: { k?: unknown; v?: unknown; seq?: unknown; sig?: unknown; salt?: unknown; target?: unknown; info_hash?: unknown } };\ntype QueryPeer = { address: string; port: number };\n/** The parts of bittorrent-dht's node (no API for them) through which it answers queries. */\ninterface DhtInternals { _onquery(query: Query, peer: QueryPeer): void; _rpc: { error(peer: QueryPeer, query: Query, error: [number, string]): void } }\n\n/**\n * A source on loopback is this machine, never a forged address from outside (a packet from the network claiming one is\n * dropped before it gets here): each of its ports is a node of its own (a loopback testnet's nodes all share the host),\n * counted apart. Any other address is counted whatever its port, as a forged source's port is the sender's choice.\n */\nconst LOOPBACK = /^(127\\.|::1$|::ffff:127\\.)/;\nconst bytes = (value: unknown, length: number): boolean => Buffer.isBuffer(value) && value.length === length;\n/** BEP44's bound on an item's value, which bittorrent-dht checks only on what has a `length` (not a dictionary). */\nconst VALUE_MAX = 1_000;\n\n/**\n * What the node answers strangers: queries at `DhtQueryLimit`'s rate, ping, find_node and get/get_peers as BEP5/BEP44\n * say, and puts of signed mutable items only, which is what Pkarr packets are (the testnet's nodes and the public DHT\n * keep each other's that way). It refuses what the app has no use for and bittorrent-dht kept for anyone and served to\n * anyone: immutable items and peers announced for torrents. A put's value is a string of at most 1000 bytes and its seq\n * a non-negative integer, as every Pkarr packet's: bittorrent-dht bounds only a value with a `length`, so a dictionary\n * of 60 KB was kept and served whole to every get. A query whose hash, key, signature or salt is not the string\n * BEP5/BEP44 say (a put signed without a key, a number for a target) threw out of the socket handler: an error nobody\n * caught, one per datagram. It is refused before bittorrent-dht reads it.\n */\nfunction answerBounded(dht: DHT, limit = new DhtQueryLimit()): void {\n const node = dht as unknown as DhtInternals;\n const answer = node._onquery.bind(dht);\n node._onquery = (query, peer) => {\n if (!query || !peer || !limit.take(LOOPBACK.test(peer.address) ? `${peer.address}:${peer.port}` : peer.address)) return;\n const q = query.q?.toString(), a = query.a ?? {};\n if (q === \"announce_peer\") return node._rpc.error(peer, query, [204, \"announce_peer is not served here\"]);\n if (q === \"put\" && (!bytes(a.k, 32) || !bytes(a.sig, SIGNATURE))) return node._rpc.error(peer, query, [203, \"only signed mutable items are stored here\"]);\n if (q === \"put\" && !(Buffer.isBuffer(a.v) && a.v.length <= VALUE_MAX)) return node._rpc.error(peer, query, [205, \"only values of at most 1000 bytes are stored here\"]);\n const malformed = ((q === \"get\" || q === \"find_node\") && !bytes(a.target, 20)) || (q === \"get_peers\" && !bytes(a.info_hash, 20))\n || (q === \"put\" && !(Number.isSafeInteger(a.seq) && (a.seq as number) >= 0))\n || (q === \"put\" && a.salt !== undefined && !(Buffer.isBuffer(a.salt) && a.salt.length <= 64));\n if (malformed) return node._rpc.error(peer, query, [203, \"malformed query\"]);\n try { answer(query, peer); } catch { /* a query bittorrent-dht could not read goes unanswered */ }\n };\n}\n\n/**\n * Every DHT node asked refused a put for holding a later-dated packet of the key (BEP44 error 302, \"sequence number less\n * than current\"): one put by this key's earlier clock, ahead of this one, before a restart forgot its date.\n */\nexport class DhtRefusedError extends Error {\n constructor(reason: string) {\n super(`The DHT holds a later-dated packet of this key (${reason})`);\n this.name = \"DhtRefusedError\";\n }\n}\n\n/**\n * A DHT node of this process: puts and gets Pkarr packets. The node starts at the first thing asked of it: a command\n * that reads only the profile (`chat list`, `settings get`) or a profile set offline asks nothing, and before, every\n * command bound a UDP port and bootstrapped from the public routers all the same, sending them this machine's address.\n */\nexport class Mainline {\n private node: { dht: DHT; listening: Promise<void> } | null = null;\n private closed = false;\n private readonly timeoutMs: number;\n\n constructor(private readonly options: MainlineOptions = {}) {\n this.timeoutMs = options.timeoutMs ?? 20_000;\n }\n\n private get dht(): DHT { return this.started().dht; }\n\n private started(): { dht: DHT; listening: Promise<void> } {\n if (this.closed) throw new Error(\"The DHT node is closed\");\n if (this.node) return this.node;\n const { host } = this.options;\n const bootstrap = this.options.bootstrap === false ? false : this.options.bootstrap?.length ? this.options.bootstrap : undefined;\n // `maxValues` reaches the `lru` that holds others' items, which takes `{ max, maxAge }` as well as a number.\n const dht = new DHT({ verify, maxValues: VALUES_KEPT, ...(bootstrap !== undefined ? { bootstrap } : {}), ...(host ? { host } : {}) });\n // A node of the table that errors must not end the process.\n dht.on(\"error\", () => {});\n answerBounded(dht);\n this.node = { dht, listening: new Promise((resolve) => dht.listen(0, host, () => resolve())) };\n return this.node;\n }\n\n /** Whether the node started (something was put, got or added). */\n get running(): boolean { return this.node !== null; }\n /** Its UDP socket is bound (starts the node). */\n get listening(): Promise<void> { return this.started().listening; }\n\n /** Adds a node (a testnet's peers). */\n addNode(host: string, port: number): void { this.dht.addNode({ host, port }); }\n address(): { port: number } { return this.dht.address() as { port: number }; }\n\n /** Puts a relay payload (`<signature><timestamp><DNS packet>`) as the mutable item of `pubKeyZ32`; resolves with the nodes that took it. */\n put(pubKeyZ32: string, payload: Uint8Array): Promise<number> {\n const k = Buffer.from(publicKeyFromZ32(pubKeyZ32));\n const sig = Buffer.from(payload.subarray(0, SIGNATURE));\n const seq = Number(new DataView(payload.buffer, payload.byteOffset + SIGNATURE, TIMESTAMP).getBigUint64(0));\n const v = Buffer.from(payload.subarray(SIGNATURE + TIMESTAMP));\n return this.bounded(new Promise((resolve, reject) => {\n this.dht.put({ k, v, seq, sig }, (error, _hash, nodes) => {\n if (error) reject((error as Error & { code?: unknown }).code === 302 ? new DhtRefusedError(error.message) : error);\n else if (!nodes) reject(new Error(\"No DHT node took the packet\")); else resolve(nodes);\n });\n }));\n }\n\n /** The newest packet of `pubKeyZ32` the DHT holds, checked; null when nobody has one. */\n get(pubKeyZ32: string): Promise<SignedPacket | null> {\n const k = Buffer.from(publicKeyFromZ32(pubKeyZ32));\n // A mutable item without salt is found under the SHA-1 of its public key (BEP44).\n const target = createHash(\"sha1\").update(k).digest();\n return this.bounded(new Promise((resolve, reject) => {\n this.dht.get(target, { cache: false, verify: verifyUnsalted }, (error, found) => {\n if (error) return reject(error);\n // A record is what its node sent, checked only by its signature: one signed with no `seq` (bittorrent-dht signs\n // `seq || 0`) or with a dictionary for `v` threw here, out of the socket's handler.\n if (!found || !Buffer.isBuffer(found.v) || !Buffer.isBuffer(found.sig) || !Number.isSafeInteger(found.seq) || found.seq < 0) return resolve(null);\n try {\n const timestamp = new Uint8Array(TIMESTAMP);\n new DataView(timestamp.buffer).setBigUint64(0, BigInt(found.seq));\n const payload = new Uint8Array(SIGNATURE + TIMESTAMP + found.v.length);\n payload.set(found.sig, 0); payload.set(timestamp, SIGNATURE); payload.set(found.v, SIGNATURE + TIMESTAMP);\n resolve(parseRelayPayload(pubKeyZ32, payload));\n } catch { resolve(null); }\n });\n }));\n }\n\n private bounded<T>(work: Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(\"DHT lookup timed out\")), this.timeoutMs);\n work.then((value) => { clearTimeout(timer); resolve(value); }, (error) => { clearTimeout(timer); reject(error); });\n });\n }\n\n /** Closes the node and its socket, if it started; the next thing asked of it starts it again. */\n stop(): Promise<void> {\n const node = this.node;\n this.node = null;\n return node ? new Promise((resolve) => node.dht.destroy(() => resolve())) : Promise.resolve();\n }\n\n destroy(): Promise<void> {\n this.closed = true;\n return this.stop();\n }\n}\n\n/** Keys a `RelaysAndDht` remembers as found nowhere (`missing`). */\nconst MISSING_KEPT = 256;\n\n/** How long a key that asked for a background DHT read counts among those that share the budget (`DhtBackgroundBudget`). */\nconst ASKERS_WINDOW_MS = 2 * 60_000;\n/** The same for a background DHT write: past a chat's 4-minute upkeep, with room for its turn (a control envelope's life). */\nconst WRITERS_WINDOW_MS = 10 * 60_000;\nconst MINUTE_MS = 60_000;\n\n/**\n * Background reads that go to the DHT in the relays' place (every relay failing, or failing this read), within the share\n * the relays would have given them (`BACKGROUND_REQUESTS_PER_MINUTE` a minute on each relay): a minute's lookups at\n * most, and each key in its turn, no sooner than the keys asking share that minute (`n` keys at `perMinute` a minute:\n * once every `n / perMinute` minutes). Without it, a daemon looked up every contact away on the DHT four times a minute\n * for as long as the relays failed (200 lookups a minute at 50 contacts, 1,200 at 300), where with the relays up it\n * made 26-54 relay reads a minute in all; each lookup on the real DHT is dozens of UDP queries.\n * Reads someone waits on (not `background`, or `urgent`, `signal`, `door`, `resume`) never wait for it, nor count.\n */\nexport class DhtBackgroundBudget {\n private readonly spent: number[] = [];\n /** Per key, when it last asked (oldest first) and when its last lookup went. */\n private readonly askedAt = new Map<string, number>();\n private readonly lookedAt = new Map<string, number>();\n /** The time of the last `take`: none of the above is dated after it. */\n private latest = -Infinity;\n\n /** `askersWindowMs`: how long a key counts among those sharing the budget since it last asked (`ASKERS_WINDOW_MS`). */\n constructor(private readonly perMinute: () => number, private readonly askersWindowMs = ASKERS_WINDOW_MS) {}\n\n /** 0: the lookup goes now (counted). Otherwise how long until this key's turn, in ms; nothing is counted. */\n take(pubKeyZ32: string, now = Date.now()): number {\n // The clock went back (an NTP step, a clock that ran ahead fixed by hand): what is dated after now counts as of now,\n // as just spent. Counted as it was, an hour's step back held every key's lookup for 56 minutes (bug hunt, 2026-11-07).\n if (now < this.latest) {\n this.spent.forEach((at, i) => { this.spent[i] = Math.min(at, now); });\n for (const times of [this.askedAt, this.lookedAt]) for (const [key, at] of times) if (at > now) times.set(key, now);\n }\n this.latest = now;\n this.askedAt.delete(pubKeyZ32);\n this.askedAt.set(pubKeyZ32, now);\n for (const [key, at] of this.askedAt) {\n if (now - at < this.askersWindowMs) break;\n this.askedAt.delete(key);\n this.lookedAt.delete(key);\n }\n while (this.spent.length && now - this.spent[0]! >= MINUTE_MS) this.spent.shift();\n const limit = Math.max(1, this.perMinute());\n const turn = Math.ceil(this.askedAt.size * MINUTE_MS / limit);\n const last = this.lookedAt.get(pubKeyZ32);\n const ownTurn = last === undefined ? 0 : last + turn - now;\n // The minute's lookups are spent (keys new to it, all at once): this key's turn, or the minute's next free one if later.\n const minute = this.spent.length >= limit ? this.spent[0]! + MINUTE_MS - now : 0;\n if (ownTurn > 0 || minute > 0) return Math.max(ownTurn, minute, last === undefined ? turn : 0);\n this.spent.push(now);\n this.lookedAt.set(pubKeyZ32, now);\n return 0;\n }\n}\n\n/** A read nobody waits on: what the relays' budget calls background, and what the DHT's (`DhtBackgroundBudget`) holds. */\nconst waitable = (options: PkarrRequestOptions): boolean =>\n !!options.background && !options.urgent && !options.signal && !options.door && !options.resume;\n\n/**\n * The relays first, as the web app reaches Pkarr (its contacts read only the relays), and the DHT beside them: every\n * packet also goes to the DHT, and a read goes there when every relay is failing, the read failed, or this app's own\n * request budget held it back (the DHT has no budget), or every relay rate limits this address (429). A background read\n * this app's budget holds waits for it. Background reads the DHT answers in the relays' place keep to the relays'\n * background share (`DhtBackgroundBudget`), and so do background writes on the DHT: one past it goes to the relays alone.\n *\n * `pinned`: the relays given are the only ones (`GHOSTLY_PKARR_RELAYS`, a private network): the profile's `relays`\n * setting does not replace them. With no DHT (`dht` null), the relays alone carry every packet.\n */\nexport class RelaysAndDht implements PkarrTransport {\n readonly relays: RelayTransport;\n private lastVia: \"relay\" | \"dht\" = \"relay\";\n /**\n * Keys a hedged read found nowhere: the DHT said so before the relays' slow 404 came, so the next poll of the key\n * hedges late too (`HEDGE_MISSING_MS`), not only once that 404 lands. The newest `MISSING_KEPT`.\n */\n private readonly missing = new Set<string>();\n /** Background reads on the DHT in the relays' place, at their background share (`DhtBackgroundBudget`). */\n private readonly dhtBackground = new DhtBackgroundBudget(() => BACKGROUND_REQUESTS_PER_MINUTE * this.relays.describe().relays.length);\n /**\n * Background writes on the DHT (upkeep nobody waits on: a chat's heartbeat and keep-alive while its contact is away)\n * at the same share. Without it, every chat put two packets there every 4 minutes for as long as the daemon ran,\n * whatever the relays' budget held of the same: ~104 puts a minute at 200 chats, each a whole iterative lookup.\n * A key counts among those sharing it for longer than a read's (`WRITERS_WINDOW_MS`): one that went asks again only\n * at the next upkeep, 4 minutes on, and forgotten by then it came back as new, without its turn: some chats were put\n * every 4 minutes and others not once in 25.\n * `writeTurns`: keys whose write `publishHeld` let go, not counted again when the publish comes.\n */\n private readonly dhtBackgroundWrites = new DhtBackgroundBudget(() => BACKGROUND_REQUESTS_PER_MINUTE * this.relays.describe().relays.length, WRITERS_WINDOW_MS);\n private readonly writeTurns = new Set<string>();\n\n /** Off while the profile keeps to the relays (Hide my IP from contacts, `configure`'s `dhtDirect: false`). */\n private direct = true;\n\n constructor(private readonly mainline: Mainline | null, relays: RelayTransportOptions = {}, private readonly pinned = false) {\n this.relays = new RelayTransport(relays);\n }\n\n /** The DHT this transport reaches now: none while the profile keeps to the relays. */\n private get dht(): Mainline | null { return this.direct ? this.mainline : null; }\n\n async publish(identity: Identity, records: GhostRecord[], options: PkarrRequestOptions = {}): Promise<void> {\n // BEP44 sequence numbers must strictly increase, on the relays and on the DHT alike: one payload for both, dated\n // past every packet put or read under the key (`RelayTransport.publishDated`), whichever clock dated those.\n // With the DHT, the packet goes there whatever the relays' budgets say: signed every time. Without it (a private\n // network's relays only), a publish none of them takes now is not signed at all. A background write the DHT's\n // share holds goes to the relays alone, as without the DHT, or waits its turn there while every relay fails.\n const toDht = this.dht !== null && this.dhtWriteTurn(identity.pubKeyZ32, options);\n await this.relays.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putBoth(key, payload, options, conflict, timestamp, toDht), options, false, toDht);\n }\n\n async publishPayload(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions = {}): Promise<void> {\n return this.putBoth(pubKeyZ32, payload, options, undefined, undefined, this.dhtWriteTurn(pubKeyZ32, options));\n }\n\n /** Every relay is left alone for failing: what goes to them alone goes nowhere. */\n private relaysDown(): boolean {\n return this.relays.discovery().relays.every((relay) => relay.state === \"failing\");\n }\n\n /**\n * Whether this write goes to the DHT too (`dhtWriteWait`). One the DHT's share holds while every relay fails is held\n * back until its turn there (a `DiscoveryBudgetError`), as a background read is: tried on the relays alone, it failed,\n * and the link tried it again every 4 s until that turn came, 15 packets built a minute per chat whose contact was\n * away (~2,300 a minute at 200 chats, twice the CPU of the daemon before the share, bug hunt 2026-11-14).\n */\n private dhtWriteTurn(pubKeyZ32: string, options: PkarrRequestOptions): boolean {\n const wait = this.dhtWriteWait(pubKeyZ32, options);\n if (wait > 0 && this.relaysDown()) throw new DiscoveryBudgetError(wait, \"Background DHT writes in the relays' place are at their share; retry shortly\");\n return wait === 0;\n }\n\n /**\n * 0: this write goes to the DHT now (a background one counted in its share, unless `publishHeld` already let it go).\n * Otherwise how long until its turn there. Writes someone waits on never wait for it, nor count; with no relay set at\n * all the DHT is the only way.\n */\n private dhtWriteWait(pubKeyZ32: string, options: PkarrRequestOptions, ahead = false): number {\n if (!this.dht || !waitable(options) || this.relays.describe().relays.length === 0) return 0;\n if (this.writeTurns.delete(pubKeyZ32)) return 0;\n const wait = this.dhtBackgroundWrites.take(pubKeyZ32);\n if (ahead && wait === 0) this.writeTurns.add(pubKeyZ32);\n return wait;\n }\n\n /**\n * `timestamp`: the payload was just signed here (`publish`), dated so; its signature is not checked again on the way\n * to the relays. Without it (`publishPayload`, signed elsewhere) the relays' side checks it to read its date.\n * `toDht` false: the relays alone (a background write the DHT's share holds).\n */\n private async putBoth(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions, conflict?: (relay: string, read?: () => Promise<bigint | null>) => void, timestamp?: bigint, toDht = true): Promise<void> {\n const toRelays = () => timestamp === undefined\n ? this.relays.publishPayload(pubKeyZ32, payload, options, conflict)\n : this.relays.putSigned(pubKeyZ32, payload, timestamp, options, conflict);\n if (!this.dht || !toDht) return toRelays();\n const onDht = this.dht.put(pubKeyZ32, payload);\n onDht.catch(() => {});\n const onRelays = toRelays();\n onRelays.catch(() => {});\n // Out on the DHT is out (a Pkarr relay reads the DHT for a key it has not got): a relay that takes the request and\n // never answers held each publish for its 10 s timeout, an invite's first among them, while the DHT took it in\n // milliseconds. The relays' copy finishes in the background. A budget's hold is said before any request goes, so\n // it wins this race: once the DHT took the packet, that is out too, and the relays get it when their budget frees\n // (`putLater`; browser contacts read only them). Said held back, the link signed it and put it on the DHT again in\n // 0.25-4 s, at budget 1.5-2.2x the DHT puts of a DHT-only daemon.\n let refused: unknown;\n const tookIt = onDht.then(() => true, (error: unknown) => {\n refused = error;\n // The DHT holds a later-dated packet of this key, as a relay that answers 409 does: its date is read there, and\n // the records go again dated just past it (`publishDated`). After a clock that ran ahead was set right, a\n // restarted CLI had every put refused, tried again every 4 s until the clock caught up (15 a minute per chat), and\n // texts to a contact away stayed queued.\n if (error instanceof DhtRefusedError) conflict?.(\"dht\", () => this.fromDht(pubKeyZ32).then((packet) => packet?.timestampMicros ?? null));\n return false;\n });\n if (await Promise.race([onRelays.then(() => false, () => false), tookIt])) return;\n try {\n await onRelays;\n } catch (error) {\n if (isDiscoveryBudgetError(error)) {\n if (!(await tookIt)) throw error;\n this.relays.putLater(pubKeyZ32, payload, timestamp, options);\n return;\n }\n // The relays failed: the DHT's answer is the publish's, and its refusal is said with theirs.\n if (!(await tookIt)) throw refused instanceof Error ? new Error(`${error instanceof Error ? error.message : String(error)}; ${refused.message}`, { cause: error }) : error;\n }\n }\n\n async resolve(pubKeyZ32: string, options: PkarrRequestOptions = {}, keptOnFailure = true): Promise<SignedPacket | null> {\n if (!this.dht) return this.relays.resolve(pubKeyZ32, options, keptOnFailure);\n let fromRelays: SignedPacket | null = null, failed: unknown = null;\n // Every relay left alone for failing: the relays answer from what they last saw, if anything; the DHT is asked.\n const down = () => this.relays.discovery().relays.every((relay) => relay.state === \"failing\");\n if (!down()) {\n const started = Date.now();\n // A read the relays failed asks the DHT at once, their last copy kept to weigh against its packet. Handed back\n // as their answer, it stood for each 20 s cooldown until the breaker opened: about 40 s of a contact's old packet\n // with the newer one on the DHT (bug hunt, 2026-10-17).\n const relays = this.relays.resolve(pubKeyZ32, options, false).then((packet) => ({ packet, failed: null as unknown }), (error: unknown) => ({ packet: null, failed: error }));\n let timer: ReturnType<typeof setTimeout> | undefined;\n // A key whose last read found nothing: the relays take 3-5 s to say a key is not there\n // (they ask the DHT themselves), and a hedge at HEDGE_MS made every poll of an unused invite's key a DHT lookup\n // of its own (+47 in 10 min: agents#1595). Their own hedge waits as long (`RelayTransport`, `HEDGE_MISSING_MS`).\n const hedgeAfter = this.relays.lastReadMissing(pubKeyZ32) || this.missing.has(pubKeyZ32) ? HEDGE_MISSING_MS : HEDGE_MS;\n const answered = await Promise.race([relays, new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), hedgeAfter); })]);\n clearTimeout(timer);\n // The relays have not answered within a hedge's time (one that takes requests and never answers held each read\n // for its 10 s timeout): the DHT is asked too.\n if (!answered) {\n const found = await this.hedged(pubKeyZ32, relays, started);\n this.missing.delete(pubKeyZ32);\n if (!found) { this.missing.add(pubKeyZ32); if (this.missing.size > MISSING_KEPT) this.missing.delete(this.missing.values().next().value!); }\n return found;\n }\n ({ packet: fromRelays, failed } = answered);\n // No relay is asked now: each one rate limits this address (429) for as long as it said, or fails. Their answer is\n // what they last saw, or a wait, and the DHT is asked in their place, as when they all fail (a background read\n // at their share). Taken as their answer, a daemon whose relays answered 429 for 10 minutes read none of its 50\n // contacts in that time, and looked none up on the DHT (bug hunt, 2026-11-11).\n const refusing = this.relays.discovery().relays.every((relay) => relay.state !== \"ok\");\n // The relays' budget held the read back: the DHT, which has no budget and already has a contact's first\n // envelope, is asked instead. Waiting for the relays' minute made each pairing past ~10 chats on working relays\n // take 3-18 s (13-37 s on one relay), where DHT-only pairings take 0.1-2.8 s (agents#1715). Found nowhere there,\n // or a background read, it is still a wait.\n if (isDiscoveryBudgetError(failed) && !(refusing && options.background)) return this.heldBack(pubKeyZ32, failed, options);\n if (failed instanceof RelaysFailedError) fromRelays = failed.kept;\n if (!failed) this.lastVia = \"relay\";\n if (!failed && !down() && !refusing) return fromRelays;\n }\n try {\n // A background read the DHT answers instead of the relays waits its turn there (`DhtBackgroundBudget`), as it did\n // on them: held back, as their budget holds one. With no relay set at all the DHT is the only way, not a stand-in.\n if (waitable(options) && this.relays.describe().relays.length > 0) {\n const wait = this.dhtBackground.take(pubKeyZ32);\n if (wait > 0) throw new DiscoveryBudgetError(wait, \"Background DHT reads in the relays' place are at their share; retry shortly\");\n }\n const fromDht = await this.fromDht(pubKeyZ32);\n this.lastVia = \"dht\";\n return newerPacket(fromRelays, fromDht);\n } catch (error) {\n // Nothing answered, the DHT neither: the relays' last copy is the answer, or, for a caller that asks, the failure\n // that carries it (`keptOnFailure`).\n if (fromRelays && (keptOnFailure || !(failed instanceof RelaysFailedError))) return fromRelays;\n throw failed ?? error;\n }\n }\n\n private async heldBack(pubKeyZ32: string, held: unknown, options: PkarrRequestOptions): Promise<SignedPacket> {\n if (options.background) throw held;\n const fromDht = await this.fromDht(pubKeyZ32).catch(() => null);\n if (!fromDht) throw held;\n this.lastVia = \"dht\";\n return fromDht;\n }\n\n private async fromDht(pubKeyZ32: string): Promise<SignedPacket | null> {\n // The switch turned while a read was on its way to the DHT: it does not go.\n if (!this.dht) throw new Error(\"The DHT is not reached while the profile keeps to the relays\");\n const packet = await this.dht.get(pubKeyZ32);\n if (packet) this.relays.sawTimestamp(pubKeyZ32, packet.timestampMicros);\n return packet;\n }\n\n /**\n * A read the relays are slow to answer, the DHT asked beside them. The relays' packet first is the answer, as without\n * the hedge. The DHT's first waits for the relays until a slow relay would have had its say (`SLOW_MS`, a relay\n * fetching the packet from the DHT itself), or until they answer, and the newer of the two is the answer: taken at\n * once, the DHT's older copy won every read over a relay that took 2 s with the newer one (agents#1594). The DHT\n * finding none is the answer once that time is up too, or once the relays answered. Both failing: the relays' reason.\n */\n private async hedged(pubKeyZ32: string, relays: Promise<{ packet: SignedPacket | null; failed: unknown }>, started: number): Promise<SignedPacket | null> {\n const dht = this.fromDht(pubKeyZ32).then((packet) => ({ packet, failed: null as unknown, via: \"dht\" as const }), (error: unknown) => ({ packet: null, failed: error, via: \"dht\" as const }));\n const viaRelays = relays.then((r) => ({ ...r, via: \"relay\" as const }));\n const first = await Promise.race([viaRelays, dht]);\n if (first.packet && first.via === \"relay\") { this.lastVia = \"relay\"; return first.packet; }\n const fromDht = await dht;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const slowAfter = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), Math.max(0, SLOW_MS - (Date.now() - started))); });\n const fromRelays = await Promise.race([viaRelays, slowAfter]);\n clearTimeout(timer);\n if (fromDht.packet) {\n const newer = newerPacket(fromRelays?.packet, fromDht.packet);\n this.lastVia = newer === fromDht.packet ? \"dht\" : \"relay\";\n return newer;\n }\n if (fromRelays?.packet) { this.lastVia = \"relay\"; return fromRelays.packet; }\n if (!fromDht.failed) { this.lastVia = \"dht\"; return null; }\n if (!fromRelays) throw fromDht.failed;\n if (!fromRelays.failed) return null;\n throw fromRelays.failed;\n }\n\n describe(): { protocol: string; relays: string[] } {\n return { protocol: this.dht ? \"Pkarr relays (HTTP), and the Mainline DHT (BEP44) directly\" : \"Pkarr relays (HTTP)\", relays: this.relays.describe().relays };\n }\n discovery(): DiscoveryStatus {\n const status = this.relays.discovery();\n return this.lastVia === \"dht\" ? { ...status, path: { via: \"dht\" } } : status;\n }\n subscribe(listener: Parameters<RelayTransport[\"subscribe\"]>[0]): () => void { return this.relays.subscribe(listener); }\n /** A relay's answer only: a packet the DHT hands back when the relays are down may be older than one already read. */\n readAnsweredAt(pubKeyZ32: string): number | undefined { return this.relays.readAnsweredAt(pubKeyZ32); }\n readHeldBackFor(pubKeyZ32: string): number | undefined { return this.relays.readHeldBackFor(pubKeyZ32); }\n /**\n * With the DHT a packet goes there too, whatever the relays' budgets say: nothing is held, but a background write past\n * the DHT's share (`dhtBackgroundWrites`), which goes to the relays alone and is held as they say, or until its turn\n * on the DHT while every relay fails (`dhtWriteTurn`).\n */\n publishHeld(pubKeyZ32: string, options: PkarrRequestOptions = {}): DiscoveryBudgetError | null {\n if (!this.dht) return this.relays.publishHeld(pubKeyZ32, options);\n const wait = this.dhtWriteWait(pubKeyZ32, options, true);\n if (wait === 0) return null;\n return this.relaysDown() ? new DiscoveryBudgetError(wait, \"Background DHT writes in the relays' place are at their share; retry shortly\") : this.relays.publishHeld(pubKeyZ32, options);\n }\n onServerTime(listener: Parameters<RelayTransport[\"onServerTime\"]>[0]): () => void { return this.relays.onServerTime(listener); }\n /**\n * `dhtDirect: false` (Hide my IP from contacts): no packet is put on or read from the DHT, and its node is closed, so\n * no UDP goes from this machine to a DHT node; true again starts it at the next put or read. Absent leaves it as it is.\n */\n configure({ relays, dhtDirect }: { relays: string[]; readRelays: boolean; dhtDirect?: boolean }): void {\n if (!this.pinned) this.relays.setRelays(relays);\n if (dhtDirect === undefined) return;\n this.direct = dhtDirect;\n if (!dhtDirect) this.mainline?.stop().catch(() => {});\n }\n /**\n * The relays' side, and a write's turn `publishHeld` gave that no publish took (`writeTurns`). What the DHT side keeps\n * per key otherwise is bounded (`missing`, `MISSING_KEPT`; the background budgets' windows).\n */\n forget(keys: Iterable<string>): void {\n const gone = [...keys];\n for (const key of gone) this.writeTurns.delete(key);\n this.relays.forget(gone);\n }\n}\n"],"mappings":";;;;;;AA2BA,IAAM,YAAY;AAAI,IAAA,YAAY;AAClC,IAAMA,YAAU,KAAiB,SAAqB,QAAoB;CAAE,IAAI;EAAE,OAAO,QAAQ,OAAO,KAAK,SAAS,GAAG;CAAG,QAAQ;EAAE,OAAO;CAAO;AAAE;;;;;;AAMtJ,IAAM,SAAS,OAAO,KAAK,QAAQ;AACnC,IAAM,kBAAkB,KAAiB,SAAqB,QAC5D,CAAC,OAAO,KAAK,QAAQ,QAAQ,QAAQ,YAAY,KAAK,IAAI,QAAQ,QAAQ,OAAO,MAAM,CAAC,CAAC,CAAC,OAAO,MAAM,KAAKA,SAAO,KAAK,SAAS,GAAG;;AAGtI,IAAM,eAAe;CAAE,YAAY;CAAG,iBAAiB;CAAI,OAAO;CAAI,YAAY;AAAI;;AAEtF,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ACvD,IAAI,SAAS,GAAG,OAAO;EACvB,OAAO,KAAK,WAAW,IAAI,IAAI,qBAAqB,MAAM,8EAA8E,IAAI,KAAK,OAAO,YAAY,WAAW,OAAO;CACxL;CACA,aAAa,UAAqE;EAAE,OAAO,KAAK,OAAO,aAAa,QAAQ;CAAG;;;;;CAK/H,UAAU,EAAE,QAAQ,aAAmF;EACrG,IAAI,CAAC,KAAK,QAAQ,KAAK,OAAO,UAAU,MAAM;EAC9C,IAAI,cAAc,KAAA,GAAW;EAC7B,KAAK,SAAS;EACd,IAAI,CAAC,WAAW,KAAK,UAAU,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC;CACtD;;;;;CAKA,OAAO,MAA8B;EACnC,MAAM,OAAO,CAAC,GAAG,IAAI;EACrB,KAAK,MAAM,OAAO,MAAM,KAAK,WAAW,OAAO,GAAG;EAClD,KAAK,OAAO,OAAO,IAAI;CACzB;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { a as fromZ32, f as utf8Encode, i as fromBase64Url, l as toBase64Url, s as randomBytes, t as bytesEqual, u as toZ32 } from "./bytes-C1DNGY18.js";
2
2
  import { c as openRelayPayload, d as signRelayPayload, m as encodeTxtPacket, p as decodeTxtPacket, r as PacketTooLargeError, t as MAX_DNS_PACKET_BYTES } from "./pkarr-BQo4PcCg.js";
3
- import { c as normalizeRelayUrl, t as DEFAULT_RELAYS } from "./relay-Cjfmdec0.js";
3
+ import { c as normalizeRelayUrl, t as DEFAULT_RELAYS } from "./relay-CHWg5hpZ.js";
4
4
  import { s as IdentityCheckUnavailable, u as boundVerifiedIdentity } from "./identityProofs-Cksc_K7_.js";
5
5
  import { l as providerDescriptorProblems } from "./types-CdWwgvyt.js";
6
6
  import { ed25519 } from "@noble/curves/ed25519.js";
@@ -859,4 +859,4 @@ function setOwnDidSource(read) {
859
859
  var ownDid = () => source();
860
860
  export { normalizePubkyKey as C, pubkyProofPath as E, newPubkyProofFolder as S, pubkyProofFile as T, resolveDidDht as _, registeredLightningProviders as a, isPubkyKey as b, boundedIdentityFetch as c, testSwitch as d, DidDhtError as f, encodeDidDhtPacket as g, encodeDidDhtDeactivated as h, registeredIdentityProviders as i, verifyIdentity as l, didDhtFromPublicKey as m, setOwnDidSource as n, registeredOnchainProviders as o, didDhtDocument as p, onAdaptersChanged as r, reserveAdapterIds as s, ownDid as t, testBuild as u, signDidDhtPacket as v, pubkyProofCapability as w, isPubkyProofFolder as x, PUBKY_PROOF_MAX_BYTES as y };
861
861
 
862
- //# sourceMappingURL=ownDid-DY3rYqDI.js.map
862
+ //# sourceMappingURL=ownDid-BErplN7N.js.map