@ghostlytools/cli 1.10.5 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +27 -22
  2. package/SKILL.md +8 -5
  3. package/dist/assets/api-B-52sVYp.js +3 -0
  4. package/dist/assets/{api-DppWqAP3.js → api-CTqIcdu7.js} +532 -197
  5. package/dist/assets/api-CTqIcdu7.js.map +1 -0
  6. package/dist/assets/{apiKit-DFIho4Ev.js → apiKit-CZq4Lq4f.js} +97 -13
  7. package/dist/assets/apiKit-CZq4Lq4f.js.map +1 -0
  8. package/dist/assets/{apps-yBnbEtfV.js → apps-C_X0zgSG.js} +16 -4
  9. package/dist/assets/apps-C_X0zgSG.js.map +1 -0
  10. package/dist/assets/{apps-1MkGMH8m.js → apps-kRsY9S2S.js} +1 -1
  11. package/dist/assets/{arkade-bFAS6imn.js → arkade-_aaB7VbW.js} +2 -2
  12. package/dist/assets/{arkade-bFAS6imn.js.map → arkade-_aaB7VbW.js.map} +1 -1
  13. package/dist/assets/{backup-ejIX59o7.js → backup-DBg388Ke.js} +1 -1
  14. package/dist/assets/{backup-vj4J7M3e.js → backup-OTvrmk-w.js} +35 -7
  15. package/dist/assets/backup-OTvrmk-w.js.map +1 -0
  16. package/dist/assets/{blobFiles-XZ9PEXYy.js → blobFiles-BmsrvZc3.js} +3 -3
  17. package/dist/assets/{blobFiles-XZ9PEXYy.js.map → blobFiles-BmsrvZc3.js.map} +1 -1
  18. package/dist/assets/buttons-4EKtQl-7.js +2 -0
  19. package/dist/assets/{buttons-BoDMx3Ky.js → buttons-DUu7hxxT.js} +61 -30
  20. package/dist/assets/buttons-DUu7hxxT.js.map +1 -0
  21. package/dist/assets/{client-BQArefYa.js → client-DDpZP1R1.js} +55 -10
  22. package/dist/assets/client-DDpZP1R1.js.map +1 -0
  23. package/dist/assets/{codec-_MwTUz5E.js → codec-DrryGcPT.js} +2 -2
  24. package/dist/assets/{codec-_MwTUz5E.js.map → codec-DrryGcPT.js.map} +1 -1
  25. package/dist/assets/{envelope-CeZBNGX-.js → envelope-Q_rMgoE9.js} +2 -2
  26. package/dist/assets/{envelope-CeZBNGX-.js.map → envelope-Q_rMgoE9.js.map} +1 -1
  27. package/dist/assets/{irohWeb-C_Wnw7Q9.js → fedimintSdk-CqTeMdF0.js} +2 -354
  28. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +1 -0
  29. package/dist/assets/{fileBytes-DqnfKIkj.js → fileBytes-B0z9A6Le.js} +2 -2
  30. package/dist/assets/{fileBytes-DqnfKIkj.js.map → fileBytes-B0z9A6Le.js.map} +1 -1
  31. package/dist/assets/{fileBytes-BABGEF13.js → fileBytes-BLPZq9YU.js} +3 -3
  32. package/dist/assets/{fileBytes-BABGEF13.js.map → fileBytes-BLPZq9YU.js.map} +1 -1
  33. package/dist/assets/{fileBytes-CQQK2uOh.js → fileBytes-BtIyoDF2.js} +1 -1
  34. package/dist/assets/{fileBytesIdb-DrXmDUSy.js → fileBytesIdb-Bmlrl9EO.js} +3 -3
  35. package/dist/assets/{fileBytesIdb-DrXmDUSy.js.map → fileBytesIdb-Bmlrl9EO.js.map} +1 -1
  36. package/dist/assets/fileBytesIdb-D8mAK4pF.js +2 -0
  37. package/dist/assets/{fileBytesOpfs-udKCzcLe.js → fileBytesOpfs-DBS0kbPT.js} +3 -3
  38. package/dist/assets/{fileBytesOpfs-udKCzcLe.js.map → fileBytesOpfs-DBS0kbPT.js.map} +1 -1
  39. package/dist/assets/{fixedHosts-B_2Rvyja.js → fixedHosts-BV5GDiTU.js} +3 -3
  40. package/dist/assets/{fixedHosts-B_2Rvyja.js.map → fixedHosts-BV5GDiTU.js.map} +1 -1
  41. package/dist/assets/{host-DFLzzKNr.js → host-BlUzZgQL.js} +336 -84
  42. package/dist/assets/host-BlUzZgQL.js.map +1 -0
  43. package/dist/assets/{hyperdhtRelay-CV6qMrom.js → hyperdhtRelay-BvI_uNZO.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-CV6qMrom.js.map → hyperdhtRelay-BvI_uNZO.js.map} +1 -1
  45. package/dist/assets/{idb-BHsAqENE.js → idb-CEuoNsTv.js} +16 -5
  46. package/dist/assets/idb-CEuoNsTv.js.map +1 -0
  47. package/dist/assets/{groupFiles-D-ZUUHrx.js → irohWeb-CqPN8VPY.js} +469 -16
  48. package/dist/assets/irohWeb-CqPN8VPY.js.map +1 -0
  49. package/dist/assets/{main-xO8MnXxD.js → main-vQjlgEnt.js} +409 -126
  50. package/dist/assets/main-vQjlgEnt.js.map +1 -0
  51. package/dist/assets/{mainline-Bx184Ixg.js → mainline-p6HOW7sb.js} +2 -2
  52. package/dist/assets/{mainline-Bx184Ixg.js.map → mainline-p6HOW7sb.js.map} +1 -1
  53. package/dist/assets/{networkReason-BlQhTbXk.js → networkReason-DMffkiJ6.js} +4 -4
  54. package/dist/assets/{networkReason-BlQhTbXk.js.map → networkReason-DMffkiJ6.js.map} +1 -1
  55. package/dist/assets/{nwc-B3-PHX0L.js → nwc-2vH18oNy.js} +4 -4
  56. package/dist/assets/nwc-2vH18oNy.js.map +1 -0
  57. package/dist/assets/{nwcProvider-BeQBPB2q.js → nwcProvider-DpeDy0bV.js} +11 -3
  58. package/dist/assets/nwcProvider-DpeDy0bV.js.map +1 -0
  59. package/dist/assets/{ownDid-DAzW-Urb.js → ownDid-iKz8u_fM.js} +2 -2
  60. package/dist/assets/{ownDid-DAzW-Urb.js.map → ownDid-iKz8u_fM.js.map} +1 -1
  61. package/dist/assets/{words-BvdNuw_v.js → ownStatus-BlRKnM5F.js} +56 -4
  62. package/dist/assets/ownStatus-BlRKnM5F.js.map +1 -0
  63. package/dist/assets/{profiles-Bg43mRXu.js → profiles-B5e0TyvS.js} +22 -12
  64. package/dist/assets/profiles-B5e0TyvS.js.map +1 -0
  65. package/dist/assets/{registry-CAk2-5BQ.js → registry-Cc_PQb3k.js} +1 -1
  66. package/dist/assets/{registry-BDnsZJBi.js → registry-CnFO2Pp5.js} +123 -99
  67. package/dist/assets/registry-CnFO2Pp5.js.map +1 -0
  68. package/dist/assets/{resolve-UAfshn6j.js → resolve-DI8uAM_Y.js} +2 -2
  69. package/dist/assets/{resolve-UAfshn6j.js.map → resolve-DI8uAM_Y.js.map} +1 -1
  70. package/dist/assets/{restoredRows-YhlbokEE.js → restoredRows-C3LcxmOw.js} +4 -4
  71. package/dist/assets/{restoredRows-YhlbokEE.js.map → restoredRows-C3LcxmOw.js.map} +1 -1
  72. package/dist/assets/{server-DYdR0_Fj.js → server-DdtPxkqI.js} +2057 -655
  73. package/dist/assets/server-DdtPxkqI.js.map +1 -0
  74. package/dist/assets/{src-BTRPAi5X.js → src-BnpEQqzk.js} +813 -144
  75. package/dist/assets/src-BnpEQqzk.js.map +1 -0
  76. package/dist/assets/{sshForges-KtHK5x1x.js → sshForges-cdIAraDw.js} +2 -2
  77. package/dist/assets/{sshForges-KtHK5x1x.js.map → sshForges-cdIAraDw.js.map} +1 -1
  78. package/dist/assets/{translate-CYuygrvA.js → translate-kNopA04L.js} +2 -2
  79. package/dist/assets/{translate-CYuygrvA.js.map → translate-kNopA04L.js.map} +1 -1
  80. package/dist/assets/{usdt-Dw9IENe_.js → usdt-CDaLhEYh.js} +3 -3
  81. package/dist/assets/{usdt-Dw9IENe_.js.map → usdt-CDaLhEYh.js.map} +1 -1
  82. package/dist/assets/{waitNotice-Ce3YCinu.js → waitNotice-Cn0WJ-He.js} +3 -1
  83. package/dist/assets/waitNotice-Cn0WJ-He.js.map +1 -0
  84. package/dist/ghostly.mjs +1 -1
  85. package/examples/claude-code-agent.sh +5 -0
  86. package/package.json +2 -2
  87. package/dist/assets/api-DppWqAP3.js.map +0 -1
  88. package/dist/assets/api-K-i5MrP-.js +0 -3
  89. package/dist/assets/apiKit-DFIho4Ev.js.map +0 -1
  90. package/dist/assets/apps-yBnbEtfV.js.map +0 -1
  91. package/dist/assets/backup-vj4J7M3e.js.map +0 -1
  92. package/dist/assets/buttons-BoDMx3Ky.js.map +0 -1
  93. package/dist/assets/buttons-DG1CKgAI.js +0 -2
  94. package/dist/assets/client-BQArefYa.js.map +0 -1
  95. package/dist/assets/fileBytesIdb-BtXATa7j.js +0 -2
  96. package/dist/assets/groupFiles-D-ZUUHrx.js.map +0 -1
  97. package/dist/assets/host-DFLzzKNr.js.map +0 -1
  98. package/dist/assets/idb-BHsAqENE.js.map +0 -1
  99. package/dist/assets/irohWeb-C_Wnw7Q9.js.map +0 -1
  100. package/dist/assets/main-xO8MnXxD.js.map +0 -1
  101. package/dist/assets/nwc-B3-PHX0L.js.map +0 -1
  102. package/dist/assets/nwcProvider-BeQBPB2q.js.map +0 -1
  103. package/dist/assets/profiles-Bg43mRXu.js.map +0 -1
  104. package/dist/assets/registry-BDnsZJBi.js.map +0 -1
  105. package/dist/assets/server-DYdR0_Fj.js.map +0 -1
  106. package/dist/assets/src-BTRPAi5X.js.map +0 -1
  107. package/dist/assets/waitNotice-Ce3YCinu.js.map +0 -1
  108. package/dist/assets/words-BvdNuw_v.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { Du as RelayTransport, Eu as HEDGE_MS, Fu as DiscoveryBudgetError, Hu as newerPacket, Ju as publicKeyFromZ32, Lu as isDiscoveryBudgetError, Ou as RelaysFailedError, Tu as HEDGE_MISSING_MS, Wu as parseRelayPayload, ku as SLOW_MS } from "./src-BTRPAi5X.js";
1
+ import { Fu as HEDGE_MISSING_MS, Gu as DiscoveryBudgetError, Iu as HEDGE_MS, Lu as RelayTransport, Qu as newerPacket, Ru as RelaysFailedError, ed as parseRelayPayload, id as publicKeyFromZ32, qu as isDiscoveryBudgetError, zu as SLOW_MS } from "./src-BnpEQqzk.js";
2
2
  import { ed25519 } from "@noble/curves/ed25519.js";
3
3
  import { createHash } from "node:crypto";
4
4
  import DHT from "bittorrent-dht";
