@ghostlytools/cli 1.10.0 → 1.10.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 (87) hide show
  1. package/README.md +9 -9
  2. package/SKILL.md +2 -2
  3. package/dist/assets/api-BOWLZYXM.js +3 -0
  4. package/dist/assets/{api-BF_KwecF.js → api-Bi6hCcwG.js} +27 -20
  5. package/dist/assets/api-Bi6hCcwG.js.map +1 -0
  6. package/dist/assets/{apiKit-Du1u2l4x.js → apiKit-DzXHZojD.js} +20 -3
  7. package/dist/assets/apiKit-DzXHZojD.js.map +1 -0
  8. package/dist/assets/{apps-Bti9fDoW.js → apps-0Ks6KjqS.js} +1 -1
  9. package/dist/assets/{apps-DwPfp54I.js → apps-DIQbzG08.js} +31 -10
  10. package/dist/assets/apps-DIQbzG08.js.map +1 -0
  11. package/dist/assets/{arkade-DOWpA2Kr.js → arkade-zozCldAE.js} +2 -2
  12. package/dist/assets/{arkade-DOWpA2Kr.js.map → arkade-zozCldAE.js.map} +1 -1
  13. package/dist/assets/{backup-DZ_Q1eSu.js → backup-BL49Kt-T.js} +6 -5
  14. package/dist/assets/{backup-DZ_Q1eSu.js.map → backup-BL49Kt-T.js.map} +1 -1
  15. package/dist/assets/{backup-CeRckyl2.js → backup-BvIFcZM7.js} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{buttons-BxIThdg9.js → buttons-CAW5v5EE.js} +3 -3
  19. package/dist/assets/{buttons-BxIThdg9.js.map → buttons-CAW5v5EE.js.map} +1 -1
  20. package/dist/assets/buttons-oJI5mHSL.js +2 -0
  21. package/dist/assets/childEnv-BVOQK9EA.js +21 -0
  22. package/dist/assets/childEnv-BVOQK9EA.js.map +1 -0
  23. package/dist/assets/{client-D5E1RQYB.js → client-CyApKBEw.js} +2 -2
  24. package/dist/assets/{client-D5E1RQYB.js.map → client-CyApKBEw.js.map} +1 -1
  25. package/dist/assets/codec-DqFxxB_q.js +13 -0
  26. package/dist/assets/codec-DqFxxB_q.js.map +1 -0
  27. package/dist/assets/{envelope-CugS9qwQ.js → envelope-CMUgz31I.js} +3 -12
  28. package/dist/assets/envelope-CMUgz31I.js.map +1 -0
  29. package/dist/assets/{fixedHosts-B4E4VrYE.js → fixedHosts-C2hdCfzK.js} +4 -4
  30. package/dist/assets/{fixedHosts-B4E4VrYE.js.map → fixedHosts-C2hdCfzK.js.map} +1 -1
  31. package/dist/assets/{groupFiles-NonOYBKN.js → groupFiles-BAQIt_bJ.js} +68 -144
  32. package/dist/assets/groupFiles-BAQIt_bJ.js.map +1 -0
  33. package/dist/assets/{host-DvcVt5YI.js → host-CaRlDMTd.js} +143 -42
  34. package/dist/assets/host-CaRlDMTd.js.map +1 -0
  35. package/dist/assets/{hyperdhtRelay-Ce42sR8x.js → hyperdhtRelay-BxADl3SG.js} +2 -2
  36. package/dist/assets/{hyperdhtRelay-Ce42sR8x.js.map → hyperdhtRelay-BxADl3SG.js.map} +1 -1
  37. package/dist/assets/{irohWeb-C9ChbD-c.js → irohWeb-D2sh6EWp.js} +10 -6
  38. package/dist/assets/irohWeb-D2sh6EWp.js.map +1 -0
  39. package/dist/assets/{main-4qE381KM.js → main-Bc4Ow56Z.js} +46 -30
  40. package/dist/assets/main-Bc4Ow56Z.js.map +1 -0
  41. package/dist/assets/{mainline-DOwZDHVy.js → mainline-DWh4Ccri.js} +2 -2
  42. package/dist/assets/{mainline-DOwZDHVy.js.map → mainline-DWh4Ccri.js.map} +1 -1
  43. package/dist/assets/networkReason-DT_D_Wpc.js +474 -0
  44. package/dist/assets/networkReason-DT_D_Wpc.js.map +1 -0
  45. package/dist/assets/{nwc-CHLWFV1R.js → nwc-DoSEhUKb.js} +3 -3
  46. package/dist/assets/{nwc-CHLWFV1R.js.map → nwc-DoSEhUKb.js.map} +1 -1
  47. package/dist/assets/{nwcProvider-BlkPOJen.js → nwcProvider-CGWqUjpB.js} +2 -2
  48. package/dist/assets/{nwcProvider-BlkPOJen.js.map → nwcProvider-CGWqUjpB.js.map} +1 -1
  49. package/dist/assets/{ownDid-yXtY_1B5.js → ownDid-CbGjRLBn.js} +2 -2
  50. package/dist/assets/{ownDid-yXtY_1B5.js.map → ownDid-CbGjRLBn.js.map} +1 -1
  51. package/dist/assets/{profiles-vbXHs0Mq.js → profiles-DgIfvBeN.js} +10 -4
  52. package/dist/assets/profiles-DgIfvBeN.js.map +1 -0
  53. package/dist/assets/{registry-chCD0KWS.js → registry-BSyxGjN6.js} +11 -9
  54. package/dist/assets/registry-BSyxGjN6.js.map +1 -0
  55. package/dist/assets/{registry-BN9r2pR4.js → registry-C5cn80Rw.js} +1 -1
  56. package/dist/assets/{resolve-Dtzogt2W.js → resolve-D-9YRFhl.js} +2 -2
  57. package/dist/assets/{resolve-Dtzogt2W.js.map → resolve-D-9YRFhl.js.map} +1 -1
  58. package/dist/assets/{server-BZnsm5X5.js → server-BufntkX8.js} +240 -289
  59. package/dist/assets/server-BufntkX8.js.map +1 -0
  60. package/dist/assets/{src-DZagapGt.js → src-CCt5s4DK.js} +3162 -2825
  61. package/dist/assets/src-CCt5s4DK.js.map +1 -0
  62. package/dist/assets/{sshForges-BkTgy5rx.js → sshForges-D8CPaIbR.js} +2 -2
  63. package/dist/assets/{sshForges-BkTgy5rx.js.map → sshForges-D8CPaIbR.js.map} +1 -1
  64. package/dist/assets/{translate-B9SMd6uf.js → translate-Cb-6hMhD.js} +11 -7
  65. package/dist/assets/{translate-B9SMd6uf.js.map → translate-Cb-6hMhD.js.map} +1 -1
  66. package/dist/assets/{usdt-BU4ezonh.js → usdt-ds461mzA.js} +3 -3
  67. package/dist/assets/{usdt-BU4ezonh.js.map → usdt-ds461mzA.js.map} +1 -1
  68. package/dist/assets/{words-jYy7lTcb.js → words-B1ylON2h.js} +2 -2
  69. package/dist/assets/{words-jYy7lTcb.js.map → words-B1ylON2h.js.map} +1 -1
  70. package/dist/ghostly.mjs +1 -1
  71. package/package.json +1 -1
  72. package/dist/assets/api-BF_KwecF.js.map +0 -1
  73. package/dist/assets/api-DdrA86Ur.js +0 -3
  74. package/dist/assets/apiKit-Du1u2l4x.js.map +0 -1
  75. package/dist/assets/apps-DwPfp54I.js.map +0 -1
  76. package/dist/assets/buttons-D9QBHS9Y.js +0 -2
  77. package/dist/assets/envelope-CugS9qwQ.js.map +0 -1
  78. package/dist/assets/groupFiles-NonOYBKN.js.map +0 -1
  79. package/dist/assets/host-DvcVt5YI.js.map +0 -1
  80. package/dist/assets/irohWeb-C9ChbD-c.js.map +0 -1
  81. package/dist/assets/main-4qE381KM.js.map +0 -1
  82. package/dist/assets/networkReason-MInk1Y63.js +0 -154
  83. package/dist/assets/networkReason-MInk1Y63.js.map +0 -1
  84. package/dist/assets/profiles-vbXHs0Mq.js.map +0 -1
  85. package/dist/assets/registry-chCD0KWS.js.map +0 -1
  86. package/dist/assets/server-BZnsm5X5.js.map +0 -1
  87. package/dist/assets/src-DZagapGt.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { Au as newerPacket, Iu as publicKeyFromZ32, Mu as parseRelayPayload, Tu as isDiscoveryBudgetError, _u as RelayTransport, gu as HEDGE_MS, hu as HEDGE_MISSING_MS, vu as RelaysFailedError, yu as SLOW_MS } from "./src-DZagapGt.js";
