@ghostlytools/cli 1.11.2 → 1.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -10
- package/dist/assets/{api-BM3PsXbB.js → api-DBlaoz8i.js} +129 -37
- package/dist/assets/api-DBlaoz8i.js.map +1 -0
- package/dist/assets/{api-CtXgscmK.js → api-DgU4MZPD.js} +2 -2
- package/dist/assets/{apiKit-lCTQ0EBG.js → apiKit-DesObIDf.js} +4 -4
- package/dist/assets/{apiKit-lCTQ0EBG.js.map → apiKit-DesObIDf.js.map} +1 -1
- package/dist/assets/{appFetch-BKHy5H8J.js → appFetch-C8yZIq1e.js} +3 -3
- package/dist/assets/{appFetch-BKHy5H8J.js.map → appFetch-C8yZIq1e.js.map} +1 -1
- package/dist/assets/{apps-Do26w3c7.js → apps-DkMjDHML.js} +104 -33
- package/dist/assets/apps-DkMjDHML.js.map +1 -0
- package/dist/assets/{apps-DO_gAZgm.js → apps-rzxsjfBV.js} +1 -1
- package/dist/assets/{arkade-CZrLbz-M.js → arkade-CarKONmH.js} +2 -2
- package/dist/assets/{arkade-CZrLbz-M.js.map → arkade-CarKONmH.js.map} +1 -1
- package/dist/assets/{backup-j47AzDvG.js → backup-C0OJCJlM.js} +17 -25
- package/dist/assets/backup-C0OJCJlM.js.map +1 -0
- package/dist/assets/{backup-D21x1f5P.js → backup-CgWU7x0T.js} +1 -1
- package/dist/assets/buttons-Cco0Agfa.js +2 -0
- package/dist/assets/{buttons-CiGlBVBT.js → buttons-fZTEa_2i.js} +34 -5
- package/dist/assets/buttons-fZTEa_2i.js.map +1 -0
- package/dist/assets/{client-raIncVtF.js → client-Ibk3-e60.js} +2 -2
- package/dist/assets/{client-raIncVtF.js.map → client-Ibk3-e60.js.map} +1 -1
- package/dist/assets/{codec-DcG2AeyE.js → codec-DMpQqVSt.js} +2 -2
- package/dist/assets/{codec-DcG2AeyE.js.map → codec-DMpQqVSt.js.map} +1 -1
- package/dist/assets/{envelope-Dud6lntA.js → envelope-CvQVCGdf.js} +2 -2
- package/dist/assets/{envelope-Dud6lntA.js.map → envelope-CvQVCGdf.js.map} +1 -1
- package/dist/assets/{fedimintSdk-DRKRSw14.js → fedimintSdk-zV_5Qdqz.js} +2 -2
- package/dist/assets/{fedimintSdk-DRKRSw14.js.map → fedimintSdk-zV_5Qdqz.js.map} +1 -1
- package/dist/assets/{fixedHosts-CNX7QiUD.js → fixedHosts-6gKn8dp2.js} +3 -3
- package/dist/assets/{fixedHosts-CNX7QiUD.js.map → fixedHosts-6gKn8dp2.js.map} +1 -1
- package/dist/assets/{host-8RskzQgB.js → host-CYlIiY3r.js} +161 -32
- package/dist/assets/host-CYlIiY3r.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-uAThbFub.js → hyperdhtRelay-CdsLcAhY.js} +2 -2
- package/dist/assets/{hyperdhtRelay-uAThbFub.js.map → hyperdhtRelay-CdsLcAhY.js.map} +1 -1
- package/dist/assets/{irohWeb-DGelfgDJ.js → irohWeb-D2IuloLL.js} +19 -12
- package/dist/assets/irohWeb-D2IuloLL.js.map +1 -0
- package/dist/assets/{main-BC33ooYg.js → main-C0PfjKTe.js} +109 -42
- package/dist/assets/main-C0PfjKTe.js.map +1 -0
- package/dist/assets/{mainline-DYrjsS1t.js → mainline-Cu61qcPS.js} +35 -18
- package/dist/assets/mainline-Cu61qcPS.js.map +1 -0
- package/dist/assets/{networkReason-n2oBs4by.js → networkReason-Dt7Yx_n4.js} +3 -3
- package/dist/assets/{networkReason-n2oBs4by.js.map → networkReason-Dt7Yx_n4.js.map} +1 -1
- package/dist/assets/{nwc-Do3VSlIS.js → nwc-CtZypDcv.js} +3 -3
- package/dist/assets/{nwc-Do3VSlIS.js.map → nwc-CtZypDcv.js.map} +1 -1
- package/dist/assets/{nwcProvider-Du5aWNIn.js → nwcProvider-DYHkd0iu.js} +2 -2
- package/dist/assets/{nwcProvider-Du5aWNIn.js.map → nwcProvider-DYHkd0iu.js.map} +1 -1
- package/dist/assets/{ownDid-CwwYu8s2.js → ownDid-CJ0ta8CL.js} +2 -2
- package/dist/assets/{ownDid-CwwYu8s2.js.map → ownDid-CJ0ta8CL.js.map} +1 -1
- package/dist/assets/{ownStatus-D7dB4zJB.js → ownStatus-D4HC6tNR.js} +11 -6
- package/dist/assets/{ownStatus-D7dB4zJB.js.map → ownStatus-D4HC6tNR.js.map} +1 -1
- package/dist/assets/{profiles-NyF5FnYF.js → profiles-Ccdq6Xf6.js} +3 -3
- package/dist/assets/{profiles-NyF5FnYF.js.map → profiles-Ccdq6Xf6.js.map} +1 -1
- package/dist/assets/{registry-C734VrO9.js → registry-CE0PpQAE.js} +1 -1
- package/dist/assets/{registry-DKDInr0A.js → registry-LvxsLJ5S.js} +18 -7
- package/dist/assets/registry-LvxsLJ5S.js.map +1 -0
- package/dist/assets/{resolve-3Tqh9AWQ.js → resolve-6kVu2DE5.js} +2 -2
- package/dist/assets/{resolve-3Tqh9AWQ.js.map → resolve-6kVu2DE5.js.map} +1 -1
- package/dist/assets/{server-B6PQ6iae.js → server-Q3VcNqGt.js} +245 -97
- package/dist/assets/server-Q3VcNqGt.js.map +1 -0
- package/dist/assets/{src-ChJijTlM.js → src-DjVj2ynY.js} +188 -42
- package/dist/assets/src-DjVj2ynY.js.map +1 -0
- package/dist/assets/{sshForges-Brf0fslM.js → sshForges-DeZ9cN9Q.js} +4 -3
- package/dist/assets/sshForges-DeZ9cN9Q.js.map +1 -0
- package/dist/assets/{translate-xLme9Rdh.js → translate-iQZq4TnY.js} +35 -14
- package/dist/assets/translate-iQZq4TnY.js.map +1 -0
- package/dist/assets/{usdt-CSU5KzTV.js → usdt-DnyTGdTX.js} +3 -3
- package/dist/assets/{usdt-CSU5KzTV.js.map → usdt-DnyTGdTX.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-BM3PsXbB.js.map +0 -1
- package/dist/assets/apps-Do26w3c7.js.map +0 -1
- package/dist/assets/backup-j47AzDvG.js.map +0 -1
- package/dist/assets/buttons-CiGlBVBT.js.map +0 -1
- package/dist/assets/buttons-D2l2bVCG.js +0 -2
- package/dist/assets/host-8RskzQgB.js.map +0 -1
- package/dist/assets/irohWeb-DGelfgDJ.js.map +0 -1
- package/dist/assets/main-BC33ooYg.js.map +0 -1
- package/dist/assets/mainline-DYrjsS1t.js.map +0 -1
- package/dist/assets/registry-DKDInr0A.js.map +0 -1
- package/dist/assets/server-B6PQ6iae.js.map +0 -1
- package/dist/assets/src-ChJijTlM.js.map +0 -1
- package/dist/assets/sshForges-Brf0fslM.js.map +0 -1
- package/dist/assets/translate-xLme9Rdh.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nwc-Do3VSlIS.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/nwc.ts"],"sourcesContent":["import { decodeBolt11, sanitizeDisplayText } 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 const alias = typeof info.alias === \"string\" ? sanitizeDisplayText(info.alias.replace(/\\s+/g, \" \"), 40) : undefined;\n if (alias) this.alias = alias;\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,I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GAAE,aAAa,QAAQ,KAAK;GAAG,KAAK,QAAQ,OAAO,EAAE;GAAG,QAAQ,uBAAO,IAAI,MAAM,iCAAiC,CAAC;EAAG;EAChK,KAAK,MAAM,MAAM;CACnB;AACF"}
|
|
1
|
+
{"version":3,"file":"nwc-CtZypDcv.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/nwc.ts"],"sourcesContent":["import { decodeBolt11, sanitizeDisplayText } 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 const alias = typeof info.alias === \"string\" ? sanitizeDisplayText(info.alias.replace(/\\s+/g, \" \"), 40) : undefined;\n if (alias) this.alias = alias;\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;A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
const { NwcLightning } = await import("./nwc-CtZypDcv.js");
|
|
82
82
|
return NwcLightning.connect(secrets.uri, { signal: host.signal });
|
|
83
83
|
}
|
|
84
84
|
};
|
|
85
85
|
//#endregion
|
|
86
86
|
export { parseNwcUri as i, nwcAlias as n, nwcWalletName as r, nwc as t };
|
|
87
87
|
|
|
88
|
-
//# sourceMappingURL=nwcProvider-
|
|
88
|
+
//# sourceMappingURL=nwcProvider-DYHkd0iu.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nwcProvider-
|
|
1
|
+
{"version":3,"file":"nwcProvider-DYHkd0iu.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 // The wallet's key: the same URI spelled another way, or another app connection to that wallet, reads the same balance.\n wallet({ secrets }) { return parseNwcUri(secrets.uri ?? \"\").walletPubkey; },\n async create({ secrets }, host) {\n const { NwcLightning } = await import(\"./nwc\");\n return NwcLightning.connect(secrets.uri, { signal: host.signal });\n },\n};\n"],"mappings":";;;;;;AAQA,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,QAAQ;AACd,IAAM,SAAS,SAAiB,WAAW,KAAK,KAAK,MAAM,KAAK,IAAK,MAAM,SAAS,GAAG,EAAE,CAAC;;AAU1F,SAAS,WAAW,SAAyB;CAC3C,IAAI;CACJ,IAAI;EAAE,QAAQ,IAAI,IAAI,OAAO;CAAG,QAAQ;EAAE,MAAM,IAAI,MAAM,kDAAkD;CAAG;CAC/G,IAAI,MAAM,YAAY,MAAM,YAAY,MAAM,MAAM,MAAM,IAAI,MAAM,uDAAuD;CAC3H,MAAM,WAAW;EAAC;EAAa;EAAa;CAAO,CAAC,CAAC,SAAS,MAAM,QAAQ;CAC5E,IAAI,EAAE,MAAM,aAAa,UAAW,MAAM,aAAa,SAAS,WAAY,MAAM,IAAI,MAAM,6CAA6C;CACzI,OAAO,MAAM;AACf;;AAGA,SAAgB,YAAY,OAA8B;CACxD,MAAM,QAAQ,SAAS,GAAA,CAAI,KAAK;CAChC,IAAI,KAAK,SAAS,SAAS,MAAM,IAAI,MAAM,iCAAiC;CAC5E,MAAM,QAAQ,uFAAuF,KAAK,IAAI;CAC9G,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,kEAAkE;CAC9F,MAAM,SAAS,IAAI,gBAAgB,MAAM,EAAE;CAC3C,MAAM,UAAU,OAAO,IAAI,QAAQ,KAAK,GAAA,CAAI,YAAY;CACxD,IAAI,CAAC,MAAM,KAAK,MAAM,KAAK,OAAO,KAAK,MAAM,GAAG,MAAM,IAAI,MAAM,wCAAwC;CACxG,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,OAAO,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC;CAClE,IAAI,CAAC,OAAO,QAAQ,MAAM,IAAI,MAAM,mCAAmC;CACvE,IAAI,OAAO,SAAS,YAAY,MAAM,IAAI,MAAM,0CAA0C;CAC1F,OAAO;EAAE,cAAc,MAAM,EAAE,CAAC,YAAY;EAAG;EAAQ,QAAQ,MAAM,MAAM;CAAE;AAC/E;;AAMA,IAAa,YAAY,QAA4B,cAAsB,GAAG,UAAA,aAAsB,OAAO;;AAG3G,SAAgB,cAAc,OAAuB;CACnD,MAAM,KAAK,MAAM,YAAY,OAAO;CACpC,MAAM,SAAS,KAAK,IAAI,MAAM,MAAM,GAAG,EAAE,IAAI;CAC7C,OAAO,WAAA,eAAyB,KAAK;AACvC;AAEA,IAAa,MAAmC;CAC9C,IAAI;CACJ,OAAO;CACP,MAAM;CACN,aAAa;CACb,UAAU;EAAC;EAAW;EAAW;EAAU;EAAa;CAAS;CACjE,WAAW;CACX,QAAQ,CAAC;EACP,MAAM;EAAO,OAAO;EAAkB,MAAM;EAAU,aAAa;EACnE,MAAM;CACR,CAAC;CACD,SAAS,EAAE,WAAW;EAAE,YAAY,QAAQ,OAAO,EAAE;CAAG;CAExD,OAAO,EAAE,WAAW;EAAE,OAAO,YAAY,QAAQ,OAAO,EAAE,CAAC,CAAC;CAAc;CAC1E,MAAM,OAAO,EAAE,WAAW,MAAM;EAC9B,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,OAAO,aAAa,QAAQ,QAAQ,KAAK,EAAE,QAAQ,KAAK,OAAO,CAAC;CAClE;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Wi as IdentityCheckUnavailable, qi as boundVerifiedIdentity } from "./src-DjVj2ynY.js";
|
|
2
2
|
import { l as providerDescriptorProblems } from "./types-Clyb52K2.js";
|
|
3
3
|
//#region ../browser/src/shared/features.ts
|
|
4
4
|
/**
|
|
@@ -279,4 +279,4 @@ var ownDid = () => source();
|
|
|
279
279
|
//#endregion
|
|
280
280
|
export { registeredLightningProviders as a, boundedIdentityFetch as c, testSwitch as d, registeredIdentityProviders as i, verifyIdentity as l, setOwnDidSource as n, registeredOnchainProviders as o, onAdaptersChanged as r, reserveAdapterIds as s, ownDid as t, testBuild as u };
|
|
281
281
|
|
|
282
|
-
//# sourceMappingURL=ownDid-
|
|
282
|
+
//# sourceMappingURL=ownDid-CJ0ta8CL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownDid-CwwYu8s2.js","names":[],"sources":["../../../browser/src/shared/features.ts","../../../browser/src/proofs/verify.ts","../../../browser/src/plugins/bundled.ts","../../../browser/src/plugins/registry.ts","../../../browser/src/proofs/ownDid.ts"],"sourcesContent":["/** Release policy: external identity experiments are retained for future work,\n * but must not advertise capabilities, start network lookups, or expose cached\n * external profiles. This does not gate Ghostly participation authentication. */\nexport const EXTERNAL_IDENTITIES_ENABLED: boolean = false;\n\n/** Mini-apps (WISP 1200): `apps/1` on paired sessions and the engine's `app*` calls. On from release 1.2 (a version\n * before 1.2.0 is never cut with it on: `RELEASE_GUARDS` in tools/scripts/changes.mjs). Off, nothing is offered to\n * contacts and every call is refused; a host that runs no apps pins its engine off (`NodeOptions.apps`). */\nexport const APPS_ENABLED: boolean = true;\n\n/**\n * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the\n * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is\n * neither: Vite folds this to `false` there, so the storage flags the test fakes answer to are ignored. The fakes\n * themselves are still in the bundle (the registries import them); plugins may still pass fakes to the registry.\n */\nexport const testBuild = (): boolean => { try { return !!import.meta.env?.DEV || import.meta.env?.VITE_APPS_TEST === \"1\"; } catch { return false; } };\n\n/**\n * A suite's switch in the page's storage (`localStorage[\"ghostly-test-…\"]`), read only in a test build (`testBuild`): a\n * release build reads none, so a leftover or pasted key changes nothing there. Null when unset, unreadable or released.\n */\nexport const testSwitch = (key: string): string | null => {\n if (!testBuild()) return null;\n try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; }\n};\n","import { boundVerifiedIdentity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (p.recheck?.perHour !== undefined && !(Number.isInteger(p.recheck.perHour) && p.recheck.perHour >= 1)) problems.push(\"recheck.perHour must be a whole number, at least 1\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\" } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n if (target.protocol !== \"https:\" || target.username || target.password) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const response = await (options.fetcher ?? fetch)(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n","import type { GhostlyAdapterPlugin } from \"./registry\";\n\n/**\n * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`\n * names their modules (comma-separated paths from the repository root, each default-exporting a\n * `GhostlyAdapterPlugin`), and the Vite plugin in `packages/browser/vite-plugin.ts` swaps this module\n * for one that imports them. Release builds never set it; the e2e build carries the SDK example.\n */\nexport const BUNDLED_PLUGINS: readonly GhostlyAdapterPlugin[] = [];\n","import type { LightningProviderDescriptor } from \"../engine/paymentAdapters/providers/lightning\";\nimport type { OnchainProviderDescriptor } from \"../engine/paymentAdapters/providers/onchain\";\nimport { providerDescriptorProblems, type ProviderDescriptor, type ProviderKind } from \"../engine/paymentAdapters/providers/types\";\nimport type { IdentityProofProvider } from \"../proofs/contract\";\nimport { descriptorProblems } from \"../proofs/verify\";\nimport { BUNDLED_PLUGINS } from \"./bundled\";\n\n/**\n * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers\n * that register here instead of being added to the built-in lists. A plugin is a plain object naming\n * its adapters; the registries (`providers/registry.ts`, `proofs/registry.ts`) list what is registered\n * after the built-ins and before the test fakes, and the same platform and mode rules apply to all.\n *\n * Two ways in:\n * - at build time: `GHOSTLY_PLUGINS` lists the modules and `bundled.ts` is swapped for them;\n * - at run time: code already running in the engine's realm calls `registerAdapters` before the\n * pickers are shown (or after: the engine re-reads the lists when something registers).\n *\n * Trust: a plugin runs with the app's privileges, in the app's own JavaScript realm. There is no\n * sandbox, no permission prompt and no store; whoever builds a plugin in, or loads one, trusts its\n * author with everything the app can do, keys and sats included. A manifest with permissions and an\n * isolated runtime are a later phase (docs/wisps/ADAPTER-ROADMAP.md, \"Plugins, apps, catalogs\").\n *\n * The state lives on `globalThis` under a well-known symbol, so a plugin bundled with its own copy of\n * the SDK (a second copy of this module) still registers into the same lists the app reads.\n */\n\n/** The generation of the adapter contracts. A plugin says which one it was written against. */\nexport const SDK_API = 1;\nexport const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;\n\nexport interface GhostlyAdapterPlugin {\n /** Stable, unique among plugins: `^[a-z][a-z0-9-]{0,63}$`. */\n id: string;\n /** The plugin's own version, for people. */\n version?: string;\n /** The contract generation it was written against: `SDK_API`. Another one is refused. */\n sdk: number;\n lightning?: readonly LightningProviderDescriptor[];\n onchain?: readonly OnchainProviderDescriptor[];\n identities?: readonly IdentityProofProvider[];\n}\n\nexport type AdapterKind = ProviderKind | \"identity\";\n\ninterface Store {\n plugins: Map<string, GhostlyAdapterPlugin>;\n /** Ids the built-in registries own, per kind: a plugin cannot take one. */\n reserved: Record<AdapterKind, Set<string>>;\n listeners: Set<() => void>;\n seeded: boolean;\n}\n\nconst KEY = Symbol.for(\"ghostly.adapters/1\");\nfunction store(): Store {\n const g = globalThis as unknown as Record<symbol, Store | undefined>;\n return (g[KEY] ??= { plugins: new Map(), reserved: { lightning: new Set(), onchain: new Set(), identity: new Set() }, listeners: new Set(), seeded: false });\n}\n\nconst ids = (kind: AdapterKind, plugin: GhostlyAdapterPlugin): string[] => {\n // Not trusted to be well formed: pluginProblems reads it before saying what is wrong with it.\n const list: unknown = kind === \"identity\" ? plugin.identities : kind === \"lightning\" ? plugin.lightning : plugin.onchain;\n return Array.isArray(list) ? list.map((a: { id?: string } | null) => a?.id as string) : [];\n};\nconst KINDS: readonly AdapterKind[] = [\"lightning\", \"onchain\", \"identity\"];\n\n/** Problems with a plugin, empty when it can be registered. Does not look at what is already registered. */\nexport function pluginProblems(plugin: GhostlyAdapterPlugin): string[] {\n const problems: string[] = [];\n if (!plugin || typeof plugin !== \"object\") return [\"not a plugin object\"];\n if (!PLUGIN_ID.test(plugin.id ?? \"\")) problems.push(\"plugin id must match ^[a-z][a-z0-9-]{0,63}$\");\n if (plugin.sdk !== SDK_API) problems.push(`plugin was written for SDK API ${String(plugin.sdk)}; this app speaks ${SDK_API}`);\n if (plugin.version !== undefined && (typeof plugin.version !== \"string\" || plugin.version.length > 64)) problems.push(\"version must be a short string\");\n for (const kind of [\"lightning\", \"onchain\"] as const) {\n const list = plugin[kind];\n if (list === undefined) continue;\n if (!Array.isArray(list)) { problems.push(`${kind} must be a list of descriptors`); continue; }\n for (const d of list as ProviderDescriptor<unknown>[]) {\n if (!d || typeof d !== \"object\") { problems.push(`${kind} ${String(d)}: not a descriptor`); continue; }\n const own = providerDescriptorProblems(d);\n if (d?.kind && d.kind !== kind) own.push(`is listed under ${kind} but says kind ${String(d.kind)}`);\n problems.push(...own.map((p) => `${kind} ${String(d?.id)}: ${p}`));\n }\n }\n if (plugin.identities !== undefined) {\n if (!Array.isArray(plugin.identities)) problems.push(\"identities must be a list of providers\");\n else for (const p of plugin.identities) {\n if (!p || typeof p !== \"object\") problems.push(`identity ${String(p)}: not a provider`);\n else problems.push(...descriptorProblems(p).map((m) => `identity ${String(p.id)}: ${m}`));\n }\n }\n for (const kind of KINDS) {\n const list = ids(kind, plugin);\n if (new Set(list).size !== list.length) problems.push(`${kind} ids are not unique within the plugin`);\n }\n if (!KINDS.some((kind) => ids(kind, plugin).length)) problems.push(\"the plugin brings no adapter\");\n return problems;\n}\n\n/** The built-in registries say which ids are theirs. A plugin using one is refused. */\nexport function reserveAdapterIds(kind: AdapterKind, list: readonly string[]): void {\n const s = store();\n for (const id of list) s.reserved[kind].add(id);\n}\n\n/**\n * Registers a plugin's adapters. Throws, registering nothing, when the plugin is malformed, its id or\n * one of its adapters' ids is taken (by a built-in or by another plugin), or its contract generation\n * is another one. Returns the function that unregisters it.\n */\nexport function registerAdapters(plugin: GhostlyAdapterPlugin): () => void {\n const problems = pluginProblems(plugin);\n const s = store();\n if (!problems.length) {\n if (s.plugins.has(plugin.id)) problems.push(`a plugin with id ${plugin.id} is already registered`);\n for (const kind of KINDS) for (const id of ids(kind, plugin)) {\n if (s.reserved[kind].has(id)) problems.push(`${kind} ${id} is a built-in of this app`);\n for (const other of s.plugins.values()) if (ids(kind, other).includes(id)) problems.push(`${kind} ${id} is already registered by plugin ${other.id}`);\n }\n }\n if (problems.length) throw new Error(`Cannot register plugin ${String(plugin?.id)}: ${problems.join(\"; \")}`);\n s.plugins.set(plugin.id, plugin);\n notify(s);\n return () => { if (s.plugins.get(plugin.id) === plugin) { s.plugins.delete(plugin.id); notify(s); } };\n}\n\nfunction notify(s: Store) { for (const listener of s.listeners) { try { listener(); } catch { /* a listener's problem */ } } }\n\n/** Called when a plugin registers or unregisters: the engine re-reads the lists. */\nexport function onAdaptersChanged(listener: () => void): () => void {\n const s = store();\n s.listeners.add(listener);\n return () => { s.listeners.delete(listener); };\n}\n\n/** Every registered plugin, in registration order (bundled ones first). */\nexport function registeredPlugins(): readonly GhostlyAdapterPlugin[] { seed(); return [...store().plugins.values()]; }\nexport function registeredLightningProviders(): readonly LightningProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.lightning ?? []); }\nexport function registeredOnchainProviders(): readonly OnchainProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.onchain ?? []); }\nexport function registeredIdentityProviders(): readonly IdentityProofProvider[] { return registeredPlugins().flatMap((p) => p.identities ?? []); }\n\n/**\n * The plugins compiled into this build register once, when they are first asked for. A broken one is\n * reported and skipped rather than taking the app down with it; the e2e that expects it fails instead.\n */\nfunction seed() {\n const s = store();\n if (s.seeded) return;\n s.seeded = true;\n for (const plugin of BUNDLED_PLUGINS) {\n try { registerAdapters(plugin); }\n catch (error) { console.error(`[ghostly] a bundled adapter plugin was not loaded: ${error instanceof Error ? error.message : String(error)}`); }\n }\n}\n\n/** Tests only: forget every registration, including the bundled ones. */\nexport function resetAdapterRegistry(): void {\n const s = store();\n s.plugins.clear(); s.seeded = false;\n for (const kind of KINDS) s.reserved[kind].clear();\n notify(s);\n}\n","/**\n * The profile's own Ghostly did:dht, which the DID provider refuses as an external identity. The UI and the engine each\n * set where to read it. Here, not in the provider, so setting it does not load the providers.\n */\nlet source: () => string | undefined = () => undefined;\nexport function setOwnDidSource(read: () => string | undefined): void { source = read; }\nexport const ownDid = (): string | undefined => source();\n"],"mappings":";;;;;;;;;AAgBA,IAAa,kBAA2B;CAAE,IAAI;EAAE,OAAiC;CAAyC,QAAQ;EAAE,OAAO;CAAO;AAAE;;;;;AAMpJ,IAAa,cAAc,QAA+B;CACxD,IAAI,CAAC,UAAU,GAAG,OAAO;CACzB,IAAI;EAAE,OAAO,WAAW,cAAc,QAAQ,GAAG,KAAK;CAAM,QAAQ;EAAE,OAAO;CAAM;AACrF;;;ACtBA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C,WAA8B,UAAmB,KAA+C;CAChL,MAAM,EAAE,YA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jJ,SAAS,OAAO;CACd,MAAM,IAAI,MAAM;CAChB,IAAI,EAAE,QAAQ;CACd,EAAE,SAAS;CACX,KAAK,MAAM,UAAU,iBACnB,IAAI;EAAE,iBAAiB,MAAM;CAAG,SACzB,OAAO;EAAE,QAAQ,MAAM,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAAG;AAEnJ;;;;;;;ACrJA,IAAI,eAAyC,KAAA;AAC7C,SAAgB,gBAAgB,MAAsC;CAAE,SAAS;AAAM;AACvF,IAAa,eAAmC,OAAO"}
|
|
1
|
+
{"version":3,"file":"ownDid-CJ0ta8CL.js","names":[],"sources":["../../../browser/src/shared/features.ts","../../../browser/src/proofs/verify.ts","../../../browser/src/plugins/bundled.ts","../../../browser/src/plugins/registry.ts","../../../browser/src/proofs/ownDid.ts"],"sourcesContent":["/** Release policy: external identity experiments are retained for future work,\n * but must not advertise capabilities, start network lookups, or expose cached\n * external profiles. This does not gate Ghostly participation authentication. */\nexport const EXTERNAL_IDENTITIES_ENABLED: boolean = false;\n\n/** Mini-apps (WISP 1200): `apps/1` on paired sessions and the engine's `app*` calls. On from release 1.2 (a version\n * before 1.2.0 is never cut with it on: `RELEASE_GUARDS` in tools/scripts/changes.mjs). Off, nothing is offered to\n * contacts and every call is refused; a host that runs no apps pins its engine off (`NodeOptions.apps`). */\nexport const APPS_ENABLED: boolean = true;\n\n/**\n * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the\n * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is\n * neither: Vite folds this to `false` there, so the storage flags the test fakes answer to are ignored. The fakes\n * themselves are still in the bundle (the registries import them); plugins may still pass fakes to the registry.\n */\nexport const testBuild = (): boolean => { try { return !!import.meta.env?.DEV || import.meta.env?.VITE_APPS_TEST === \"1\"; } catch { return false; } };\n\n/**\n * A suite's switch in the page's storage (`localStorage[\"ghostly-test-…\"]`), read only in a test build (`testBuild`): a\n * release build reads none, so a leftover or pasted key changes nothing there. Null when unset, unreadable or released.\n */\nexport const testSwitch = (key: string): string | null => {\n if (!testBuild()) return null;\n try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; }\n};\n","import { boundVerifiedIdentity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (p.recheck?.perHour !== undefined && !(Number.isInteger(p.recheck.perHour) && p.recheck.perHour >= 1)) problems.push(\"recheck.perHour must be a whole number, at least 1\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\" } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n if (target.protocol !== \"https:\" || target.username || target.password) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const response = await (options.fetcher ?? fetch)(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n","import type { GhostlyAdapterPlugin } from \"./registry\";\n\n/**\n * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`\n * names their modules (comma-separated paths from the repository root, each default-exporting a\n * `GhostlyAdapterPlugin`), and the Vite plugin in `packages/browser/vite-plugin.ts` swaps this module\n * for one that imports them. Release builds never set it; the e2e build carries the SDK example.\n */\nexport const BUNDLED_PLUGINS: readonly GhostlyAdapterPlugin[] = [];\n","import type { LightningProviderDescriptor } from \"../engine/paymentAdapters/providers/lightning\";\nimport type { OnchainProviderDescriptor } from \"../engine/paymentAdapters/providers/onchain\";\nimport { providerDescriptorProblems, type ProviderDescriptor, type ProviderKind } from \"../engine/paymentAdapters/providers/types\";\nimport type { IdentityProofProvider } from \"../proofs/contract\";\nimport { descriptorProblems } from \"../proofs/verify\";\nimport { BUNDLED_PLUGINS } from \"./bundled\";\n\n/**\n * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers\n * that register here instead of being added to the built-in lists. A plugin is a plain object naming\n * its adapters; the registries (`providers/registry.ts`, `proofs/registry.ts`) list what is registered\n * after the built-ins and before the test fakes, and the same platform and mode rules apply to all.\n *\n * Two ways in:\n * - at build time: `GHOSTLY_PLUGINS` lists the modules and `bundled.ts` is swapped for them;\n * - at run time: code already running in the engine's realm calls `registerAdapters` before the\n * pickers are shown (or after: the engine re-reads the lists when something registers).\n *\n * Trust: a plugin runs with the app's privileges, in the app's own JavaScript realm. There is no\n * sandbox, no permission prompt and no store; whoever builds a plugin in, or loads one, trusts its\n * author with everything the app can do, keys and sats included. A manifest with permissions and an\n * isolated runtime are a later phase (docs/wisps/ADAPTER-ROADMAP.md, \"Plugins, apps, catalogs\").\n *\n * The state lives on `globalThis` under a well-known symbol, so a plugin bundled with its own copy of\n * the SDK (a second copy of this module) still registers into the same lists the app reads.\n */\n\n/** The generation of the adapter contracts. A plugin says which one it was written against. */\nexport const SDK_API = 1;\nexport const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;\n\nexport interface GhostlyAdapterPlugin {\n /** Stable, unique among plugins: `^[a-z][a-z0-9-]{0,63}$`. */\n id: string;\n /** The plugin's own version, for people. */\n version?: string;\n /** The contract generation it was written against: `SDK_API`. Another one is refused. */\n sdk: number;\n lightning?: readonly LightningProviderDescriptor[];\n onchain?: readonly OnchainProviderDescriptor[];\n identities?: readonly IdentityProofProvider[];\n}\n\nexport type AdapterKind = ProviderKind | \"identity\";\n\ninterface Store {\n plugins: Map<string, GhostlyAdapterPlugin>;\n /** Ids the built-in registries own, per kind: a plugin cannot take one. */\n reserved: Record<AdapterKind, Set<string>>;\n listeners: Set<() => void>;\n seeded: boolean;\n}\n\nconst KEY = Symbol.for(\"ghostly.adapters/1\");\nfunction store(): Store {\n const g = globalThis as unknown as Record<symbol, Store | undefined>;\n return (g[KEY] ??= { plugins: new Map(), reserved: { lightning: new Set(), onchain: new Set(), identity: new Set() }, listeners: new Set(), seeded: false });\n}\n\nconst ids = (kind: AdapterKind, plugin: GhostlyAdapterPlugin): string[] => {\n // Not trusted to be well formed: pluginProblems reads it before saying what is wrong with it.\n const list: unknown = kind === \"identity\" ? plugin.identities : kind === \"lightning\" ? plugin.lightning : plugin.onchain;\n return Array.isArray(list) ? list.map((a: { id?: string } | null) => a?.id as string) : [];\n};\nconst KINDS: readonly AdapterKind[] = [\"lightning\", \"onchain\", \"identity\"];\n\n/** Problems with a plugin, empty when it can be registered. Does not look at what is already registered. */\nexport function pluginProblems(plugin: GhostlyAdapterPlugin): string[] {\n const problems: string[] = [];\n if (!plugin || typeof plugin !== \"object\") return [\"not a plugin object\"];\n if (!PLUGIN_ID.test(plugin.id ?? \"\")) problems.push(\"plugin id must match ^[a-z][a-z0-9-]{0,63}$\");\n if (plugin.sdk !== SDK_API) problems.push(`plugin was written for SDK API ${String(plugin.sdk)}; this app speaks ${SDK_API}`);\n if (plugin.version !== undefined && (typeof plugin.version !== \"string\" || plugin.version.length > 64)) problems.push(\"version must be a short string\");\n for (const kind of [\"lightning\", \"onchain\"] as const) {\n const list = plugin[kind];\n if (list === undefined) continue;\n if (!Array.isArray(list)) { problems.push(`${kind} must be a list of descriptors`); continue; }\n for (const d of list as ProviderDescriptor<unknown>[]) {\n if (!d || typeof d !== \"object\") { problems.push(`${kind} ${String(d)}: not a descriptor`); continue; }\n const own = providerDescriptorProblems(d);\n if (d?.kind && d.kind !== kind) own.push(`is listed under ${kind} but says kind ${String(d.kind)}`);\n problems.push(...own.map((p) => `${kind} ${String(d?.id)}: ${p}`));\n }\n }\n if (plugin.identities !== undefined) {\n if (!Array.isArray(plugin.identities)) problems.push(\"identities must be a list of providers\");\n else for (const p of plugin.identities) {\n if (!p || typeof p !== \"object\") problems.push(`identity ${String(p)}: not a provider`);\n else problems.push(...descriptorProblems(p).map((m) => `identity ${String(p.id)}: ${m}`));\n }\n }\n for (const kind of KINDS) {\n const list = ids(kind, plugin);\n if (new Set(list).size !== list.length) problems.push(`${kind} ids are not unique within the plugin`);\n }\n if (!KINDS.some((kind) => ids(kind, plugin).length)) problems.push(\"the plugin brings no adapter\");\n return problems;\n}\n\n/** The built-in registries say which ids are theirs. A plugin using one is refused. */\nexport function reserveAdapterIds(kind: AdapterKind, list: readonly string[]): void {\n const s = store();\n for (const id of list) s.reserved[kind].add(id);\n}\n\n/**\n * Registers a plugin's adapters. Throws, registering nothing, when the plugin is malformed, its id or\n * one of its adapters' ids is taken (by a built-in or by another plugin), or its contract generation\n * is another one. Returns the function that unregisters it.\n */\nexport function registerAdapters(plugin: GhostlyAdapterPlugin): () => void {\n const problems = pluginProblems(plugin);\n const s = store();\n if (!problems.length) {\n if (s.plugins.has(plugin.id)) problems.push(`a plugin with id ${plugin.id} is already registered`);\n for (const kind of KINDS) for (const id of ids(kind, plugin)) {\n if (s.reserved[kind].has(id)) problems.push(`${kind} ${id} is a built-in of this app`);\n for (const other of s.plugins.values()) if (ids(kind, other).includes(id)) problems.push(`${kind} ${id} is already registered by plugin ${other.id}`);\n }\n }\n if (problems.length) throw new Error(`Cannot register plugin ${String(plugin?.id)}: ${problems.join(\"; \")}`);\n s.plugins.set(plugin.id, plugin);\n notify(s);\n return () => { if (s.plugins.get(plugin.id) === plugin) { s.plugins.delete(plugin.id); notify(s); } };\n}\n\nfunction notify(s: Store) { for (const listener of s.listeners) { try { listener(); } catch { /* a listener's problem */ } } }\n\n/** Called when a plugin registers or unregisters: the engine re-reads the lists. */\nexport function onAdaptersChanged(listener: () => void): () => void {\n const s = store();\n s.listeners.add(listener);\n return () => { s.listeners.delete(listener); };\n}\n\n/** Every registered plugin, in registration order (bundled ones first). */\nexport function registeredPlugins(): readonly GhostlyAdapterPlugin[] { seed(); return [...store().plugins.values()]; }\nexport function registeredLightningProviders(): readonly LightningProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.lightning ?? []); }\nexport function registeredOnchainProviders(): readonly OnchainProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.onchain ?? []); }\nexport function registeredIdentityProviders(): readonly IdentityProofProvider[] { return registeredPlugins().flatMap((p) => p.identities ?? []); }\n\n/**\n * The plugins compiled into this build register once, when they are first asked for. A broken one is\n * reported and skipped rather than taking the app down with it; the e2e that expects it fails instead.\n */\nfunction seed() {\n const s = store();\n if (s.seeded) return;\n s.seeded = true;\n for (const plugin of BUNDLED_PLUGINS) {\n try { registerAdapters(plugin); }\n catch (error) { console.error(`[ghostly] a bundled adapter plugin was not loaded: ${error instanceof Error ? error.message : String(error)}`); }\n }\n}\n\n/** Tests only: forget every registration, including the bundled ones. */\nexport function resetAdapterRegistry(): void {\n const s = store();\n s.plugins.clear(); s.seeded = false;\n for (const kind of KINDS) s.reserved[kind].clear();\n notify(s);\n}\n","/**\n * The profile's own Ghostly did:dht, which the DID provider refuses as an external identity. The UI and the engine each\n * set where to read it. Here, not in the provider, so setting it does not load the providers.\n */\nlet source: () => string | undefined = () => undefined;\nexport function setOwnDidSource(read: () => string | undefined): void { source = read; }\nexport const ownDid = (): string | undefined => source();\n"],"mappings":";;;;;;;;;AAgBA,IAAa,kBAA2B;CAAE,IAAI;EAAE,OAAiC;CAAyC,QAAQ;EAAE,OAAO;CAAO;AAAE;;;;;AAMpJ,IAAa,cAAc,QAA+B;CACxD,IAAI,CAAC,UAAU,GAAG,OAAO;CACzB,IAAI;EAAE,OAAO,WAAW,cAAc,QAAQ,GAAG,KAAK;CAAM,QAAQ;EAAE,OAAO;CAAM;AACrF;;;ACtBA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C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AAM,EAAE,cAAc,CAAC,CAAC;AAAG;;;;;AAMjJ,SAAS,OAAO;CACd,MAAM,IAAI,MAAM;CAChB,IAAI,EAAE,QAAQ;CACd,EAAE,SAAS;CACX,KAAK,MAAM,UAAU,iBACnB,IAAI;EAAE,iBAAiB,MAAM;CAAG,SACzB,OAAO;EAAE,QAAQ,MAAM,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAAG;AAEnJ;;;;;;;ACrJA,IAAI,eAAyC,KAAA;AAC7C,SAAgB,gBAAgB,MAAsC;CAAE,SAAS;AAAM;AACvF,IAAa,eAAmC,OAAO"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Mo as STATUS_CARD_LIMITS, Qr as STATUS_AVAILABILITIES, _d as sanitizeDisplayText, go as reactionEmoji, ni as sanitizeStatusText } from "./src-DjVj2ynY.js";
|
|
2
2
|
import { t as CliError } from "./errors-Dt-ZnyOX.js";
|
|
3
|
-
import { N as state, l as findGroup, r as chatOrGroup, w as node } from "./apiKit-
|
|
3
|
+
import { N as state, l as findGroup, r as chatOrGroup, w as node } from "./apiKit-DesObIDf.js";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
//#region src/engineMethods.ts
|
|
6
6
|
/**
|
|
@@ -329,14 +329,17 @@ function turnRef(where, messageId) {
|
|
|
329
329
|
var TURN_REF = /^t_[0-9a-f]{32}$/;
|
|
330
330
|
var isRef = (value) => typeof value === "string" && TURN_REF.test(value);
|
|
331
331
|
/**
|
|
332
|
-
* `params` with each turn's id in `message`, `reply` and `
|
|
333
|
-
* among the chat's (or group's) newest messages first, where a turn's almost always is, then in all of
|
|
334
|
-
* names no message stays as given, and its command says so as for any unknown id.
|
|
332
|
+
* `params` with each turn's id in `message`, `reply`, `messages`, `before` and `after` as the id its message is stored
|
|
333
|
+
* under: looked for among the chat's (or group's) newest messages first, where a turn's almost always is, then in all of
|
|
334
|
+
* them. One that names no message stays as given, and its command says so as for any unknown id. A timestamp in `before`
|
|
335
|
+
* or `after` is no turn's id and stays as it is.
|
|
335
336
|
*/
|
|
336
337
|
async function withStoredIds(ctx, params) {
|
|
337
338
|
const wanted = new Set([
|
|
338
339
|
params.message,
|
|
339
340
|
params.reply,
|
|
341
|
+
params.before,
|
|
342
|
+
params.after,
|
|
340
343
|
...Array.isArray(params.messages) ? params.messages : []
|
|
341
344
|
].filter(isRef));
|
|
342
345
|
if (!wanted.size) return params;
|
|
@@ -370,6 +373,8 @@ async function withStoredIds(ctx, params) {
|
|
|
370
373
|
...params,
|
|
371
374
|
...params.message !== void 0 && { message: stored(params.message) },
|
|
372
375
|
...params.reply !== void 0 && { reply: stored(params.reply) },
|
|
376
|
+
...params.before !== void 0 && { before: stored(params.before) },
|
|
377
|
+
...params.after !== void 0 && { after: stored(params.after) },
|
|
373
378
|
...Array.isArray(params.messages) && { messages: params.messages.map(stored) }
|
|
374
379
|
};
|
|
375
380
|
}
|
|
@@ -473,4 +478,4 @@ function statusJson(status) {
|
|
|
473
478
|
//#endregion
|
|
474
479
|
export { PAY_METHODS as a, turnRef as c, ENGINE_METHODS as d, ENGINE_PARAMS as f, engineParamsProblem as g, SECRET_RESULTS as h, CHAT_METHODS as i, withStoredIds as l, READ_PARAMS as m, statusJson as n, TRANSPORT_NAMES as o, ENGINE_READS as p, ADDRESS_TYPES as r, WALLET_TYPES as s, checkOwnStatus as t, DESTRUCTIVE_CALLS as u };
|
|
475
480
|
|
|
476
|
-
//# sourceMappingURL=ownStatus-
|
|
481
|
+
//# sourceMappingURL=ownStatus-D4HC6tNR.js.map
|