@ghostlytools/cli 1.12.1 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +8 -7
  2. package/dist/assets/{api-jRUXnBdX.js → api-DF36rBJK.js} +2 -2
  3. package/dist/assets/{api-BwEgbvvK.js → api-Dnq86JAA.js} +139 -41
  4. package/dist/assets/api-Dnq86JAA.js.map +1 -0
  5. package/dist/assets/{apiKit-BlsNk-Cx.js → apiKit-nLK4jeTq.js} +3 -3
  6. package/dist/assets/{apiKit-BlsNk-Cx.js.map → apiKit-nLK4jeTq.js.map} +1 -1
  7. package/dist/assets/{appFetch-CW9fJPHh.js → appFetch-wqBWi3Ry.js} +2 -2
  8. package/dist/assets/{appFetch-CW9fJPHh.js.map → appFetch-wqBWi3Ry.js.map} +1 -1
  9. package/dist/assets/{apps-CL8TXHhu.js → apps-DBVhKpfe.js} +10 -10
  10. package/dist/assets/apps-DBVhKpfe.js.map +1 -0
  11. package/dist/assets/{apps-BcG4u6SM.js → apps-nLtyhC2f.js} +1 -1
  12. package/dist/assets/{backup-BA41EDvh.js → backup-Bczllmzf.js} +4 -4
  13. package/dist/assets/{backup-BA41EDvh.js.map → backup-Bczllmzf.js.map} +1 -1
  14. package/dist/assets/{backup-xZfV-ytw.js → backup-D6s0LQdg.js} +1 -1
  15. package/dist/assets/{bitcoind-Dh7n9amb.js → bitcoind-DML_-Xbv.js} +2 -2
  16. package/dist/assets/{bitcoind-Dh7n9amb.js.map → bitcoind-DML_-Xbv.js.map} +1 -1
  17. package/dist/assets/{buttons-SH1tNRh7.js → buttons-B3C3vdhH.js} +30 -9
  18. package/dist/assets/buttons-B3C3vdhH.js.map +1 -0
  19. package/dist/assets/buttons-DaY5FYlV.js +1 -0
  20. package/dist/assets/{client-DGS-atRu.js → client-B7jRrSnb.js} +3 -3
  21. package/dist/assets/{client-DGS-atRu.js.map → client-B7jRrSnb.js.map} +1 -1
  22. package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
  23. package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
  24. package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
  25. package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
  26. package/dist/assets/{fixedHosts-CPSsGOI2.js → fixedHosts-H3i6o9Iy.js} +2 -2
  27. package/dist/assets/{fixedHosts-CPSsGOI2.js.map → fixedHosts-H3i6o9Iy.js.map} +1 -1
  28. package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
  29. package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
  30. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  31. package/dist/assets/{groupMeta-DxuJzko_.js → groupMeta--fxSh792.js} +165 -20
  32. package/dist/assets/groupMeta--fxSh792.js.map +1 -0
  33. package/dist/assets/{host-BxM-HMr0.js → host-CGzVFfMz.js} +211 -58
  34. package/dist/assets/host-CGzVFfMz.js.map +1 -0
  35. package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-B4_wdCtx.js} +2 -2
  36. package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-B4_wdCtx.js.map} +1 -1
  37. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-Ce-gWsRY.js} +2 -2
  38. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-Ce-gWsRY.js.map} +1 -1
  39. package/dist/assets/{irohWeb-CbnGtUo6.js → irohWeb-Dp1i8v6n.js} +13 -12
  40. package/dist/assets/irohWeb-Dp1i8v6n.js.map +1 -0
  41. package/dist/assets/{main-CwTaepxR.js → main-C8J53SwH.js} +68 -63
  42. package/dist/assets/main-C8J53SwH.js.map +1 -0
  43. package/dist/assets/{mainline-CVrd0C1n.js → mainline-DY95WbuK.js} +2 -2
  44. package/dist/assets/{mainline-CVrd0C1n.js.map → mainline-DY95WbuK.js.map} +1 -1
  45. package/dist/assets/{ownDid-DY3rYqDI.js → ownDid-oa-T2vmZ.js} +9 -5
  46. package/dist/assets/ownDid-oa-T2vmZ.js.map +1 -0
  47. package/dist/assets/{ownStatus-DtzIllg2.js → ownStatus-Bc08eNJY.js} +7 -6
  48. package/dist/assets/ownStatus-Bc08eNJY.js.map +1 -0
  49. package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-Dppn8lUN.js} +3 -3
  50. package/dist/assets/pairedTransports-Dppn8lUN.js.map +1 -0
  51. package/dist/assets/{profiles-BOYGlmu2.js → profiles-B2uy04ph.js} +3 -3
  52. package/dist/assets/{profiles-BOYGlmu2.js.map → profiles-B2uy04ph.js.map} +1 -1
  53. package/dist/assets/{registry-Bep4umOM.js → registry-DbTLLs3y.js} +9 -5
  54. package/dist/assets/registry-DbTLLs3y.js.map +1 -0
  55. package/dist/assets/{registry-4W1LGlCF.js → registry-bLIfG619.js} +1 -1
  56. package/dist/assets/{relay-Cjfmdec0.js → relay-CHWg5hpZ.js} +73 -11
  57. package/dist/assets/relay-CHWg5hpZ.js.map +1 -0
  58. package/dist/assets/{resolve-CIc3KZMV.js → resolve-DNX-eecG.js} +9 -4
  59. package/dist/assets/resolve-DNX-eecG.js.map +1 -0
  60. package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
  61. package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
  62. package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
  63. package/dist/assets/{server-D4gf-LnD.js → server-DWJ4RzJn.js} +748 -222
  64. package/dist/assets/server-DWJ4RzJn.js.map +1 -0
  65. package/dist/assets/{translate-BcbSWkuq.js → translate-CHj_PdLg.js} +13 -8
  66. package/dist/assets/translate-CHj_PdLg.js.map +1 -0
  67. package/dist/assets/{waitNotice-DQvZgz2T.js → waitNotice-Cvz5CiKR.js} +57 -3
  68. package/dist/assets/waitNotice-Cvz5CiKR.js.map +1 -0
  69. package/dist/ghostly.mjs +1 -1
  70. package/npm-shrinkwrap.json +2 -2
  71. package/package.json +1 -1
  72. package/dist/assets/api-BwEgbvvK.js.map +0 -1
  73. package/dist/assets/apps-CL8TXHhu.js.map +0 -1
  74. package/dist/assets/buttons-CsGdQNnR.js +0 -1
  75. package/dist/assets/buttons-SH1tNRh7.js.map +0 -1
  76. package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
  77. package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
  78. package/dist/assets/groupMeta-DxuJzko_.js.map +0 -1
  79. package/dist/assets/host-BxM-HMr0.js.map +0 -1
  80. package/dist/assets/irohWeb-CbnGtUo6.js.map +0 -1
  81. package/dist/assets/main-CwTaepxR.js.map +0 -1
  82. package/dist/assets/ownDid-DY3rYqDI.js.map +0 -1
  83. package/dist/assets/ownStatus-DtzIllg2.js.map +0 -1
  84. package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
  85. package/dist/assets/registry-Bep4umOM.js.map +0 -1
  86. package/dist/assets/relay-Cjfmdec0.js.map +0 -1
  87. package/dist/assets/resolve-CIc3KZMV.js.map +0 -1
  88. package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
  89. package/dist/assets/server-D4gf-LnD.js.map +0 -1
  90. package/dist/assets/translate-BcbSWkuq.js.map +0 -1
  91. package/dist/assets/waitNotice-DQvZgz2T.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,QAC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AAG;CACtG,gBAAgB,WAAuC;EAAE,OAAO,KAAK,OAAO,gBAAgB,SAAS;CAAG;;;;;;CAMxG,YAAY,WAAmB,UAA+B,CAAC,GAAgC;EAC7F,IAAI,CAAC,KAAK,KAAK,OAAO,KAAK,OAAO,YAAY,WAAW,OAAO;EAChE,MAAM,OAAO,KAAK,aAAa,WAAW,SAAS,IAAI;EACvD,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