1
+ import { Bu as publicKeyFromZ32, Cu as SLOW_MS, Iu as parseRelayPayload, Pu as newerPacket, Su as RelaysFailedError, bu as HEDGE_MS, ku as isDiscoveryBudgetError, xu as RelayTransport, yu as HEDGE_MISSING_MS } from "./src-CCt5s4DK.js";
2
2
  import { ed25519 } from "@noble/curves/ed25519.js";
3
3
  import { createHash } from "node:crypto";
4
4
  import DHT from "bittorrent-dht";
@@ -335,4 +335,4 @@ var RelaysAndDht = class {
335
335
  //#endregion
336
336
  export { Mainline, RelaysAndDht };
337
337
 
338
- //# sourceMappingURL=mainline-DOwZDHVy.js.map
338
+ //# sourceMappingURL=mainline-DWh4Ccri.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mainline-DOwZDHVy.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 HEDGE_MISSING_MS, HEDGE_MS, RelayTransport, RelaysFailedError, SLOW_MS, isDiscoveryBudgetError, newerPacket, parseRelayPayload, publicKeyFromZ32,\n type DiscoveryBudgetError, 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/**\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 const dht = new DHT({ verify, ...(bootstrap !== undefined ? { bootstrap } : {}), ...(host ? { host } : {}) });\n // A node of the table that errors must not end the process.\n dht.on(\"error\", () => {});\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 }, (error, found) => {\n if (error) return reject(error);\n if (!found?.v || !found.sig) return resolve(null);\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 try { resolve(parseRelayPayload(pubKeyZ32, payload)); } 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 destroy(): Promise<void> {\n const node = this.node;\n this.closed = true;\n return node ? new Promise((resolve) => node.dht.destroy(() => resolve())) : Promise.resolve();\n }\n}\n\n/** Keys a `RelaysAndDht` remembers as found nowhere (`missing`). */\nconst MISSING_KEPT = 256;\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). A background read the budget holds waits for it.\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\n constructor(private readonly dht: Mainline | null, relays: RelayTransportOptions = {}, private readonly pinned = false) {\n this.relays = new RelayTransport(relays);\n }\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.\n await this.relays.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putBoth(key, payload, options, conflict, timestamp), options, false, this.dht !== null);\n }\n\n publishPayload(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions = {}): Promise<void> {\n return this.putBoth(pubKeyZ32, payload, options);\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 */\n private async putBoth(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions, conflict?: (relay: string, read?: () => Promise<bigint | null>) => void, timestamp?: bigint): 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) 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 = {}): Promise<SignedPacket | null> {\n if (!this.dht) return this.relays.resolve(pubKeyZ32, options);\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 // 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)) return this.heldBack(pubKeyZ32, failed, options);\n if (failed instanceof RelaysFailedError) fromRelays = failed.kept;\n if (!failed) this.lastVia = \"relay\";\n if (!failed && !down()) return fromRelays;\n }\n try {\n const fromDht = await this.fromDht(pubKeyZ32);\n this.lastVia = \"dht\";\n return newerPacket(fromRelays, fromDht);\n } catch (error) {\n if (fromRelays) 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 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 /** With the DHT every packet goes there too, whatever the relays' budgets say: nothing is held. */\n publishHeld(pubKeyZ32: string, options?: PkarrRequestOptions): DiscoveryBudgetError | null { return this.dht ? null : this.relays.publishHeld(pubKeyZ32, options); }\n onServerTime(listener: Parameters<RelayTransport[\"onServerTime\"]>[0]): () => void { return this.relays.onServerTime(listener); }\n configure({ relays }: { relays: string[]; readRelays: boolean }): void { if (!this.pinned) this.relays.setRelays(relays); }\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,IAAa,kBAAb,cAAqC,MAAM;CACzC,YAAY,QAAgB;EAC1B,MAAM,mDAAmD,OAAO,EAAE;EAClE,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,WAAb,MAAsB;CAKS;CAJ7B,OAA8D;CAC9D,SAAiB;CACjB;CAEA,YAAY,UAA4C,CAAC,GAAG;EAA/B,KAAA,UAAA;EAC3B,KAAK,YAAY,QAAQ,aAAa;CACxC;CAEA,IAAY,MAAW;EAAE,OAAO,KAAK,QAAQ,CAAC,CAAC;CAAK;CAEpD,UAA0D;EACxD,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,wBAAwB;EACzD,IAAI,KAAK,MAAM,O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uC;EAAE,OAAO,KAAK,OAAO,gBAAgB,SAAS;CAAG;;CAExG,YAAY,WAAmB,SAA4D;EAAE,OAAO,KAAK,MAAM,OAAO,KAAK,OAAO,YAAY,WAAW,OAAO;CAAG;CACnK,aAAa,UAAqE;EAAE,OAAO,KAAK,OAAO,aAAa,QAAQ;CAAG;CAC/H,UAAU,EAAE,UAA2D;EAAE,IAAI,CAAC,KAAK,QAAQ,KAAK,OAAO,UAAU,MAAM;CAAG;AAC5H"}
1
+ {"version":3,"file":"mainline-DWh4Ccri.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 HEDGE_MISSING_MS, HEDGE_MS, RelayTransport, RelaysFailedError, SLOW_MS, isDiscoveryBudgetError, newerPacket, parseRelayPayload, publicKeyFromZ32,\n type DiscoveryBudgetError, 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/**\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 const dht = new DHT({ verify, ...(bootstrap !== undefined ? { bootstrap } : {}), ...(host ? { host } : {}) });\n // A node of the table that errors must not end the process.\n dht.on(\"error\", () => {});\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 }, (error, found) => {\n if (error) return reject(error);\n if (!found?.v || !found.sig) return resolve(null);\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 try { resolve(parseRelayPayload(pubKeyZ32, payload)); } 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 destroy(): Promise<void> {\n const node = this.node;\n this.closed = true;\n return node ? new Promise((resolve) => node.dht.destroy(() => resolve())) : Promise.resolve();\n }\n}\n\n/** Keys a `RelaysAndDht` remembers as found nowhere (`missing`). */\nconst MISSING_KEPT = 256;\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). A background read the budget holds waits for it.\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\n constructor(private readonly dht: Mainline | null, relays: RelayTransportOptions = {}, private readonly pinned = false) {\n this.relays = new RelayTransport(relays);\n }\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.\n await this.relays.publishDated(identity, records, (key, payload, timestamp, conflict) => this.putBoth(key, payload, options, conflict, timestamp), options, false, this.dht !== null);\n }\n\n publishPayload(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions = {}): Promise<void> {\n return this.putBoth(pubKeyZ32, payload, options);\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 */\n private async putBoth(pubKeyZ32: string, payload: Uint8Array, options: PkarrRequestOptions, conflict?: (relay: string, read?: () => Promise<bigint | null>) => void, timestamp?: bigint): 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) 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 = {}): Promise<SignedPacket | null> {\n if (!this.dht) return this.relays.resolve(pubKeyZ32, options);\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 // 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)) return this.heldBack(pubKeyZ32, failed, options);\n if (failed instanceof RelaysFailedError) fromRelays = failed.kept;\n if (!failed) this.lastVia = \"relay\";\n if (!failed && !down()) return fromRelays;\n }\n try {\n const fromDht = await this.fromDht(pubKeyZ32);\n this.lastVia = \"dht\";\n return newerPacket(fromRelays, fromDht);\n } catch (error) {\n if (fromRelays) 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 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 /** With the DHT every packet goes there too, whatever the relays' budgets say: nothing is held. */\n publishHeld(pubKeyZ32: string, options?: PkarrRequestOptions): DiscoveryBudgetError | null { return this.dht ? null : this.relays.publishHeld(pubKeyZ32, options); }\n onServerTime(listener: Parameters<RelayTransport[\"onServerTime\"]>[0]): () => void { return this.relays.onServerTime(listener); }\n configure({ relays }: { relays: string[]; readRelays: boolean }): void { if (!this.pinned) this.relays.setRelays(relays); }\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,IAAa,kBAAb,cAAqC,MAAM;CACzC,YAAY,QAAgB;EAC1B,MAAM,mDAAmD,OAAO,EAAE;EAClE,KAAK,OAAO;CACd;AACF;;;;;;AAOA,IAAa,WAAb,MAAsB;CAKS;CAJ7B,OAA8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AAM,SAAS,KAAK,OAAO,UAAU;EACrC,OAAO,KAAK,YAAY,QAAQ;GAAE,GAAG;GAAQ,MAAM,EAAE,KAAK,MAAM;EAAE,IAAI;CACxE;CACA,UAAU,UAAkE;EAAE,OAAO,KAAK,OAAO,UAAU,QAAQ;CAAG;;CAEtH,eAAe,WAAuC;EAAE,OAAO,KAAK,OAAO,eAAe,SAAS;CAAG;CACtG,gBAAgB,WAAuC;EAAE,OAAO,KAAK,OAAO,gBAAgB,SAAS;CAAG;;CAExG,YAAY,WAAmB,SAA4D;EAAE,OAAO,KAAK,MAAM,OAAO,KAAK,OAAO,YAAY,WAAW,OAAO;CAAG;CACnK,aAAa,UAAqE;EAAE,OAAO,KAAK,OAAO,aAAa,QAAQ;CAAG;CAC/H,UAAU,EAAE,UAA2D;EAAE,IAAI,CAAC,KAAK,QAAQ,KAAK,OAAO,UAAU,MAAM;CAAG;AAC5H"}
@@ -0,0 +1,474 @@
1
+ import { Qn as engineText, Yu as toBase64Url, Zn as engineError } from "./src-CCt5s4DK.js";
2
+ import { f as openDb, g as wrap, h as transact, i as STORES, m as store } from "./idb-BHsAqENE.js";
3
+ import { t as fromBase64Url } from "./codec-DqFxxB_q.js";
4
+ import { sha256 } from "@noble/hashes/sha2.js";
5
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
6
+ //#region ../browser/src/shared/profileKey.ts
7
+ /**
8
+ * Only the record key can hold a newline: the other parts come from the code, so the joined binding still reads one
9
+ * way (the first two lines, the last line, and the key between them).
10
+ */
11
+ function binding(b) {
12
+ for (const part of [
13
+ b.db,
14
+ b.store,
15
+ b.field
16
+ ]) if (!part || part.includes("\n")) throw new Error("Invalid sealed field binding");
17
+ return new TextEncoder().encode([
18
+ "ghostly-field/2",
19
+ b.db,
20
+ b.store,
21
+ b.key,
22
+ b.field
23
+ ].join("\n"));
24
+ }
25
+ function isSealedField(value) {
26
+ const v = value;
27
+ return !!v && typeof v === "object" && v.v === 2 && typeof v.iv === "string" && typeof v.ct === "string";
28
+ }
29
+ /** Seals one field under DK with a fresh random 96-bit nonce and no KDF per field. */
30
+ async function sealField(key, where, value) {
31
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
32
+ const ct = new Uint8Array(await crypto.subtle.encrypt({
33
+ name: "AES-GCM",
34
+ iv,
35
+ additionalData: binding(where)
36
+ }, key, new TextEncoder().encode(value)));
37
+ return {
38
+ v: 2,
39
+ iv: toBase64Url(iv),
40
+ ct: toBase64Url(ct)
41
+ };
42
+ }
43
+ /** Opens a field sealed for exactly this place under this DK; anything else fails instead of opening wrong. */
44
+ async function openField(key, where, sealed) {
45
+ if (!isSealedField(sealed)) throw new Error("Unsupported sealed field version");
46
+ const aad = binding(where);
47
+ try {
48
+ const iv = fromBase64Url(sealed.iv);
49
+ if (iv.length !== 12) throw new Error("nonce");
50
+ return new TextDecoder().decode(await crypto.subtle.decrypt({
51
+ name: "AES-GCM",
52
+ iv,
53
+ additionalData: aad
54
+ }, key, fromBase64Url(sealed.ct)));
55
+ } catch {
56
+ throw new Error("A sealed field could not be opened: it was changed, or it belongs to another record");
57
+ }
58
+ }
59
+ //#endregion
60
+ //#region ../browser/src/engine/dataKey.ts
61
+ var PEER_DB = "ghostly";
62
+ /**
63
+ * The profile's data key (DK), when the profile is encrypted and unlocked: the one slot the engine owns. A
64
+ * non-extractable key; nothing writes it anywhere. Empty, every secret is sealed as today (version 1).
65
+ */
66
+ var slot = null;
67
+ /**
68
+ * The profile's migration is over (no `migrating` mark): a sealed place then takes version 2 only. A version 1 or plain
69
+ * value there was put by someone who could write the profile's database but not read it, and is refused.
70
+ */
71
+ var sealedOnly = false;
72
+ var onDrop = /* @__PURE__ */ new Set();
73
+ var LOCKED = "This profile is locked. Enter its passphrase first.";
74
+ function hasDataKey() {
75
+ return slot !== null;
76
+ }
77
+ /** Whether a sealed place may still hold a version 1 or plain value. */
78
+ function takesUnsealed() {
79
+ return !(slot && sealedOnly);
80
+ }
81
+ /** A cache of opened secrets empties itself when the key goes. Returns the way to stop listening. */
82
+ function whenDataKeyDropped(drop) {
83
+ onDrop.add(drop);
84
+ return () => {
85
+ onDrop.delete(drop);
86
+ };
87
+ }
88
+ async function sealSecret(value, at) {
89
+ if (slot) return sealField(slot, {
90
+ db: PEER_DB,
91
+ ...at
92
+ }, value);
93
+ const deviceKey = newDeviceKey();
94
+ return {
95
+ sealed: await sealSeed(value, deviceKey),
96
+ deviceKey
97
+ };
98
+ }
99
+ /** Version 2 only, for a field the database layer seals: refused while the profile is locked, never version 1. */
100
+ async function sealPlace(value, at) {
101
+ if (!slot) throw new Error(LOCKED);
102
+ return sealField(slot, {
103
+ db: PEER_DB,
104
+ ...at
105
+ }, value);
106
+ }
107
+ /** Reads both versions: a profile being encrypted holds some of each until its migration ends. */
108
+ async function openSecret(secret, at) {
109
+ if (!isSealedField(secret)) {
110
+ if (!takesUnsealed()) throw new Error("A secret of this profile was not sealed with its key");
111
+ return unsealSeed(secret.sealed, secret.deviceKey);
112
+ }
113
+ if (!slot) throw new Error(LOCKED);
114
+ return openField(slot, {
115
+ db: PEER_DB,
116
+ ...at
117
+ }, secret);
118
+ }
119
+ //#endregion
120
+ //#region ../browser/src/engine/sealedRows.ts
121
+ /**
122
+ * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act
123
+ * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,
124
+ * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read
125
+ * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.
126
+ */
127
+ var FIELDS = {
128
+ [STORES.links]: [
129
+ "seedB64",
130
+ "encKeyB64",
131
+ "participationSeed",
132
+ "transportSeeds",
133
+ "inviteCode",
134
+ "pairedPeerKey",
135
+ "peerTrust.verifiedKey",
136
+ "ratchetState"
137
+ ],
138
+ [STORES.groups]: [
139
+ "invitation.seedB64",
140
+ "entry.seedB64",
141
+ "joining.seedB64",
142
+ "state.seedB64",
143
+ "state.secrets",
144
+ "community.seedB64",
145
+ "community.secrets",
146
+ "community.entry.seedB64",
147
+ "community.rv"
148
+ ],
149
+ [STORES.swaps]: ["swap", "token"],
150
+ [STORES.melts]: ["secrets", "outputs"],
151
+ [STORES.payments]: ["token"],
152
+ [STORES.quotes]: ["outputs"],
153
+ [STORES.intents]: ["prepared.swap", "prepared.token"]
154
+ };
155
+ /** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */
156
+ var NESTED = { [STORES.groups]: "previous" };
157
+ /**
158
+ * A proof's secret is its row's key (`keyPath: "secret"`), and a sealed value can't be one: a sealed proof is kept under
159
+ * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a
160
+ * transaction, where WebCrypto can't be waited for.
161
+ */
162
+ var proofKey = (secret) => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\n${secret}`)));
163
+ var SEALED_SECRET = "sealedSecret";
164
+ var keyOf = (store, row) => String(store === STORES.melts || store === STORES.quotes ? row.quote : store === STORES.intents ? read(row, "review.id") : row.id);
165
+ function read(row, path) {
166
+ return path.split(".").reduce((at, part) => at && typeof at === "object" ? at[part] : void 0, row);
167
+ }
168
+ /** The row with `value` at `path`, copied along the way: the caller's row is never changed. */
169
+ function written(row, [part, ...rest], value) {
170
+ return {
171
+ ...row,
172
+ [part]: rest.length ? written(row[part], rest, value) : value
173
+ };
174
+ }
175
+ /** Every phase 1 value of a row that is there, with its path. */
176
+ function places(store, row, prefix = "") {
177
+ const found = (FIELDS[store] ?? []).map((path) => ({
178
+ path: prefix + path,
179
+ value: read(row, path)
180
+ })).filter(({ value }) => value !== void 0);
181
+ const nested = NESTED[store] && row[NESTED[store]];
182
+ return nested && typeof nested === "object" ? [...found, ...places(store, nested, `${prefix}${NESTED[store]}.`)] : found;
183
+ }
184
+ function sealWith(store, value, seal) {
185
+ const row = value;
186
+ if (store === STORES.proofs) {
187
+ if (row[SEALED_SECRET] !== void 0) return value;
188
+ const secret = String(row.secret), key = proofKey(secret);
189
+ return {
190
+ ...row,
191
+ secret: key,
192
+ [SEALED_SECRET]: seal(JSON.stringify(secret), {
193
+ store,
194
+ key,
195
+ field: "secret"
196
+ })
197
+ };
198
+ }
199
+ const key = keyOf(store, row);
200
+ let out = row;
201
+ for (const { path, value: at } of places(store, row)) if (!isSealedField(at)) out = written(out, path.split("."), seal(JSON.stringify(at), {
202
+ store,
203
+ key,
204
+ field: path
205
+ }));
206
+ return out;
207
+ }
208
+ var slotOf = (json, at) => [
209
+ at.store,
210
+ at.key,
211
+ at.field,
212
+ json
213
+ ].join("\n");
214
+ /**
215
+ * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for
216
+ * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile
217
+ * makes a write fail, never go out in the clear.
218
+ */
219
+ var RowSeals = class RowSeals {
220
+ /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */
221
+ static turn = Promise.resolve();
222
+ on = hasDataKey();
223
+ ready = /* @__PURE__ */ new Map();
224
+ /** What these rows (or the proofs of these secrets) hold, sealed now. */
225
+ async prepare(store, rows) {
226
+ if (!this.on) return this;
227
+ const wanted = /* @__PURE__ */ new Map();
228
+ for (const row of rows) sealWith(store, row, (json, at) => {
229
+ wanted.set(slotOf(json, at), [json, at]);
230
+ return {
231
+ v: 2,
232
+ iv: "",
233
+ ct: ""
234
+ };
235
+ });
236
+ const sealing = RowSeals.turn.then(async () => {
237
+ for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));
238
+ });
239
+ RowSeals.turn = sealing.catch(() => {});
240
+ await sealing;
241
+ return this;
242
+ }
243
+ /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */
244
+ row(store, row) {
245
+ if (!this.on) return row;
246
+ return sealWith(store, row, (json, at) => {
247
+ const sealed = this.ready.get(slotOf(json, at));
248
+ if (!sealed) throw new Error("A secret was not sealed before it was saved");
249
+ return sealed;
250
+ });
251
+ }
252
+ };
253
+ async function sealRow(store, row) {
254
+ return (await new RowSeals().prepare(store, [row])).row(store, row);
255
+ }
256
+ /**
257
+ * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.
258
+ * Without the data key, the store itself.
259
+ */
260
+ function sealedStore(store, seals) {
261
+ if (!seals.on) return store;
262
+ const proofs = store.name === STORES.proofs;
263
+ return new Proxy(store, { get(target, name) {
264
+ if (name === "put") return (row, ...key) => target.put(seals.row(target.name, row), ...key);
265
+ if (proofs && name === "delete") return (secret) => {
266
+ target.delete(secret);
267
+ return target.delete(proofKey(secret));
268
+ };
269
+ if (proofs && name === "get") return (secret) => target.get(proofKey(secret));
270
+ const value = Reflect.get(target, name, target);
271
+ return typeof value === "function" ? value.bind(target) : value;
272
+ } });
273
+ }
274
+ function unsealed() {
275
+ if (!takesUnsealed()) throw new Error("A secret of this profile was not sealed with its key");
276
+ }
277
+ /** The row as the engine uses it: every sealed value opened, where it was. */
278
+ async function openRow(store, value) {
279
+ if (!hasDataKey() || !value) return value;
280
+ const row = value;
281
+ if (store === STORES.proofs) {
282
+ const sealed = row[SEALED_SECRET];
283
+ if (sealed === void 0) {
284
+ unsealed();
285
+ return value;
286
+ }
287
+ const key = String(row.secret), secret = JSON.parse(await openSecret(sealed, {
288
+ store,
289
+ key,
290
+ field: "secret"
291
+ }));
292
+ if (proofKey(secret) !== key) throw new Error("A sealed field could not be opened: it was changed, or it belongs to another record");
293
+ const { [SEALED_SECRET]: _sealed, ...rest } = row;
294
+ return {
295
+ ...rest,
296
+ secret
297
+ };
298
+ }
299
+ const key = keyOf(store, row);
300
+ let out = row;
301
+ for (const { path, value: at } of places(store, row)) {
302
+ if (!isSealedField(at)) {
303
+ unsealed();
304
+ continue;
305
+ }
306
+ out = written(out, path.split("."), JSON.parse(await openSecret(at, {
307
+ store,
308
+ key,
309
+ field: path
310
+ })));
311
+ }
312
+ return out;
313
+ }
314
+ function openRows(store, rows) {
315
+ return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);
316
+ }
317
+ //#endregion
318
+ //#region ../browser/src/engine/paymentAdapters/persistence.ts
319
+ /**
320
+ * A USDT payment is one transaction at one account nonce. Another payment from the same account and chain that is
321
+ * submitted or of unknown outcome holds its nonce until it confirms. A review made after it was sent took the next
322
+ * nonce and may go at once. One made before (or read from an RPC that had not seen it yet) has the same or a lower
323
+ * nonce: sent, it would replace the earlier transaction or be dropped, so it is refused. A row with no nonce refuses.
324
+ */
325
+ function nonceTaken(review, intents) {
326
+ if (review.method !== "usdt") return false;
327
+ const from = review.evm?.from?.toLowerCase(), nonce = review.evm?.nonce;
328
+ return intents.some(({ review: other }) => other.id !== review.id && other.method === "usdt" && other.chainId === review.chainId && other.evm?.from?.toLowerCase() === from && ["submitted", "unknown"].includes(other.state) && !(typeof nonce === "number" && typeof other.evm?.nonce === "number" && nonce > other.evm.nonce));
329
+ }
330
+ /**
331
+ * A Cashu review's swap and token are sealed when the profile is encrypted (sealedRows): they are read here opened.
332
+ * `claim` and `cancel` change only the review, so they put back the row as it was read, sealed fields and all.
333
+ */
334
+ var intentRepository = {
335
+ async get(id) {
336
+ return openRow(STORES.intents, await wrap((await store(STORES.intents, "readonly")).get(id)));
337
+ },
338
+ async list() {
339
+ return openRows(STORES.intents, await wrap((await store(STORES.intents, "readonly")).getAll()));
340
+ },
341
+ async put(intent) {
342
+ const row = await sealRow(STORES.intents, intent);
343
+ await transact([STORES.intents], (s) => {
344
+ s[STORES.intents].put(row);
345
+ });
346
+ },
347
+ async claim(id) {
348
+ const tx = (await openDb()).transaction(STORES.intents, "readwrite");
349
+ return new Promise((resolve, reject) => {
350
+ let saved;
351
+ let reason = engineText("alreadySubmitted");
352
+ const request = tx.objectStore(STORES.intents).getAll();
353
+ request.onsuccess = () => {
354
+ const intents = request.result;
355
+ saved = intents.find((item) => item.review.id === id);
356
+ if (!saved || saved.review.state !== "pending") {
357
+ tx.abort();
358
+ return;
359
+ }
360
+ if (saved.review.requestId && intents.some(({ review }) => review.id !== id && review.requestId === saved.review.requestId && review.linkId === saved.review.linkId && [
361
+ "submitted",
362
+ "settled",
363
+ "unknown"
364
+ ].includes(review.state))) {
365
+ tx.abort();
366
+ return;
367
+ }
368
+ if (nonceTaken(saved.review, intents)) {
369
+ reason = engineText("sentAfterReview");
370
+ tx.abort();
371
+ return;
372
+ }
373
+ saved.review = {
374
+ ...saved.review,
375
+ state: "submitted",
376
+ error: void 0,
377
+ submittedAt: Date.now()
378
+ };
379
+ tx.objectStore(STORES.intents).put(saved);
380
+ };
381
+ tx.oncomplete = () => resolve(openRow(STORES.intents, saved));
382
+ tx.onabort = tx.onerror = () => reject(new Error(reason));
383
+ });
384
+ },
385
+ async cancel(id) {
386
+ const tx = (await openDb()).transaction(STORES.intents, "readwrite");
387
+ return new Promise((resolve, reject) => {
388
+ let saved;
389
+ const request = tx.objectStore(STORES.intents).get(id);
390
+ request.onsuccess = () => {
391
+ saved = request.result;
392
+ if (!saved || saved.review.state !== "pending") {
393
+ tx.abort();
394
+ return;
395
+ }
396
+ saved.review = {
397
+ ...saved.review,
398
+ state: "cancelled"
399
+ };
400
+ tx.objectStore(STORES.intents).put(saved);
401
+ };
402
+ tx.oncomplete = () => resolve(openRow(STORES.intents, saved));
403
+ tx.onabort = tx.onerror = () => reject(engineError("cannotCancelSubmitted"));
404
+ });
405
+ }
406
+ };
407
+ /** Key for a wallet that needs no password: its seed is protected like the Cashu proofs in the same database. */
408
+ function newDeviceKey() {
409
+ return btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)))).replace(/=+$/, "");
410
+ }
411
+ async function passwordKey(password, salt) {
412
+ const material = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), "PBKDF2", false, ["deriveKey"]);
413
+ return crypto.subtle.deriveKey({
414
+ name: "PBKDF2",
415
+ hash: "SHA-256",
416
+ salt,
417
+ iterations: 6e5
418
+ }, material, {
419
+ name: "AES-GCM",
420
+ length: 256
421
+ }, false, ["encrypt", "decrypt"]);
422
+ }
423
+ async function sealSeed(seed, password) {
424
+ if (password.length < 12) throw new Error("Use at least 12 characters for the wallet password");
425
+ const salt = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
426
+ const ciphertext = await crypto.subtle.encrypt({
427
+ name: "AES-GCM",
428
+ iv
429
+ }, await passwordKey(password, salt), new TextEncoder().encode(seed));
430
+ return {
431
+ version: 1,
432
+ salt: [...salt],
433
+ iv: [...iv],
434
+ ciphertext: [...new Uint8Array(ciphertext)]
435
+ };
436
+ }
437
+ async function unsealSeed(seed, password) {
438
+ if (seed.version !== 1) throw new Error("Unsupported wallet backup version");
439
+ try {
440
+ return new TextDecoder().decode(await crypto.subtle.decrypt({
441
+ name: "AES-GCM",
442
+ iv: new Uint8Array(seed.iv)
443
+ }, await passwordKey(password, new Uint8Array(seed.salt)), new Uint8Array(seed.ciphertext)));
444
+ } catch {
445
+ throw new Error("Could not unlock the wallet. Check the password and backup.");
446
+ }
447
+ }
448
+ //#endregion
449
+ //#region ../browser/src/engine/paymentAdapters/networkReason.ts
450
+ /**
451
+ * A request's failure as a person says it, when the browser's own words say nothing: a request that timed out or was
452
+ * given up ("Fetch is aborted" in Safari, "signal timed out" in Chromium) did not answer in time; one that never left
453
+ * ("Failed to fetch", "Load failed") could not reach it. `host` names what was asked, when known. Anything else is
454
+ * `null`: its own words are kept.
455
+ */
456
+ function networkReason(error, host) {
457
+ const name = error instanceof Error ? error.name : "";
458
+ const text = error instanceof Error ? error.message : String(error);
459
+ if (name === "AbortError" || name === "TimeoutError" || /^(fetch is aborted|signal timed out|signal is aborted without reason|the (user|operation) (aborted a request|was aborted)\.?|this operation was aborted|the operation timed out\.?)$/i.test(text.trim())) return host ? engineText("hostTimedOut", { host }) : engineText("networkTimedOut");
460
+ if (/^(failed to fetch|load failed|fetch failed|networkerror when attempting to fetch resource\.?|network request failed)$/i.test(text.trim())) return host ? engineText("hostUnreachable", { host }) : engineText("networkUnreachable");
461
+ return null;
462
+ }
463
+ /** A request URL's host, for a reason that names it; the URL itself when it does not parse. */
464
+ function rpcHost(url) {
465
+ try {
466
+ return new URL(url).host;
467
+ } catch {
468
+ return url;
469
+ }
470
+ }
471
+ //#endregion
472
+ export { sealSeed as a, openRow as c, sealedStore as d, openSecret as f, newDeviceKey as i, openRows as l, whenDataKeyDropped as m, rpcHost as n, unsealSeed as o, sealSecret as p, intentRepository as r, RowSeals as s, networkReason as t, sealRow as u };
473
+
474
+ //# sourceMappingURL=networkReason-DT_D_Wpc.js.map