@@ -487,4 +487,4 @@ var RelaysAndDht = class {
487
487
  //#endregion
488
488
  export { Mainline, RelaysAndDht };
489
489
 
490
- //# sourceMappingURL=mainline-Bx184Ixg.js.map
490
+ //# sourceMappingURL=mainline-p6HOW7sb.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mainline-Bx184Ixg.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/** 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; 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\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 query whose hash, key, signature or salt is not the\n * string BEP5/BEP44 say (a put signed without a key, a number for a target) threw out of the socket handler: an error\n * nobody 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 const malformed = ((q === \"get\" || q === \"find_node\") && !bytes(a.target, 20)) || (q === \"get_peers\" && !bytes(a.info_hash, 20))\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 }, (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/** 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;\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 constructor(private readonly perMinute: () => number) {}\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 < ASKERS_WINDOW_MS) 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). A background read the budget holds waits for it. Background reads\n * the DHT answers in the relays' place keep to the relays' background share (`DhtBackgroundBudget`).\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 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 = {}, 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 // 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 // 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 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 * The relays' side only: the DHT side keeps nothing per key it puts. What it keeps per key it reads is bounded\n * (`missing`, `MISSING_KEPT`; the background budget's two-minute window).\n */\n forget(keys: Iterable<string>): void { this.relays.forget(keys); }\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;;AAGtJ,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;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AAM,WAAW;CACnB;CAEA,WAAmD;EACjD,OAAO;GAAE,UAAU,KAAK,MAAM,+DAA+D;GAAuB,QAAQ,KAAK,OAAO,SAAS,CAAC,CAAC;EAAO;CAC5J;CACA,YAA6B;EAC3B,MAAM,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;;;;;CAK1H,OAAO,MAA8B;EAAE,KAAK,OAAO,OAAO,IAAI;CAAG;AACnE"}
1
+ {"version":3,"file":"mainline-p6HOW7sb.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/** 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; 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\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 query whose hash, key, signature or salt is not the\n * string BEP5/BEP44 say (a put signed without a key, a number for a target) threw out of the socket handler: an error\n * nobody 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 const malformed = ((q === \"get\" || q === \"find_node\") && !bytes(a.target, 20)) || (q === \"get_peers\" && !bytes(a.info_hash, 20))\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 }, (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/** 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;\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 constructor(private readonly perMinute: () => number) {}\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 < ASKERS_WINDOW_MS) 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). A background read the budget holds waits for it. Background reads\n * the DHT answers in the relays' place keep to the relays' background share (`DhtBackgroundBudget`).\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 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 = {}, 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 // 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 // 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 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 * The relays' side only: the DHT side keeps nothing per key it puts. What it keeps per key it reads is bounded\n * (`missing`, `MISSING_KEPT`; the background budget's two-minute window).\n */\n forget(keys: Iterable<string>): void { this.relays.forget(keys); }\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;;AAGtJ,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;GAC3F,OAAO,KAAK;GACZ,OAAO;EACT;EACA,MAAM,MAAM,KAAK,MAAM,OAAO,KAAK,KAAK,KAAK,OAAO,OAAO,KAAK,OAAO,UAAU;EACjF,MAAM,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI,GAAG,KAAK,OAAO,YAAY,KAAK,OAAO,eAA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M,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;;;;;CAK1H,OAAO,MAA8B;EAAE,KAAK,OAAO,OAAO,IAAI;CAAG;AACnE"}
@@ -1,6 +1,6 @@
1
- import { $n as engineError, ad as toBase64Url, er as engineText } from "./src-BTRPAi5X.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-_MwTUz5E.js";
1
+ import { $n as engineError, er as engineText, hd as toBase64Url } from "./src-BnpEQqzk.js";
2
+ import { _ as openDb, b as transact, s as STORES, x as wrap, y as store } from "./idb-CEuoNsTv.js";
3
+ import { t as fromBase64Url } from "./codec-DrryGcPT.js";
4
4
  import { sha256 } from "@noble/hashes/sha2.js";
5
5
  import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
6
6
  //#region ../browser/src/shared/profileKey.ts
@@ -471,4 +471,4 @@ function rpcHost(url) {
471
471
  //#endregion
472
472
  export { sealSeed as a, openRow as c, sealRow as d, sealedStore as f, whenDataKeyDropped as g, sealSecret as h, newDeviceKey as i, openRows as l, openSecret as m, rpcHost as n, unsealSeed as o, hasDataKey as p, intentRepository as r, RowSeals as s, networkReason as t, proofKey as u };
473
473
 
474
- //# sourceMappingURL=networkReason-BlQhTbXk.js.map
474
+ //# sourceMappingURL=networkReason-DMffkiJ6.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"networkReason-BlQhTbXk.js","names":[],"sources":["../../../browser/src/shared/profileKey.ts","../../../browser/src/engine/dataKey.ts","../../../browser/src/engine/sealedRows.ts","../../../browser/src/engine/paymentAdapters/persistence.ts","../../../browser/src/engine/paymentAdapters/networkReason.ts"],"sourcesContent":["import { fromBase64Url, toBase64Url } from \"../backup/codec\";\n\n/**\n * The encrypted profile's keys (WISP 04, Encrypted profile): a random data key (DK) per profile seals each secret\n * field, and is stored only wrapped under a key derived from the passphrase (KEK). The passphrase never encrypts\n * data directly, so changing it rewraps 32 bytes and rewrites nothing else.\n */\nexport interface ProfileKeyRecord {\n format: \"ghostly-profile-key\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n /** The profile id, empty for the default: the record opens only in its own profile's slot. */\n profile: string;\n ciphertext: string;\n}\n/** A field sealed under DK. Version 1 is the `{version:1,salt,iv,ciphertext}` seed sealed with a device key. */\nexport interface SealedField { v: 2; iv: string; ct: string }\n/**\n * Where a sealed field lives: a ciphertext moved to another database, store, record or field fails to open instead\n * of being read as that one. `db` is `local` for local storage.\n */\nexport interface FieldBinding { db: string; store: string; key: string; field: string }\n\nconst ITERATIONS = 600_000;\nconst MAX_ITERATIONS = 10_000_000;\nconst DK_BYTES = 32;\nconst TAG_BYTES = 16;\n\nasync function kekFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\", \"unwrapKey\"]);\n}\n\n/** The clear header is the wrap's associated data, `profile` included: changing any of it makes the record fail to open. */\nconst header = (r: Omit<ProfileKeyRecord, \"ciphertext\">) =>\n new TextEncoder().encode([r.format, r.version, r.kdf.name, r.kdf.iterations, r.kdf.salt, r.cipher.name, r.cipher.iv, r.profile].join(\"\\n\"));\n\nconst importDataKey = (raw: Uint8Array) => crypto.subtle.importKey(\"raw\", raw as BufferSource, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n\nfunction checkPassphrase(passphrase: string) {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the profile passphrase\");\n}\n\nasync function wrap(raw: Uint8Array, passphrase: string, profile: string): Promise<ProfileKeyRecord> {\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const clear = { format: \"ghostly-profile-key\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, profile } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await kekFrom(passphrase, salt, ITERATIONS), raw as BufferSource));\n return { ...clear, ciphertext: toBase64Url(ciphertext) };\n}\n\n/** Refuses what this version can't read before any KDF runs, as backups do. */\nfunction checked(record: ProfileKeyRecord, profile: string) {\n if (record?.format !== \"ghostly-profile-key\") throw new Error(\"This is not a Ghostly profile key\");\n if (record.version !== 1) throw new Error(\"This profile key comes from a newer Ghostly; update to open it\");\n if (record.kdf?.name !== \"PBKDF2-SHA256\" || !Number.isInteger(record.kdf.iterations) || record.kdf.iterations < ITERATIONS || record.kdf.iterations > MAX_ITERATIONS || record.cipher?.name !== \"AES-256-GCM\") throw new Error(\"Unsupported profile key encryption\");\n if (typeof record.profile !== \"string\" || record.profile !== profile) throw new Error(\"This profile key belongs to another profile\");\n const salt = fromBase64Url(record.kdf.salt), iv = fromBase64Url(record.cipher.iv), ciphertext = fromBase64Url(record.ciphertext);\n if (salt.length !== 16 || iv.length !== 12 || ciphertext.length !== DK_BYTES + TAG_BYTES) throw new Error(\"Unsupported profile key encryption\");\n return { salt, iv, ciphertext };\n}\n\n/** Turning encryption on: a fresh DK, wrapped under the passphrase, and the DK itself as a key that can't be read back. */\nexport async function createProfileKey(passphrase: string, profile: string): Promise<{ record: ProfileKeyRecord; key: CryptoKey }> {\n checkPassphrase(passphrase);\n const raw = crypto.getRandomValues(new Uint8Array(DK_BYTES));\n try { return { record: await wrap(raw, passphrase, profile), key: await importDataKey(raw) }; } finally { raw.fill(0); }\n}\n\n/** The start gate: the DK as a non-extractable key, or \"Wrong passphrase\" with nothing else read. */\nexport async function unlockProfileKey(record: ProfileKeyRecord, passphrase: string, profile: string): Promise<CryptoKey> {\n const { salt, iv, ciphertext } = checked(record, profile);\n const kek = await kekFrom(passphrase, salt, record.kdf.iterations);\n try {\n return await crypto.subtle.unwrapKey(\"raw\", ciphertext as BufferSource, kek, { name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n } catch { throw new Error(\"Wrong passphrase\"); }\n}\n\n/** Change passphrase: the same DK under a new KEK, salt and nonce. No sealed field changes. */\nexport async function rewrapProfileKey(record: ProfileKeyRecord, passphrase: string, next: string, profile: string): Promise<ProfileKeyRecord> {\n checkPassphrase(next);\n const { salt, iv, ciphertext } = checked(record, profile);\n let raw: Uint8Array;\n try {\n raw = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, await kekFrom(passphrase, salt, record.kdf.iterations), ciphertext as BufferSource));\n } catch { throw new Error(\"Wrong passphrase\"); }\n try { return await wrap(raw, next, profile); } finally { raw.fill(0); }\n}\n\n/**\n * Only the record key can hold a newline: the other parts come from the code, so the joined binding still reads one\n * way (the first two lines, the last line, and the key between them).\n */\nfunction binding(b: FieldBinding): Uint8Array {\n for (const part of [b.db, b.store, b.field]) if (!part || part.includes(\"\\n\")) throw new Error(\"Invalid sealed field binding\");\n return new TextEncoder().encode([\"ghostly-field/2\", b.db, b.store, b.key, b.field].join(\"\\n\"));\n}\n\nexport function isSealedField(value: unknown): value is SealedField {\n const v = value as Partial<SealedField> | null;\n return !!v && typeof v === \"object\" && v.v === 2 && typeof v.iv === \"string\" && typeof v.ct === \"string\";\n}\n\n/** Seals one field under DK with a fresh random 96-bit nonce and no KDF per field. */\nexport async function sealField(key: CryptoKey, where: FieldBinding, value: string): Promise<SealedField> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: binding(where) as BufferSource }, key, new TextEncoder().encode(value)));\n return { v: 2, iv: toBase64Url(iv), ct: toBase64Url(ct) };\n}\n\n/** Opens a field sealed for exactly this place under this DK; anything else fails instead of opening wrong. */\nexport async function openField(key: CryptoKey, where: FieldBinding, sealed: SealedField): Promise<string> {\n if (!isSealedField(sealed)) throw new Error(\"Unsupported sealed field version\");\n const aad = binding(where);\n try {\n const iv = fromBase64Url(sealed.iv);\n if (iv.length !== 12) throw new Error(\"nonce\");\n return new TextDecoder().decode(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: aad as BufferSource }, key, fromBase64Url(sealed.ct) as BufferSource));\n } catch { throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\"); }\n}\n","import { isSealedField, openField, sealField, type FieldBinding, type SealedField } from \"../shared/profileKey\";\nimport { newDeviceKey, sealSeed, unsealSeed, type EncryptedSeed } from \"./paymentAdapters/persistence\";\n\n/** Version 1: sealed under a random key stored beside it. It keeps a secret from a log, not from a reader of the profile. */\nexport interface DeviceSealed { sealed: EncryptedSeed; deviceKey: string }\n/** A secret the engine keeps: version 1 while the profile is not encrypted, version 2 under its data key once it is. */\nexport type SealedSecret = DeviceSealed | SealedField;\n/**\n * Where a secret belongs, in the peer database (WISP 04, Encrypted profile): its store, its own id (stable when the\n * secret moves inside its record, as a proof key does into the revocations) and what it is.\n */\nexport type SecretPlace = Omit<FieldBinding, \"db\">;\n\nconst PEER_DB = \"ghostly\";\n\n/**\n * The profile's data key (DK), when the profile is encrypted and unlocked: the one slot the engine owns. A\n * non-extractable key; nothing writes it anywhere. Empty, every secret is sealed as today (version 1).\n */\nlet slot: CryptoKey | null = null;\n/**\n * The profile's migration is over (no `migrating` mark): a sealed place then takes version 2 only. A version 1 or plain\n * value there was put by someone who could write the profile's database but not read it, and is refused.\n */\nlet sealedOnly = false;\nconst onDrop = new Set<() => void>();\nconst LOCKED = \"This profile is locked. Enter its passphrase first.\";\n\nexport function setDataKey(key: CryptoKey): void { slot = key; }\nexport function hasDataKey(): boolean { return slot !== null; }\n/** Off until the migration that seals every place has ended; set by it. */\nexport function setSealedOnly(on: boolean): void { sealedOnly = on; }\n/** Whether a sealed place may still hold a version 1 or plain value. */\nexport function takesUnsealed(): boolean { return !(slot && sealedOnly); }\n/** \"Lock and stop\", or a profile switch: the key goes, and so does every secret opened with it and kept in memory. */\nexport function dropDataKey(): void {\n slot = null;\n sealedOnly = false;\n for (const drop of [...onDrop]) drop();\n}\n/** A cache of opened secrets empties itself when the key goes. Returns the way to stop listening. */\nexport function whenDataKeyDropped(drop: () => void): () => void {\n onDrop.add(drop);\n return () => { onDrop.delete(drop); };\n}\n\nexport async function sealSecret(value: string, at: SecretPlace): Promise<SealedSecret> {\n if (slot) return sealField(slot, { db: PEER_DB, ...at }, value);\n const deviceKey = newDeviceKey();\n return { sealed: await sealSeed(value, deviceKey), deviceKey };\n}\n\n/** Version 2 only, for a field the database layer seals: refused while the profile is locked, never version 1. */\nexport async function sealPlace(value: string, at: SecretPlace): Promise<SealedField> {\n if (!slot) throw new Error(LOCKED);\n return sealField(slot, { db: PEER_DB, ...at }, value);\n}\n\n/** Reads both versions: a profile being encrypted holds some of each until its migration ends. */\nexport async function openSecret(secret: SealedSecret, at: SecretPlace): Promise<string> {\n if (!isSealedField(secret)) {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n return unsealSeed(secret.sealed, secret.deviceKey);\n }\n if (!slot) throw new Error(LOCKED);\n return openField(slot, { db: PEER_DB, ...at }, secret);\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\nimport { STORES } from \"../shared/idb\";\nimport { isSealedField, type SealedField } from \"../shared/profileKey\";\nimport { hasDataKey, openSecret, sealPlace, takesUnsealed, type SecretPlace } from \"./dataKey\";\n\n/**\n * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act\n * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,\n * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read\n * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.\n */\nconst FIELDS: Record<string, readonly string[]> = {\n [STORES.links]: [\"seedB64\", \"encKeyB64\", \"participationSeed\", \"transportSeeds\", \"inviteCode\", \"pairedPeerKey\", \"peerTrust.verifiedKey\", \"ratchetState\"],\n [STORES.groups]: [\"invitation.seedB64\", \"entry.seedB64\", \"joining.seedB64\", \"state.seedB64\", \"state.secrets\", \"community.seedB64\", \"community.secrets\", \"community.entry.seedB64\", \"community.rv\"],\n [STORES.swaps]: [\"swap\", \"token\"],\n [STORES.melts]: [\"secrets\", \"outputs\"],\n // A sent token kept for Take it back, the outputs of a paid invoice not minted yet, and a Cashu review's swap and token.\n [STORES.payments]: [\"token\"],\n [STORES.quotes]: [\"outputs\"],\n [STORES.intents]: [\"prepared.swap\", \"prepared.token\"],\n};\n/** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */\nconst NESTED: Record<string, string> = { [STORES.groups]: \"previous\" };\n\n/**\n * 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\n * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a\n * transaction, where WebCrypto can't be waited for.\n */\nexport const proofKey = (secret: string): string => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\\n${secret}`)));\nconst SEALED_SECRET = \"sealedSecret\";\n\ntype Row = Record<string, unknown>;\ntype Seal = (json: string, at: SecretPlace) => SealedField;\n\nconst keyOf = (store: string, row: Row) =>\n String(store === STORES.melts || store === STORES.quotes ? row.quote : store === STORES.intents ? read(row, \"review.id\") : row.id);\n\nfunction read(row: Row, path: string): unknown {\n return path.split(\".\").reduce<unknown>((at, part) => (at && typeof at === \"object\" ? (at as Row)[part] : undefined), row);\n}\n/** The row with `value` at `path`, copied along the way: the caller's row is never changed. */\nfunction written(row: Row, [part, ...rest]: string[], value: unknown): Row {\n return { ...row, [part]: rest.length ? written(row[part] as Row, rest, value) : value };\n}\n\n/** Every phase 1 value of a row that is there, with its path. */\nfunction places(store: string, row: Row, prefix = \"\"): { path: string; value: unknown }[] {\n const found = (FIELDS[store] ?? []).map((path) => ({ path: prefix + path, value: read(row, path) })).filter(({ value }) => value !== undefined);\n const nested = NESTED[store] && row[NESTED[store]];\n return nested && typeof nested === \"object\" ? [...found, ...places(store, nested as Row, `${prefix}${NESTED[store]}.`)] : found;\n}\n\nfunction sealWith<T>(store: string, value: T, seal: Seal): T {\n const row = value as Row;\n if (store === STORES.proofs) {\n if (row[SEALED_SECRET] !== undefined) return value;\n const secret = String(row.secret), key = proofKey(secret);\n return { ...row, secret: key, [SEALED_SECRET]: seal(JSON.stringify(secret), { store, key, field: \"secret\" }) } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) out = written(out, path.split(\".\"), seal(JSON.stringify(at), { store, key, field: path }));\n }\n return out as T;\n}\n\nconst slotOf = (json: string, at: SecretPlace) => [at.store, at.key, at.field, json].join(\"\\n\");\n\n/**\n * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for\n * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile\n * makes a write fail, never go out in the clear.\n */\nexport class RowSeals {\n /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */\n private static turn: Promise<unknown> = Promise.resolve();\n readonly on = hasDataKey();\n private ready = new Map<string, SealedField>();\n\n /** What these rows (or the proofs of these secrets) hold, sealed now. */\n async prepare(store: string, rows: readonly object[]): Promise<this> {\n if (!this.on) return this;\n const wanted = new Map<string, [string, SecretPlace]>();\n for (const row of rows) sealWith(store, row, (json, at) => { wanted.set(slotOf(json, at), [json, at]); return { v: 2, iv: \"\", ct: \"\" }; });\n const sealing = RowSeals.turn.then(async () => {\n for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));\n });\n RowSeals.turn = sealing.catch(() => {});\n await sealing;\n return this;\n }\n\n /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */\n row<T>(store: string, row: T): T {\n if (!this.on) return row;\n return sealWith(store, row, (json, at) => {\n const sealed = this.ready.get(slotOf(json, at));\n if (!sealed) throw new Error(\"A secret was not sealed before it was saved\");\n return sealed;\n });\n }\n}\n\nexport async function sealRow<T extends object>(store: string, row: T): Promise<T> {\n return (await new RowSeals().prepare(store, [row])).row(store, row);\n}\n\n/**\n * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.\n * Without the data key, the store itself.\n */\nexport function sealedStore(store: IDBObjectStore, seals: RowSeals): IDBObjectStore {\n if (!seals.on) return store;\n const proofs = store.name === STORES.proofs;\n return new Proxy(store, {\n get(target, name) {\n if (name === \"put\") return (row: object, ...key: [IDBValidKey?]) => target.put(seals.row(target.name, row), ...key);\n // A proof stored before the profile was encrypted is kept under its secret until the migration reseals it.\n if (proofs && name === \"delete\") return (secret: string) => { target.delete(secret); return target.delete(proofKey(secret)); };\n if (proofs && name === \"get\") return (secret: string) => target.get(proofKey(secret));\n const value: unknown = Reflect.get(target, name, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\nfunction unsealed(): void {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n}\n\n/** The row as the engine uses it: every sealed value opened, where it was. */\nexport async function openRow<T>(store: string, value: T): Promise<T> {\n if (!hasDataKey() || !value) return value;\n const row = value as Row;\n if (store === STORES.proofs) {\n const sealed = row[SEALED_SECRET];\n if (sealed === undefined) { unsealed(); return value; }\n const key = String(row.secret), secret = JSON.parse(await openSecret(sealed as SealedField, { store, key, field: \"secret\" })) as string;\n if (proofKey(secret) !== key) throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\");\n const { [SEALED_SECRET]: _sealed, ...rest } = row;\n return { ...rest, secret } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) { unsealed(); continue; }\n out = written(out, path.split(\".\"), JSON.parse(await openSecret(at, { store, key, field: path })));\n }\n return out as T;\n}\n\nexport function openRows<T>(store: string, rows: T[]): Promise<T[]> {\n return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);\n}\n","import { engineError, engineText } from \"@ghostly/core\";\nimport { STORES, openDb, store, transact, wrap } from \"../../shared/idb\";\nimport { openRow, openRows, sealRow } from \"../sealedRows\";\nimport type { IntentRepository, SavedIntent } from \"./coordinator\";\n/**\n * A USDT payment is one transaction at one account nonce. Another payment from the same account and chain that is\n * submitted or of unknown outcome holds its nonce until it confirms. A review made after it was sent took the next\n * 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\n * nonce: sent, it would replace the earlier transaction or be dropped, so it is refused. A row with no nonce refuses.\n */\nfunction nonceTaken(review:SavedIntent[\"review\"],intents:SavedIntent[]):boolean {\n if(review.method!==\"usdt\")return false;\n const from=review.evm?.from?.toLowerCase(), nonce=review.evm?.nonce;\n 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)\n && !(typeof nonce===\"number\" && typeof other.evm?.nonce===\"number\" && nonce>other.evm.nonce));\n}\n/**\n * A Cashu review's swap and token are sealed when the profile is encrypted (sealedRows): they are read here opened.\n * `claim` and `cancel` change only the review, so they put back the row as it was read, sealed fields and all.\n */\nexport const intentRepository: IntentRepository = {\n async get(id) { return openRow(STORES.intents,await wrap<SavedIntent | undefined>((await store(STORES.intents,\"readonly\")).get(id))); },\n async list() { return openRows(STORES.intents,await wrap<SavedIntent[]>((await store(STORES.intents,\"readonly\")).getAll())); },\n async put(intent) { const row=await sealRow(STORES.intents,intent); await transact([STORES.intents],s=>{s[STORES.intents].put(row);}); },\n async claim(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n let reason=engineText(\"alreadySubmitted\");\n const request=tx.objectStore(STORES.intents).getAll();\n request.onsuccess=()=>{\n const intents:SavedIntent[]=request.result;\n saved=intents.find(item=>item.review.id===id)!;\n if(!saved || saved.review.state!==\"pending\") {tx.abort();return;}\n const duplicate=saved.review.requestId && intents.some(({review})=>review.id!==id && review.requestId===saved.review.requestId && review.linkId===saved.review.linkId && [\"submitted\",\"settled\",\"unknown\"].includes(review.state));\n if(duplicate){tx.abort();return;}\n if(nonceTaken(saved.review,intents)){reason=engineText(\"sentAfterReview\");tx.abort();return;}\n saved.review={...saved.review,state:\"submitted\",error:undefined,submittedAt:Date.now()};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(new Error(reason));\n });\n },\n async cancel(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n const request=tx.objectStore(STORES.intents).get(id);\n request.onsuccess=()=>{\n saved=request.result;\n if(!saved || saved.review.state!==\"pending\"){tx.abort();return;}\n saved.review={...saved.review,state:\"cancelled\"};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(engineError(\"cannotCancelSubmitted\"));\n });\n },\n};\n/** Key for a wallet that needs no password: its seed is protected like the Cashu proofs in the same database. */\nexport function newDeviceKey():string {return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/=+$/,\"\");}\nexport interface EncryptedSeed {version:1;salt:number[];iv:number[];ciphertext:number[]}\nasync function passwordKey(password:string,salt:Uint8Array<ArrayBuffer>) {\n const material=await crypto.subtle.importKey(\"raw\",new TextEncoder().encode(password),\"PBKDF2\",false,[\"deriveKey\"]);\n return crypto.subtle.deriveKey({name:\"PBKDF2\",hash:\"SHA-256\",salt,iterations:600000},material,{name:\"AES-GCM\",length:256},false,[\"encrypt\",\"decrypt\"]);\n}\nexport async function sealSeed(seed:string,password:string):Promise<EncryptedSeed> {\n if(password.length<12)throw new Error(\"Use at least 12 characters for the wallet password\");\n const salt=crypto.getRandomValues(new Uint8Array(16)),iv=crypto.getRandomValues(new Uint8Array(12));\n const ciphertext=await crypto.subtle.encrypt({name:\"AES-GCM\",iv},await passwordKey(password,salt),new TextEncoder().encode(seed));\n return {version:1,salt:[...salt],iv:[...iv],ciphertext:[...new Uint8Array(ciphertext)]};\n}\nexport async function unsealSeed(seed:EncryptedSeed,password:string):Promise<string> {\n if(seed.version!==1)throw new Error(\"Unsupported wallet backup version\");\n try {return new TextDecoder().decode(await crypto.subtle.decrypt({name:\"AES-GCM\",iv:new Uint8Array(seed.iv)},await passwordKey(password,new Uint8Array(seed.salt)),new Uint8Array(seed.ciphertext)));}\n catch {throw new Error(\"Could not unlock the wallet. Check the password and backup.\");}\n}\n","import { engineText } from \"@ghostly/core\";\n\n/**\n * A request's failure as a person says it, when the browser's own words say nothing: a request that timed out or was\n * given up (\"Fetch is aborted\" in Safari, \"signal timed out\" in Chromium) did not answer in time; one that never left\n * (\"Failed to fetch\", \"Load failed\") could not reach it. `host` names what was asked, when known. Anything else is\n * `null`: its own words are kept.\n */\nexport function networkReason(error: unknown, host?: string): string | null {\n const name = error instanceof Error ? error.name : \"\";\n const text = error instanceof Error ? error.message : String(error);\n 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()))\n return host ? engineText(\"hostTimedOut\", { host }) : engineText(\"networkTimedOut\");\n if (/^(failed to fetch|load failed|fetch failed|networkerror when attempting to fetch resource\\.?|network request failed)$/i.test(text.trim()))\n return host ? engineText(\"hostUnreachable\", { host }) : engineText(\"networkUnreachable\");\n return null;\n}\n\n/** A request URL's host, for a reason that names it; the URL itself when it does not parse. */\nexport function rpcHost(url: string): string {\n try { return new URL(url).host; } catch { return url; }\n}\n"],"mappings":";;;;;;;;;;AA6FA,SAAS,QAAQ,GAA6B;CAC5C,KAAK,MAAM,QAAQ;EAAC,EAAE;EAAI,EAAE;EAAO,EAAE;CAAK,GAAG,IAAI,CAAC,QAAQ,KAAK,SAAS,IAAI,GAAG,MAAM,IAAI,MAAM,8BAA8B;CAC7H,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO;EAAC;EAAmB,EAAE;EAAI,EAAE;EAAO,EAAE;EAAK,EAAE;CAAK,CAAC,CAAC,KAAK,IAAI,CAAC;AAC/F;AAEA,SAAgB,cAAc,OAAsC;CAClE,MAAM,IAAI;CACV,OAAO,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,EAAE,MAAM,KAAK,OAAO,EAAE,OAAO,YAAY,OAAO,EAAE,OAAO;AAClG;;AAGA,eAAsB,UAAU,KAAgB,OAAqB,OAAqC;CACxG,MAAM,KAAK,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC;CACpD,MAAM,KAAK,IAAI,WAAW,MAAM,OAAO,OAAO,QAAQ;EAAE,MAAM;EAAW;EAAI,gBAAgB,QAAQ,KAAK;CAAkB,GAAG,KAAK,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC;CACpK,OAAO;EAAE,GAAG;EAAG,IAAI,YAAY,EAAE;EAAG,IAAI,YAAY,EAAE;CAAE;AAC1D;;AAGA,eAAsB,UAAU,KAAgB,OAAqB,QAAsC;CACzG,IAAI,CAAC,cAAc,MAAM,GAAG,MAAM,IAAI,MAAM,kCAAkC;CAC9E,MAAM,MAAM,QAAQ,KAAK;CACzB,I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,IAAI,WAAW,KAAK,IAAI,CAAC,GAAE,IAAI,WAAW,KAAK,UAAU,CAAC,CAAC;CAAE,QAC/L;EAAC,MAAM,IAAI,MAAM,6DAA6D;CAAE;AACxF;;;;;;;;;ACrEA,SAAgB,cAAc,OAAgB,MAA8B;CAC1E,MAAM,OAAO,iBAAiB,QAAQ,MAAM,OAAO;CACnD,MAAM,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAClE,IAAI,SAAS,gBAAgB,SAAS,kBAAkB,wLAAwL,KAAK,KAAK,KAAK,CAAC,GAC9P,OAAO,OAAO,WAAW,gBAAgB,EAAE,KAAK,CAAC,IAAI,WAAW,iBAAiB;CACnF,IAAI,yHAAyH,KAAK,KAAK,KAAK,CAAC,GAC3I,OAAO,OAAO,WAAW,mBAAmB,EAAE,KAAK,CAAC,IAAI,WAAW,oBAAoB;CACzF,OAAO;AACT;;AAGA,SAAgB,QAAQ,KAAqB;CAC3C,IAAI;EAAE,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CAAM,QAAQ;EAAE,OAAO;CAAK;AACxD"}
1
+ {"version":3,"file":"networkReason-DMffkiJ6.js","names":[],"sources":["../../../browser/src/shared/profileKey.ts","../../../browser/src/engine/dataKey.ts","../../../browser/src/engine/sealedRows.ts","../../../browser/src/engine/paymentAdapters/persistence.ts","../../../browser/src/engine/paymentAdapters/networkReason.ts"],"sourcesContent":["import { fromBase64Url, toBase64Url } from \"../backup/codec\";\n\n/**\n * The encrypted profile's keys (WISP 04, Encrypted profile): a random data key (DK) per profile seals each secret\n * field, and is stored only wrapped under a key derived from the passphrase (KEK). The passphrase never encrypts\n * data directly, so changing it rewraps 32 bytes and rewrites nothing else.\n */\nexport interface ProfileKeyRecord {\n format: \"ghostly-profile-key\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n /** The profile id, empty for the default: the record opens only in its own profile's slot. */\n profile: string;\n ciphertext: string;\n}\n/** A field sealed under DK. Version 1 is the `{version:1,salt,iv,ciphertext}` seed sealed with a device key. */\nexport interface SealedField { v: 2; iv: string; ct: string }\n/**\n * Where a sealed field lives: a ciphertext moved to another database, store, record or field fails to open instead\n * of being read as that one. `db` is `local` for local storage.\n */\nexport interface FieldBinding { db: string; store: string; key: string; field: string }\n\nconst ITERATIONS = 600_000;\nconst MAX_ITERATIONS = 10_000_000;\nconst DK_BYTES = 32;\nconst TAG_BYTES = 16;\n\nasync function kekFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\", \"unwrapKey\"]);\n}\n\n/** The clear header is the wrap's associated data, `profile` included: changing any of it makes the record fail to open. */\nconst header = (r: Omit<ProfileKeyRecord, \"ciphertext\">) =>\n new TextEncoder().encode([r.format, r.version, r.kdf.name, r.kdf.iterations, r.kdf.salt, r.cipher.name, r.cipher.iv, r.profile].join(\"\\n\"));\n\nconst importDataKey = (raw: Uint8Array) => crypto.subtle.importKey(\"raw\", raw as BufferSource, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n\nfunction checkPassphrase(passphrase: string) {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the profile passphrase\");\n}\n\nasync function wrap(raw: Uint8Array, passphrase: string, profile: string): Promise<ProfileKeyRecord> {\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const clear = { format: \"ghostly-profile-key\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, profile } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await kekFrom(passphrase, salt, ITERATIONS), raw as BufferSource));\n return { ...clear, ciphertext: toBase64Url(ciphertext) };\n}\n\n/** Refuses what this version can't read before any KDF runs, as backups do. */\nfunction checked(record: ProfileKeyRecord, profile: string) {\n if (record?.format !== \"ghostly-profile-key\") throw new Error(\"This is not a Ghostly profile key\");\n if (record.version !== 1) throw new Error(\"This profile key comes from a newer Ghostly; update to open it\");\n if (record.kdf?.name !== \"PBKDF2-SHA256\" || !Number.isInteger(record.kdf.iterations) || record.kdf.iterations < ITERATIONS || record.kdf.iterations > MAX_ITERATIONS || record.cipher?.name !== \"AES-256-GCM\") throw new Error(\"Unsupported profile key encryption\");\n if (typeof record.profile !== \"string\" || record.profile !== profile) throw new Error(\"This profile key belongs to another profile\");\n const salt = fromBase64Url(record.kdf.salt), iv = fromBase64Url(record.cipher.iv), ciphertext = fromBase64Url(record.ciphertext);\n if (salt.length !== 16 || iv.length !== 12 || ciphertext.length !== DK_BYTES + TAG_BYTES) throw new Error(\"Unsupported profile key encryption\");\n return { salt, iv, ciphertext };\n}\n\n/** Turning encryption on: a fresh DK, wrapped under the passphrase, and the DK itself as a key that can't be read back. */\nexport async function createProfileKey(passphrase: string, profile: string): Promise<{ record: ProfileKeyRecord; key: CryptoKey }> {\n checkPassphrase(passphrase);\n const raw = crypto.getRandomValues(new Uint8Array(DK_BYTES));\n try { return { record: await wrap(raw, passphrase, profile), key: await importDataKey(raw) }; } finally { raw.fill(0); }\n}\n\n/** The start gate: the DK as a non-extractable key, or \"Wrong passphrase\" with nothing else read. */\nexport async function unlockProfileKey(record: ProfileKeyRecord, passphrase: string, profile: string): Promise<CryptoKey> {\n const { salt, iv, ciphertext } = checked(record, profile);\n const kek = await kekFrom(passphrase, salt, record.kdf.iterations);\n try {\n return await crypto.subtle.unwrapKey(\"raw\", ciphertext as BufferSource, kek, { name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n } catch { throw new Error(\"Wrong passphrase\"); }\n}\n\n/** Change passphrase: the same DK under a new KEK, salt and nonce. No sealed field changes. */\nexport async function rewrapProfileKey(record: ProfileKeyRecord, passphrase: string, next: string, profile: string): Promise<ProfileKeyRecord> {\n checkPassphrase(next);\n const { salt, iv, ciphertext } = checked(record, profile);\n let raw: Uint8Array;\n try {\n raw = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, await kekFrom(passphrase, salt, record.kdf.iterations), ciphertext as BufferSource));\n } catch { throw new Error(\"Wrong passphrase\"); }\n try { return await wrap(raw, next, profile); } finally { raw.fill(0); }\n}\n\n/**\n * Only the record key can hold a newline: the other parts come from the code, so the joined binding still reads one\n * way (the first two lines, the last line, and the key between them).\n */\nfunction binding(b: FieldBinding): Uint8Array {\n for (const part of [b.db, b.store, b.field]) if (!part || part.includes(\"\\n\")) throw new Error(\"Invalid sealed field binding\");\n return new TextEncoder().encode([\"ghostly-field/2\", b.db, b.store, b.key, b.field].join(\"\\n\"));\n}\n\nexport function isSealedField(value: unknown): value is SealedField {\n const v = value as Partial<SealedField> | null;\n return !!v && typeof v === \"object\" && v.v === 2 && typeof v.iv === \"string\" && typeof v.ct === \"string\";\n}\n\n/** Seals one field under DK with a fresh random 96-bit nonce and no KDF per field. */\nexport async function sealField(key: CryptoKey, where: FieldBinding, value: string): Promise<SealedField> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: binding(where) as BufferSource }, key, new TextEncoder().encode(value)));\n return { v: 2, iv: toBase64Url(iv), ct: toBase64Url(ct) };\n}\n\n/** Opens a field sealed for exactly this place under this DK; anything else fails instead of opening wrong. */\nexport async function openField(key: CryptoKey, where: FieldBinding, sealed: SealedField): Promise<string> {\n if (!isSealedField(sealed)) throw new Error(\"Unsupported sealed field version\");\n const aad = binding(where);\n try {\n const iv = fromBase64Url(sealed.iv);\n if (iv.length !== 12) throw new Error(\"nonce\");\n return new TextDecoder().decode(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: aad as BufferSource }, key, fromBase64Url(sealed.ct) as BufferSource));\n } catch { throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\"); }\n}\n","import { isSealedField, openField, sealField, type FieldBinding, type SealedField } from \"../shared/profileKey\";\nimport { newDeviceKey, sealSeed, unsealSeed, type EncryptedSeed } from \"./paymentAdapters/persistence\";\n\n/** Version 1: sealed under a random key stored beside it. It keeps a secret from a log, not from a reader of the profile. */\nexport interface DeviceSealed { sealed: EncryptedSeed; deviceKey: string }\n/** A secret the engine keeps: version 1 while the profile is not encrypted, version 2 under its data key once it is. */\nexport type SealedSecret = DeviceSealed | SealedField;\n/**\n * Where a secret belongs, in the peer database (WISP 04, Encrypted profile): its store, its own id (stable when the\n * secret moves inside its record, as a proof key does into the revocations) and what it is.\n */\nexport type SecretPlace = Omit<FieldBinding, \"db\">;\n\nconst PEER_DB = \"ghostly\";\n\n/**\n * The profile's data key (DK), when the profile is encrypted and unlocked: the one slot the engine owns. A\n * non-extractable key; nothing writes it anywhere. Empty, every secret is sealed as today (version 1).\n */\nlet slot: CryptoKey | null = null;\n/**\n * The profile's migration is over (no `migrating` mark): a sealed place then takes version 2 only. A version 1 or plain\n * value there was put by someone who could write the profile's database but not read it, and is refused.\n */\nlet sealedOnly = false;\nconst onDrop = new Set<() => void>();\nconst LOCKED = \"This profile is locked. Enter its passphrase first.\";\n\nexport function setDataKey(key: CryptoKey): void { slot = key; }\nexport function hasDataKey(): boolean { return slot !== null; }\n/** Off until the migration that seals every place has ended; set by it. */\nexport function setSealedOnly(on: boolean): void { sealedOnly = on; }\n/** Whether a sealed place may still hold a version 1 or plain value. */\nexport function takesUnsealed(): boolean { return !(slot && sealedOnly); }\n/** \"Lock and stop\", or a profile switch: the key goes, and so does every secret opened with it and kept in memory. */\nexport function dropDataKey(): void {\n slot = null;\n sealedOnly = false;\n for (const drop of [...onDrop]) drop();\n}\n/** A cache of opened secrets empties itself when the key goes. Returns the way to stop listening. */\nexport function whenDataKeyDropped(drop: () => void): () => void {\n onDrop.add(drop);\n return () => { onDrop.delete(drop); };\n}\n\nexport async function sealSecret(value: string, at: SecretPlace): Promise<SealedSecret> {\n if (slot) return sealField(slot, { db: PEER_DB, ...at }, value);\n const deviceKey = newDeviceKey();\n return { sealed: await sealSeed(value, deviceKey), deviceKey };\n}\n\n/** Version 2 only, for a field the database layer seals: refused while the profile is locked, never version 1. */\nexport async function sealPlace(value: string, at: SecretPlace): Promise<SealedField> {\n if (!slot) throw new Error(LOCKED);\n return sealField(slot, { db: PEER_DB, ...at }, value);\n}\n\n/** Reads both versions: a profile being encrypted holds some of each until its migration ends. */\nexport async function openSecret(secret: SealedSecret, at: SecretPlace): Promise<string> {\n if (!isSealedField(secret)) {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n return unsealSeed(secret.sealed, secret.deviceKey);\n }\n if (!slot) throw new Error(LOCKED);\n return openField(slot, { db: PEER_DB, ...at }, secret);\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\nimport { STORES } from \"../shared/idb\";\nimport { isSealedField, type SealedField } from \"../shared/profileKey\";\nimport { hasDataKey, openSecret, sealPlace, takesUnsealed, type SecretPlace } from \"./dataKey\";\n\n/**\n * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act\n * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,\n * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read\n * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.\n */\nconst FIELDS: Record<string, readonly string[]> = {\n [STORES.links]: [\"seedB64\", \"encKeyB64\", \"participationSeed\", \"transportSeeds\", \"inviteCode\", \"pairedPeerKey\", \"peerTrust.verifiedKey\", \"ratchetState\"],\n [STORES.groups]: [\"invitation.seedB64\", \"entry.seedB64\", \"joining.seedB64\", \"state.seedB64\", \"state.secrets\", \"community.seedB64\", \"community.secrets\", \"community.entry.seedB64\", \"community.rv\"],\n [STORES.swaps]: [\"swap\", \"token\"],\n [STORES.melts]: [\"secrets\", \"outputs\"],\n // A sent token kept for Take it back, the outputs of a paid invoice not minted yet, and a Cashu review's swap and token.\n [STORES.payments]: [\"token\"],\n [STORES.quotes]: [\"outputs\"],\n [STORES.intents]: [\"prepared.swap\", \"prepared.token\"],\n};\n/** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */\nconst NESTED: Record<string, string> = { [STORES.groups]: \"previous\" };\n\n/**\n * 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\n * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a\n * transaction, where WebCrypto can't be waited for.\n */\nexport const proofKey = (secret: string): string => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\\n${secret}`)));\nconst SEALED_SECRET = \"sealedSecret\";\n\ntype Row = Record<string, unknown>;\ntype Seal = (json: string, at: SecretPlace) => SealedField;\n\nconst keyOf = (store: string, row: Row) =>\n String(store === STORES.melts || store === STORES.quotes ? row.quote : store === STORES.intents ? read(row, \"review.id\") : row.id);\n\nfunction read(row: Row, path: string): unknown {\n return path.split(\".\").reduce<unknown>((at, part) => (at && typeof at === \"object\" ? (at as Row)[part] : undefined), row);\n}\n/** The row with `value` at `path`, copied along the way: the caller's row is never changed. */\nfunction written(row: Row, [part, ...rest]: string[], value: unknown): Row {\n return { ...row, [part]: rest.length ? written(row[part] as Row, rest, value) : value };\n}\n\n/** Every phase 1 value of a row that is there, with its path. */\nfunction places(store: string, row: Row, prefix = \"\"): { path: string; value: unknown }[] {\n const found = (FIELDS[store] ?? []).map((path) => ({ path: prefix + path, value: read(row, path) })).filter(({ value }) => value !== undefined);\n const nested = NESTED[store] && row[NESTED[store]];\n return nested && typeof nested === \"object\" ? [...found, ...places(store, nested as Row, `${prefix}${NESTED[store]}.`)] : found;\n}\n\nfunction sealWith<T>(store: string, value: T, seal: Seal): T {\n const row = value as Row;\n if (store === STORES.proofs) {\n if (row[SEALED_SECRET] !== undefined) return value;\n const secret = String(row.secret), key = proofKey(secret);\n return { ...row, secret: key, [SEALED_SECRET]: seal(JSON.stringify(secret), { store, key, field: \"secret\" }) } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) out = written(out, path.split(\".\"), seal(JSON.stringify(at), { store, key, field: path }));\n }\n return out as T;\n}\n\nconst slotOf = (json: string, at: SecretPlace) => [at.store, at.key, at.field, json].join(\"\\n\");\n\n/**\n * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for\n * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile\n * makes a write fail, never go out in the clear.\n */\nexport class RowSeals {\n /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */\n private static turn: Promise<unknown> = Promise.resolve();\n readonly on = hasDataKey();\n private ready = new Map<string, SealedField>();\n\n /** What these rows (or the proofs of these secrets) hold, sealed now. */\n async prepare(store: string, rows: readonly object[]): Promise<this> {\n if (!this.on) return this;\n const wanted = new Map<string, [string, SecretPlace]>();\n for (const row of rows) sealWith(store, row, (json, at) => { wanted.set(slotOf(json, at), [json, at]); return { v: 2, iv: \"\", ct: \"\" }; });\n const sealing = RowSeals.turn.then(async () => {\n for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));\n });\n RowSeals.turn = sealing.catch(() => {});\n await sealing;\n return this;\n }\n\n /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */\n row<T>(store: string, row: T): T {\n if (!this.on) return row;\n return sealWith(store, row, (json, at) => {\n const sealed = this.ready.get(slotOf(json, at));\n if (!sealed) throw new Error(\"A secret was not sealed before it was saved\");\n return sealed;\n });\n }\n}\n\nexport async function sealRow<T extends object>(store: string, row: T): Promise<T> {\n return (await new RowSeals().prepare(store, [row])).row(store, row);\n}\n\n/**\n * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.\n * Without the data key, the store itself.\n */\nexport function sealedStore(store: IDBObjectStore, seals: RowSeals): IDBObjectStore {\n if (!seals.on) return store;\n const proofs = store.name === STORES.proofs;\n return new Proxy(store, {\n get(target, name) {\n if (name === \"put\") return (row: object, ...key: [IDBValidKey?]) => target.put(seals.row(target.name, row), ...key);\n // A proof stored before the profile was encrypted is kept under its secret until the migration reseals it.\n if (proofs && name === \"delete\") return (secret: string) => { target.delete(secret); return target.delete(proofKey(secret)); };\n if (proofs && name === \"get\") return (secret: string) => target.get(proofKey(secret));\n const value: unknown = Reflect.get(target, name, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\nfunction unsealed(): void {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n}\n\n/** The row as the engine uses it: every sealed value opened, where it was. */\nexport async function openRow<T>(store: string, value: T): Promise<T> {\n if (!hasDataKey() || !value) return value;\n const row = value as Row;\n if (store === STORES.proofs) {\n const sealed = row[SEALED_SECRET];\n if (sealed === undefined) { unsealed(); return value; }\n const key = String(row.secret), secret = JSON.parse(await openSecret(sealed as SealedField, { store, key, field: \"secret\" })) as string;\n if (proofKey(secret) !== key) throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\");\n const { [SEALED_SECRET]: _sealed, ...rest } = row;\n return { ...rest, secret } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) { unsealed(); continue; }\n out = written(out, path.split(\".\"), JSON.parse(await openSecret(at, { store, key, field: path })));\n }\n return out as T;\n}\n\nexport function openRows<T>(store: string, rows: T[]): Promise<T[]> {\n return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);\n}\n","import { engineError, engineText } from \"@ghostly/core\";\nimport { STORES, openDb, store, transact, wrap } from \"../../shared/idb\";\nimport { openRow, openRows, sealRow } from \"../sealedRows\";\nimport type { IntentRepository, SavedIntent } from \"./coordinator\";\n/**\n * A USDT payment is one transaction at one account nonce. Another payment from the same account and chain that is\n * submitted or of unknown outcome holds its nonce until it confirms. A review made after it was sent took the next\n * 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\n * nonce: sent, it would replace the earlier transaction or be dropped, so it is refused. A row with no nonce refuses.\n */\nfunction nonceTaken(review:SavedIntent[\"review\"],intents:SavedIntent[]):boolean {\n if(review.method!==\"usdt\")return false;\n const from=review.evm?.from?.toLowerCase(), nonce=review.evm?.nonce;\n 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)\n && !(typeof nonce===\"number\" && typeof other.evm?.nonce===\"number\" && nonce>other.evm.nonce));\n}\n/**\n * A Cashu review's swap and token are sealed when the profile is encrypted (sealedRows): they are read here opened.\n * `claim` and `cancel` change only the review, so they put back the row as it was read, sealed fields and all.\n */\nexport const intentRepository: IntentRepository = {\n async get(id) { return openRow(STORES.intents,await wrap<SavedIntent | undefined>((await store(STORES.intents,\"readonly\")).get(id))); },\n async list() { return openRows(STORES.intents,await wrap<SavedIntent[]>((await store(STORES.intents,\"readonly\")).getAll())); },\n async put(intent) { const row=await sealRow(STORES.intents,intent); await transact([STORES.intents],s=>{s[STORES.intents].put(row);}); },\n async claim(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n let reason=engineText(\"alreadySubmitted\");\n const request=tx.objectStore(STORES.intents).getAll();\n request.onsuccess=()=>{\n const intents:SavedIntent[]=request.result;\n saved=intents.find(item=>item.review.id===id)!;\n if(!saved || saved.review.state!==\"pending\") {tx.abort();return;}\n const duplicate=saved.review.requestId && intents.some(({review})=>review.id!==id && review.requestId===saved.review.requestId && review.linkId===saved.review.linkId && [\"submitted\",\"settled\",\"unknown\"].includes(review.state));\n if(duplicate){tx.abort();return;}\n if(nonceTaken(saved.review,intents)){reason=engineText(\"sentAfterReview\");tx.abort();return;}\n saved.review={...saved.review,state:\"submitted\",error:undefined,submittedAt:Date.now()};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(new Error(reason));\n });\n },\n async cancel(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n const request=tx.objectStore(STORES.intents).get(id);\n request.onsuccess=()=>{\n saved=request.result;\n if(!saved || saved.review.state!==\"pending\"){tx.abort();return;}\n saved.review={...saved.review,state:\"cancelled\"};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(engineError(\"cannotCancelSubmitted\"));\n });\n },\n};\n/** Key for a wallet that needs no password: its seed is protected like the Cashu proofs in the same database. */\nexport function newDeviceKey():string {return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/=+$/,\"\");}\nexport interface EncryptedSeed {version:1;salt:number[];iv:number[];ciphertext:number[]}\nasync function passwordKey(password:string,salt:Uint8Array<ArrayBuffer>) {\n const material=await crypto.subtle.importKey(\"raw\",new TextEncoder().encode(password),\"PBKDF2\",false,[\"deriveKey\"]);\n return crypto.subtle.deriveKey({name:\"PBKDF2\",hash:\"SHA-256\",salt,iterations:600000},material,{name:\"AES-GCM\",length:256},false,[\"encrypt\",\"decrypt\"]);\n}\nexport async function sealSeed(seed:string,password:string):Promise<EncryptedSeed> {\n if(password.length<12)throw new Error(\"Use at least 12 characters for the wallet password\");\n const salt=crypto.getRandomValues(new Uint8Array(16)),iv=crypto.getRandomValues(new Uint8Array(12));\n const ciphertext=await crypto.subtle.encrypt({name:\"AES-GCM\",iv},await passwordKey(password,salt),new TextEncoder().encode(seed));\n return {version:1,salt:[...salt],iv:[...iv],ciphertext:[...new Uint8Array(ciphertext)]};\n}\nexport async function unsealSeed(seed:EncryptedSeed,password:string):Promise<string> {\n if(seed.version!==1)throw new Error(\"Unsupported wallet backup version\");\n try {return new TextDecoder().decode(await crypto.subtle.decrypt({name:\"AES-GCM\",iv:new Uint8Array(seed.iv)},await passwordKey(password,new Uint8Array(seed.salt)),new Uint8Array(seed.ciphertext)));}\n catch {throw new Error(\"Could not unlock the wallet. Check the password and backup.\");}\n}\n","import { engineText } from \"@ghostly/core\";\n\n/**\n * A request's failure as a person says it, when the browser's own words say nothing: a request that timed out or was\n * given up (\"Fetch is aborted\" in Safari, \"signal timed out\" in Chromium) did not answer in time; one that never left\n * (\"Failed to fetch\", \"Load failed\") could not reach it. `host` names what was asked, when known. Anything else is\n * `null`: its own words are kept.\n */\nexport function networkReason(error: unknown, host?: string): string | null {\n const name = error instanceof Error ? error.name : \"\";\n const text = error instanceof Error ? error.message : String(error);\n 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()))\n return host ? engineText(\"hostTimedOut\", { host }) : engineText(\"networkTimedOut\");\n if (/^(failed to fetch|load failed|fetch failed|networkerror when attempting to fetch resource\\.?|network request failed)$/i.test(text.trim()))\n return host ? engineText(\"hostUnreachable\", { host }) : engineText(\"networkUnreachable\");\n return null;\n}\n\n/** A request URL's host, for a reason that names it; the URL itself when it does not parse. */\nexport function rpcHost(url: string): string {\n try { return new URL(url).host; } catch { return url; }\n}\n"],"mappings":";;;;;;;;;;AA6FA,SAAS,QAAQ,GAA6B;CAC5C,KAAK,MAAM,QAAQ;EAAC,EAAE;EAA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K,KAAK,KAAK,CAAC,GAC9P,OAAO,OAAO,WAAW,gBAAgB,EAAE,KAAK,CAAC,IAAI,WAAW,iBAAiB;CACnF,IAAI,yHAAyH,KAAK,KAAK,KAAK,CAAC,GAC3I,OAAO,OAAO,WAAW,mBAAmB,EAAE,KAAK,CAAC,IAAI,WAAW,oBAAoB;CACzF,OAAO;AACT;;AAGA,SAAgB,QAAQ,KAAqB;CAC3C,IAAI;EAAE,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CAAM,QAAQ;EAAE,OAAO;CAAK;AACxD"}
@@ -1,6 +1,6 @@
1
- import { kn as decodeBolt11 } from "./src-BTRPAi5X.js";
1
+ import { kn as decodeBolt11 } from "./src-BnpEQqzk.js";
2
2
  import { t as NothingSpentError } from "./types-C4_KafL_.js";
3
- import { n as parseNwcUri } from "./nwcProvider-BeQBPB2q.js";
3
+ import { i as parseNwcUri, n as nwcAlias } from "./nwcProvider-DpeDy0bV.js";
4
4
  import { sha256 } from "@noble/hashes/sha2.js";
5
5
  import * as nip04 from "nostr-tools/nip04";
6
6
  import * as nip44 from "nostr-tools/nip44";
@@ -481,7 +481,7 @@ var NwcLightning = class NwcLightning {
481
481
  }
482
482
  return {
483
483
  network: this.network,
484
- alias: `${this.alias ?? "NWC wallet"} via ${new URL(this.relay.url).host}`,
484
+ alias: nwcAlias(this.alias, new URL(this.relay.url).host),
485
485
  balance
486
486
  };
487
487
  }
@@ -609,4 +609,4 @@ var NwcLightning = class NwcLightning {
609
609
  //#endregion
610
610
  export { NwcLightning };
611
611
 
612
- //# sourceMappingURL=nwc-B3-PHX0L.js.map
612
+ //# sourceMappingURL=nwc-2vH18oNy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nwc-2vH18oNy.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/nwc.ts"],"sourcesContent":["import { decodeBolt11 } from \"@ghostly/core\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport * as nip04 from \"nostr-tools/nip04\";\nimport * as nip44 from \"nostr-tools/nip44\";\nimport { finalizeEvent, getPublicKey, verifyEvent, type Event } from \"nostr-tools/pure\";\nimport type { InvoiceStatus, LightningCapabilities, LightningInfo, LightningInvoice, LightningPayResult, LightningPaymentRef, LightningPaymentStatus, LightningProvider } from \"./lightning\";\nimport { nwcAlias, parseNwcUri, type NwcConnection } from \"./nwcProvider\";\nimport { NothingSpentError, type ProviderNetwork } from \"./types\";\n\n/**\n * Lightning through a wallet reached over Nostr Wallet Connect (NIP-47): Alby Hub, a node's NWC service, a\n * hosted wallet. The person pastes the wallet's `nostr+walletconnect://` URI; requests are signed with the\n * key it carries, encrypted to the wallet (NIP-44, or NIP-04 when its info event offers nothing else) and\n * sent through its relay; the answers come back the same way. That wallet holds the sats, applies its own\n * fee limit, and is custodial or not depending on what it is.\n *\n * Money safety (PROVIDERS.md): a request that never reached the relay, or an error code the wallet answers\n * before it tries to pay, is `NothingSpentError`. A `pay_invoice` whose answer does not come back in time,\n * or any other error, is an unknown outcome, and `paymentStatus` asks `lookup_invoice` until it ends.\n */\n\nconst KIND = { info: 13194, request: 23194, response: 23195 } as const;\n/** A relay message, an encrypted answer, an info event, an invoice: nothing bigger is read. */\nconst MAX_MESSAGE = 256 * 1024;\nconst MAX_CONTENT = 64 * 1024;\nconst MAX_INFO = 4096;\nconst MAX_INVOICE = 7089;\nconst CONNECT_MS = 10_000;\nconst ACK_MS = 10_000;\nconst REQUEST_MS = 20_000;\n/** A payment may take a while to route; an answer after this is an unknown outcome, looked up later. */\nconst PAY_MS = 90_000;\n/** The wallet must not start a payment it receives after this (NIP-47 `expiration`). */\nconst PAY_EXPIRY_S = 60;\n/** A payment the wallet never heard of is failed once its invoice can no longer be paid, with room for clocks. */\nconst EXPIRED_MARGIN_MS = 10 * 60_000;\nconst INVOICE_EXPIRY_S = 3600;\n\n/** Error codes a wallet answers before it tries to pay: nothing can have left it. (`BAD_REQUEST`: Alby Hub, an invoice it cannot read.) */\nconst REFUSED_BEFORE_PAYING = new Set([\"RATE_LIMITED\", \"NOT_IMPLEMENTED\", \"INSUFFICIENT_BALANCE\", \"QUOTA_EXCEEDED\", \"RESTRICTED\", \"UNAUTHORIZED\", \"UNSUPPORTED_ENCRYPTION\", \"BAD_REQUEST\"]);\nconst NETWORKS: Record<string, ProviderNetwork> = { mainnet: \"bitcoin\", bitcoin: \"bitcoin\", testnet: \"testnet\", testnet3: \"testnet\", testnet4: \"testnet\", signet: \"signet\", mutinynet: \"mutinynet\", regtest: \"regtest\" };\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst bytes = (text: string) => Uint8Array.from(text.match(/../g)!, (b) => parseInt(b, 16));\nconst now = () => Math.floor(Date.now() / 1000);\nconst isMsat = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;\n\n// -- one relay -----------------------------------------------------------------------------------------\n\n/** The request never reached the relay (not connected, refused by it): the wallet cannot have seen it. */\nexport class NotDelivered extends Error {\n constructor(message: string) { super(message); this.name = \"NotDelivered\"; }\n}\n/** An error the wallet answered, with its NIP-47 code. */\nexport class NwcError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = \"NwcError\"; }\n}\n/** No answer in time. The request may or may not have been acted on. */\nexport class NoAnswer extends Error {\n constructor(method: string) { super(`The wallet did not answer ${method} in time`); this.name = \"NoAnswer\"; }\n}\n\ninterface Filter { kinds: number[]; authors: string[]; \"#p\"?: string[]; since?: number; limit?: number }\ninterface Subscription { filter: Filter; event(event: unknown): void; eose?(): void }\n\n/**\n * A minimal NIP-01 client for one relay: it knows exactly whether an event was written to an open socket\n * and whether the relay acknowledged it, which is what tells \"nothing sent\" from \"unknown\" apart.\n * It reconnects when asked to send again, and subscriptions follow it.\n */\nexport class RelayConnection {\n private socket?: WebSocket;\n private opening?: Promise<WebSocket>;\n private readonly subs = new Map<string, Subscription>();\n private readonly acks = new Map<string, { ok(): void; fail(error: Error): void }>();\n private closed = false;\n\n constructor(readonly url: string, private readonly WebSocketImpl: typeof WebSocket = globalThis.WebSocket) {}\n\n open(): Promise<WebSocket> {\n if (this.closed) return Promise.reject(new Error(\"The wallet connection is closed\"));\n if (this.socket?.readyState === 1) return Promise.resolve(this.socket);\n if (!this.opening) {\n const opening = this.connectSocket();\n this.opening = opening;\n opening.catch(() => {}).finally(() => { if (this.opening === opening) this.opening = undefined; });\n }\n return this.opening;\n }\n\n private connectSocket(): Promise<WebSocket> {\n return new Promise<WebSocket>((resolve, reject) => {\n let settled = false;\n const socket = new this.WebSocketImpl(this.url);\n const done = (error?: Error) => {\n if (settled) return;\n settled = true; clearTimeout(timer);\n if (error) { try { socket.close(); } catch { /* already closed */ } reject(error); return; }\n if (this.closed) { socket.close(); reject(new Error(\"The wallet connection is closed\")); return; }\n this.socket = socket;\n for (const [id, sub] of this.subs) this.write([\"REQ\", id, sub.filter]);\n resolve(socket);\n };\n const timer = setTimeout(() => done(new Error(\"The wallet's relay did not answer\")), CONNECT_MS);\n socket.onopen = () => done();\n socket.onerror = () => done(new Error(\"Could not reach the wallet's relay\"));\n socket.onclose = () => {\n done(new Error(\"The wallet's relay closed the connection\"));\n if (this.socket !== socket) return;\n this.socket = undefined;\n // Written, not acknowledged: whether the relay kept it is unknown.\n for (const [id, ack] of this.acks) { this.acks.delete(id); ack.fail(new Error(\"The relay connection dropped before it confirmed the request\")); }\n };\n socket.onmessage = (message) => { if (this.socket === socket) this.receive(message.data); };\n });\n }\n\n subscribe(id: string, filter: Filter, sub: Omit<Subscription, \"filter\">) {\n this.subs.set(id, { ...sub, filter });\n this.write([\"REQ\", id, filter]);\n }\n\n unsubscribe(id: string) {\n if (this.subs.delete(id)) this.write([\"CLOSE\", id]);\n }\n\n /**\n * Events matching `filter` the relay has stored, until it says that is all (or `ms` pass). With\n * `waitForOne`, a relay that has none yet is listened to until one arrives live, within `ms`.\n */\n async fetch(filter: Filter, { ms = CONNECT_MS, waitForOne = false }: { ms?: number; waitForOne?: boolean } = {}): Promise<unknown[]> {\n await this.open();\n const id = `q${hex(crypto.getRandomValues(new Uint8Array(6)))}`, events: unknown[] = [];\n try {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms);\n let stored = false;\n const finish = () => { clearTimeout(timer); resolve(); };\n this.subscribe(id, filter, {\n event: (e) => { if (events.length < 20) events.push(e); if (stored) finish(); },\n eose: () => { stored = true; if (events.length || !waitForOne) finish(); },\n });\n });\n } finally { this.unsubscribe(id); }\n return events;\n }\n\n /**\n * Resolves once the relay accepted the event. `NotDelivered` when it certainly did not reach it (no open\n * socket, refused); any other rejection means it may have.\n */\n async publish(event: Event): Promise<void> {\n let socket: WebSocket;\n try { socket = await this.open(); } catch (error) { throw new NotDelivered(error instanceof Error ? error.message : \"Could not reach the wallet's relay\"); }\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => { this.acks.delete(event.id); reject(new Error(\"The relay did not confirm the request\")); }, ACK_MS);\n this.acks.set(event.id, { ok: () => { clearTimeout(timer); resolve(); }, fail: (error) => { clearTimeout(timer); reject(error); } });\n // A socket that is not open anymore drops what it is given without a word: nothing was sent.\n if (socket.readyState !== 1 || socket !== this.socket) { this.acks.delete(event.id); clearTimeout(timer); reject(new NotDelivered(\"The relay connection closed\")); return; }\n socket.send(JSON.stringify([\"EVENT\", event]));\n });\n }\n\n close() {\n this.closed = true;\n for (const [id, ack] of this.acks) { this.acks.delete(id); ack.fail(new Error(\"The wallet connection is closed\")); }\n this.subs.clear();\n try { this.socket?.close(); } catch { /* already closed */ }\n this.socket = undefined;\n }\n\n private write(message: unknown[]) {\n if (this.socket?.readyState === 1) this.socket.send(JSON.stringify(message));\n }\n\n private receive(data: unknown) {\n if (typeof data !== \"string\" || data.length > MAX_MESSAGE) return;\n let message: unknown;\n try { message = JSON.parse(data); } catch { return; }\n if (!Array.isArray(message) || typeof message[1] !== \"string\") return;\n const [type, id] = message as [string, string];\n if (type === \"EVENT\") this.subs.get(id)?.event(message[2]);\n else if (type === \"EOSE\") this.subs.get(id)?.eose?.();\n else if (type === \"OK\") {\n const ack = this.acks.get(id);\n if (!ack) return;\n this.acks.delete(id);\n const reason = typeof message[3] === \"string\" ? message[3].slice(0, 120) : \"\";\n // \"duplicate:\" is a relay saying it already has it: delivered.\n if (message[2] === true || reason.startsWith(\"duplicate:\")) ack.ok();\n else ack.fail(new NotDelivered(`The relay refused the request${reason ? ` (${reason})` : \"\"}`));\n }\n }\n}\n\n// -- the wallet ----------------------------------------------------------------------------------------\n\n/** What `lookup_invoice` (and `make_invoice`) answer, as far as it is read. Amounts in millisats. */\ninterface NwcTransaction {\n type?: string;\n state?: string;\n invoice?: string;\n payment_hash?: string;\n preimage?: string;\n amount?: number;\n fees_paid?: number;\n settled_at?: number | null;\n expires_at?: number | null;\n}\n\nexport interface NwcOptions {\n signal?: AbortSignal;\n /** For tests: time limits, and a WebSocket other than the global one. */\n requestMs?: number;\n /** How long to wait for the wallet's info event (a new app connection publishes it a moment later). */\n infoMs?: number;\n payMs?: number;\n WebSocket?: typeof WebSocket;\n}\n\ninterface Pending { method: string; resolve(result: Record<string, unknown>): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }\n\nexport class NwcLightning implements LightningProvider {\n /** From the info event, then narrowed to what this connection may do (`get_info`). */\n capabilities: LightningCapabilities;\n private readonly clientPubkey: string;\n private readonly subscription = `nwc${hex(crypto.getRandomValues(new Uint8Array(6)))}`;\n private readonly pending = new Map<string, Pending>();\n private conversationKey?: Uint8Array;\n private network: ProviderNetwork = \"bitcoin\";\n private alias?: string;\n private closed = false;\n\n private constructor(private readonly connection: NwcConnection, private readonly relay: RelayConnection, readonly encryption: \"nip44_v2\" | \"nip04\", methods: ReadonlySet<string>, private readonly options: NwcOptions) {\n this.clientPubkey = getPublicKey(connection.secret);\n if (encryption === \"nip44_v2\") this.conversationKey = nip44.v2.utils.getConversationKey(connection.secret, connection.walletPubkey);\n this.capabilities = this.capabilitiesOf(methods);\n }\n\n /**\n * Reaches the wallet through the first relay that answers, reads its info event (the methods and the\n * encryption it offers), listens for its answers, and asks `get_info` for its network.\n */\n static async connect(uri: string, options: NwcOptions = {}): Promise<NwcLightning> {\n const connection = parseNwcUri(uri);\n options.signal?.throwIfAborted();\n let relay: RelayConnection | undefined, lastError: unknown;\n for (const url of connection.relays) {\n const candidate = new RelayConnection(url, options.WebSocket);\n try { await candidate.open(); relay = candidate; break; } catch (error) { candidate.close(); lastError = error; }\n }\n if (!relay) throw lastError instanceof Error ? lastError : new Error(\"Could not reach the wallet's relay\");\n let wallet: NwcLightning | undefined;\n try {\n const info = NwcLightning.newestInfo(await relay.fetch({ kinds: [KIND.info], authors: [connection.walletPubkey], limit: 5 }, { waitForOne: true, ms: options.infoMs }), connection.walletPubkey);\n if (!info) throw new Error(`The wallet has not published its NWC info on ${new URL(relay.url).host}: check the URI, or that the wallet is running`);\n const offered = (info.tags.find((t) => t[0] === \"encryption\")?.slice(1).join(\" \") ?? \"\").split(/\\s+/).filter(Boolean);\n // NIP-47: no `encryption` tag means a wallet that only speaks NIP-04.\n const encryption = offered.includes(\"nip44_v2\") ? \"nip44_v2\" : !offered.length || offered.includes(\"nip04\") ? \"nip04\" : undefined;\n if (!encryption) throw new Error(\"The wallet offers no encryption Ghostly speaks (NIP-44 or NIP-04)\");\n const methods = new Set(info.content.split(/\\s+/).filter(Boolean));\n wallet = new NwcLightning(connection, relay, encryption, methods, options);\n wallet.listen();\n if (options.signal) {\n const opened = wallet;\n if (options.signal.aborted) throw options.signal.reason;\n options.signal.addEventListener(\"abort\", () => void opened.close(), { once: true });\n }\n await wallet.readInfo(methods);\n return wallet;\n } catch (error) {\n if (wallet) await wallet.close(); else relay.close();\n throw error;\n }\n }\n\n private static newestInfo(events: unknown[], walletPubkey: string): Event | undefined {\n return (events as Event[])\n .filter((e) => e && e.kind === KIND.info && e.pubkey === walletPubkey && typeof e.content === \"string\" && e.content.length <= MAX_INFO && Array.isArray(e.tags) && verifyEvent(e))\n .sort((a, b) => b.created_at - a.created_at)[0];\n }\n\n private capabilitiesOf(methods: ReadonlySet<string>): LightningCapabilities {\n const lookup = methods.has(\"lookup_invoice\");\n // Paying needs looking up: a payment whose answer is lost could never be settled, and would hold the source.\n return { receive: methods.has(\"make_invoice\"), send: methods.has(\"pay_invoice\") && lookup, balance: methods.has(\"get_balance\"), lookup };\n }\n\n /**\n * `get_info` says the network and the methods this connection may use (the info event lists the\n * service's). Without it the wallet is taken to be on Bitcoin: a test wallet is then refused in the\n * Testnet mode and its invoices in the Mainnet one, while a real-money wallet never passes for a test one.\n */\n private async readInfo(offered: ReadonlySet<string>) {\n if (!offered.has(\"get_info\")) return;\n let info: Record<string, unknown>;\n try { info = await this.request(\"get_info\", {}); }\n catch (error) {\n // The service has it, this connection may not use it: the same as a wallet without it.\n if (error instanceof NwcError && [\"RESTRICTED\", \"UNAUTHORIZED\", \"NOT_IMPLEMENTED\"].includes(error.code)) return;\n throw error;\n }\n if (info.network !== undefined) {\n const network = typeof info.network === \"string\" ? NETWORKS[info.network.toLowerCase()] : undefined;\n if (!network) throw new Error(\"The wallet is on a network Ghostly does not know\");\n this.network = network;\n }\n if (typeof info.alias === \"string\" && info.alias.trim()) this.alias = info.alias.trim().slice(0, 40);\n if (Array.isArray(info.methods) && info.methods.every((m) => typeof m === \"string\")) {\n this.capabilities = this.capabilitiesOf(new Set(info.methods as string[]));\n }\n }\n\n private listen() {\n this.relay.subscribe(this.subscription, { kinds: [KIND.response], authors: [this.connection.walletPubkey], \"#p\": [this.clientPubkey], since: now() - 60 }, { event: (e) => this.answer(e) });\n }\n\n // -- requests and answers --\n\n private encrypt(text: string) {\n return this.conversationKey ? nip44.v2.encrypt(text, this.conversationKey) : nip04.encrypt(this.connection.secret, this.connection.walletPubkey, text);\n }\n\n private decrypt(content: string) {\n if (this.conversationKey && !content.includes(\"?iv=\")) return nip44.v2.decrypt(content, this.conversationKey);\n return nip04.decrypt(this.connection.secret, this.connection.walletPubkey, content);\n }\n\n /**\n * Sends one request and waits for its answer. `NotDelivered` when it never reached the relay; `NwcError`\n * for an error the wallet answered; `NoAnswer` (or a relay error) when the outcome is unknown.\n */\n async request(method: string, params: Record<string, unknown>, { ms = this.options.requestMs ?? REQUEST_MS, expiresIn }: { ms?: number; expiresIn?: number } = {}): Promise<Record<string, unknown>> {\n if (this.closed) throw new NotDelivered(\"The wallet connection is closed\");\n const tags = [[\"p\", this.connection.walletPubkey]];\n if (this.conversationKey) tags.push([\"encryption\", \"nip44_v2\"]);\n if (expiresIn) tags.push([\"expiration\", String(now() + expiresIn)]);\n const event = finalizeEvent({ kind: KIND.request, created_at: now(), tags, content: this.encrypt(JSON.stringify({ method, params })) }, this.connection.secret);\n const answer = new Promise<Record<string, unknown>>((resolve, reject) => {\n const timer = setTimeout(() => { this.pending.delete(event.id); reject(new NoAnswer(method)); }, ms);\n this.pending.set(event.id, { method, resolve, reject, timer });\n });\n // The answer can come before the relay's acknowledgement (or without one): whichever decides first wins.\n const delivered = this.relay.publish(event).then(() => undefined, (error: unknown) => {\n const waiting = this.pending.get(event.id);\n if (!(error instanceof NotDelivered) || !waiting) return undefined;\n clearTimeout(waiting.timer); this.pending.delete(event.id);\n return error;\n });\n return Promise.race([answer, delivered.then((error) => (error ? Promise.reject(error) : answer))]);\n }\n\n /** Reads an answer: from the wallet, signed, about a request of ours, of the method asked. Anything else is dropped. */\n private answer(raw: unknown) {\n const event = raw as Event;\n if (!event || typeof event !== \"object\" || event.kind !== KIND.response || event.pubkey !== this.connection.walletPubkey) return;\n if (typeof event.content !== \"string\" || event.content.length > MAX_CONTENT || !Array.isArray(event.tags)) return;\n const ref = event.tags.find((t) => Array.isArray(t) && t[0] === \"e\")?.[1];\n const pending = typeof ref === \"string\" ? this.pending.get(ref) : undefined;\n if (!pending || !event.tags.some((t) => Array.isArray(t) && t[0] === \"p\" && t[1] === this.clientPubkey)) return;\n if (!verifyEvent(event)) return;\n let body: { result_type?: unknown; error?: { code?: unknown; message?: unknown } | null; result?: unknown };\n try { body = JSON.parse(this.decrypt(event.content)); } catch { return; }\n if (!body || typeof body !== \"object\" || body.result_type !== pending.method) return;\n clearTimeout(pending.timer);\n this.pending.delete(ref!);\n if (body.error) {\n const code = typeof body.error.code === \"string\" ? body.error.code.slice(0, 40) : \"OTHER\";\n const message = typeof body.error.message === \"string\" && body.error.message.trim() ? body.error.message.trim().slice(0, 200) : code;\n pending.reject(new NwcError(code, message));\n } else if (body.result && typeof body.result === \"object\" && !Array.isArray(body.result)) pending.resolve(body.result as Record<string, unknown>);\n else pending.reject(new NwcError(\"OTHER\", \"The wallet sent an empty answer\"));\n }\n\n private async lookup(paymentHash: string): Promise<NwcTransaction> {\n const tx = await this.request(\"lookup_invoice\", { payment_hash: paymentHash }) as NwcTransaction;\n if (tx.payment_hash !== undefined && String(tx.payment_hash).toLowerCase() !== paymentHash) throw new Error(\"The wallet answered about another invoice\");\n return tx;\n }\n\n // -- LightningProvider --\n\n async info(): Promise<LightningInfo> {\n let balance: number | undefined;\n if (this.capabilities.balance) {\n const result = await this.request(\"get_balance\", {});\n if (!isMsat(result.balance)) throw new Error(\"The wallet returned an invalid balance\");\n balance = Math.floor(result.balance / 1000);\n }\n return { network: this.network, alias: nwcAlias(this.alias, new URL(this.relay.url).host), balance };\n }\n\n async createInvoice(amount: number, memo?: string): Promise<LightningInvoice> {\n if (!Number.isSafeInteger(amount) || amount <= 0 || !Number.isSafeInteger(amount * 1000)) throw new Error(\"Invalid amount\");\n const result = await this.request(\"make_invoice\", { amount: amount * 1000, ...(memo ? { description: memo.slice(0, 200) } : {}), expiry: INVOICE_EXPIRY_S }) as NwcTransaction;\n const text = typeof result.invoice === \"string\" && result.invoice.length <= MAX_INVOICE ? result.invoice : \"\";\n const decoded = decodeBolt11(text);\n if (!decoded?.paymentHash || decoded.amountMsat !== BigInt(amount) * 1000n) throw new Error(\"The wallet returned an invoice that does not match the request\");\n if (result.payment_hash !== undefined && String(result.payment_hash).toLowerCase() !== decoded.paymentHash) throw new Error(\"The wallet returned an invoice that does not match its payment hash\");\n return { invoice: decoded.invoice, paymentHash: decoded.paymentHash, amount, expiresAt: decoded.expiresAt * 1000 };\n }\n\n async invoiceStatus(invoice: LightningInvoice): Promise<InvoiceStatus> {\n let tx: NwcTransaction;\n try { tx = await this.lookup(invoice.paymentHash); }\n catch (error) {\n if (error instanceof NwcError && error.code === \"NOT_FOUND\" && invoice.expiresAt < Date.now()) return { state: \"expired\" };\n throw error;\n }\n const expired = invoice.expiresAt < Date.now();\n if (tx.type === \"outgoing\") return { state: expired ? \"expired\" : \"open\" };\n // An incoming invoice's preimage is known before it is paid: only `state` or `settled_at` say it was.\n const state = tx.state ?? (tx.settled_at ? \"settled\" : \"pending\");\n if (state === \"settled\") return { state: \"paid\", amount: isMsat(tx.amount) ? Math.floor(tx.amount / 1000) : invoice.amount };\n if (state === \"expired\" || state === \"failed\") return { state: \"expired\" };\n return { state: expired ? \"expired\" : \"open\" };\n }\n\n /**\n * Pays through the wallet. NIP-47 carries no fee limit: the wallet applies its own, and the fee it\n * reports is passed on as it is.\n */\n async payInvoice(invoice: string, _maxFee: number): Promise<LightningPayResult> {\n const decoded = decodeBolt11(invoice);\n if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError(\"That invoice cannot be paid through NWC\");\n if (!this.capabilities.send) throw new NothingSpentError(\"This wallet connection may not pay and look up invoices\");\n let result: Record<string, unknown>;\n try {\n result = await this.request(\"pay_invoice\", { invoice: decoded.invoice }, { ms: this.options.payMs ?? PAY_MS, expiresIn: PAY_EXPIRY_S });\n } catch (error) {\n if (error instanceof NotDelivered) throw new NothingSpentError(`The payment did not reach the wallet: ${error.message}`);\n if (error instanceof NwcError && REFUSED_BEFORE_PAYING.has(error.code)) throw new NothingSpentError(`The wallet refused the payment: ${error.message}`);\n // Any other code may come after the wallet tried (Alby Hub answers INTERNAL with LND's failure reason).\n if (error instanceof NwcError) return this.confirmFailure(decoded.invoice, decoded.paymentHash, error);\n throw error;\n }\n const preimage = typeof result.preimage === \"string\" ? result.preimage.toLowerCase() : \"\";\n // \"Paid\" without a proof that pays this invoice is not taken at its word: it is looked up instead.\n if (!HEX64.test(preimage) || hex(sha256(bytes(preimage))) !== decoded.paymentHash) throw new Error(\"The wallet said it paid, without a proof that matches the invoice\");\n return { state: \"paid\", preimage, fee: isMsat(result.fees_paid) ? Math.ceil(result.fees_paid / 1000) : undefined };\n }\n\n /**\n * An error after the wallet may have tried (`PAYMENT_FAILED` \"may be due to a timeout\", `INTERNAL`,\n * `OTHER`…): its own record decides. Only a payment it records as failed is `NothingSpentError`; one it\n * records as paid is paid; anything else is pending, or unknown when it cannot be asked.\n */\n private async confirmFailure(invoice: string, paymentHash: string, failure: NwcError): Promise<LightningPayResult> {\n let status: LightningPaymentStatus;\n try { status = await this.paymentStatus({ invoice, paymentHash }); }\n catch { throw new Error(`The wallet said the payment failed (${failure.message}), and cannot confirm it yet`); }\n if (status.state === \"failed\") throw new NothingSpentError(`The payment failed: ${failure.message}`);\n return status.state === \"paid\" ? { state: \"paid\", fee: status.fee, preimage: status.preimage } : { state: \"pending\" };\n }\n\n async paymentStatus(payment: LightningPaymentRef): Promise<LightningPaymentStatus> {\n let tx: NwcTransaction;\n try { tx = await this.lookup(payment.paymentHash); }\n catch (error) {\n if (!(error instanceof NwcError && error.code === \"NOT_FOUND\")) throw error;\n // The wallet never heard of it: failed once nobody can pay that invoice anymore, until then it may still start.\n const expiresAt = (decodeBolt11(payment.invoice)?.expiresAt ?? Infinity) * 1000;\n return { state: expiresAt + EXPIRED_MARGIN_MS < Date.now() ? \"failed\" : \"pending\" };\n }\n // Our own invoice (a wallet paying itself): not an answer about the payment.\n if (tx.type === \"incoming\") return { state: \"pending\" };\n const preimage = typeof tx.preimage === \"string\" && HEX64.test(tx.preimage.toLowerCase()) ? tx.preimage.toLowerCase() : undefined;\n const proven = !!preimage && hex(sha256(bytes(preimage))) === payment.paymentHash;\n const state = tx.state ?? (tx.settled_at || proven ? \"settled\" : \"pending\");\n const fee = isMsat(tx.fees_paid) ? Math.ceil(tx.fees_paid / 1000) : undefined;\n if (state === \"settled\") {\n if (preimage && !proven) throw new Error(\"The wallet's proof of payment does not match the invoice\");\n return { state: \"paid\", fee, preimage };\n }\n if (state === \"failed\" || state === \"expired\") return { state: \"failed\" };\n return { state: \"pending\" };\n }\n\n async close() {\n if (this.closed) return;\n this.closed = true;\n for (const [id, pending] of this.pending) { clearTimeout(pending.timer); this.pending.delete(id); pending.reject(new Error(\"The wallet connection is closed\")); }\n this.relay.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,IAAM,OAAO;CAAE,MAAM;CAAO,SAAS;CAAO,UAAU;AAAM;;AAE5D,IAAM,cAAc;AACpB,IAAM,cAAc;AACpB,IAAM,WAAW;AACjB,IAAM,cAAc;AACpB,IAAM,aAAa;AACnB,IAAM,SAAS;AACf,IAAM,aAAa;;AAEnB,IAAM,SAAS;;AAEf,IAAM,eAAe;;AAErB,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;;AAGzB,IAAM,wCAAwB,IAAI,IAAI;CAAC;CAAgB;CAAmB;CAAwB;CAAkB;CAAc;CAAgB;CAA0B;AAAa,CAAC;AAC1L,IAAM,WAA4C;CAAE,SAAS;CAAW,SAAS;CAAW,SAAS;CAAW,UAAU;CAAW,UAAU;CAAW,QAAQ;CAAU,WAAW;CAAa,SAAS;AAAU;AAEvN,IAAM,QAAQ;AACd,IAAM,OAAO,UAAsB,MAAM,KAAK,QAAQ,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AACpG,IAAM,SAAS,SAAiB,WAAW,KAAK,KAAK,MAAM,KAAK,IAAK,MAAM,SAAS,GAAG,EAAE,CAAC;AAC1F,IAAM,YAAY,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAC9C,IAAM,UAAU,UAAoC,OAAO,cAAc,KAAK,KAAM,SAAoB;;AAKxG,IAAa,eAAb,cAA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,MAAM,QAAQ,CAAC,CAAC,MAAM,QAAQ;EACtE,MAAM,QAAQ,GAAG,UAAU,GAAG,cAAc,SAAS,YAAY;EACjE,MAAM,MAAM,OAAO,GAAG,SAAS,IAAI,KAAK,KAAK,GAAG,YAAY,GAAI,IAAI,KAAA;EACpE,IAAI,UAAU,WAAW;GACvB,IAAI,YAAY,CAAC,QAAQ,MAAM,IAAI,MAAM,0DAA0D;GACnG,OAAO;IAAE,OAAO;IAAQ;IAAK;GAAS;EACxC;EACA,IAAI,UAAU,YAAY,UAAU,WAAW,OAAO,EAAE,OAAO,SAAS;EACxE,OAAO,EAAE,OAAO,UAAU;CAC5B;CAEA,MAAM,QAAQ;EACZ,IAAI,KAAK,QAAQ;EACjB,KAAK,SAAS;EACd,KAAK,MAAM,CAAC,IAAI,YAAY,KAAK,SAAS;GAAE,aAAa,QAAQ,KAAK;GAAG,KAAK,QAAQ,OAAO,EAAE;GAAG,QAAQ,uBAAO,IAAI,MAAM,iCAAiC,CAAC;EAAG;EAChK,KAAK,MAAM,MAAM;CACnB;AACF"}
@@ -43,6 +43,14 @@ function parseNwcUri(input) {
43
43
  secret: bytes(secret)
44
44
  };
45
45
  }
46
+ /** The name the NWC client gives its source: the wallet's own name and its relay's host. */
47
+ var nwcAlias = (wallet, relayHost) => `${wallet ?? "NWC wallet"} via ${relayHost}`;
48
+ /** The wallet's own name in an `nwcAlias` ("" when the wallet did not say one). The host never holds a space. */
49
+ function nwcWalletName(alias) {
50
+ const at = alias.lastIndexOf(" via ");
51
+ const wallet = at > 0 ? alias.slice(0, at) : alias;
52
+ return wallet === "NWC wallet" ? "" : wallet;
53
+ }
46
54
  var nwc = {
47
55
  id: "nwc",
48
56
  label: "Nostr Wallet Connect",
@@ -67,11 +75,11 @@ var nwc = {
67
75
  parseNwcUri(secrets.uri ?? "");
68
76
  },
69
77
  async create({ secrets }, host) {
70
- const { NwcLightning } = await import("./nwc-B3-PHX0L.js");
78
+ const { NwcLightning } = await import("./nwc-2vH18oNy.js");
71
79
  return NwcLightning.connect(secrets.uri, { signal: host.signal });
72
80
  }
73
81
  };
74
82
  //#endregion
75
- export { parseNwcUri as n, nwc as t };
83
+ export { parseNwcUri as i, nwcAlias as n, nwcWalletName as r, nwc as t };
76
84
 
77
- //# sourceMappingURL=nwcProvider-BeQBPB2q.js.map
85
+ //# sourceMappingURL=nwcProvider-DpeDy0bV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nwcProvider-DpeDy0bV.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/nwcProvider.ts"],"sourcesContent":["import type { LightningProviderDescriptor } from \"./lightning\";\nimport { PROVIDER_PLATFORMS } from \"./types\";\n\n/**\n * Nostr Wallet Connect as the source picker lists it, and its connection URI. The client (`./nwc`) and its NIP-04 /\n * NIP-44 encryption load when a wallet connects, not with the app.\n */\n\nconst MAX_URI = 2048;\nconst MAX_RELAYS = 5;\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst bytes = (text: string) => Uint8Array.from(text.match(/../g)!, (b) => parseInt(b, 16));\n\nexport interface NwcConnection {\n walletPubkey: string;\n relays: string[];\n /** The client key the wallet granted: a secret. */\n secret: Uint8Array;\n}\n\n/** Only secure relays, except on this machine (a local test relay). */\nfunction checkRelay(address: string): string {\n let relay: URL;\n try { relay = new URL(address); } catch { throw new Error(\"The connection URI has a relay that is not a URL\"); }\n if (relay.username || relay.password || relay.hash) throw new Error(\"The connection URI has a relay with credentials in it\");\n const loopback = [\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(relay.hostname);\n if (!(relay.protocol === \"wss:\" || (relay.protocol === \"ws:\" && loopback))) throw new Error(\"Use a wallet whose relay is secure (wss://)\");\n return relay.href;\n}\n\n/** Reads a `nostr+walletconnect://` URI. Its errors never repeat it: it holds a secret. */\nexport function parseNwcUri(input: string): NwcConnection {\n const text = (input ?? \"\").trim();\n if (text.length > MAX_URI) throw new Error(\"That connection URI is too long\");\n const match = /^(?:nostr\\+walletconnect|nostrwalletconnect):(?:\\/\\/)?([0-9a-fA-F]{64})\\/?\\?([^#]*)$/.exec(text);\n if (!match) throw new Error(\"That is not a Nostr Wallet Connect URI (nostr+walletconnect://…)\");\n const params = new URLSearchParams(match[2]);\n const secret = (params.get(\"secret\") ?? \"\").toLowerCase();\n if (!HEX64.test(secret) || /^0+$/.test(secret)) throw new Error(\"The connection URI has no valid secret\");\n const relays = [...new Set(params.getAll(\"relay\").map(checkRelay))];\n if (!relays.length) throw new Error(\"The connection URI names no relay\");\n if (relays.length > MAX_RELAYS) throw new Error(\"The connection URI names too many relays\");\n return { walletPubkey: match[1].toLowerCase(), relays, secret: bytes(secret) };\n}\n\n/** What an NWC wallet that does not say its name is called. */\nexport const NWC_UNNAMED = \"NWC wallet\";\n\n/** The name the NWC client gives its source: the wallet's own name and its relay's host. */\nexport const nwcAlias = (wallet: string | undefined, relayHost: string) => `${wallet ?? NWC_UNNAMED} via ${relayHost}`;\n\n/** The wallet's own name in an `nwcAlias` (\"\" when the wallet did not say one). The host never holds a space. */\nexport function nwcWalletName(alias: string): string {\n const at = alias.lastIndexOf(\" via \");\n const wallet = at > 0 ? alias.slice(0, at) : alias;\n return wallet === NWC_UNNAMED ? \"\" : wallet;\n}\n\nexport const nwc: LightningProviderDescriptor = {\n id: \"nwc\",\n label: \"Nostr Wallet Connect\",\n kind: \"lightning\",\n description: \"A wallet you connect with its NWC URI (Alby Hub, a node's NWC service, a hosted wallet). That wallet holds the sats and sets its own fee limit: custodial or not depends on the wallet.\",\n networks: [\"bitcoin\", \"testnet\", \"signet\", \"mutinynet\", \"regtest\"],\n platforms: PROVIDER_PLATFORMS,\n fields: [{\n name: \"uri\", label: \"Connection URI\", kind: \"secret\", placeholder: \"nostr+walletconnect://…\",\n help: \"From your wallet's app connections. Allow making, paying and looking up invoices, and reading the balance.\",\n }],\n validate({ secrets }) { parseNwcUri(secrets.uri ?? \"\"); },\n async create({ secrets }, host) {\n const { NwcLightning } = await import(\"./nwc\");\n return NwcLightning.connect(sec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