+ {"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,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,OAAO,GAAK;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AAK,WAAW,OAAO,GAAG;EAClD,KAAK,OAAO,OAAO,IAAI;CACzB;AACF"}
@@ -1,7 +1,8 @@
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
+ import { p as isOwnPkarrRelayUrl } from "./resolve-DNX-eecG.js";
5
6
  import { l as providerDescriptorProblems } from "./types-CdWwgvyt.js";
6
7
  import { ed25519 } from "@noble/curves/ed25519.js";
7
8
  import { sha256 } from "@noble/hashes/sha2.js";
@@ -664,14 +665,17 @@ function descriptorProblems(p) {
664
665
  * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,
665
666
  * redirects refused unless asked for.
666
667
  * `online` false refuses everything (the person turned the network off).
668
+ * A did:dht read of the profile's own Pkarr relays (`ownPkarrRelay`) may be http://, through `relayFetcher`: those are
669
+ * the relays the person chose, as the chats read them, not an address a contact named.
667
670
  */
668
671
  function boundedIdentityFetch(options = { online: () => true }) {
669
- return async (url, { headers, maxBytes = 65536, signal, redirect = "error" } = {}) => {
672
+ return async (url, { headers, maxBytes = 65536, signal, redirect = "error", ownPkarrRelay } = {}) => {
670
673
  if (!options.online()) throw new IdentityCheckUnavailable("Offline: this identity cannot be checked now");
671
674
  const target = new URL(url);
672
- if (target.protocol !== "https:" || target.username || target.password) throw new Error("Identity checks use HTTPS only");
675
+ const ownRelay = ownPkarrRelay === true && isOwnPkarrRelayUrl(target);
676
+ if (!ownRelay && (target.protocol !== "https:" || target.username || target.password)) throw new Error("Identity checks use HTTPS only");
673
677
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 1e4);
674
- const response = await (options.fetcher ?? fetch)(target.href, {
678
+ const response = await ((ownRelay ? options.relayFetcher : void 0) ?? options.fetcher ?? fetch)(target.href, {
675
679
  headers,
676
680
  signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
677
681
  credentials: "omit",
@@ -859,4 +863,4 @@ function setOwnDidSource(read) {
859
863
  var ownDid = () => source();
860
864
  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
865
 
862
- //# sourceMappingURL=ownDid-DY3rYqDI.js.map
866
+ //# sourceMappingURL=ownDid-oa-T2vmZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ownDid-oa-T2vmZ.js","names":[],"sources":["../../../core/src/pubkyProofs.ts","../../../core/src/didDht.ts","../../../browser/src/shared/features.ts","../../../browser/src/proofs/verify.ts","../../../browser/src/plugins/bundled.ts","../../../browser/src/plugins/registry.ts","../../../browser/src/proofs/ownDid.ts"],"sourcesContent":["import { fromZ32, randomBytes, toZ32 } from \"./bytes\";\nimport type { IdentityStatement } from \"./identityProofs\";\n\n/**\n * A Pubky identity proof, by publication (WISP 302, docs/wisps/302-pubky.md). Neither Pubky Ring nor Pubky\n * Passport signs arbitrary text: they approve standard Pubky auth requests. So Ghostly asks, through one of them,\n * for write access to ONE fresh folder of the key's homeserver, `/pub/ghostly.app/proofs/<folder>/`, and writes the\n * identity statement there (the #80 statement: the Pubky key authorizes this profile's per-proof key). A contact's\n * app reads the file back, finding the homeserver through the key's own signed PKDNS records (pkdns.ts), never\n * through a host or URL from the proof. The folder is random, so the path says nothing about the profile.\n */\n\nexport const PUBKY_PROOF_ROOT = \"/pub/ghostly.app/proofs/\";\n/** The file is the statement, a few hundred bytes: anything larger is not ours. */\nexport const PUBKY_PROOF_MAX_BYTES = 1024;\nconst Z32 = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\nconst FOLDER = /^[a-f0-9]{64}$/;\nconst STATEMENT_ID = /^[a-f0-9]{64}$/;\n\n/** A canonical Pubky key: 52 characters of z-base-32 that decode to 32 bytes and back. */\nexport function isPubkyKey(value: unknown): value is string {\n if (typeof value !== \"string\" || !Z32.test(value)) return false;\n try { return toZ32(fromZ32(value)) === value; } catch { return false; }\n}\n\n/** The z-base-32 key for what a person typed or pasted: the bare key, `pubky<key>`, `pk:<key>` or `pubky://<key>`. */\nexport function normalizePubkyKey(input: string): string {\n const match = /^(?:pubky:\\/\\/|pubky|pk:)?([a-z0-9]{52})\\/?$/i.exec(typeof input === \"string\" ? input.trim() : \"\");\n const key = match?.[1].toLowerCase();\n if (!key || !isPubkyKey(key)) throw new Error(\"That is not a Pubky key: 52 characters, like the one Pubky Ring shows\");\n return key;\n}\n\nexport const isPubkyProofFolder = (value: unknown): value is string => typeof value === \"string\" && FOLDER.test(value);\n\n/** A fresh folder name: 32 random bytes, hex. One per proof, so two proofs never share a path. */\nexport const newPubkyProofFolder = () => Array.from(randomBytes(32), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n/** The only capability Ghostly ever asks for: write access to one proof folder. */\nexport function pubkyProofCapability(folder: string): `/pub/${string}/:w` {\n if (!isPubkyProofFolder(folder)) throw new Error(\"Invalid Pubky proof folder\");\n return `${PUBKY_PROOF_ROOT}${folder}/:w`;\n}\n\n/** Where the statement goes: in its folder, named by the statement id. */\nexport function pubkyProofPath(folder: string, statementId: string): `/pub/${string}` {\n if (!isPubkyProofFolder(folder) || !STATEMENT_ID.test(statementId)) throw new Error(\"Invalid Pubky proof path\");\n return `${PUBKY_PROOF_ROOT}${folder}/${statementId}.txt`;\n}\n\n/** The file's exact contents: the statement's one line, nothing added. The verifier compares bytes. */\nexport const pubkyProofFile = (statement: IdentityStatement): string => statement.text;\n","import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { p256 } from \"@noble/curves/nist.js\";\nimport { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesEqual, fromBase64Url, fromZ32, toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { decodeTxtPacket, encodeTxtPacket, type NsRecord, type TxtRecord } from \"./dns\";\nimport type { Identity } from \"./identity\";\nimport { MAX_DNS_PACKET_BYTES, PacketTooLargeError, openRelayPayload, signRelayPayload } from \"./pkarr\";\nimport { DEFAULT_RELAYS, normalizeRelayUrl } from \"./relay\";\n\n/**\n * did:dht (the DIF method, https://github.com/decentralized-identity/did-dht/blob/main/spec/spec.md): a W3C DID document written as DNS records into the\n * Pkarr packet of an Ed25519 key, the BEP44 mutable item Ghostly already publishes chats under. This\n * module maps a document to that packet and back (strictly: a malformed packet is an error, never a\n * guess) and resolves a did:dht through Pkarr relays. WISP 310-did-dht describes Ghostly's use.\n */\n\nexport const DID_DHT_PREFIX = \"did:dht:\";\n/** The TTL the spec recommends: Mainline's default record lifetime. */\nexport const DID_DHT_TTL = 7200;\n/** The spec version this module writes and the only one it reads (`v=0`). */\nexport const DID_DHT_VERSION = \"0\";\n/** A relay answer: 64 bytes of signature, 8 of sequence number, then at most 1000 of DNS packet. */\nexport const DID_DHT_MAX_PAYLOAD = 64 + 8 + MAX_DNS_PACKET_BYTES;\n\nexport interface DidDhtJwk {\n kty: \"OKP\" | \"EC\";\n crv: \"Ed25519\" | \"secp256k1\" | \"P-256\" | \"X25519\";\n x: string;\n y?: string;\n alg: string;\n kid: string;\n}\n\nexport interface DidDhtVerificationMethod {\n id: string;\n type: \"JsonWebKey\";\n controller: string;\n publicKeyJwk: DidDhtJwk;\n}\n\nexport interface DidDhtService {\n id: string;\n type: string;\n serviceEndpoint: string[];\n /** Registered extra properties (the spec's registry): which keys sign and encrypt for it. */\n sig?: string | string[];\n enc?: string | string[];\n}\n\n/** A did:dht document in W3C DID Core JSON: no `@context`, every reference fully qualified. */\nexport interface DidDhtDocument {\n id: string;\n controller?: string | string[];\n alsoKnownAs?: string[];\n verificationMethod: DidDhtVerificationMethod[];\n authentication?: string[];\n assertionMethod?: string[];\n keyAgreement?: string[];\n capabilityInvocation?: string[];\n capabilityDelegation?: string[];\n service?: DidDhtService[];\n}\n\n/** Why a did:dht could not be read: the message is meant for a person. */\nexport class DidDhtError extends Error {\n constructor(message: string, readonly code: \"invalid-did\" | \"not-found\" | \"invalid-signature\" | \"malformed\" | \"unreachable\") {\n super(message);\n this.name = \"DidDhtError\";\n }\n}\n\nconst malformed = (detail: string) => new DidDhtError(`The did:dht document is malformed: ${detail}`, \"malformed\");\n\n// ── Identifiers ───────────────────────────────────────────────────────────────────────────────────────\n\n/** `did:dht:<z-base-32 of the Ed25519 public key>`. */\nexport function didDhtFromPublicKey(publicKey: Uint8Array): string {\n if (publicKey.length !== 32) throw new Error(\"A did:dht identity key is 32 bytes of Ed25519 public key\");\n return DID_DHT_PREFIX + toZ32(publicKey);\n}\n\n/** The identity key of a did:dht. Only the exact DID: no path, query or fragment, canonical z-base-32. */\nexport function didDhtKey(did: string): { z32: string; publicKey: Uint8Array } {\n const invalid = () => new DidDhtError(\"This is not a valid did:dht\", \"invalid-did\");\n if (typeof did !== \"string\" || !did.startsWith(DID_DHT_PREFIX)) throw invalid();\n const z32 = did.slice(DID_DHT_PREFIX.length);\n if (!/^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/.test(z32)) throw invalid();\n const publicKey = fromZ32(z32);\n // 52 characters carry 260 bits: the last four must be zero, or two DIDs would name one key.\n if (toZ32(publicKey) !== z32) throw invalid();\n // Nor a point of small order: no secret key goes with one, and it \"verifies\" a constant signature of any packet.\n let fit: boolean;\n try { fit = !ed25519.Point.fromBytes(publicKey).isSmallOrder(); } catch { fit = false; }\n if (!fit) throw invalid();\n return { z32, publicKey };\n}\n\n// ── Documents ─────────────────────────────────────────────────────────────────────────────────────────\n\nconst KEY_TYPES = [\n { kty: \"OKP\", crv: \"Ed25519\", alg: \"EdDSA\" },\n { kty: \"EC\", crv: \"secp256k1\", alg: \"ES256K\" },\n { kty: \"EC\", crv: \"P-256\", alg: \"ES256\" },\n { kty: \"OKP\", crv: \"X25519\", alg: \"ECDH-ES+A256KW\" },\n] as const;\n\nconst RELATIONSHIPS = [\n [\"auth\", \"authentication\"],\n [\"asm\", \"assertionMethod\"],\n [\"agm\", \"keyAgreement\"],\n [\"inv\", \"capabilityInvocation\"],\n [\"del\", \"capabilityDelegation\"],\n] as const;\n\n/**\n * The document of an identity key alone, as the spec's Create step makes it: the key as `#0`, with the\n * four relationships it requires (authentication, assertion, capability invocation and delegation).\n * `alsoKnownAs` adds other identifiers of the same subject (URIs), which the document makes public.\n */\nexport function didDhtDocument(publicKey: Uint8Array, options: { alsoKnownAs?: string[] } = {}): DidDhtDocument {\n const id = didDhtFromPublicKey(publicKey);\n const key = `${id}#0`;\n return {\n id,\n ...(options.alsoKnownAs?.length ? { alsoKnownAs: [...options.alsoKnownAs] } : {}),\n verificationMethod: [{\n id: key,\n type: \"JsonWebKey\",\n controller: id,\n publicKeyJwk: { kty: \"OKP\", crv: \"Ed25519\", x: toBase64Url(publicKey), alg: \"EdDSA\", kid: \"0\" },\n }],\n authentication: [key],\n assertionMethod: [key],\n capabilityInvocation: [key],\n capabilityDelegation: [key],\n };\n}\n\n/** RFC 7638 thumbprint: SHA-256 of the required members in lexicographic order. */\nexport function jwkThumbprint(jwk: Pick<DidDhtJwk, \"kty\" | \"crv\" | \"x\" | \"y\">): string {\n const members = jwk.kty === \"EC\" ? { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y } : { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n return toBase64Url(sha256(utf8Encode(JSON.stringify(members))));\n}\n\nfunction publicKeyBytes(type: number, jwk: DidDhtJwk): Uint8Array {\n const x = fromBase64Url(jwk.x);\n if (type === 0 || type === 3) return x;\n // Compressed point: the x-coordinate and the sign of y (the spec's size rule).\n const curve = type === 1 ? secp256k1 : p256;\n return curve.Point.fromAffine({ x: bigintOf(x), y: bigintOf(fromBase64Url(jwk.y ?? \"\")) }).toBytes(true);\n}\n\nfunction bigintOf(bytes: Uint8Array): bigint {\n let n = 0n;\n for (const b of bytes) n = (n << 8n) | BigInt(b);\n return n;\n}\n\nfunction jwkOf(type: number, bytes: Uint8Array, alg: string, kid: string): DidDhtJwk {\n const kind = KEY_TYPES[type];\n if (type === 0) {\n if (bytes.length !== 32) throw malformed(\"an Ed25519 key is not 32 bytes\");\n let smallOrder: boolean;\n try { smallOrder = ed25519.Point.fromBytes(bytes).isSmallOrder(); } catch { throw malformed(\"an Ed25519 key is not a point of the curve\"); }\n if (smallOrder) throw malformed(\"an Ed25519 key is a point of small order, which no secret key goes with\");\n return { kty: \"OKP\", crv: \"Ed25519\", x: toBase64Url(bytes), alg, kid };\n }\n if (type === 3) {\n if (bytes.length !== 32) throw malformed(\"an X25519 key is not 32 bytes\");\n return { kty: \"OKP\", crv: \"X25519\", x: toBase64Url(bytes), alg, kid };\n }\n if (bytes.length !== 33 && bytes.length !== 65) throw malformed(`a ${kind.crv} key is neither a compressed nor an uncompressed point`);\n let raw: Uint8Array;\n try {\n raw = (type === 1 ? secp256k1 : p256).Point.fromBytes(bytes).toBytes(false);\n } catch {\n throw malformed(`a ${kind.crv} key is not a point of the curve`);\n }\n return { kty: \"EC\", crv: kind.crv, x: toBase64Url(raw.subarray(1, 33)), y: toBase64Url(raw.subarray(33)), alg, kid };\n}\n\n// ── Document → DNS records ────────────────────────────────────────────────────────────────────────────\n\nexport interface DidDhtPacketOptions {\n /** Type indexing (`_typ._did.`), integers from the spec's registry. */\n types?: number[];\n /** Authoritative gateways, as NS records of the root name. */\n gateways?: string[];\n /**\n * Other records of the same key. A key has exactly one packet: whatever else it publishes goes in\n * with the document, and the whole must fit the 1000 bytes.\n */\n extra?: TxtRecord[];\n}\n\nconst fragmentOf = (documentId: string, ref: string, what: string): string => {\n if (!ref.startsWith(`${documentId}#`)) throw new Error(`${what} ${ref} is not a fragment of ${documentId}`);\n const fragment = ref.slice(documentId.length + 1);\n if (!FRAGMENT.test(fragment)) throw new Error(`${what} ${ref} has an unusable fragment`);\n return fragment;\n};\n\nconst listValue = (values: string[], what: string): string => {\n for (const v of values) if (!v || /[,;\\s]/.test(v)) throw new Error(`${what} ${JSON.stringify(v)} cannot be written into a did:dht record`);\n return values.join(\",\");\n};\n\n/**\n * The DNS records of a document, in the spec's layout (names `_did.<ID>.` and `_kN._did.`). The root\n * record comes after the records it names, gateways last: the order @web5/dids writes, and the only one\n * it reads correctly (it resolves `vm`/`auth` references in packet order). Order-free readers don't mind.\n */\nexport function didDhtRecords(document: DidDhtDocument, options: DidDhtPacketOptions = {}): (TxtRecord | NsRecord)[] {\n const { z32, publicKey } = didDhtKey(document.id);\n const methods = document.verificationMethod;\n const first = methods[0];\n if (!first || first.id !== `${document.id}#0` || first.publicKeyJwk.crv !== \"Ed25519\" || !bytesEqual(fromBase64Url(first.publicKeyJwk.x), publicKey)) {\n throw new Error(\"The first verification method of a did:dht document is its identity key, #0\");\n }\n\n const aliases = new Map<string, string>();\n const keyRecords: TxtRecord[] = methods.map((method, index) => {\n const alias = `k${index}`;\n if (aliases.has(method.id)) throw new Error(`Verification method ${method.id} appears twice`);\n aliases.set(method.id, alias);\n const fragment = fragmentOf(document.id, method.id, \"Verification method\");\n const type = KEY_TYPES.findIndex((k) => k.crv === method.publicKeyJwk.crv);\n if (type < 0) throw new Error(`Key type ${method.publicKeyJwk.crv} has no did:dht index`);\n const jwk = method.publicKeyJwk;\n const parts: string[] = [];\n // The identity key's id is always 0, and one that is the thumbprint can be computed back: both are left out.\n if (index > 0 && fragment !== jwkThumbprint(jwk)) parts.push(`id=${fragment}`);\n parts.push(`t=${type}`, `k=${toBase64Url(publicKeyBytes(type, jwk))}`);\n if (jwk.alg !== KEY_TYPES[type].alg) parts.push(`a=${jwk.alg}`);\n if (method.controller !== document.id) parts.push(`c=${listValue([method.controller], \"Controller\")}`);\n return { name: `_${alias}._did.`, value: parts.join(\";\"), ttl: DID_DHT_TTL };\n });\n\n const services = document.service ?? [];\n const serviceRecords: TxtRecord[] = services.map((service, index) => {\n const parts = [\n `id=${fragmentOf(document.id, service.id, \"Service\")}`,\n `t=${listValue([service.type], \"Service type\")}`,\n `se=${listValue(service.serviceEndpoint, \"Service endpoint\")}`,\n ];\n for (const extra of [\"sig\", \"enc\"] as const) {\n const v = service[extra];\n if (v !== undefined) parts.push(`${extra}=${listValue(Array.isArray(v) ? v : [v], `Service ${extra}`)}`);\n }\n return { name: `_s${index}._did.`, value: parts.join(\";\"), ttl: DID_DHT_TTL };\n });\n\n const root = [`v=${DID_DHT_VERSION}`, `vm=${keyRecords.map((_, i) => `k${i}`).join(\",\")}`];\n for (const [short, property] of RELATIONSHIPS) {\n const refs = document[property] ?? [];\n if (refs.length === 0) continue;\n root.push(`${short}=${refs.map((ref) => {\n const alias = aliases.get(ref);\n if (!alias) throw new Error(`${property} refers to ${ref}, which is not a verification method of the document`);\n return alias;\n }).join(\",\")}`);\n }\n if (serviceRecords.length) root.push(`svc=${serviceRecords.map((_, i) => `s${i}`).join(\",\")}`);\n\n const records: (TxtRecord | NsRecord)[] = [];\n if (document.alsoKnownAs?.length) records.push({ name: \"_aka._did.\", value: listValue(document.alsoKnownAs, \"Also-known-as\"), ttl: DID_DHT_TTL });\n if (document.controller !== undefined) {\n const controllers = Array.isArray(document.controller) ? document.controller : [document.controller];\n records.push({ name: \"_cnt._did.\", value: listValue(controllers, \"Controller\"), ttl: DID_DHT_TTL });\n }\n records.push(...keyRecords, ...serviceRecords);\n if (options.types?.length) {\n for (const t of options.types) if (!Number.isSafeInteger(t) || t < 0) throw new Error(`Type ${t} is not a registry integer`);\n records.push({ name: \"_typ._did.\", value: `id=${options.types.join(\",\")}`, ttl: DID_DHT_TTL });\n }\n records.push({ name: `_did.${z32}.`, value: root.join(\";\"), ttl: DID_DHT_TTL });\n for (const host of options.gateways ?? []) records.push({ type: \"NS\", name: `_did.${z32}.`, host, ttl: DID_DHT_TTL });\n records.push(...(options.extra ?? []));\n return records;\n}\n\n/** The compressed, authoritative DNS packet of a document. Throws `PacketTooLargeError` past 1000 bytes. */\nexport function encodeDidDhtPacket(document: DidDhtDocument, options: DidDhtPacketOptions = {}): Uint8Array {\n const packet = encodeTxtPacket(didDhtRecords(document, options), { authoritative: true });\n if (packet.length > MAX_DNS_PACKET_BYTES) throw new PacketTooLargeError(packet.length);\n return packet;\n}\n\n/**\n * The packet that ends a DID: its root record alone, reading `deactivated`. Resolvers then answer with\n * `deactivated: true` and a document holding the id alone, until the record leaves the DHT.\n */\nexport function encodeDidDhtDeactivated(publicKey: Uint8Array): Uint8Array {\n const { z32 } = didDhtKey(didDhtFromPublicKey(publicKey));\n return encodeTxtPacket([{ name: `_did.${z32}.`, value: \"deactivated\", ttl: DID_DHT_TTL }], { authoritative: true });\n}\n\n/**\n * The relay payload of a document: its packet, signed by the identity key. `seq` is the BEP44 sequence\n * number, which did:dht defines as the UNIX time in seconds (Ghostly's chat records use microseconds).\n */\nexport function signDidDhtPacket(identity: Identity, dnsPacket: Uint8Array, seq: number): Uint8Array {\n if (!Number.isSafeInteger(seq) || seq < 0) throw new Error(\"A did:dht sequence number is a UNIX time in seconds\");\n return signRelayPayload(identity, dnsPacket, BigInt(seq));\n}\n\n// ── DNS records → document ────────────────────────────────────────────────────────────────────────────\n\nconst FRAGMENT = /^[A-Za-z0-9._~-]{1,64}$/;\nconst ALG = /^[A-Za-z0-9+._-]{1,32}$/;\nconst DID = /^did:[a-z0-9]+:[A-Za-z0-9._:%-]+$/;\nconst URI = /^[A-Za-z][A-Za-z0-9+.-]*:[^\\s,;]+$/;\n\n/** `a=1;b=x,y`: each property once, names in lower case. */\nfunction properties(value: string, where: string): Map<string, string> {\n const out = new Map<string, string>();\n for (const pair of value.split(\";\")) {\n const at = pair.indexOf(\"=\");\n const name = pair.slice(0, at);\n if (at <= 0 || !/^[a-z]+$/.test(name)) throw malformed(`${where} has a property that is not name=value`);\n if (out.has(name)) throw malformed(`${where} has ${name} twice`);\n out.set(name, pair.slice(at + 1));\n }\n return out;\n}\n\nfunction list(value: string | undefined, where: string, item: RegExp): string[] {\n if (value === undefined) return [];\n const items = value.split(\",\");\n for (const v of items) if (!item.test(v)) throw malformed(`${where} has an unexpected value`);\n return items;\n}\n\nexport interface DecodedDidDht {\n document: DidDhtDocument;\n /** The root record says `deactivated`: the document holds the id alone. */\n deactivated: boolean;\n /** Type indexing integers (`_typ._did.`), when present. */\n types?: number[];\n}\n\n/**\n * The document in a did:dht DNS packet. Other records of the key (anything not ending in `_did`) are\n * ignored, and so are did:dht records this version does not know (`_prv`, future ones); everything it\n * does know must be well formed and consistent, or the packet is refused.\n */\nexport function decodeDidDhtPacket(did: string, dnsPacket: Uint8Array): DecodedDidDht {\n const { z32, publicKey } = didDhtKey(did);\n let txt: TxtRecord[];\n try {\n txt = decodeTxtPacket(dnsPacket);\n } catch (error) {\n throw malformed(`not a DNS packet (${error instanceof Error ? error.message : String(error)})`);\n }\n\n // `_k0._did` as the spec writes it, or `_k0._did.<ID>` as a Pkarr client that appends its origin does.\n const byName = new Map<string, string>();\n let rootValue: string | undefined;\n for (const record of txt) {\n const name = record.name.toLowerCase().replace(/\\.$/, \"\");\n if (name === `_did.${z32}`) {\n if (rootValue !== undefined) throw malformed(\"two root records\");\n rootValue = record.value;\n continue;\n }\n const match = /^(_[a-z0-9]+)\\._did(?:\\.([a-z0-9]+))?$/.exec(name);\n if (!match || (match[2] !== undefined && match[2] !== z32)) continue;\n if (byName.has(match[1])) throw malformed(`two ${match[1]} records`);\n byName.set(match[1], record.value);\n }\n if (rootValue === undefined) throw malformed(\"no root record\");\n if (rootValue === \"deactivated\") return { document: { id: did, verificationMethod: [] }, deactivated: true };\n\n const root = properties(rootValue, \"the root record\");\n if (root.get(\"v\") !== DID_DHT_VERSION) throw malformed(`version ${root.get(\"v\") ?? \"(none)\"} is not supported`);\n const vm = list(root.get(\"vm\"), \"the root record's vm\", /^k\\d{1,3}$/);\n if (!vm.includes(\"k0\")) throw malformed(\"the identity key k0 is not listed\");\n if (new Set(vm).size !== vm.length) throw malformed(\"a key is listed twice\");\n\n const document: DidDhtDocument = { id: did, verificationMethod: [] };\n const methodIds = new Map<string, string>();\n for (const alias of vm) {\n const value = byName.get(`_${alias}`);\n if (value === undefined) throw malformed(`the key ${alias} has no record`);\n const props = properties(value, `the key ${alias}`);\n const type = Number(props.get(\"t\"));\n if (!/^[0-3]$/.test(props.get(\"t\") ?? \"\")) throw malformed(`the key ${alias} has an unknown type`);\n const alg = props.get(\"a\") ?? KEY_TYPES[type].alg;\n if (!ALG.test(alg)) throw malformed(`the key ${alias} has an unusable algorithm`);\n const k = props.get(\"k\") ?? \"\";\n // 4n+1 characters encode no byte string: atob would throw a DOMException, not a DidDhtError.\n const bytes = /^[A-Za-z0-9_-]+$/.test(k) && k.length % 4 !== 1 ? fromBase64Url(k) : new Uint8Array();\n if (bytes.length === 0 || toBase64Url(bytes) !== k) throw malformed(`the key ${alias} is not unpadded base64url`);\n const controller = props.get(\"c\") ?? did;\n if (!DID.test(controller)) throw malformed(`the key ${alias} has a controller that is not a DID`);\n\n let fragment: string;\n let jwk: DidDhtJwk;\n if (alias === \"k0\") {\n if (type !== 0 || !bytesEqual(bytes, publicKey)) throw malformed(\"k0 is not the DID's identity key\");\n if (props.has(\"id\") && props.get(\"id\") !== \"0\") throw malformed(\"the identity key's id is not 0\");\n fragment = \"0\";\n jwk = jwkOf(type, bytes, alg, fragment);\n } else {\n const provisional = jwkOf(type, bytes, alg, \"\");\n fragment = props.get(\"id\") ?? jwkThumbprint(provisional);\n if (!FRAGMENT.test(fragment)) throw malformed(`the key ${alias} has an unusable id`);\n jwk = { ...provisional, kid: fragment };\n }\n const id = `${did}#${fragment}`;\n if ([...methodIds.values()].includes(id)) throw malformed(`two keys have the id ${fragment}`);\n methodIds.set(alias, id);\n document.verificationMethod.push({ id, type: \"JsonWebKey\", controller, publicKeyJwk: jwk });\n }\n\n for (const [short, property] of RELATIONSHIPS) {\n const refs = list(root.get(short), `the root record's ${short}`, /^k\\d{1,3}$/);\n if (refs.length === 0) continue;\n document[property] = refs.map((alias) => {\n const id = methodIds.get(alias);\n if (!id) throw malformed(`${short} names ${alias}, which is not a listed key`);\n return id;\n });\n }\n\n const services = list(root.get(\"svc\"), \"the root record's svc\", /^s\\d{1,3}$/);\n if (new Set(services).size !== services.length) throw malformed(\"a service is listed twice\");\n for (const alias of services) {\n const value = byName.get(`_${alias}`);\n if (value === undefined) throw malformed(`the service ${alias} has no record`);\n const props = properties(value, `the service ${alias}`);\n const fragment = props.get(\"id\") ?? \"\";\n const type = props.get(\"t\") ?? \"\";\n if (!FRAGMENT.test(fragment)) throw malformed(`the service ${alias} has an unusable id`);\n if (!/^[A-Za-z0-9._:/-]{1,64}$/.test(type)) throw malformed(`the service ${alias} has an unusable type`);\n const service: DidDhtService = { id: `${did}#${fragment}`, type, serviceEndpoint: list(props.get(\"se\") ?? \"\", `the service ${alias}'s endpoint`, URI) };\n for (const extra of [\"sig\", \"enc\"] as const) {\n const v = props.get(extra);\n if (v !== undefined) service[extra] = v.includes(\",\") ? list(v, `the service ${alias}'s ${extra}`, /^[^\\s,;]+$/) : v;\n }\n if (document.service?.some((s) => s.id === service.id)) throw malformed(`two services have the id ${fragment}`);\n (document.service ??= []).push(service);\n }\n\n const controller = byName.get(\"_cnt\");\n if (controller !== undefined) {\n const controllers = list(controller, \"the controller record\", DID);\n document.controller = controllers.length === 1 ? controllers[0] : controllers;\n }\n const aka = byName.get(\"_aka\");\n if (aka !== undefined) document.alsoKnownAs = list(aka, \"the also-known-as record\", URI);\n\n const decoded: DecodedDidDht = { document, deactivated: false };\n const typ = byName.get(\"_typ\");\n if (typ !== undefined) {\n const props = properties(typ, \"the type record\");\n decoded.types = list(props.get(\"id\"), \"the type record\", /^\\d{1,9}$/).map(Number);\n }\n return decoded;\n}\n\n// ── Resolution ────────────────────────────────────────────────────────────────────────────────────────\n\nexport interface DidDhtFetchResponse { status: number; bytes: Uint8Array }\n/** A bounded GET (the identity proofs' `ctx.fetch` is one). */\nexport type DidDhtFetch = (url: string, options?: { maxBytes?: number; signal?: AbortSignal; redirect?: \"error\" }) => Promise<DidDhtFetchResponse>;\n\nexport interface ResolveDidDhtOptions {\n fetch: DidDhtFetch;\n /** Pkarr relays (or did:dht gateways, which answer the same GET) to ask, all of them. Default: `DEFAULT_RELAYS`. */\n relays?: string[];\n signal?: AbortSignal;\n}\n\nexport interface DidDhtMetadata {\n /** The BEP44 sequence number. */\n versionId: string;\n /** When it was published, from the sequence number. */\n updated: string;\n deactivated?: true;\n types?: number[];\n}\n\nexport interface DidDhtResolution {\n document: DidDhtDocument;\n metadata: DidDhtMetadata;\n /** The relay that answered. */\n relay: string;\n}\n\n/** A packet opened and decoded: the signature is the identity key's, the document well formed. */\nexport function openDidDhtPayload(did: string, payload: Uint8Array): DecodedDidDht & { seq: bigint } {\n const { z32 } = didDhtKey(did);\n let opened: { seq: bigint; dnsPacket: Uint8Array };\n try {\n opened = openRelayPayload(z32, payload);\n } catch (error) {\n if (error instanceof Error && error.message === \"Invalid signature\") {\n throw new DidDhtError(\"The did:dht record is not signed by the DID's key\", \"invalid-signature\");\n }\n throw malformed(error instanceof Error ? error.message : String(error));\n }\n return { ...decodeDidDhtPacket(did, opened.dnsPacket), seq: opened.seq };\n}\n\n/** The spec's `seq` is in seconds; Pkarr clients write microseconds. Either way, a date. */\nfunction seqDate(seq: bigint): string {\n const n = Number(seq);\n const ms = n < 1e11 ? n * 1000 : n < 1e14 ? n : n / 1000;\n const date = new Date(ms);\n return Number.isNaN(date.getTime()) ? new Date(0).toISOString() : date.toISOString();\n}\n\n/**\n * Resolves a did:dht through Pkarr relays: one GET to each, all at once, and the newest packet that\n * checks out wins (the highest sequence number; on a tie, the relay listed first), so a relay holding\n * an older version cannot bring back a removed key or undo a deactivation. Each answer is bounded to\n * a BEP44 item, its signature checked against the DID's key and its records parsed strictly; a relay\n * that has nothing, fails or serves a packet that does not check out does not count. A deactivated DID\n * resolves (`metadata.deactivated`); everything else that goes wrong throws a `DidDhtError`.\n */\nexport async function resolveDidDht(did: string, options: ResolveDidDhtOptions): Promise<DidDhtResolution> {\n const { z32 } = didDhtKey(did);\n const relays = [...new Set((options.relays ?? DEFAULT_RELAYS).map(normalizeRelayUrl).filter((r): r is string => r !== null))];\n if (relays.length === 0) throw new DidDhtError(\"No Pkarr relay to ask\", \"unreachable\");\n options.signal?.throwIfAborted();\n\n const responses = await Promise.all(relays.map((relay) =>\n options.fetch(`${relay}/${z32}`, { maxBytes: DID_DHT_MAX_PAYLOAD, signal: options.signal, redirect: \"error\" }).catch(() => undefined)));\n options.signal?.throwIfAborted();\n\n let notFound = false;\n let refused: DidDhtError | undefined;\n let newest: (DecodedDidDht & { seq: bigint; relay: string }) | undefined;\n for (const [i, relay] of relays.entries()) {\n const response = responses[i];\n if (response?.status === 404) notFound = true;\n if (response?.status !== 200) continue;\n try {\n const opened = openDidDhtPayload(did, response.bytes);\n if (!newest || opened.seq > newest.seq) newest = { ...opened, relay };\n } catch (error) {\n if (!(error instanceof DidDhtError)) throw error;\n refused = error;\n }\n }\n if (newest) {\n return {\n document: newest.document,\n metadata: {\n versionId: newest.seq.toString(),\n updated: seqDate(newest.seq),\n ...(newest.deactivated ? { deactivated: true as const } : {}),\n ...(newest.types ? { types: newest.types } : {}),\n },\n relay: newest.relay,\n };\n }\n if (refused) throw refused;\n if (notFound) throw new DidDhtError(\"No document is published for this did:dht\", \"not-found\");\n throw new DidDhtError(\"No Pkarr relay answered for this did:dht\", \"unreachable\");\n}\n","/** Release policy: external identity experiments are retained for future work,\n * but must not advertise capabilities, start network lookups, or expose cached\n * external profiles. This does not gate Ghostly participation authentication. */\nexport const EXTERNAL_IDENTITIES_ENABLED: boolean = false;\n\n/** Mini-apps (WISP 1200): `apps/1` on paired sessions and the engine's `app*` calls. On from release 1.2 (a version\n * before 1.2.0 is never cut with it on: `RELEASE_GUARDS` in tools/scripts/changes.mjs). Off, nothing is offered to\n * contacts and every call is refused; a host that runs no apps pins its engine off (`NodeOptions.apps`). */\nexport const APPS_ENABLED: boolean = true;\n\n/**\n * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the\n * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is\n * neither: Vite folds this to `false` there, so the storage flags the test fakes answer to are ignored. The fakes\n * themselves are still in the bundle (the registries import them); plugins may still pass fakes to the registry.\n */\nexport const testBuild = (): boolean => { try { return !!import.meta.env?.DEV || import.meta.env?.VITE_APPS_TEST === \"1\"; } catch { return false; } };\n\n/**\n * A suite's switch in the page's storage (`localStorage[\"ghostly-test-…\"]`), read only in a test build (`testBuild`): a\n * release build reads none, so a leftover or pasted key changes nothing there. Null when unset, unreadable or released.\n */\nexport const testSwitch = (key: string): string | null => {\n if (!testBuild()) return null;\n try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; }\n};\n","import { boundVerifiedIdentity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\nimport { isOwnPkarrRelayUrl } from \"./pkarrRelays\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (p.recheck?.perHour !== undefined && !(Number.isInteger(p.recheck.perHour) && p.recheck.perHour >= 1)) problems.push(\"recheck.perHour must be a whole number, at least 1\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n * A did:dht read of the profile's own Pkarr relays (`ownPkarrRelay`) may be http://, through `relayFetcher`: those are\n * the relays the person chose, as the chats read them, not an address a contact named.\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch; relayFetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\", ownPkarrRelay } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n const ownRelay = ownPkarrRelay === true && isOwnPkarrRelayUrl(target);\n if (!ownRelay && (target.protocol !== \"https:\" || target.username || target.password)) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const fetcher = (ownRelay ? options.relayFetcher : undefined) ?? options.fetcher ?? fetch;\n const response = await fetcher(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n","import type { GhostlyAdapterPlugin } from \"./registry\";\n\n/**\n * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`\n * names their modules (comma-separated paths from the repository root, each default-exporting a\n * `GhostlyAdapterPlugin`), and the Vite plugin in `packages/browser/vite-plugin.ts` swaps this module\n * for one that imports them. Release builds never set it; the e2e build carries the SDK example.\n */\nexport const BUNDLED_PLUGINS: readonly GhostlyAdapterPlugin[] = [];\n","import type { LightningProviderDescriptor } from \"../engine/paymentAdapters/providers/lightning\";\nimport type { OnchainProviderDescriptor } from \"../engine/paymentAdapters/providers/onchain\";\nimport { providerDescriptorProblems, type ProviderDescriptor, type ProviderKind } from \"../engine/paymentAdapters/providers/types\";\nimport type { IdentityProofProvider } from \"../proofs/contract\";\nimport { descriptorProblems } from \"../proofs/verify\";\nimport { BUNDLED_PLUGINS } from \"./bundled\";\n\n/**\n * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers\n * that register here instead of being added to the built-in lists. A plugin is a plain object naming\n * its adapters; the registries (`providers/registry.ts`, `proofs/registry.ts`) list what is registered\n * after the built-ins and before the test fakes, and the same platform and mode rules apply to all.\n *\n * Two ways in:\n * - at build time: `GHOSTLY_PLUGINS` lists the modules and `bundled.ts` is swapped for them;\n * - at run time: code already running in the engine's realm calls `registerAdapters` before the\n * pickers are shown (or after: the engine re-reads the lists when something registers).\n *\n * Trust: a plugin runs with the app's privileges, in the app's own JavaScript realm. There is no\n * sandbox, no permission prompt and no store; whoever builds a plugin in, or loads one, trusts its\n * author with everything the app can do, keys and sats included. A manifest with permissions and an\n * isolated runtime are a later phase (docs/wisps/ADAPTER-ROADMAP.md, \"Plugins, apps, catalogs\").\n *\n * The state lives on `globalThis` under a well-known symbol, so a plugin bundled with its own copy of\n * the SDK (a second copy of this module) still registers into the same lists the app reads.\n */\n\n/** The generation of the adapter contracts. A plugin says which one it was written against. */\nexport const SDK_API = 1;\nexport const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;\n\nexport interface GhostlyAdapterPlugin {\n /** Stable, unique among plugins: `^[a-z][a-z0-9-]{0,63}$`. */\n id: string;\n /** The plugin's own version, for people. */\n version?: string;\n /** The contract generation it was written against: `SDK_API`. Another one is refused. */\n sdk: number;\n lightning?: readonly LightningProviderDescriptor[];\n onchain?: readonly OnchainProviderDescriptor[];\n identities?: readonly IdentityProofProvider[];\n}\n\nexport type AdapterKind = ProviderKind | \"identity\";\n\ninterface Store {\n plugins: Map<string, GhostlyAdapterPlugin>;\n /** Ids the built-in registries own, per kind: a plugin cannot take one. */\n reserved: Record<AdapterKind, Set<string>>;\n listeners: Set<() => void>;\n seeded: boolean;\n}\n\nconst KEY = Symbol.for(\"ghostly.adapters/1\");\nfunction store(): Store {\n const g = globalThis as unknown as Record<symbol, Store | undefined>;\n return (g[KEY] ??= { plugins: new Map(), reserved: { lightning: new Set(), onchain: new Set(), identity: new Set() }, listeners: new Set(), seeded: false });\n}\n\nconst ids = (kind: AdapterKind, plugin: GhostlyAdapterPlugin): string[] => {\n // Not trusted to be well formed: pluginProblems reads it before saying what is wrong with it.\n const list: unknown = kind === \"identity\" ? plugin.identities : kind === \"lightning\" ? plugin.lightning : plugin.onchain;\n return Array.isArray(list) ? list.map((a: { id?: string } | null) => a?.id as string) : [];\n};\nconst KINDS: readonly AdapterKind[] = [\"lightning\", \"onchain\", \"identity\"];\n\n/** Problems with a plugin, empty when it can be registered. Does not look at what is already registered. */\nexport function pluginProblems(plugin: GhostlyAdapterPlugin): string[] {\n const problems: string[] = [];\n if (!plugin || typeof plugin !== \"object\") return [\"not a plugin object\"];\n if (!PLUGIN_ID.test(plugin.id ?? \"\")) problems.push(\"plugin id must match ^[a-z][a-z0-9-]{0,63}$\");\n if (plugin.sdk !== SDK_API) problems.push(`plugin was written for SDK API ${String(plugin.sdk)}; this app speaks ${SDK_API}`);\n if (plugin.version !== undefined && (typeof plugin.version !== \"string\" || plugin.version.length > 64)) problems.push(\"version must be a short string\");\n for (const kind of [\"lightning\", \"onchain\"] as const) {\n const list = plugin[kind];\n if (list === undefined) continue;\n if (!Array.isArray(list)) { problems.push(`${kind} must be a list of descriptors`); continue; }\n for (const d of list as ProviderDescriptor<unknown>[]) {\n if (!d || typeof d !== \"object\") { problems.push(`${kind} ${String(d)}: not a descriptor`); continue; }\n const own = providerDescriptorProblems(d);\n if (d?.kind && d.kind !== kind) own.push(`is listed under ${kind} but says kind ${String(d.kind)}`);\n problems.push(...own.map((p) => `${kind} ${String(d?.id)}: ${p}`));\n }\n }\n if (plugin.identities !== undefined) {\n if (!Array.isArray(plugin.identities)) problems.push(\"identities must be a list of providers\");\n else for (const p of plugin.identities) {\n if (!p || typeof p !== \"object\") problems.push(`identity ${String(p)}: not a provider`);\n else problems.push(...descriptorProblems(p).map((m) => `identity ${String(p.id)}: ${m}`));\n }\n }\n for (const kind of KINDS) {\n const list = ids(kind, plugin);\n if (new Set(list).size !== list.length) problems.push(`${kind} ids are not unique within the plugin`);\n }\n if (!KINDS.some((kind) => ids(kind, plugin).length)) problems.push(\"the plugin brings no adapter\");\n return problems;\n}\n\n/** The built-in registries say which ids are theirs. A plugin using one is refused. */\nexport function reserveAdapterIds(kind: AdapterKind, list: readonly string[]): void {\n const s = store();\n for (const id of list) s.reserved[kind].add(id);\n}\n\n/**\n * Registers a plugin's adapters. Throws, registering nothing, when the plugin is malformed, its id or\n * one of its adapters' ids is taken (by a built-in or by another plugin), or its contract generation\n * is another one. Returns the function that unregisters it.\n */\nexport function registerAdapters(plugin: GhostlyAdapterPlugin): () => void {\n const problems = pluginProblems(plugin);\n const s = store();\n if (!problems.length) {\n if (s.plugins.has(plugin.id)) problems.push(`a plugin with id ${plugin.id} is already registered`);\n for (const kind of KINDS) for (const id of ids(kind, plugin)) {\n if (s.reserved[kind].has(id)) problems.push(`${kind} ${id} is a built-in of this app`);\n for (const other of s.plugins.values()) if (ids(kind, other).includes(id)) problems.push(`${kind} ${id} is already registered by plugin ${other.id}`);\n }\n }\n if (problems.length) throw new Error(`Cannot register plugin ${String(plugin?.id)}: ${problems.join(\"; \")}`);\n s.plugins.set(plugin.id, plugin);\n notify(s);\n return () => { if (s.plugins.get(plugin.id) === plugin) { s.plugins.delete(plugin.id); notify(s); } };\n}\n\nfunction notify(s: Store) { for (const listener of s.listeners) { try { listener(); } catch { /* a listener's problem */ } } }\n\n/** Called when a plugin registers or unregisters: the engine re-reads the lists. */\nexport function onAdaptersChanged(listener: () => void): () => void {\n const s = store();\n s.listeners.add(listener);\n return () => { s.listeners.delete(listener); };\n}\n\n/** Every registered plugin, in registration order (bundled ones first). */\nexport function registeredPlugins(): readonly GhostlyAdapterPlugin[] { seed(); return [...store().plugins.values()]; }\nexport function registeredLightningProviders(): readonly LightningProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.lightning ?? []); }\nexport function registeredOnchainProviders(): readonly OnchainProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.onchain ?? []); }\nexport function registeredIdentityProviders(): readonly IdentityProofProvider[] { return registeredPlugins().flatMap((p) => p.identities ?? []); }\n\n/**\n * The plugins compiled into this build register once, when they are first asked for. A broken one is\n * reported and skipped rather than taking the app down with it; the e2e that expects it fails instead.\n */\nfunction seed() {\n const s = store();\n if (s.seeded) return;\n s.seeded = true;\n for (const plugin of BUNDLED_PLUGINS) {\n try { registerAdapters(plugin); }\n catch (error) { console.error(`[ghostly] a bundled adapter plugin was not loaded: ${error instanceof Error ? error.message : String(error)}`); }\n }\n}\n\n/** Tests only: forget every registration, including the bundled ones. */\nexport function resetAdapterRegistry(): void {\n const s = store();\n s.plugins.clear(); s.seeded = false;\n for (const kind of KINDS) s.reserved[kind].clear();\n notify(s);\n}\n","/**\n * The profile's own Ghostly did:dht, which the DID provider refuses as an external identity. The UI and the engine each\n * set where to read it. Here, not in the provider, so setting it does not load the providers.\n */\nlet source: () => string | undefined = () => undefined;\nexport function setOwnDidSource(read: () => string | undefined): void { source = read; }\nexport const ownDid = (): string | undefined => source();\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAYA,IAAa,mBAAmB;;AAEhC,IAAa,wBAAwB;AACrC,IAAM,MAAM;AACZ,IAAM,SAAS;AACf,IAAM,eAAe;;AAGrB,SAAgB,WAAW,OAAiC;CAC1D,IAAI,OAAO,UAAU,YAAY,CAAC,IAAI,KAAK,KAAK,GAAG,OAAO;CAC1D,IAAI;EAAE,OAAO,MAAM,QAAQ,KAAK,CAAC,MAAM;CAAO,QAAQ;EAAE,OAAO;CAAO;AACxE;;AAGA,SAAgB,kBAAkB,OAAuB;CAEvD,MAAM,MADQ,gDAAgD,KAAK,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI,EAClG,CAAA,GAAQ,EAAE,CAAC,YAAY;CACnC,IAAI,CAAC,OAAO,CAAC,WAAW,GAAG,GAAG,MAAM,IAAI,MAAM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,OAAO,CAAC;AAAG;AACrH,SAAgB,+BAAuE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,aAAa,CAAC,CAAC;AAAG;AACvJ,SAAgB,6BAAmE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,CAAC,CAAC;AAAG;AACjJ,SAAgB,8BAAgE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,cAAc,CAAC,CAAC;AAAG;;;;;AAMjJ,SAAS,OAAO;CACd,MAAM,IAAI,MAAM;CAChB,IAAI,EAAE,QAAQ;CACd,EAAE,SAAS;CACX,KAAK,MAAM,UAAU,iBACnB,IAAI;EAAE,iBAAiB,MAAM;CAAG,SACzB,OAAO;EAAE,QAAQ,MAAM,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAAG;AAEnJ;;;;;;ACrJA,IAAI,eAAyC,KAAA;AAC7C,SAAgB,gBAAgB,MAAsC;CAAE,SAAS;AAAM;AACvF,IAAa,eAAmC,OAAO"}
@@ -1,7 +1,7 @@
1
1
  import { r as sanitizeDisplayText } from "./text-li76pThX.js";
2
- import { Zn as reactionEmoji, bt as STATUS_AVAILABILITIES, gr as STATUS_CARD_LIMITS, wt as sanitizeStatusText } from "./groupMeta-DxuJzko_.js";
3
- import { t as CliError } from "./errors-DDLFO4Gf.js";
4
- import { T as node, p as groupOf, r as chatOrGroup } from "./apiKit-BlsNk-Cx.js";
2
+ import { $n as reactionEmoji, Tt as sanitizeStatusText, vr as STATUS_CARD_LIMITS, xt as STATUS_AVAILABILITIES } from "./groupMeta--fxSh792.js";
3
+ import { o as shownValue, t as CliError } from "./errors-JVJsO8Iu.js";
4
+ import { T as node, p as groupOf, r as chatOrGroup } from "./apiKit-nLK4jeTq.js";
5
5
  import { createHash } from "node:crypto";
6
6
  // src/engineMethods.ts
7
7
  /**
@@ -209,6 +209,7 @@ var ENGINE_PARAMS = {
209
209
  setGroupCall: "{ groupId, sfu, e2ee? }",
210
210
  groupCallToken: "{ groupId }",
211
211
  groupCallKey: "{ groupId }",
212
+ groupCallModerate: "{ groupId, act, target?, src? }",
212
213
  forgetGroup: "{ groupId }",
213
214
  setGroupManage: "{ groupId, on }",
214
215
  deviceEnrollInvite: "{ name }",
@@ -504,12 +505,12 @@ function checkOwnStatus(input, name, code, now = Date.now()) {
504
505
  const fail = (field, rule) => new CliError(code, `${name(field)} ${rule}`);
505
506
  const status = {};
506
507
  if (input.availability !== void 0) {
507
- if (!STATUS_AVAILABILITIES.includes(input.availability)) throw fail("availability", `takes ${STATUS_AVAILABILITIES.join(", ")}, not ${JSON.stringify(input.availability)}`);
508
+ if (!STATUS_AVAILABILITIES.includes(input.availability)) throw fail("availability", `takes ${STATUS_AVAILABILITIES.join(", ")}, not ${shownValue(input.availability)}`);
508
509
  status.availability = input.availability;
509
510
  }
510
511
  if (input.emoji !== void 0) {
511
512
  const emoji = reactionEmoji(input.emoji);
512
- if (!emoji) throw fail("emoji", `takes one emoji, not ${JSON.stringify(input.emoji)}`);
513
+ if (!emoji) throw fail("emoji", `takes one emoji, not ${shownValue(input.emoji)}`);
513
514
  status.emoji = emoji;
514
515
  }
515
516
  const oneLine = input.text?.replace(/\s+/g, " ").trim();
@@ -541,4 +542,4 @@ function statusJson(status) {
541
542
  }
542
543
  export { hideSecretFields as _, PAY_METHODS as a, turnRef as c, ENGINE_METHODS as d, ENGINE_PARAMS as f, engineParamsProblem as g, SECRET_RESULTS as h, CHAT_METHODS as i, withStoredIds as l, READ_PARAMS as m, statusJson as n, TRANSPORT_NAMES as o, ENGINE_READS as p, ADDRESS_TYPES as r, WALLET_TYPES as s, checkOwnStatus as t, DESTRUCTIVE_CALLS as u };
543
544
 
544
- //# sourceMappingURL=ownStatus-DtzIllg2.js.map
545
+ //# sourceMappingURL=ownStatus-Bc08eNJY.js.map