@ghostlytools/cli 1.11.1 → 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.
Files changed (107) hide show
  1. package/README.md +32 -23
  2. package/dist/assets/{api-DL0Uazf6.js → api-DBlaoz8i.js} +478 -141
  3. package/dist/assets/api-DBlaoz8i.js.map +1 -0
  4. package/dist/assets/{api-D89ubgas.js → api-DgU4MZPD.js} +2 -2
  5. package/dist/assets/{apiKit-D78MXTrk.js → apiKit-DesObIDf.js} +19 -9
  6. package/dist/assets/apiKit-DesObIDf.js.map +1 -0
  7. package/dist/assets/appFetch-C8yZIq1e.js +194 -0
  8. package/dist/assets/appFetch-C8yZIq1e.js.map +1 -0
  9. package/dist/assets/{apps--pAqmfgQ.js → apps-DkMjDHML.js} +142 -67
  10. package/dist/assets/apps-DkMjDHML.js.map +1 -0
  11. package/dist/assets/{apps-BlSl1nGn.js → apps-rzxsjfBV.js} +1 -1
  12. package/dist/assets/{arkade-DxB-MR43.js → arkade-CarKONmH.js} +2 -2
  13. package/dist/assets/{arkade-DxB-MR43.js.map → arkade-CarKONmH.js.map} +1 -1
  14. package/dist/assets/{backup-B3JJd75o.js → backup-C0OJCJlM.js} +90 -47
  15. package/dist/assets/backup-C0OJCJlM.js.map +1 -0
  16. package/dist/assets/{backup-T7gFpU80.js → backup-CgWU7x0T.js} +1 -1
  17. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  18. package/dist/assets/{bitcoind-CZchoh43.js → bitcoind-CdSmvy2y.js} +3 -3
  19. package/dist/assets/{bitcoind-CZchoh43.js.map → bitcoind-CdSmvy2y.js.map} +1 -1
  20. package/dist/assets/{bitcoindProvider-DGw3xBSa.js → bitcoindProvider-BvoRh0D5.js} +2 -2
  21. package/dist/assets/{bitcoindProvider-DGw3xBSa.js.map → bitcoindProvider-BvoRh0D5.js.map} +1 -1
  22. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  23. package/dist/assets/buttons-Cco0Agfa.js +2 -0
  24. package/dist/assets/{buttons-C1VbDihe.js → buttons-fZTEa_2i.js} +47 -7
  25. package/dist/assets/buttons-fZTEa_2i.js.map +1 -0
  26. package/dist/assets/{childEnv-BVOQK9EA.js → childEnv-K_IzUqQx.js} +4 -3
  27. package/dist/assets/childEnv-K_IzUqQx.js.map +1 -0
  28. package/dist/assets/{client-CGLuWFRV.js → client-Ibk3-e60.js} +31 -3
  29. package/dist/assets/client-Ibk3-e60.js.map +1 -0
  30. package/dist/assets/{codec-YGJDr7uH.js → codec-DMpQqVSt.js} +2 -2
  31. package/dist/assets/{codec-YGJDr7uH.js.map → codec-DMpQqVSt.js.map} +1 -1
  32. package/dist/assets/endpoint-DarqblYE.js +5052 -0
  33. package/dist/assets/endpoint-DarqblYE.js.map +1 -0
  34. package/dist/assets/{envelope-Dwq8EN8x.js → envelope-CvQVCGdf.js} +2 -2
  35. package/dist/assets/{envelope-Dwq8EN8x.js.map → envelope-CvQVCGdf.js.map} +1 -1
  36. package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-zV_5Qdqz.js} +6 -3
  37. package/dist/assets/fedimintSdk-zV_5Qdqz.js.map +1 -0
  38. package/dist/assets/{fixedHosts-CINXidpd.js → fixedHosts-6gKn8dp2.js} +3 -3
  39. package/dist/assets/{fixedHosts-CINXidpd.js.map → fixedHosts-6gKn8dp2.js.map} +1 -1
  40. package/dist/assets/{host-CGlHkiQv.js → host-CYlIiY3r.js} +455 -104
  41. package/dist/assets/host-CYlIiY3r.js.map +1 -0
  42. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js → hyperdhtRelay-CdsLcAhY.js} +2 -2
  43. package/dist/assets/{hyperdhtRelay-Bj5jJT5w.js.map → hyperdhtRelay-CdsLcAhY.js.map} +1 -1
  44. package/dist/assets/{irohWeb-CYn0uB_A.js → irohWeb-D2IuloLL.js} +705 -43
  45. package/dist/assets/irohWeb-D2IuloLL.js.map +1 -0
  46. package/dist/assets/jsonOut-POtMBS_V.js +16 -0
  47. package/dist/assets/jsonOut-POtMBS_V.js.map +1 -0
  48. package/dist/assets/{main-CgLW_Gyx.js → main-C0PfjKTe.js} +263 -128
  49. package/dist/assets/main-C0PfjKTe.js.map +1 -0
  50. package/dist/assets/{mainline-B0h8RchD.js → mainline-Cu61qcPS.js} +60 -24
  51. package/dist/assets/mainline-Cu61qcPS.js.map +1 -0
  52. package/dist/assets/{networkReason-BBosp2KG.js → networkReason-Dt7Yx_n4.js} +3 -3
  53. package/dist/assets/{networkReason-BBosp2KG.js.map → networkReason-Dt7Yx_n4.js.map} +1 -1
  54. package/dist/assets/{nwc-SSNS1aJ-.js → nwc-CtZypDcv.js} +6 -5
  55. package/dist/assets/nwc-CtZypDcv.js.map +1 -0
  56. package/dist/assets/{nwcProvider-BXqJmM98.js → nwcProvider-DYHkd0iu.js} +6 -3
  57. package/dist/assets/{nwcProvider-BXqJmM98.js.map → nwcProvider-DYHkd0iu.js.map} +1 -1
  58. package/dist/assets/{ownDid--DtH_Jdi.js → ownDid-CJ0ta8CL.js} +3 -3
  59. package/dist/assets/{ownDid--DtH_Jdi.js.map → ownDid-CJ0ta8CL.js.map} +1 -1
  60. package/dist/assets/{ownStatus-CQPGjCUR.js → ownStatus-D4HC6tNR.js} +12 -6
  61. package/dist/assets/{ownStatus-CQPGjCUR.js.map → ownStatus-D4HC6tNR.js.map} +1 -1
  62. package/dist/assets/{profiles-4UQ1Hsds.js → profiles-Ccdq6Xf6.js} +82 -6
  63. package/dist/assets/profiles-Ccdq6Xf6.js.map +1 -0
  64. package/dist/assets/{registry-B6BXKv6Q.js → registry-CE0PpQAE.js} +1 -1
  65. package/dist/assets/{registry-BKCFTEYp.js → registry-LvxsLJ5S.js} +88 -25
  66. package/dist/assets/registry-LvxsLJ5S.js.map +1 -0
  67. package/dist/assets/{resolve-MFeFljsN.js → resolve-6kVu2DE5.js} +4 -3
  68. package/dist/assets/resolve-6kVu2DE5.js.map +1 -0
  69. package/dist/assets/{server-rHKhnog1.js → server-Q3VcNqGt.js} +630 -933
  70. package/dist/assets/server-Q3VcNqGt.js.map +1 -0
  71. package/dist/assets/{src-BzsyAvPf.js → src-DjVj2ynY.js} +580 -168
  72. package/dist/assets/src-DjVj2ynY.js.map +1 -0
  73. package/dist/assets/{sshForges-qITn-RoV.js → sshForges-DeZ9cN9Q.js} +4 -3
  74. package/dist/assets/sshForges-DeZ9cN9Q.js.map +1 -0
  75. package/dist/assets/{translate-Bkr_iDgp.js → translate-iQZq4TnY.js} +36 -15
  76. package/dist/assets/translate-iQZq4TnY.js.map +1 -0
  77. package/dist/assets/{types-C4_KafL_.js → types-Clyb52K2.js} +2 -1
  78. package/dist/assets/types-Clyb52K2.js.map +1 -0
  79. package/dist/assets/{usdt-Bp7T2iqt.js → usdt-DnyTGdTX.js} +3 -3
  80. package/dist/assets/{usdt-Bp7T2iqt.js.map → usdt-DnyTGdTX.js.map} +1 -1
  81. package/dist/ghostly.mjs +1 -1
  82. package/npm-shrinkwrap.json +3592 -0
  83. package/package.json +5 -3
  84. package/dist/assets/api-DL0Uazf6.js.map +0 -1
  85. package/dist/assets/apiKit-D78MXTrk.js.map +0 -1
  86. package/dist/assets/apps--pAqmfgQ.js.map +0 -1
  87. package/dist/assets/backup-B3JJd75o.js.map +0 -1
  88. package/dist/assets/buttons-C1VbDihe.js.map +0 -1
  89. package/dist/assets/buttons-DwWuK_uN.js +0 -2
  90. package/dist/assets/childEnv-BVOQK9EA.js.map +0 -1
  91. package/dist/assets/client-CGLuWFRV.js.map +0 -1
  92. package/dist/assets/endpoint-DWHkXWVM.js +0 -419
  93. package/dist/assets/endpoint-DWHkXWVM.js.map +0 -1
  94. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +0 -1
  95. package/dist/assets/host-CGlHkiQv.js.map +0 -1
  96. package/dist/assets/irohWeb-CYn0uB_A.js.map +0 -1
  97. package/dist/assets/main-CgLW_Gyx.js.map +0 -1
  98. package/dist/assets/mainline-B0h8RchD.js.map +0 -1
  99. package/dist/assets/nwc-SSNS1aJ-.js.map +0 -1
  100. package/dist/assets/profiles-4UQ1Hsds.js.map +0 -1
  101. package/dist/assets/registry-BKCFTEYp.js.map +0 -1
  102. package/dist/assets/resolve-MFeFljsN.js.map +0 -1
  103. package/dist/assets/server-rHKhnog1.js.map +0 -1
  104. package/dist/assets/src-BzsyAvPf.js.map +0 -1
  105. package/dist/assets/sshForges-qITn-RoV.js.map +0 -1
  106. package/dist/assets/translate-Bkr_iDgp.js.map +0 -1
  107. package/dist/assets/types-C4_KafL_.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bitcoind-CZchoh43.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/bitcoind.ts"],"sourcesContent":["import { base64, hex } from \"@scure/base\";\nimport { Address, OutScript, Transaction } from \"@scure/btc-signer\";\nimport type { WalletMode } from \"../../../shared/mints\";\nimport type { OnchainBalance, OnchainInfo, OnchainPrepared, OnchainProvider, OnchainSendRequest, OnchainTx, OnchainTxStatus } from \"./onchain\";\nimport { NothingSpentError, networkMode, type ProviderHost, type ProviderNetwork } from \"./types\";\n\nexport { bitcoindRpc, credentials } from \"./bitcoindProvider\";\n\n/**\n * On-chain Bitcoin from a wallet of the person's own Bitcoin Core node, over its JSON-RPC.\n *\n * bitcoind answers no CORS preflight, so a page cannot call it: this runs on Desktop only, where the\n * `bitcoind_rpc` Tauri command (apps/desktop/src/bitcoind_rpc.rs, reached through `ProviderHost.invoke`)\n * makes the call. That command forwards only the methods below, to the URL configured here, and says\n * whether a failed call could have reached the node (`kind`), which is what lets `broadcast` tell\n * \"nothing spent\" from \"unknown\".\n *\n * A payment: `walletcreatefundedpsbt` picks and locks the coins, `walletprocesspsbt` signs, `finalizepsbt`\n * finalizes, and the result is checked here (outputs, fee, txid) before it is shown for review. Nothing is\n * broadcast until approval (`sendrawtransaction`); a cancelled review unlocks the coins (`lockunspent`).\n */\n\nexport interface BitcoindCall {\n url: string;\n /** Empty: the node's default wallet. */\n wallet: string;\n user: string;\n password: string;\n method: string;\n params: unknown[];\n}\n/** Resolves with the JSON-RPC `result`; rejects with a `BitcoindRpcError`-shaped object. */\nexport type BitcoindTransport = (call: BitcoindCall) => Promise<unknown>;\n\n/** What the Tauri command rejects with. See `RpcError` in bitcoind_rpc.rs for what each `kind` proves. */\nexport interface BitcoindRpcFailure { kind: \"refused\" | \"connect\" | \"auth\" | \"rpc\" | \"transport\"; code?: number; message: string }\n\nexport class BitcoindRpcError extends Error {\n constructor(readonly kind: BitcoindRpcFailure[\"kind\"], message: string, readonly code?: number) { super(message); this.name = \"BitcoindRpcError\"; }\n /** The node never ran the call: it was not sent, could not connect, or the credentials were refused. */\n get neverRan() { return this.kind === \"refused\" || this.kind === \"connect\" || this.kind === \"auth\"; }\n}\n\n/** The Tauri command, through the Desktop host. */\nexport function tauriTransport(invoke: ProviderHost[\"invoke\"]): BitcoindTransport {\n if (!invoke) throw new Error(\"Bitcoin Core needs the Ghostly desktop app: a browser cannot reach its RPC\");\n return (call) => invoke(\"bitcoind_rpc\", { ...call });\n}\n\n/** Bitcoin Core's JSON-RPC error codes this module acts on (src/rpc/protocol.h). */\nconst RPC = { INVALID_ADDRESS_OR_KEY: -5, VERIFY_ERROR: -25, VERIFY_REJECTED: -26, VERIFY_ALREADY_IN_CHAIN: -27, DESERIALIZATION_ERROR: -22 } as const;\n\nconst CHAINS: Record<string, ProviderNetwork> = { main: \"bitcoin\", test: \"testnet\", testnet4: \"testnet\", signet: \"signet\", regtest: \"regtest\" };\n/** A fee rate for the test networks when the node has too few blocks to estimate one (regtest always). */\nconst TEST_FALLBACK_FEE_RATE = 2;\nconst TXID = /^[0-9a-f]{64}$/;\n/** Address encodings, for btc-signer to read the outputs back as addresses. */\nconst TESTNET_ENCODING = { bech32: \"tb\", pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef };\nconst BTC_NETWORKS: Record<ProviderNetwork, typeof TESTNET_ENCODING> = {\n bitcoin: { bech32: \"bc\", pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80 },\n testnet: TESTNET_ENCODING, signet: TESTNET_ENCODING, mutinynet: TESTNET_ENCODING,\n regtest: { ...TESTNET_ENCODING, bech32: \"bcrt\" },\n};\nconst TX_OPTS = { allowUnknownOutputs: true, allowUnknownInputs: true, disableScriptCheck: true, allowLegacyWitnessUtxo: true };\n\n/** Whole sats as the exact decimal string bitcoind reads as BTC (never a float). */\nexport const satsToBtc = (sats: number) => {\n if (!Number.isSafeInteger(sats) || sats < 0) throw new Error(\"Amounts are whole sats\");\n const digits = sats.toString().padStart(9, \"0\");\n return `${digits.slice(0, -8)}.${digits.slice(-8)}`;\n};\n/** A BTC amount from bitcoind (a JSON number with at most 8 decimals) as whole sats. */\nexport const btcToSats = (btc: unknown) => {\n if (typeof btc !== \"number\" || !Number.isFinite(btc)) throw new Error(\"The node returned an amount that is not a number\");\n return Math.round(btc * 1e8);\n};\n\nconst object = (value: unknown, what: string): Record<string, unknown> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(`The node returned no ${what}`);\n return value as Record<string, unknown>;\n};\nconst text = (value: unknown, what: string) => { if (typeof value !== \"string\" || !value) throw new Error(`The node returned no ${what}`); return value; };\n\ninterface Outpoint { txid: string; vout: number }\n\nexport interface BitcoindConfig { url: string; wallet: string; user: string; password: string }\n\nexport class BitcoindOnchain implements OnchainProvider {\n private closed = false;\n private network?: ProviderNetwork;\n\n constructor(private readonly config: BitcoindConfig, private readonly transport: BitcoindTransport) {}\n\n /** Connects and checks the wallet is there and the node is on a network of `mode`. */\n static async connect(config: BitcoindConfig, mode: WalletMode, transport: BitcoindTransport, signal?: AbortSignal): Promise<BitcoindOnchain> {\n const provider = new BitcoindOnchain(config, transport);\n signal?.addEventListener(\"abort\", () => void provider.close(), { once: true });\n const { network } = await provider.info();\n if (networkMode(network) !== mode) throw new Error(mode === \"mainnet\" ? `This node is on ${network}, not Bitcoin mainnet` : \"This node is on Bitcoin mainnet: set it up as a Mainnet wallet instead\");\n const wallet = object(await provider.call(\"getwalletinfo\"), \"wallet information\");\n if (wallet.private_keys_enabled === false) throw new Error(\"This wallet has no private keys: it cannot sign a payment\");\n return provider;\n }\n\n private async call(method: string, ...params: unknown[]): Promise<unknown> {\n if (this.closed) throw new BitcoindRpcError(\"refused\", \"This Bitcoin Core source is closed\");\n try {\n return await this.transport({ ...this.config, method, params });\n } catch (error) {\n if (error instanceof BitcoindRpcError) throw error;\n const failure = error as Partial<BitcoindRpcFailure> | null;\n if (failure && typeof failure === \"object\" && typeof failure.kind === \"string\" && typeof failure.message === \"string\") throw new BitcoindRpcError(failure.kind, failure.message, failure.code);\n // Something that is not the command's answer (no Tauri, a crash): nothing proves the node did not run it.\n throw new BitcoindRpcError(\"transport\", error instanceof Error ? error.message : String(error));\n }\n }\n\n async info(): Promise<OnchainInfo> {\n const chain = object(await this.call(\"getblockchaininfo\"), \"chain information\").chain;\n const network = typeof chain === \"string\" ? CHAINS[chain] : undefined;\n if (!network) throw new Error(`Ghostly does not know the chain \"${String(chain).slice(0, 20)}\"`);\n this.network = network;\n return { network, alias: this.config.wallet || \"Bitcoin Core\" };\n }\n\n async receiveAddress(): Promise<string> {\n return text(await this.call(\"getnewaddress\", \"Ghostly\"), \"address\");\n }\n\n async balance(): Promise<OnchainBalance> {\n const mine = object(object(await this.call(\"getbalances\"), \"balances\").mine, \"balances\");\n // `trusted` is spendable: confirmed coins plus the change of our own transactions.\n return { confirmed: btcToSats(mine.trusted), unconfirmed: btcToSats(mine.untrusted_pending) };\n }\n\n private async feeRate(request: OnchainSendRequest): Promise<number> {\n if (request.feeRate !== undefined) {\n if (!Number.isFinite(request.feeRate) || request.feeRate < 1 || request.feeRate > 10_000) throw new Error(\"The fee rate must be between 1 and 10,000 sat/vB\");\n return request.feeRate;\n }\n const estimate = object(await this.call(\"estimatesmartfee\", 6), \"fee estimate\");\n if (typeof estimate.feerate === \"number\" && estimate.feerate > 0) return Math.max(1, Math.ceil(estimate.feerate * 1e5 * 1000) / 1000);\n if ((this.network ?? (await this.info()).network) === \"bitcoin\") throw new Error(\"Your node cannot estimate a fee yet. Nothing was sent.\");\n return TEST_FALLBACK_FEE_RATE;\n }\n\n async prepareSend(request: OnchainSendRequest): Promise<OnchainPrepared> {\n if (!Number.isSafeInteger(request.amount) || request.amount <= 0) throw new Error(\"Amounts are whole sats\");\n const network = this.network ?? (await this.info()).network;\n const feeRate = await this.feeRate(request);\n const funded = object(await this.call(\"walletcreatefundedpsbt\", [], [{ [request.address]: satsToBtc(request.amount) }], 0, { fee_rate: feeRate, lockUnspents: true, replaceable: true }), \"funded transaction\");\n const inputs = this.outpoints(Transaction.fromPSBT(base64.decode(text(funded.psbt, \"funded transaction\")), TX_OPTS));\n try {\n const fee = btcToSats(funded.fee);\n if (fee > request.feeCap) throw new Error(`The fee (${fee} sats) is above your limit of ${request.feeCap}`);\n const signed = object(await this.call(\"walletprocesspsbt\", funded.psbt, true, \"ALL\"), \"signed transaction\");\n if (signed.complete !== true) throw new Error(\"The wallet could not sign this payment (is it locked, or watch-only?)\");\n const final = object(await this.call(\"finalizepsbt\", signed.psbt, false), \"finalized transaction\");\n if (final.complete !== true) throw new Error(\"The wallet could not finalize this payment\");\n return this.check(Transaction.fromPSBT(base64.decode(text(final.psbt, \"finalized transaction\")), TX_OPTS), request, inputs, feeRate, network);\n } catch (error) {\n // Nothing was broadcast: what the node locked for this payment goes back.\n await this.unlock(inputs).catch(() => {});\n throw error;\n }\n }\n\n /** The transaction the node signed is exactly the one asked for, before anyone reviews it. */\n private check(tx: Transaction, request: OnchainSendRequest, funded: Outpoint[], feeRate: number, network: ProviderNetwork): OnchainPrepared {\n const same = (a: Outpoint[], b: Outpoint[]) => a.length === b.length && a.every((o, i) => o.txid === b[i].txid && o.vout === b[i].vout);\n if (!same(this.outpoints(tx), funded)) throw new Error(\"The node signed other coins than it funded the payment with\");\n // Scripts, not address strings: a bech32 address is the same one in upper case (the QR form of a bitcoin: link).\n const script = (() => { try { return hex.encode(OutScript.encode(Address(BTC_NETWORKS[network]).decode(request.address))); } catch { return undefined; } })();\n let paid = 0;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n if (script !== undefined && output.script && hex.encode(output.script) === script) paid += Number(output.amount ?? 0n);\n }\n if (paid !== request.amount) throw new Error(\"The node built a transaction that does not pay the address and amount asked for\");\n const fee = Number(tx.fee);\n if (!Number.isSafeInteger(fee) || fee < 0 || fee > request.feeCap) throw new Error(`The fee (${fee} sats) is above your limit of ${request.feeCap}`);\n const txid = tx.id;\n if (!TXID.test(txid)) throw new Error(\"The node returned a transaction without a valid id\");\n return { txid, address: request.address, amount: request.amount, fee, feeRate, signed: hex.encode(tx.extract()) };\n }\n\n private outpoints(tx: Transaction): Outpoint[] {\n const out: Outpoint[] = [];\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (!input.txid || input.index === undefined) throw new Error(\"The node returned a transaction with an unreadable input\");\n out.push({ txid: hex.encode(input.txid), vout: input.index });\n }\n return out;\n }\n\n private async unlock(outpoints: Outpoint[]) {\n if (outpoints.length) await this.call(\"lockunspent\", true, outpoints);\n }\n\n private signedTx(prepared: OnchainPrepared) {\n if (!/^[0-9a-f]+$/.test(prepared.signed)) throw new Error(\"This prepared payment has no signed transaction\");\n const tx = Transaction.fromRaw(hex.decode(prepared.signed), TX_OPTS);\n if (tx.id !== prepared.txid) throw new Error(\"This prepared payment's transaction is not the one reviewed\");\n return tx;\n }\n\n async broadcast(prepared: OnchainPrepared): Promise<string> {\n const tx = this.signedTx(prepared);\n let txid: unknown;\n try {\n txid = await this.call(\"sendrawtransaction\", prepared.signed);\n } catch (error) {\n if (!(error instanceof BitcoindRpcError)) throw error;\n if (error.kind === \"rpc\" && error.code === RPC.VERIFY_ALREADY_IN_CHAIN) return prepared.txid;\n const rejected = error.kind === \"rpc\" && ([RPC.VERIFY_ERROR, RPC.VERIFY_REJECTED, RPC.DESERIALIZATION_ERROR] as number[]).includes(error.code ?? 0);\n if (!error.neverRan && !rejected) throw error; // A time-out, a cut connection: it may have gone out.\n // Refused, or never sent. The wallet learns of a transaction only once its node accepted it: if it has\n // never seen this one, nobody has, and nothing was spent. If it has (this is a re-broadcast of one that\n // went out before), other nodes may still hold it: the outcome stays unknown and its coins locked.\n const seen = rejected ? await this.known(prepared.txid) : await this.known(prepared.txid).catch(() => undefined);\n if (seen) {\n if ([\"mempool\", \"confirmed\"].includes((await this.status(prepared)).state)) return prepared.txid;\n throw error; // Not a NothingSpentError: an unknown outcome, reconciled by txid.\n }\n if (seen === false) await this.unlock(this.outpoints(tx)).catch(() => {});\n throw new NothingSpentError(`Your node did not send it: ${error.message}`);\n }\n if (txid !== prepared.txid) throw new Error(\"The node broadcast a different transaction than the one reviewed\");\n return prepared.txid;\n }\n\n /** Whether the wallet knows this transaction (it does once its node accepted it, even if it was dropped since). */\n private async known(txid: string): Promise<boolean> {\n try { await this.call(\"gettransaction\", txid); return true; }\n catch (error) { if (error instanceof BitcoindRpcError && error.kind === \"rpc\" && error.code === RPC.INVALID_ADDRESS_OR_KEY) return false; throw error; }\n }\n\n async status(prepared: OnchainPrepared): Promise<OnchainTxStatus> {\n if (!TXID.test(prepared.txid)) throw new Error(\"Not a transaction id\");\n let tx: Record<string, unknown>;\n try {\n tx = object(await this.call(\"gettransaction\", prepared.txid), \"transaction\");\n } catch (error) {\n if (error instanceof BitcoindRpcError && error.kind === \"rpc\" && error.code === RPC.INVALID_ADDRESS_OR_KEY) return { state: \"missing\", confirmations: 0 };\n throw error;\n }\n const confirmations = typeof tx.confirmations === \"number\" ? tx.confirmations : 0;\n if (confirmations > 0) return { state: \"confirmed\", confirmations };\n // Negative: a transaction in a block spent the same coins.\n if (confirmations < 0) return { state: \"conflicted\", confirmations: 0 };\n if (Array.isArray(tx.mempoolconflicts) && tx.mempoolconflicts.length > 0) return { state: \"conflicted\", confirmations: 0 };\n try {\n await this.call(\"getmempoolentry\", prepared.txid);\n return { state: \"mempool\", confirmations: 0 };\n } catch (error) {\n if (error instanceof BitcoindRpcError && error.kind === \"rpc\" && error.code === RPC.INVALID_ADDRESS_OR_KEY) return { state: \"missing\", confirmations: 0 };\n throw error;\n }\n }\n\n async release(prepared: OnchainPrepared): Promise<void> {\n await this.unlock(this.outpoints(this.signedTx(prepared)));\n }\n\n async history(limit: number): Promise<OnchainTx[]> {\n const count = Math.max(1, Math.min(200, Math.floor(limit) * 3));\n const entries = await this.call(\"listtransactions\", \"*\", count, 0, true);\n if (!Array.isArray(entries)) throw new Error(\"The node returned no transaction list\");\n const byTxid = new Map<string, OnchainTx>();\n // Oldest first: one entry per output of ours, so a payment with change or to ourselves has several.\n for (const raw of entries as Record<string, unknown>[]) {\n if (!raw || typeof raw.txid !== \"string\" || !TXID.test(raw.txid) || raw.category === \"orphan\") continue;\n const tx = byTxid.get(raw.txid) ?? { txid: raw.txid, amount: 0, confirmations: typeof raw.confirmations === \"number\" ? Math.max(0, raw.confirmations) : 0 };\n tx.amount += btcToSats(raw.amount);\n if (raw.category === \"send\" && typeof raw.fee === \"number\" && tx.fee === undefined) tx.fee = Math.abs(btcToSats(raw.fee));\n if (typeof raw.time === \"number\") tx.timestamp = raw.time * 1000;\n byTxid.delete(raw.txid);\n byTxid.set(raw.txid, tx);\n }\n return [...byTxid.values()].reverse().slice(0, Math.max(0, limit));\n }\n\n /** The wallet's receives on this address, newest first: only `receive` entries paying exactly it count. */\n async received(address: string): Promise<OnchainTx[]> {\n const entries = await this.call(\"listtransactions\", \"*\", 200, 0, true);\n if (!Array.isArray(entries)) throw new Error(\"The node returned no transaction list\");\n const byTxid = new Map<string, OnchainTx>();\n for (const raw of entries as Record<string, unknown>[]) {\n if (!raw || raw.category !== \"receive\" || raw.address !== address || typeof raw.txid !== \"string\" || !TXID.test(raw.txid)) continue;\n const tx = byTxid.get(raw.txid) ?? { txid: raw.txid, amount: 0, confirmations: typeof raw.confirmations === \"number\" ? Math.max(0, raw.confirmations) : 0 };\n tx.amount += btcToSats(raw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GAAG,YAAY,IAAI,OAAO;GAC5D,OAAO,OAAO,IAAI,IAAI;GACtB,OAAO,IAAI,IAAI,MAAM,EAAE;EACzB;EACA,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,GAAG,KAAK,IAAI,GAAG,KAAK,CAAC;CACnE;;CAGA,MAAM,SAAS,SAAuC;EACpD,MAAM,UAAU,MAAM,KAAK,KAAK,oBAAoB,KAAK,KAAK,GAAG,IAAI;EACrE,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,MAAM,IAAI,MAAM,uCAAuC;EACpF,MAAM,yBAAS,IAAI,IAAuB;EAC1C,KAAK,MAAM,OAAO,SAAsC;GACtD,IAAI,CAAC,OAAO,IAAI,aAAa,aAAa,IAAI,YAAY,WAAW,OAAO,IAAI,SAAS,YAAY,CAAC,KAAK,KAAK,IAAI,IAAI,GAAG;GAC3H,MAAM,KAAK,OAAO,IAAI,IAAI,IAAI,KAAK;IAAE,MAAM,IAAI;IAAM,QAAQ;IAAG,eAAe,OAAO,IAAI,kBAAkB,WAAW,KAAK,IAAI,GAAG,IAAI,aAAa,IAAI;GAAE;GAC1J,GAAG,UAAU,UAAU,IAAI,MAAM;GACjC,OAAO,OAAO,IAAI,IAAI;GACtB,OAAO,IAAI,IAAI,MAAM,EAAE;EACzB;EACA,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC,CAAC,CAAC,QAAQ;CACtC;CAEA,MAAM,QAAuB;EAAE,KAAK,SAAS;CAAM;AACrD"}
1
+ {"version":3,"file":"bitcoind-CdSmvy2y.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/bitcoind.ts"],"sourcesContent":["import { base64, hex } from \"@scure/base\";\nimport { Address, OutScript, Transaction } from \"@scure/btc-signer\";\nimport type { WalletMode } from \"../../../shared/mints\";\nimport type { OnchainBalance, OnchainInfo, OnchainPrepared, OnchainProvider, OnchainSendRequest, OnchainTx, OnchainTxStatus } from \"./onchain\";\nimport { NothingSpentError, networkMode, type ProviderHost, type ProviderNetwork } from \"./types\";\n\nexport { bitcoindRpc, credentials } from \"./bitcoindProvider\";\n\n/**\n * On-chain Bitcoin from a wallet of the person's own Bitcoin Core node, over its JSON-RPC.\n *\n * bitcoind answers no CORS preflight, so a page cannot call it: this runs on Desktop only, where the\n * `bitcoind_rpc` Tauri command (apps/desktop/src/bitcoind_rpc.rs, reached through `ProviderHost.invoke`)\n * makes the call. That command forwards only the methods below, to the URL configured here, and says\n * whether a failed call could have reached the node (`kind`), which is what lets `broadcast` tell\n * \"nothing spent\" from \"unknown\".\n *\n * A payment: `walletcreatefundedpsbt` picks and locks the coins, `walletprocesspsbt` signs, `finalizepsbt`\n * finalizes, and the result is checked here (outputs, fee, txid) before it is shown for review. Nothing is\n * broadcast until approval (`sendrawtransaction`); a cancelled review unlocks the coins (`lockunspent`).\n */\n\nexport interface BitcoindCall {\n url: string;\n /** Empty: the node's default wallet. */\n wallet: string;\n user: string;\n password: string;\n method: string;\n params: unknown[];\n}\n/** Resolves with the JSON-RPC `result`; rejects with a `BitcoindRpcError`-shaped object. */\nexport type BitcoindTransport = (call: BitcoindCall) => Promise<unknown>;\n\n/** What the Tauri command rejects with. See `RpcError` in bitcoind_rpc.rs for what each `kind` proves. */\nexport interface BitcoindRpcFailure { kind: \"refused\" | \"connect\" | \"auth\" | \"rpc\" | \"transport\"; code?: number; message: string }\n\nexport class BitcoindRpcError extends Error {\n constructor(readonly kind: BitcoindRpcFailure[\"kind\"], message: string, readonly code?: number) { super(message); this.name = \"BitcoindRpcError\"; }\n /** The node never ran the call: it was not sent, could not connect, or the credentials were refused. */\n get neverRan() { return this.kind === \"refused\" || this.kind === \"connect\" || this.kind === \"auth\"; }\n}\n\n/** The Tauri command, through the Desktop host. */\nexport function tauriTransport(invoke: ProviderHost[\"invoke\"]): BitcoindTransport {\n if (!invoke) throw new Error(\"Bitcoin Core needs the Ghostly desktop app: a browser cannot reach its RPC\");\n return (call) => invoke(\"bitcoind_rpc\", { ...call });\n}\n\n/** Bitcoin Core's JSON-RPC error codes this module acts on (src/rpc/protocol.h). */\nconst RPC = { INVALID_ADDRESS_OR_KEY: -5, VERIFY_ERROR: -25, VERIFY_REJECTED: -26, VERIFY_ALREADY_IN_CHAIN: -27, DESERIALIZATION_ERROR: -22 } as const;\n\nconst CHAINS: Record<string, ProviderNetwork> = { main: \"bitcoin\", test: \"testnet\", testnet4: \"testnet\", signet: \"signet\", regtest: \"regtest\" };\n/** A fee rate for the test networks when the node has too few blocks to estimate one (regtest always). */\nconst TEST_FALLBACK_FEE_RATE = 2;\nconst TXID = /^[0-9a-f]{64}$/;\n/** Address encodings, for btc-signer to read the outputs back as addresses. */\nconst TESTNET_ENCODING = { bech32: \"tb\", pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef };\nconst BTC_NETWORKS: Record<ProviderNetwork, typeof TESTNET_ENCODING> = {\n bitcoin: { bech32: \"bc\", pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80 },\n testnet: TESTNET_ENCODING, signet: TESTNET_ENCODING, mutinynet: TESTNET_ENCODING,\n regtest: { ...TESTNET_ENCODING, bech32: \"bcrt\" },\n};\nconst TX_OPTS = { allowUnknownOutputs: true, allowUnknownInputs: true, disableScriptCheck: true, allowLegacyWitnessUtxo: true };\n\n/** Whole sats as the exact decimal string bitcoind reads as BTC (never a float). */\nexport const satsToBtc = (sats: number) => {\n if (!Number.isSafeInteger(sats) || sats < 0) throw new Error(\"Amounts are whole sats\");\n const digits = sats.toString().padStart(9, \"0\");\n return `${digits.slice(0, -8)}.${digits.slice(-8)}`;\n};\n/** A BTC amount from bitcoind (a JSON number with at most 8 decimals) as whole sats. */\nexport const btcToSats = (btc: unknown) => {\n if (typeof btc !== \"number\" || !Number.isFinite(btc)) throw new Error(\"The node returned an amount that is not a number\");\n return Math.round(btc * 1e8);\n};\n\nconst object = (value: unknown, what: string): Record<string, unknown> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(`The node returned no ${what}`);\n return value as Record<string, unknown>;\n};\nconst text = (value: unknown, what: string) => { if (typeof value !== \"string\" || !value) throw new Error(`The node returned no ${what}`); return value; };\n\ninterface Outpoint { txid: string; vout: number }\n\nexport interface BitcoindConfig { url: string; wallet: string; user: string; password: string }\n\nexport class BitcoindOnchain implements OnchainProvider {\n private closed = false;\n private network?: ProviderNetwork;\n\n constructor(private readonly config: BitcoindConfig, private readonly transport: BitcoindTransport) {}\n\n /** Connects and checks the wallet is there and the node is on a network of `mode`. */\n static async connect(config: BitcoindConfig, mode: WalletMode, transport: BitcoindTransport, signal?: AbortSignal): Promise<BitcoindOnchain> {\n const provider = new BitcoindOnchain(config, transport);\n signal?.addEventListener(\"abort\", () => void provider.close(), { once: true });\n const { network } = await provider.info();\n if (networkMode(network) !== mode) throw new Error(mode === \"mainnet\" ? `This node is on ${network}, not Bitcoin mainnet` : \"This node is on Bitcoin mainnet: set it up as a Mainnet wallet instead\");\n const wallet = object(await provider.call(\"getwalletinfo\"), \"wallet information\");\n if (wallet.private_keys_enabled === false) throw new Error(\"This wallet has no private keys: it cannot sign a payment\");\n return provider;\n }\n\n private async call(method: string, ...params: unknown[]): Promise<unknown> {\n if (this.closed) throw new BitcoindRpcError(\"refused\", \"This Bitcoin Core source is closed\");\n try {\n return await this.transport({ ...this.config, method, params });\n } catch (error) {\n if (error instanceof BitcoindRpcError) throw error;\n const failure = error as Partial<BitcoindRpcFailure> | null;\n if (failure && typeof failure === \"object\" && typeof failure.kind === \"string\" && typeof failure.message === \"string\") throw new BitcoindRpcError(failure.kind, failure.message, failure.code);\n // Something that is not the command's answer (no Tauri, a crash): nothing proves the node did not run it.\n throw new BitcoindRpcError(\"transport\", error instanceof Error ? error.message : String(error));\n }\n }\n\n async info(): Promise<OnchainInfo> {\n const chain = object(await this.call(\"getblockchaininfo\"), \"chain information\").chain;\n const network = typeof chain === \"string\" ? CHAINS[chain] : undefined;\n if (!network) throw new Error(`Ghostly does not know the chain \"${String(chain).slice(0, 20)}\"`);\n this.network = network;\n return { network, alias: this.config.wallet || \"Bitcoin Core\" };\n }\n\n async receiveAddress(): Promise<string> {\n return text(await this.call(\"getnewaddress\", \"Ghostly\"), \"address\");\n }\n\n async balance(): Promise<OnchainBalance> {\n const mine = object(object(await this.call(\"getbalances\"), \"balances\").mine, \"balances\");\n // `trusted` is spendable: confirmed coins plus the change of our own transactions.\n return { confirmed: btcToSats(mine.trusted), unconfirmed: btcToSats(mine.untrusted_pending) };\n }\n\n private async feeRate(request: OnchainSendRequest): Promise<number> {\n if (request.feeRate !== undefined) {\n if (!Number.isFinite(request.feeRate) || request.feeRate < 1 || request.feeRate > 10_000) throw new Error(\"The fee rate must be between 1 and 10,000 sat/vB\");\n return request.feeRate;\n }\n const estimate = object(await this.call(\"estimatesmartfee\", 6), \"fee estimate\");\n if (typeof estimate.feerate === \"number\" && estimate.feerate > 0) return Math.max(1, Math.ceil(estimate.feerate * 1e5 * 1000) / 1000);\n if ((this.network ?? (await this.info()).network) === \"bitcoin\") throw new Error(\"Your node cannot estimate a fee yet. Nothing was sent.\");\n return TEST_FALLBACK_FEE_RATE;\n }\n\n async prepareSend(request: OnchainSendRequest): Promise<OnchainPrepared> {\n if (!Number.isSafeInteger(request.amount) || request.amount <= 0) throw new Error(\"Amounts are whole sats\");\n const network = this.network ?? (await this.info()).network;\n const feeRate = await this.feeRate(request);\n const funded = object(await this.call(\"walletcreatefundedpsbt\", [], [{ [request.address]: satsToBtc(request.amount) }], 0, { fee_rate: feeRate, lockUnspents: true, replaceable: true }), \"funded transaction\");\n const inputs = this.outpoints(Transaction.fromPSBT(base64.decode(text(funded.psbt, \"funded transaction\")), TX_OPTS));\n try {\n const fee = btcToSats(funded.fee);\n if (fee > request.feeCap) throw new Error(`The fee (${fee} sats) is above your limit of ${request.feeCap}`);\n const signed = object(await this.call(\"walletprocesspsbt\", funded.psbt, true, \"ALL\"), \"signed transaction\");\n if (signed.complete !== true) throw new Error(\"The wallet could not sign this payment (is it locked, or watch-only?)\");\n const final = object(await this.call(\"finalizepsbt\", signed.psbt, false), \"finalized transaction\");\n if (final.complete !== true) throw new Error(\"The wallet could not finalize this payment\");\n return this.check(Transaction.fromPSBT(base64.decode(text(final.psbt, \"finalized transaction\")), TX_OPTS), request, inputs, feeRate, network);\n } catch (error) {\n // Nothing was broadcast: what the node locked for this payment goes back.\n await this.unlock(inputs).catch(() => {});\n throw error;\n }\n }\n\n /** The transaction the node signed is exactly the one asked for, before anyone reviews it. */\n private check(tx: Transaction, request: OnchainSendRequest, funded: Outpoint[], feeRate: number, network: ProviderNetwork): OnchainPrepared {\n const same = (a: Outpoint[], b: Outpoint[]) => a.length === b.length && a.every((o, i) => o.txid === b[i].txid && o.vout === b[i].vout);\n if (!same(this.outpoints(tx), funded)) throw new Error(\"The node signed other coins than it funded the payment with\");\n // Scripts, not address strings: a bech32 address is the same one in upper case (the QR form of a bitcoin: link).\n const script = (() => { try { return hex.encode(OutScript.encode(Address(BTC_NETWORKS[network]).decode(request.address))); } catch { return undefined; } })();\n let paid = 0;\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n if (script !== undefined && output.script && hex.encode(output.script) === script) paid += Number(output.amount ?? 0n);\n }\n if (paid !== request.amount) throw new Error(\"The node built a transaction that does not pay the address and amount asked for\");\n const fee = Number(tx.fee);\n if (!Number.isSafeInteger(fee) || fee < 0 || fee > request.feeCap) throw new Error(`The fee (${fee} sats) is above your limit of ${request.feeCap}`);\n const txid = tx.id;\n if (!TXID.test(txid)) throw new Error(\"The node returned a transaction without a valid id\");\n return { txid, address: request.address, amount: request.amount, fee, feeRate, signed: hex.encode(tx.extract()) };\n }\n\n private outpoints(tx: Transaction): Outpoint[] {\n const out: Outpoint[] = [];\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n if (!input.txid || input.index === undefined) throw new Error(\"The node returned a transaction with an unreadable input\");\n out.push({ txid: hex.encode(input.txid), vout: input.index });\n }\n return out;\n }\n\n private async unlock(outpoints: Outpoint[]) {\n if (outpoints.length) await this.call(\"lockunspent\", true, outpoints);\n }\n\n private signedTx(prepared: OnchainPrepared) {\n if (!/^[0-9a-f]+$/.test(prepared.signed)) throw new Error(\"This prepared payment has no signed transaction\");\n const tx = Transaction.fromRaw(hex.decode(prepared.signed), TX_OPTS);\n if (tx.id !== prepared.txid) throw new Error(\"This prepared payment's transaction is not the one reviewed\");\n return tx;\n }\n\n async broadcast(prepared: OnchainPrepared): Promise<string> {\n const tx = this.signedTx(prepared);\n let txid: unknown;\n try {\n txid = await this.call(\"sendrawtransaction\", prepared.signed);\n } catch (error) {\n if (!(error instanceof BitcoindRpcError)) throw error;\n if (error.kind === \"rpc\" && error.code === RPC.VERIFY_ALREADY_IN_CHAIN) return prepared.txid;\n const rejected = error.kind === \"rpc\" && ([RPC.VERIFY_ERROR, RPC.VERIFY_REJECTED, RPC.DESERIALIZATION_ERROR] as number[]).includes(error.code ?? 0);\n if (!error.neverRan && !rejected) throw error; // A time-out, a cut connection: it may have gone out.\n // Refused, or never sent. The wallet learns of a transaction only once its node accepted it: if it has\n // never seen this one, nobody has, and nothing was spent. If it has (this is a re-broadcast of one that\n // went out before), other nodes may still hold it: the outcome stays unknown and its coins locked.\n const seen = rejected ? await this.known(prepared.txid) : await this.known(prepared.txid).catch(() => undefined);\n if (seen) {\n if ([\"mempool\", \"confirmed\"].includes((await this.status(prepared)).state)) return prepared.txid;\n throw error; // Not a NothingSpentError: an unknown outcome, reconciled by txid.\n }\n if (seen === false) await this.unlock(this.outpoints(tx)).catch(() => {});\n throw new NothingSpentError(`Your node did not send it: ${error.message}`);\n }\n if (txid !== prepared.txid) throw new Error(\"The node broadcast a different transaction than the one reviewed\");\n return prepared.txid;\n }\n\n /** Whether the wallet knows this transaction (it does once its node accepted it, even if it was dropped since). */\n private async known(txid: string): Promise<boolean> {\n try { await this.call(\"gettransaction\", txid); return true; }\n catch (error) { if (error instanceof BitcoindRpcError && error.kind === \"rpc\" && error.code === RPC.INVALID_ADDRESS_OR_KEY) return false; throw error; }\n }\n\n async status(prepared: OnchainPrepared): Promise<OnchainTxStatus> {\n if (!TXID.test(prepared.txid)) throw new Error(\"Not a transaction id\");\n let tx: Record<string, unknown>;\n try {\n tx = object(await this.call(\"gettransaction\", prepared.txid), \"transaction\");\n } catch (error) {\n if (error instanceof BitcoindRpcError && error.kind === \"rpc\" && error.code === RPC.INVALID_ADDRESS_OR_KEY) return { state: \"missing\", confirmations: 0 };\n throw error;\n }\n const confirmations = typeof tx.confirmations === \"number\" ? tx.confirmations : 0;\n if (confirmations > 0) return { state: \"confirmed\", confirmations };\n // Negative: a transaction in a block spent the same coins.\n if (confirmations < 0) return { state: \"conflicted\", confirmations: 0 };\n if (Array.isArray(tx.mempoolconflicts) && tx.mempoolconflicts.length > 0) return { state: \"conflicted\", confirmations: 0 };\n try {\n await this.call(\"getmempoolentry\", prepared.txid);\n return { state: \"mempool\", confirmations: 0 };\n } catch (error) {\n if (error instanceof BitcoindRpcError && error.kind === \"rpc\" && error.code === RPC.INVALID_ADDRESS_OR_KEY) return { state: \"missing\", confirmations: 0 };\n throw error;\n }\n }\n\n async release(prepared: OnchainPrepared): Promise<void> {\n await this.unlock(this.outpoints(this.signedTx(prepared)));\n }\n\n async history(limit: number): Promise<OnchainTx[]> {\n const count = Math.max(1, Math.min(200, Math.floor(limit) * 3));\n const entries = await this.call(\"listtransactions\", \"*\", count, 0, true);\n if (!Array.isArray(entries)) throw new Error(\"The node returned no transaction list\");\n const byTxid = new Map<string, OnchainTx>();\n // Oldest first: one entry per output of ours, so a payment with change or to ourselves has several.\n for (const raw of entries as Record<string, unknown>[]) {\n if (!raw || typeof raw.txid !== \"string\" || !TXID.test(raw.txid) || raw.category === \"orphan\") continue;\n const tx = byTxid.get(raw.txid) ?? { txid: raw.txid, amount: 0, confirmations: typeof raw.confirmations === \"number\" ? Math.max(0, raw.confirmations) : 0 };\n tx.amount += btcToSats(raw.amount);\n if (raw.category === \"send\" && typeof raw.fee === \"number\" && tx.fee === undefined) tx.fee = Math.abs(btcToSats(raw.fee));\n if (typeof raw.time === \"number\") tx.timestamp = raw.time * 1000;\n byTxid.delete(raw.txid);\n byTxid.set(raw.txid, tx);\n }\n return [...byTxid.values()].reverse().slice(0, Math.max(0, limit));\n }\n\n /** The wallet's receives on this address, newest first: only `receive` entries paying exactly it count. */\n async received(address: string): Promise<OnchainTx[]> {\n const entries = await this.call(\"listtransactions\", \"*\", 200, 0, true);\n if (!Array.isArray(entries)) throw new Error(\"The node returned no transaction list\");\n const byTxid = new Map<string, OnchainTx>();\n for (const raw of entries as Record<string, unknown>[]) {\n if (!raw || raw.category !== \"receive\" || raw.address !== address || typeof raw.txid !== \"string\" || !TXID.test(raw.txid)) continue;\n const tx = byTxid.get(raw.txid) ?? { txid: raw.txid, amount: 0, confirmations: typeof raw.confirmations === \"number\" ? Math.max(0, raw.confirmations) : 0 };\n tx.amount += btcToSats(raw.amount);\n byTxid.delete(raw.txid);\n byTxid.set(raw.txid, tx);\n }\n return [...byTxid.values()].reverse();\n }\n\n async close(): Promise<void> { this.closed = true; }\n}\n"],"mappings":";;;;;AAqCA,IAAa,mBAAb,cAAsC,MAAM;CACrB;CAA4D;CAAjF,YAAY,MAA2C,SAAiB,MAAwB;EAAE,MAAM,OAAO;EAA1F,KAAA,OAAA;EAA4D,KAAA,OAAA;EAAiC,KAAK,OAAO;CAAoB;;CAElJ,IAAI,WAAW;EAAE,OAAO,KAAK,SAAS,aAAa,KAAK,SAAS,aAAa,KAAK,SAAS;CAAQ;AACtG;;AAGA,SAAgB,eAAe,QAAmD;CAChF,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,4EAA4E;CACzG,QAAQ,SAAS,OAAO,gBAAgB,EAAE,GAAG,KAAK,CAAC;AACrD;;AAGA,IAAM,MAAM;CAAE,wBAAwB;CAAI,cAAc;CAAK,iBAAiB;CAAK,yBAAyB;CAAK,uBAAuB;AAAI;AAE5I,IAAM,SAA0C;CAAE,MAAM;CA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,eAAe,OAAO,IAAI,kBAAkB,WAAW,KAAK,IAAI,GAAG,IAAI,aAAa,IAAI;GAAE;GAC1J,GAAG,UAAU,UAAU,IAAI,MAAM;GACjC,OAAO,OAAO,IAAI,IAAI;GACtB,OAAO,IAAI,IAAI,MAAM,EAAE;EACzB;EACA,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC,CAAC,CAAC,QAAQ;CACtC;CAEA,MAAM,QAAuB;EAAE,KAAK,SAAS;CAAM;AACrD"}
@@ -83,7 +83,7 @@ var bitcoindRpc = {
83
83
  if (!user || !password) throw new Error("Enter the RPC user and password, or paste the .cookie file");
84
84
  },
85
85
  async create(settings, host) {
86
- const { BitcoindOnchain, tauriTransport } = await import("./bitcoind-CZchoh43.js");
86
+ const { BitcoindOnchain, tauriTransport } = await import("./bitcoind-CdSmvy2y.js");
87
87
  return BitcoindOnchain.connect({
88
88
  url: settings.config.url.trim(),
89
89
  wallet: settings.config.wallet?.trim() ?? "",
@@ -94,4 +94,4 @@ var bitcoindRpc = {
94
94
  //#endregion
95
95
  export { credentials as n, bitcoindRpc as t };
96
96
 
97
- //# sourceMappingURL=bitcoindProvider-DGw3xBSa.js.map
97
+ //# sourceMappingURL=bitcoindProvider-BvoRh0D5.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bitcoindProvider-DGw3xBSa.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/bitcoindProvider.ts"],"sourcesContent":["import type { OnchainProviderDescriptor } from \"./onchain\";\nimport type { ProviderSettings } from \"./types\";\n\n/**\n * Bitcoin Core as the source picker lists it, and its settings. The client (`./bitcoind`) and btc-signer's\n * transaction code load when a wallet connects, not with the app.\n */\n\nconst WALLET_NAME = /^[A-Za-z0-9._-]{0,64}$/;\n\n/** `user:password` in the password field (the .cookie file's contents) when no user is given. */\nexport function credentials({ config, secrets }: ProviderSettings) {\n const password = secrets.password ?? \"\";\n const user = config.user?.trim() ?? \"\";\n if (!user && password.includes(\":\")) {\n const at = password.indexOf(\":\");\n return { user: password.slice(0, at), password: password.slice(at + 1) };\n }\n return { user, password };\n}\n\nexport const bitcoindRpc: OnchainProviderDescriptor = {\n id: \"bitcoind\",\n label: \"Bitcoin Core\",\n kind: \"onchain\",\n description: \"A wallet on your own Bitcoin Core node, over its RPC. Your node holds the keys and signs. Needs the desktop app.\",\n networks: [\"bitcoin\", \"testnet\", \"signet\", \"regtest\"],\n platforms: [\"desktop\"],\n experimental: true,\n fields: [\n { name: \"url\", label: \"RPC address\", kind: \"url\", placeholder: \"http://127.0.0.1:8332\", defaults: { mainnet: \"http://127.0.0.1:8332\", testnet: \"http://127.0.0.1:38332\" },\n help: \"Your node's rpcbind and rpcport: 8332 mainnet, 38332 signet, 48332 testnet4, 18443 regtest.\" },\n { name: \"wallet\", label: \"Wallet name\", kind: \"text\", optional: true, placeholder: \"ghostly\", help: \"A wallet loaded in the node (bitcoin-cli listwallets). Empty: its default wallet.\" },\n { name: \"user\", label: \"RPC user\", kind: \"text\", optional: true, help: \"Leave empty to paste the .cookie file below.\" },\n { name: \"password\", label: \"RPC password or cookie\", kind: \"secret\", help: \"rpcpassword, or the contents of the node's .cookie file (it changes when bitcoind restarts).\" },\n ],\n validate(settings) {\n const url = (() => { try { return new URL(settings.config.url?.trim() ?? \"\"); } catch { return undefined; } })();\n if (!url || ![\"http:\", \"https:\"].includes(url.protocol)) throw new Error(\"Enter the node's RPC address, like http://127.0.0.1:8332\");\n if (url.username || url.password) throw new Error(\"Put the RPC user and password in their own fields, not in the address\");\n if (url.search || url.hash) throw new Error(\"The RPC address cannot have a query or fragment\");\n if (!WALLET_NAME.test(settings.config.wallet?.trim() ?? \"\") || [\".\", \"..\"].includes(settings.config.wallet?.trim() ?? \"\")) throw new Error(\"A wallet name has only letters, digits, '-', '_' and '.'\");\n const { user, password } = credentials(settings);\n if (!user || !password) throw new Error(\"Enter the RPC user and password, or paste the .cookie file\");\n },\n async create(settings, host) {\n const { BitcoindOnchain, tauriTransport } = await import(\"./bitcoind\");\n return BitcoindOnchain.connect({ url: settings.config.url.trim(), wallet: settings.config.wallet?.trim() ?? \"\", ...credentials(settings) }, host.mode, tauriTransport(host.invoke), host.signal);\n },\n};\n"],"mappings":";;;;;AAQA,IAAM,cAAc;;AAGpB,SAAgB,YAAY,EAAE,QAAQ,WAA6B;CACjE,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,OAAO,OAAO,MAAM,KAAK,KAAK;CACpC,IAAI,CAAC,QAAQ,SAAS,SAAS,GAAG,GAAG;EACnC,MAAM,KAAK,SAAS,QAAQ,GAAG;EAC/B,OAAO;GAAE,MAAM,SAAS,MAAM,GAAG,EAAE;GAAG,UAAU,SAAS,MAAM,KAAK,CAAC;EAAE;CACzE;CACA,OAAO;EAAE;EAAM;CAAS;AAC1B;AAEA,IAAa,cAAyC;CACpD,IAAI;CACJ,OAAO;CACP,MAAM;CACN,aAAa;CACb,UAAU;EAAC;EAAW;EAAW;EAAU;CAAS;CACpD,WAAW,CAAC,SAAS;CACrB,cAAc;CACd,QAAQ;EACN;GAAE,MAAM;GAAO,OAAO;GAAe,MAAM;GAAO,aAAa;GAAyB,UAAU;IAAE,SAAS;IAAyB,SAAS;GAAyB;GACtK,MAAM;EAA8F;EACtG;GAAE,MAAM;GAAU,OAAO;GAAe,MAAM;GAAQ,UAAU;GAAM,aAAa;GAAW,MAAM;EAAoF;EACxL;GAAE,MAAM;GAAQ,OAAO;GAAY,MAAM;GAAQ,UAAU;GAAM,MAAM;EAA+C;EACtH;GAAE,MAAM;GAAY,OAAO;GAA0B,MAAM;GAAU,MAAM;EAA+F;CAC5K;CACA,SAAS,UAAU;EACjB,MAAM,aAAa;GAAE,IAAI;IAAE,OAAO,IAAI,IAAI,SAAS,OAAO,KAAK,KAAK,KAAK,EAAE;GAAG,QAAQ;IAAE;GAAkB;EAAE,EAAA,CAAG;EAC/G,IAAI,CAAC,OAAO,CAAC,CAAC,SAAS,QAAQ,CAAC,CAAC,SAAS,IAAI,QAAQ,GAAG,MAAM,IAAI,MAAM,0DAA0D;EACnI,IAAI,IAAI,YAAY,IAAI,UAAU,MAAM,IAAI,MAAM,uEAAuE;EACzH,IAAI,IAAI,UAAU,IAAI,MAAM,MAAM,IAAI,MAAM,iDAAiD;EAC7F,IAAI,CAAC,YAAY,KAAK,SAAS,OAAO,QAAQ,KAAK,KAAK,EAAE,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC,SAAS,SAAS,OAAO,QAAQ,KAAK,KAAK,EAAE,GAAG,MAAM,IAAI,MAAM,0DAA0D;EACrM,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ;EAC/C,IAAI,CAAC,QAAQ,CAAC,UAAU,MAAM,IAAI,MAAM,4DAA4D;CACtG;CACA,MAAM,OAAO,UAAU,MAAM;EAC3B,MAAM,EAAE,iBAAiB,mBAAmB,MAAM,OAAO;EACzD,OAAO,gBAAgB,QAAQ;GAAE,KAAK,SAAS,OAAO,IAAI,KAAK;GAAG,QAAQ,SAAS,OAAO,QAAQ,KAAK,KAAK;GAAI,GAAG,YAAY,QAAQ;EAAE,GAAG,KAAK,MAAM,eAAe,KAAK,MAAM,GAAG,KAAK,MAAM;CACjM;AACF"}
1
+ {"version":3,"file":"bitcoindProvider-BvoRh0D5.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/bitcoindProvider.ts"],"sourcesContent":["import type { OnchainProviderDescriptor } from \"./onchain\";\nimport type { ProviderSettings } from \"./types\";\n\n/**\n * Bitcoin Core as the source picker lists it, and its settings. The client (`./bitcoind`) and btc-signer's\n * transaction code load when a wallet connects, not with the app.\n */\n\nconst WALLET_NAME = /^[A-Za-z0-9._-]{0,64}$/;\n\n/** `user:password` in the password field (the .cookie file's contents) when no user is given. */\nexport function credentials({ config, secrets }: ProviderSettings) {\n const password = secrets.password ?? \"\";\n const user = config.user?.trim() ?? \"\";\n if (!user && password.includes(\":\")) {\n const at = password.indexOf(\":\");\n return { user: password.slice(0, at), password: password.slice(at + 1) };\n }\n return { user, password };\n}\n\nexport const bitcoindRpc: OnchainProviderDescriptor = {\n id: \"bitcoind\",\n label: \"Bitcoin Core\",\n kind: \"onchain\",\n description: \"A wallet on your own Bitcoin Core node, over its RPC. Your node holds the keys and signs. Needs the desktop app.\",\n networks: [\"bitcoin\", \"testnet\", \"signet\", \"regtest\"],\n platforms: [\"desktop\"],\n experimental: true,\n fields: [\n { name: \"url\", label: \"RPC address\", kind: \"url\", placeholder: \"http://127.0.0.1:8332\", defaults: { mainnet: \"http://127.0.0.1:8332\", testnet: \"http://127.0.0.1:38332\" },\n help: \"Your node's rpcbind and rpcport: 8332 mainnet, 38332 signet, 48332 testnet4, 18443 regtest.\" },\n { name: \"wallet\", label: \"Wallet name\", kind: \"text\", optional: true, placeholder: \"ghostly\", help: \"A wallet loaded in the node (bitcoin-cli listwallets). Empty: its default wallet.\" },\n { name: \"user\", label: \"RPC user\", kind: \"text\", optional: true, help: \"Leave empty to paste the .cookie file below.\" },\n { name: \"password\", label: \"RPC password or cookie\", kind: \"secret\", help: \"rpcpassword, or the contents of the node's .cookie file (it changes when bitcoind restarts).\" },\n ],\n validate(settings) {\n const url = (() => { try { return new URL(settings.config.url?.trim() ?? \"\"); } catch { return undefined; } })();\n if (!url || ![\"http:\", \"https:\"].includes(url.protocol)) throw new Error(\"Enter the node's RPC address, like http://127.0.0.1:8332\");\n if (url.username || url.password) throw new Error(\"Put the RPC user and password in their own fields, not in the address\");\n if (url.search || url.hash) throw new Error(\"The RPC address cannot have a query or fragment\");\n if (!WALLET_NAME.test(settings.config.wallet?.trim() ?? \"\") || [\".\", \"..\"].includes(settings.config.wallet?.trim() ?? \"\")) throw new Error(\"A wallet name has only letters, digits, '-', '_' and '.'\");\n const { user, password } = credentials(settings);\n if (!user || !password) throw new Error(\"Enter the RPC user and password, or paste the .cookie file\");\n },\n async create(settings, host) {\n const { BitcoindOnchain, tauriTransport } = await import(\"./bitcoind\");\n return BitcoindOnchain.connect({ url: settings.config.url.trim(), wallet: settings.config.wallet?.trim() ?? \"\",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AAI,MAAM,uEAAuE;EACzH,IAAI,IAAI,UAAU,IAAI,MAAM,MAAM,IAAI,MAAM,iDAAiD;EAC7F,IAAI,CAAC,YAAY,KAAK,SAAS,OAAO,QAAQ,KAAK,KAAK,EAAE,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC,SAAS,SAAS,OAAO,QAAQ,KAAK,KAAK,EAAE,GAAG,MAAM,IAAI,MAAM,0DAA0D;EACrM,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ;EAC/C,IAAI,CAAC,QAAQ,CAAC,UAAU,MAAM,IAAI,MAAM,4DAA4D;CACtG;CACA,MAAM,OAAO,UAAU,MAAM;EAC3B,MAAM,EAAE,iBAAiB,mBAAmB,MAAM,OAAO;EACzD,OAAO,gBAAgB,QAAQ;GAAE,KAAK,SAAS,OAAO,IAAI,KAAK;GAAG,QAAQ,SAAS,OAAO,QAAQ,KAAK,KAAK;GAAI,GAAG,YAAY,QAAQ;EAAE,GAAG,KAAK,MAAM,eAAe,KAAK,MAAM,GAAG,KAAK,MAAM;CACjM;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"bitcoindevkit_bg-B-iLWrmX.js","names":["import.meta.ROLLDOWN_FILE_URL_WPGYjwIlzWVNM1bYhOc83w"],"sources":["../../../../node_modules/@bitcoindevkit/bdk-wallet-web/bitcoindevkit_bg.wasm?url"],"sourcesContent":["export default import.meta.ROLLDOWN_FILE_URL_WPGYjwIlzWVNM1bYhOc83w"],"ignoreList":[0],"mappings":";AAAA,IAAA,2BAAe,IAAA,IAAA,oCAAA,YAAA,GAAmD,CAAA,CAAnDA"}
1
+ {"version":3,"file":"bitcoindevkit_bg-B-iLWrmX.js","names":["import.meta.ROLLDOWN_FILE_URL_FKNdLzKnlftW3t_gzo81yw"],"sources":["../../../../node_modules/@bitcoindevkit/bdk-wallet-web/bitcoindevkit_bg.wasm?url"],"sourcesContent":["export default import.meta.ROLLDOWN_FILE_URL_FKNdLzKnlftW3t_gzo81yw"],"ignoreList":[0],"mappings":";AAAA,IAAA,2BAAe,IAAA,IAAA,oCAAA,YAAA,GAAmD,CAAA,CAAnDA"}
@@ -0,0 +1,2 @@
1
+ import { r as buttonsOf } from "./buttons-fZTEa_2i.js";
2
+ export { buttonsOf };
@@ -1,7 +1,7 @@
1
- import { Io as checkStatusCard, No as buttonLabelClash, So as BUTTON_STYLES, _d as randomBytes, ji as BUTTONS_CAPABILITY, ko as STATUS_CARD_LIMITS, vd as toBase64Url } from "./src-BzsyAvPf.js";
1
+ import { Cd as toBase64Url, Io as buttonLabelClash, Mo as STATUS_CARD_LIMITS, Ni as BUTTONS_CAPABILITY, Sd as randomBytes, Ss as LIMITS, To as BUTTON_STYLES, zo as checkStatusCard } from "./src-DjVj2ynY.js";
2
2
  import { n as secretWords, r as findSecret } from "./secretGuard-B7Hj0Kvz.js";
3
3
  import { t as CliError } from "./errors-Dt-ZnyOX.js";
4
- import { C as nobodyJoinedChat, D as oneShotWaits, E as oneOf, P as str, T as num, _ as messageOf, i as chatOrGroup, n as bool, w as node, x as noMessage } from "./apiKit-D78MXTrk.js";
4
+ import { C as nobodyJoinedChat, D as oneShotWaits, E as oneOf, N as state, P as str, T as num, _ as messageOf, r as chatOrGroup, t as bool, w as node, x as noMessage } from "./apiKit-DesObIDf.js";
5
5
  import { n as goesOn$1 } from "./waitNotice-Cn0WJ-He.js";
6
6
  //#region src/waits.ts
7
7
  var DELIVERY_RANK = {
@@ -60,9 +60,30 @@ async function waitForRemoval(ctx, chat, messageId, ms) {
60
60
  }
61
61
  }
62
62
  /**
63
+ * A private group with no member but me (they all left, or nobody accepted an invitation yet): what I send there now
64
+ * reaches nobody, not even a member who joins later (a joiner reads nothing from before). A community's roster may not
65
+ * list every member yet, so only a private group counts.
66
+ */
67
+ var nobodyElseIn = (ctx, groupId) => {
68
+ const group = state(ctx).groups?.find((g) => g.id === groupId);
69
+ return group?.profile === "mesh" && !group.members.some((m) => !m.me);
70
+ };
71
+ /**
72
+ * Why I am no longer in a group (removed, say), or null while I am. A member removed while away learns it only after
73
+ * it is back, so what it sent in between is never taken, and from then on nothing goes. A community's `lost` is not
74
+ * out: it asks to be let in again by itself.
75
+ */
76
+ var outOf = (ctx, groupId) => {
77
+ const group = state(ctx).groups?.find((g) => g.id === groupId);
78
+ return group?.status && group.status !== "active" && group.status !== "lost" ? group.statusReason ?? "You are not in this group" : null;
79
+ };
80
+ /**
63
81
  * Waits until an edge took my group message, or its edit number `edit`, or my reaction to it numbered `reaction`, or my
64
82
  * pin numbered `pin` (WISP 902: a group has no receipts, so this is as far as the author sees): a member's edge in a
65
- * private group, an edge to one of my hubs in a community.
83
+ * private group, an edge to one of my hubs in a community. In a private group with nobody else in it, 0 at once: no
84
+ * edge will ever take it, and the wait sat its whole time, then said "it goes when one opens" and exited 4, which a
85
+ * bot retries, sending it again each time. Refused as soon as I learn I am out of the group: it sat its whole time
86
+ * there too and said the same, though nothing goes any more.
66
87
  */
67
88
  async function waitForGroupFrame(ctx, groupId, messageId, edit, ms) {
68
89
  const until = performance.now() + ms;
@@ -73,7 +94,12 @@ async function waitForGroupFrame(ctx, groupId, messageId, edit, ms) {
73
94
  messageId,
74
95
  ...which
75
96
  });
76
- if (taken > 0) return taken;
97
+ if (taken > 0 || nobodyElseIn(ctx, groupId)) return taken;
98
+ const out = outOf(ctx, groupId);
99
+ if (out) throw new CliError("refused", `${out}: no member took it, and it no longer goes`, {
100
+ messageId,
101
+ ..."edit" in which ? { edits: which.edit } : which
102
+ });
77
103
  if (performance.now() >= until || stopped(ctx)) throw new CliError("timeout", `${ended(ctx, ms)}: no member's edge took it yet (it stays in the group and goes when one opens). It ${goesOn(ctx)}`, known(ctx, {
78
104
  messageId,
79
105
  ..."edit" in which ? { edits: which.edit } : which
@@ -156,6 +182,19 @@ async function waitForDelivery(ctx, chat, messageId, target, ms) {
156
182
  });
157
183
  }
158
184
  //#endregion
185
+ //#region src/textSize.ts
186
+ /**
187
+ * A text past what a chat or a group carries (16 KiB of UTF-8, as the engine counts it: trimmed) is refused before the
188
+ * secret guard reads it and before the engine is asked, with its size and the bound, as `send` and `edit` refuse it.
189
+ */
190
+ function checkTextSize(text) {
191
+ const bytes = new TextEncoder().encode(text.trim()).length;
192
+ if (bytes > LIMITS.maxChatMessageBytes) throw new CliError("bad_request", `Message exceeds ${LIMITS.maxChatMessageBytes} UTF-8 bytes (${bytes}): shorten it, or send it as a file`, {
193
+ bytes,
194
+ max: LIMITS.maxChatMessageBytes
195
+ });
196
+ }
197
+ //#endregion
159
198
  //#region src/buttons.ts
160
199
  /**
161
200
  * `--button id:Label` (again for each, 1 to 6), `--style id=primary|neutral|danger`, `--once` and `--id`, as the
@@ -248,6 +287,7 @@ async function updateButtons(ctx, params) {
248
287
  const close = bool(params, "close");
249
288
  const newText = str(params, "text");
250
289
  if (chosen === void 0 && !close && newText === void 0) throw new CliError("bad_request", "Nothing to update: give chosen, close or text");
290
+ if (newText !== void 0) checkTextSize(newText);
251
291
  if (newText !== void 0 && !bool(params, "force")) {
252
292
  const secret = findSecret(newText);
253
293
  if (secret) throw new CliError("confirm", `The text looks like ${secretWords(secret)}; update with --force if you mean to`, { kind: secret.kind });
@@ -261,7 +301,7 @@ async function updateButtons(ctx, params) {
261
301
  edits: message.edit.seq
262
302
  });
263
303
  const before = message.card;
264
- if (chosen !== void 0 && !before.buttons.some((b) => b.id === chosen)) throw new CliError("bad_request", `That message has no button ${JSON.stringify(chosen)}; its buttons: ${before.buttons.map((b) => b.id).join(", ")}`, { card: before });
304
+ if (chosen !== void 0 && !before.buttons.some((b) => b.id === chosen)) throw new CliError("not_found", `That message has no button ${JSON.stringify(chosen)}; its buttons: ${before.buttons.map((b) => b.id).join(", ")}`, { card: before });
265
305
  const card = checked({
266
306
  ...before,
267
307
  ...chosen !== void 0 && { chosen },
@@ -358,6 +398,6 @@ var BUTTON_METHODS = {
358
398
  "button.update": updateButtons
359
399
  };
360
400
  //#endregion
361
- export { goesOn as a, waitForGroupFrame as c, pressable as i, waitForMessage as l, buttonsCard as n, waitForConfirmed as o, buttonsOf as r, waitForEdit as s, BUTTON_METHODS as t, waitForRemoval as u };
401
+ export { checkTextSize as a, waitForConfirmed as c, waitForMessage as d, waitForRemoval as f, pressable as i, waitForEdit as l, buttonsCard as n, goesOn as o, buttonsOf as r, nobodyElseIn as s, BUTTON_METHODS as t, waitForGroupFrame as u };
362
402
 
363
- //# sourceMappingURL=buttons-C1VbDihe.js.map
403
+ //# sourceMappingURL=buttons-fZTEa_2i.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buttons-fZTEa_2i.js","names":["goesOnIn"],"sources":["../../src/waits.ts","../../src/textSize.ts","../../src/buttons.ts"],"sourcesContent":["import type { StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { noMessage, nobodyJoinedChat, node, state, type ApiContext } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { goesOn as goesOnIn } from \"./waitNotice\";\n\n/*\n * Waiting on what a command sent (WISP 1100): a message's delivery, an edit's confirmation, a group frame taken by an\n * edge. Shared by the chat, group and status card methods. A deadline counts on `performance.now()`: on `Date.now()`\n * a wall clock set back while a wait ran (NTP, a person fixing the time) stretched it by as much, past the client's\n * own deadline, which told the bot to restart a sound daemon.\n */\n\nconst DELIVERY_RANK: Record<string, number> = { sending: 0, waiting: 1, queued: 1, held: 2, sent: 2, delivered: 3 };\n\n/**\n * What a timed-out wait says of what happens next: a daemon goes on, a one-shot's profile closes now. A one-shot's\n * `edit` and `group edit` said \"while this profile is online\" too, as it was about to leave. Ctrl-C says the same.\n * On a chat nobody joined yet nothing goes before they do: it said \"goes with this profile's next command\".\n */\nexport const goesOn = (ctx: ApiContext, chat?: string) => chat !== undefined && nobodyJoinedChat(ctx, chat)\n ? `goes once the contact joins this chat (nobody has yet)${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}`\n : ctx.mode === \"daemon\" && stopped(ctx) ? \"goes by itself once this profile is online again\" : goesOnIn(ctx.mode);\n\n/**\n * A daemon that stops (`ApiContext.stopping`) ends every wait still open at once, with what it knows, as a timeout:\n * what was asked is done and goes on by itself. Its connections ended under the waits before, and the command failed\n * as `unavailable` \"The daemon went away\" with no `messageId`: a bot that sent again sent the message twice.\n */\nconst stopped = (ctx: ApiContext) => ctx.stopping?.aborted === true;\n\n/** How a wait that ends short of its aim begins: its time ran out, or the daemon stopped under it. */\nconst ended = (ctx: ApiContext, ms: number) => stopped(ctx) ? \"The daemon stopped before the wait ended\" : `Timed out after ${Math.round(ms / 1000)} s`;\n\n/** A timed-out wait's details, and `reason: \"daemon-stopped\"` when the daemon's stop ended it. */\nconst known = (ctx: ApiContext, details: Record<string, unknown>) => stopped(ctx) ? { ...details, reason: \"daemon-stopped\" } : details;\n\n/** Waits until the contact confirmed the latest edit of one of my messages (it is no longer pending). */\nexport async function waitForEdit(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<StoredMessage> {\n const until = performance.now() + ms;\n for (;;) {\n const message = await node(ctx).getMessage(chat, messageId);\n if (!message) throw noMessage(messageId, { group: false, ref: chat });\n if (!message.edit?.pending) return message;\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the contact has not confirmed the edit yet (it needs a live chat and a contact's app that shows edits). It ${goesOn(ctx, chat)}`, known(ctx, { messageId, edits: message.edit.seq }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/** Waits until the contact confirmed my removal of a message, which is already gone here. */\nexport async function waitForRemoval(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<void> {\n const until = performance.now() + ms;\n while (node(ctx).removalPending({ linkId: chat, messageId })) {\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the message is gone here and the contact has not confirmed yet. Its removal ${goesOn(ctx, chat)}`, known(ctx, { messageId }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * A private group with no member but me (they all left, or nobody accepted an invitation yet): what I send there now\n * reaches nobody, not even a member who joins later (a joiner reads nothing from before). A community's roster may not\n * list every member yet, so only a private group counts.\n */\nexport const nobodyElseIn = (ctx: ApiContext, groupId: string): boolean => {\n const group = state(ctx).groups?.find((g) => g.id === groupId);\n return group?.profile === \"mesh\" && !group.members.some((m) => !m.me);\n};\n\n/**\n * Why I am no longer in a group (removed, say), or null while I am. A member removed while away learns it only after\n * it is back, so what it sent in between is never taken, and from then on nothing goes. A community's `lost` is not\n * out: it asks to be let in again by itself.\n */\nconst outOf = (ctx: ApiContext, groupId: string): string | null => {\n const group = state(ctx).groups?.find((g) => g.id === groupId);\n return group?.status && group.status !== \"active\" && group.status !== \"lost\" ? group.statusReason ?? \"You are not in this group\" : null;\n};\n\n/**\n * Waits until an edge took my group message, or its edit number `edit`, or my reaction to it numbered `reaction`, or my\n * pin numbered `pin` (WISP 902: a group has no receipts, so this is as far as the author sees): a member's edge in a\n * private group, an edge to one of my hubs in a community. In a private group with nobody else in it, 0 at once: no\n * edge will ever take it, and the wait sat its whole time, then said \"it goes when one opens\" and exited 4, which a\n * bot retries, sending it again each time. Refused as soon as I learn I am out of the group: it sat its whole time\n * there too and said the same, though nothing goes any more.\n */\nexport async function waitForGroupFrame(ctx: ApiContext, groupId: string, messageId: string, edit: number | { reaction: number } | { pin: number } | undefined, ms: number): Promise<number> {\n const until = performance.now() + ms;\n const which = typeof edit === \"object\" ? edit : edit ? { edit } : {};\n for (;;) {\n const taken = node(ctx).groupTaken({ groupId, messageId, ...which });\n if (taken > 0 || nobodyElseIn(ctx, groupId)) return taken;\n const out = outOf(ctx, groupId);\n if (out) throw new CliError(\"refused\", `${out}: no member took it, and it no longer goes`, { messageId, ...(\"edit\" in which ? { edits: which.edit } : which) });\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: no member's edge took it yet (it stays in the group and goes when one opens). It ${goesOn(ctx)}`, known(ctx, { messageId, ...(\"edit\" in which ? { edits: which.edit } : which) }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * A one-shot whose text went over the live link waits this long for its receipt before it leaves (`waitForMessage`).\n * Left at `sent`, the engine stopping took the text for unconfirmed, the next start sent it again on the DHT, and that\n * copy took the chat's one DHT text awaiting a receipt: a script's next one-shot send waited 30 s behind it, every 5-8\n * messages, and the last text showed \"Connection closed before receipt\" though the contact had it (agents#1640).\n */\nexport const ONE_SHOT_RECEIPT_MS = 2_000;\n\n/**\n * Waits until the contact confirmed my reaction or pin in a 1:1 chat (WISP 401): until `pending` no longer finds it in\n * what the contact has not confirmed (`chatUnconfirmed`). It goes on the live session, a reaction also on the DHT\n * envelopes; one not confirmed in time is kept and said again.\n */\nexport async function waitForConfirmed(ctx: ApiContext, chat: string, what: \"reaction\" | \"pin\", pending: (left: { reactions: number[]; pin: number | null }) => boolean, ms: number): Promise<void> {\n const until = performance.now() + ms;\n while (pending(node(ctx).chatUnconfirmed({ linkId: chat }))) {\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the contact has not confirmed the ${what} yet. It is kept here and ${goesOn(ctx, chat)}`, known(ctx, { chat }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * Waits until a message of mine reached `target` (`sent`: on its way to the contact; `delivered`: acknowledged). A\n * one-shot's text sent over the live link waits a moment more for its receipt (`ONE_SHOT_RECEIPT_MS`).\n */\nexport async function waitForMessage(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const reached = await waitForDelivery(ctx, chat, messageId, target, ms);\n if (ctx.mode !== \"one-shot\" || target !== \"sent\" || reached.delivery !== \"sent\" || reached.via !== \"datalink\") return reached;\n return waitForDelivery(ctx, chat, messageId, \"delivered\", ONE_SHOT_RECEIPT_MS).catch(async () => (await node(ctx).getMessage(chat, messageId)) ?? reached);\n}\n\nasync function waitForDelivery(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const want = DELIVERY_RANK[target];\n const look = (message: StoredMessage | undefined) => {\n if (!message) return undefined;\n const delivery = message.delivery ?? \"sent\";\n if (delivery === \"failed\") throw new CliError(\"engine\", message.deliveryError ?? \"The message could not be sent\", { messageId, delivery });\n return (DELIVERY_RANK[delivery] ?? 0) >= want ? message : undefined;\n };\n return new Promise<StoredMessage>((resolve, reject) => {\n let settled = false;\n const finish = (error: unknown, message?: StoredMessage) => {\n if (settled) return;\n settled = true; clearTimeout(timer); off(); ctx.stopping?.removeEventListener(\"abort\", giveUp);\n if (error) reject(error); else resolve(message!);\n };\n const check = (last = false) => void node(ctx).getMessage(chat, messageId).then((message) => {\n try {\n const done = look(message);\n if (done) finish(null, done);\n else if (last) finish(new CliError(\"timeout\", `${ended(ctx, ms)}: the message is ${message?.delivery ?? \"not sent yet\"} and ${goesOn(ctx, chat)}`, known(ctx, { messageId, delivery: message?.delivery ?? null })));\n } catch (error) { finish(error); }\n }, finish);\n const giveUp = () => check(true);\n const timer = setTimeout(giveUp, ms);\n // Any event naming the message: a message first seen already delivered comes as `message.sent`, never as\n // `message.delivery`. Listening before the first read leaves no gap for a change to slip through.\n const off = ctx.hub.onEvent((event: GhostlyEvent) => {\n if (event.chat === chat && (event.messageId === messageId || (event.message as { id?: string } | undefined)?.id === messageId)) check();\n });\n if (stopped(ctx)) giveUp();\n else { ctx.stopping?.addEventListener(\"abort\", giveUp, { once: true }); check(); }\n });\n}\n","import { LIMITS } from \"@ghostly/core\";\nimport { CliError } from \"./errors\";\n\n/**\n * A text past what a chat or a group carries (16 KiB of UTF-8, as the engine counts it: trimmed) is refused before the\n * secret guard reads it and before the engine is asked, with its size and the bound, as `send` and `edit` refuse it.\n */\nexport function checkTextSize(text: string): void {\n const bytes = new TextEncoder().encode(text.trim()).length;\n if (bytes > LIMITS.maxChatMessageBytes) throw new CliError(\"bad_request\", `Message exceeds ${LIMITS.maxChatMessageBytes} UTF-8 bytes (${bytes}): shorten it, or send it as a file`, { bytes, max: LIMITS.maxChatMessageBytes });\n}\n","import { BUTTONS_CAPABILITY, BUTTON_STYLES, STATUS_CARD_LIMITS, buttonLabelClash, checkStatusCard, randomBytes, toBase64Url, type ButtonsCard } from \"@ghostly/core\";\nimport type { LinkView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport type { Parsed } from \"./args\";\nimport { bool, chatOrGroup, messageOf, noMessage, node, num, oneOf, oneShotWaits, str, type Method, type Params, type RefPlace } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport { findSecret, secretWords } from \"./secretGuard\";\nimport { checkTextSize } from \"./textSize\";\nimport { waitForEdit, waitForGroupFrame, waitForMessage } from \"./waits\";\n\n/*\n * Message buttons (WISP 406 · Message Buttons), the bot's side: a message whose text is the question, with up to six\n * buttons under it (`send --button yes:Yes`). A press comes back as a reply whose text is the button's label; the\n * engine marks it (`press`) and `listen` says `button.pressed`. `button update` then shows the answer (`chosen`) and\n * closes the buttons, by editing the message with the same buttons.\n */\n\n/**\n * `--button id:Label` (again for each, 1 to 6), `--style id=primary|neutral|danger`, `--once` and `--id`, as the\n * method's parameters: `buttons` and `buttonsId`. Nothing when no `--button` is given. The label may hold colons: the\n * id ends at the first one. An id given twice, two labels that read the same (ignoring case and spaces at the ends), a\n * label that is another button's id, or a style not listed are a usage error here, before the profile opens; other\n * bounds (ids, labels, how many) are the card's, checked when it is sent.\n */\nexport function buttonsOf(options: Parsed[\"options\"]): { buttons: Record<string, unknown>[]; buttonsId?: string } | undefined {\n const given = Array.isArray(options.button) ? options.button as string[] : [];\n if (!given.length) {\n for (const flag of [\"style\", \"once\", \"id\"] as const)\n if (options[flag] !== undefined) throw new CliError(\"usage\", `--${flag} goes with --button id:Label`);\n return undefined;\n }\n const buttons: Record<string, unknown>[] = given.map((value) => {\n const colon = value.indexOf(\":\");\n if (colon < 1 || colon === value.length - 1) throw new CliError(\"usage\", `--button takes id:Label, like yes:Yes, not ${JSON.stringify(value)}`);\n return { id: value.slice(0, colon), label: value.slice(colon + 1).trim() };\n });\n const twice = buttons.findIndex((button, at) => buttons.findIndex((other) => other.id === button.id) !== at);\n if (twice !== -1) throw new CliError(\"usage\", `--button ${JSON.stringify(given[twice])} repeats the id ${JSON.stringify(buttons[twice].id)}: each button takes its own`);\n // Two buttons a typed answer could not tell apart: the same label, or a label that is another's id (ignoring case).\n const clash = buttonLabelClash(buttons);\n if (clash) {\n const [at, other] = [JSON.stringify(given[clash.at]), JSON.stringify(given[clash.with])];\n throw new CliError(\"usage\", clash.kind === \"label\"\n ? `--button ${at} repeats the label of --button ${other} (ignoring case and spaces): a typed answer could not tell them apart`\n : `--button ${at} has a label that is the id of --button ${other}: a typed answer could not tell them apart`);\n }\n for (const value of Array.isArray(options.style) ? options.style as string[] : []) {\n const eq = value.indexOf(\"=\");\n const button = eq > 0 ? buttons.find((b) => b.id === value.slice(0, eq)) : undefined;\n if (!button) throw new CliError(\"usage\", `--style takes id=primary|neutral|danger for one of the buttons, not ${JSON.stringify(value)}`);\n const style = value.slice(eq + 1);\n if (!(BUTTON_STYLES as readonly string[]).includes(style)) throw new CliError(\"usage\", `--style ${JSON.stringify(value)}: a button's style is ${BUTTON_STYLES.join(\", \")}`);\n button.style = style;\n }\n if (options.once === true) for (const button of buttons) button.once = true;\n return { buttons, ...(options.id !== undefined && { buttonsId: String(options.id) }) };\n}\n\n/** A buttons card checked by the sender's rule, or a `bad_request` that says what is wrong. */\nfunction checked(card: Record<string, unknown>): ButtonsCard {\n const result = checkStatusCard(card);\n if (\"error\" in result) throw new CliError(\"bad_request\", `Buttons: ${result.error}`, { card });\n return result.card as ButtonsCard;\n}\n\n/**\n * The card a send's `buttons` (and `buttonsId`) make, or undefined when it names none. `buttons` is a list of\n * `{id, label, style?, once?}`; the id of the question is made up (`ask-…`) unless given.\n */\nexport function buttonsCard(params: Params): ButtonsCard | undefined {\n const buttons = params.buttons;\n if (buttons === undefined || buttons === null) {\n if (params.buttonsId !== undefined) throw new CliError(\"bad_request\", \"buttonsId goes with buttons\");\n return undefined;\n }\n if (!Array.isArray(buttons)) throw new CliError(\"bad_request\", \"buttons must be a list of {id, label, style?, once?}\");\n const id = str(params, \"buttonsId\") ?? `ask-${toBase64Url(randomBytes(6))}`;\n return checked({ kind: \"buttons\", id, buttons });\n}\n\n/** Whether a 1:1 contact's app shows and presses buttons: null until its app said what it offers. */\nexport function pressable(link: LinkView): boolean | null {\n const peer = link.sessionOffers?.peer;\n return peer ? peer.includes(BUTTONS_CAPABILITY) : null;\n}\n\n/** The message of mine with buttons that `button update` names, by its id here (or the id both sides know). */\nfunction buttonsMessage(message: StoredMessage | undefined, ref: string, place: RefPlace): StoredMessage & { card: ButtonsCard } {\n if (!message) throw noMessage(ref, place, { whose: \"of yours\" });\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons: send one with send --button id:Label\");\n return message as StoredMessage & { card: ButtonsCard };\n}\n\n/**\n * `button update`: the answer shown on a question's buttons (`chosen`), the buttons closed (`close`), or a new text\n * (`text`), by editing the message with the same buttons. What is not given stays as it was.\n */\nasync function updateButtons(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const chosen = str(params, \"chosen\");\n const close = bool(params, \"close\");\n const newText = str(params, \"text\");\n if (chosen === undefined && !close && newText === undefined) throw new CliError(\"bad_request\", \"Nothing to update: give chosen, close or text\");\n // A new text is a message like any other: the same size check and guard as `send` and `edit`.\n if (newText !== undefined) checkTextSize(newText);\n if (newText !== undefined && !bool(params, \"force\")) {\n const secret = findSecret(newText);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; update with --force if you mean to`, { kind: secret.kind });\n }\n const message = buttonsMessage(await messageOf(ctx, target.linkId, ref, (m) => m.sender === \"me\"), ref, { group: target.group, ref: str(params, \"chat\", true) });\n if ((message.edit?.seq ?? 0) >= STATUS_CARD_LIMITS.edits)\n throw new CliError(\"refused\", `This message took ${STATUS_CARD_LIMITS.edits} updates, the most one takes: ask again with a new send`, { messageId: message.id, edits: message.edit!.seq });\n const before = message.card;\n // Said here, with the buttons it has, as a press says it (not_found, exit 3): the card's own check names only the field.\n if (chosen !== undefined && !before.buttons.some((b) => b.id === chosen))\n throw new CliError(\"not_found\", `That message has no button ${JSON.stringify(chosen)}; its buttons: ${before.buttons.map((b) => b.id).join(\", \")}`, { card: before });\n const card = checked({ ...before, ...(chosen !== undefined && { chosen }), ...((close || before.closed) && { closed: true }) });\n const text = newText ?? message.text;\n const wait = oneOf(params, \"wait\", target.group ? [\"none\", \"sent\"] as const : [\"none\", \"confirmed\"] as const, \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).editMessage({ linkId: target.linkId, messageId: message.id, text, card });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n let edited = await node(ctx).getMessage(target.linkId, message.id);\n if (wait === \"confirmed\" && edited?.edit?.pending) edited = await waitForEdit(ctx, target.linkId, message.id, ms);\n const edges = wait === \"sent\" && edited?.edit ? await waitForGroupFrame(ctx, target.id, message.id, edited.edit.seq, ms) : undefined;\n return {\n [target.group ? \"group\" : \"chat\"]: target.id, buttons: card.id, messageId: message.id, card, edits: edited?.edit?.seq ?? 0,\n ...(target.group ? { ...(edges !== undefined && { edges }) } : { confirmed: !!edited && !edited.edit?.pending }),\n };\n}\n\n/**\n * `button press`: the other side of a question, as the app's tap: a press on a button of someone else's message, by\n * its id here (or the id both sides know). The engine sends a reply whose text is the button's label, and refuses what\n * an app would: a button the message does not have, closed buttons, a second answer past `once`, a second press\n * within a second. A one-shot in a chat waits until the press went out, as `send` does.\n */\nasync function pressButton(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const buttonId = str(params, \"button\", true);\n const where = target.group ? \"group\" : \"chat\";\n const message = await messageOf(ctx, target.linkId, ref, (m) => m.sender !== \"me\");\n if (!message) throw noMessage(ref, { group: target.group, ref: str(params, \"chat\", true) }, { whose: \"from someone else\" });\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons\");\n const button = message.card.buttons.find((b) => b.id === buttonId);\n if (!button) throw new CliError(\"not_found\", `That message has no button ${JSON.stringify(buttonId)}; its buttons: ${message.card.buttons.map((b) => b.id).join(\", \")}`);\n const wait = target.group\n ? oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\")\n : oneOf(params, \"wait\", [\"none\", \"sent\", \"delivered\"] as const, oneShotWaits(ctx, target.linkId) ? \"sent\" : \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).pressButton({ linkId: target.linkId, messageId: message.id, buttonId });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error, result.paced ? { paced: true } : undefined);\n const replyId = result.messageId ?? null;\n const answer = { [where]: target.id, messageId: message.id, button: button.id, label: button.label, replyId };\n if (!replyId) return answer;\n if (target.group) {\n const edges = wait === \"sent\" ? await waitForGroupFrame(ctx, target.id, replyId, undefined, ms) : node(ctx).groupTaken({ groupId: target.id, messageId: replyId });\n return { ...answer, edges };\n }\n const reply = wait === \"none\" ? await node(ctx).getMessage(target.linkId, replyId) : await waitForMessage(ctx, target.linkId, replyId, wait, ms);\n return { ...answer, delivery: reply?.delivery ?? null };\n}\n\nexport const BUTTON_METHODS: Record<string, Method> = {\n /** WISP 406 · Message Buttons: a press on a button of someone else's message, as the app's tap. */\n \"button.press\": pressButton,\n /** WISP 406 · Message Buttons: the answer chosen on a question of mine, its buttons closed, or its text changed. */\n \"button.update\": updateButtons,\n};\n"],"mappings":";;;;;;AAaA,IAAM,gBAAwC;CAAE,SAAS;CAAG,SAAS;CAAG,QAAQ;CAAG,MAAM;CAAG,MAAM;CAAG,WAAW;AAAE;;;;;;AAOlH,IAAa,UAAU,KAAiB,SAA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,CAAC,YAAY;EAAE,QAAQ,OAAO;EAAQ,WAAW,QAAQ;EAAI;CAAS,CAAC;CACrG,IAAI,OAAO,OAAO,MAAM,IAAI,SAAS,OAAO,UAAU,YAAY,eAAe,OAAO,OAAO,OAAO,QAAQ,EAAE,OAAO,KAAK,IAAI,KAAA,CAAS;CACzI,MAAM,UAAU,OAAO,aAAa;CACpC,MAAM,SAAS;GAAG,QAAQ,OAAO;EAAI,WAAW,QAAQ;EAAI,QAAQ,OAAO;EAAI,OAAO,OAAO;EAAO;CAAQ;CAC5G,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI,OAAO,OAAO;EAChB,MAAM,QAAQ,SAAS,SAAS,MAAM,kBAAkB,KAAK,OAAO,IAAI,SAAS,KAAA,GAAW,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC,WAAW;GAAE,SAAS,OAAO;GAAI,WAAW;EAAQ,CAAC;EACjK,OAAO;GAAE,GAAG;GAAQ;EAAM;CAC5B;CACA,MAAM,QAAQ,SAAS,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,WAAW,OAAO,QAAQ,OAAO,IAAI,MAAM,eAAe,KAAK,OAAO,QAAQ,SAAS,MAAM,EAAE;CAC/I,OAAO;EAAE,GAAG;EAAQ,UAAU,OAAO,YAAY;CAAK;AACxD;AAEA,IAAa,iBAAyC;;CAEpD,gBAAgB;;CAEhB,iBAAiB;AACnB"}
@@ -2,9 +2,10 @@
2
2
  /**
3
3
  * Environment variables only the command that reads them needs: the backup passphrase is read by a one-shot
4
4
  * `profile backup`/`profile restore` and sent as a call parameter, so no other process (the daemon, a hook, ffmpeg,
5
- * the translator, `ps`, `xattr`) ever needs it. The one list every child's environment is cleaned with.
5
+ * the translator, `ps`, `xattr`) ever needs it; `listen` reads its webhook's URL (a bridge's token in it) once, at the
6
+ * start, and a hook it runs never needs it. The one list every child's environment is cleaned with.
6
7
  */
7
- var SECRET_ENV = ["GHOSTLY_BACKUP_PASSPHRASE"];
8
+ var SECRET_ENV = ["GHOSTLY_BACKUP_PASSPHRASE", "GHOSTLY_WEBHOOK"];
8
9
  /** `env` less the secrets in `SECRET_ENV`: what a process this one starts gets. */
9
10
  function childEnv(env = process.env) {
10
11
  const rest = { ...env };
@@ -18,4 +19,4 @@ function dropSecretEnv(env = process.env) {
18
19
  //#endregion
19
20
  export { dropSecretEnv as n, childEnv as t };
20
21
 
21
- //# sourceMappingURL=childEnv-BVOQK9EA.js.map
22
+ //# sourceMappingURL=childEnv-K_IzUqQx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"childEnv-K_IzUqQx.js","names":[],"sources":["../../src/childEnv.ts"],"sourcesContent":["/**\n * Environment variables only the command that reads them needs: the backup passphrase is read by a one-shot\n * `profile backup`/`profile restore` and sent as a call parameter, so no other process (the daemon, a hook, ffmpeg,\n * the translator, `ps`, `xattr`) ever needs it; `listen` reads its webhook's URL (a bridge's token in it) once, at the\n * start, and a hook it runs never needs it. The one list every child's environment is cleaned with.\n */\nexport const SECRET_ENV = [\"GHOSTLY_BACKUP_PASSPHRASE\", \"GHOSTLY_WEBHOOK\"] as const;\n\n/** `env` less the secrets in `SECRET_ENV`: what a process this one starts gets. */\nexport function childEnv(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n const rest = { ...env };\n for (const name of SECRET_ENV) delete rest[name];\n return rest;\n}\n\n/** Removes the secrets in `SECRET_ENV` from this process's own environment (the daemon, which never reads them). */\nexport function dropSecretEnv(env: NodeJS.ProcessEnv = process.env): void {\n for (const name of SECRET_ENV) delete env[name];\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa,CAAC,6BAA6B,iBAAiB;;AAGzE,SAAgB,SAAS,MAAyB,QAAQ,KAAwB;CAChF,MAAM,OAAO,EAAE,GAAG,IAAI;CACtB,KAAK,MAAM,QAAQ,YAAY,OAAO,KAAK;CAC3C,OAAO;AACT;;AAGA,SAAgB,cAAc,MAAyB,QAAQ,KAAW;CACxE,KAAK,MAAM,QAAQ,YAAY,OAAO,IAAI;AAC5C"}
@@ -1,5 +1,5 @@
1
1
  import { t as CliError } from "./errors-Dt-ZnyOX.js";
2
- import { S as ownSocket, f as lockPath } from "./profiles-4UQ1Hsds.js";
2
+ import { m as lockPath, w as ownSocket } from "./profiles-Ccdq6Xf6.js";
3
3
  import { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
@@ -38,6 +38,8 @@ var PlaybackQueue = class {
38
38
  head = 0;
39
39
  length = 0;
40
40
  lastPush = 0;
41
+ /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */
42
+ owed = false;
41
43
  frame;
42
44
  max;
43
45
  silence;
@@ -54,10 +56,15 @@ var PlaybackQueue = class {
54
56
  push(chunk) {
55
57
  if (!chunk.length) return 0;
56
58
  this.lastPush = this.now();
59
+ if (this.owed) {
60
+ this.owed = false;
61
+ chunk = chunk.subarray(1);
62
+ }
57
63
  const room = this.max - this.length;
58
64
  const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));
59
65
  const lost = chunk.length - kept.length;
60
66
  this.dropped += lost;
67
+ if (lost % 2) this.owed = true;
61
68
  if (kept.length) {
62
69
  this.chunks.push(Buffer.from(kept));
63
70
  this.length += kept.length;
@@ -91,6 +98,7 @@ var PlaybackQueue = class {
91
98
  /** Drops everything queued; returns how much, in milliseconds. */
92
99
  flush() {
93
100
  const ms = this.queuedMs;
101
+ if (this.length % 2) this.owed = true;
94
102
  this.chunks = [];
95
103
  this.head = 0;
96
104
  this.length = 0;
@@ -102,6 +110,19 @@ var PlaybackQueue = class {
102
110
  if (frames > 0) this.take(frames * this.frame);
103
111
  return Math.max(0, frames) * 20;
104
112
  }
113
+ /**
114
+ * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is
115
+ * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much
116
+ * was dropped, in milliseconds.
117
+ */
118
+ newWriter() {
119
+ const ms = this.queuedMs;
120
+ this.chunks = [];
121
+ this.head = 0;
122
+ this.length = 0;
123
+ this.owed = false;
124
+ return ms;
125
+ }
105
126
  take(bytes) {
106
127
  const out = Buffer.allocUnsafe(bytes);
107
128
  let filled = 0;
@@ -291,6 +312,13 @@ function wentAway(leaving) {
291
312
  function endedUnanswered(error) {
292
313
  return error instanceof CliError && unanswered.has(error);
293
314
  }
315
+ /**
316
+ * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are
317
+ * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.
318
+ */
319
+ function endedUnsent(error) {
320
+ return endedUnanswered(error) && error.details?.reason !== "daemon-stopped";
321
+ }
294
322
  function isNotTheDaemon(error) {
295
323
  return error instanceof CliError && error.code === "refused" && error.details?.reason === "not-the-daemon";
296
324
  }
@@ -519,6 +547,6 @@ function connectDaemon(address, timeoutMs = 2e3, { greetingMs = GREETING_MS } =
519
547
  });
520
548
  }
521
549
  //#endregion
522
- export { isCallRate as _, isNotTheDaemon as a, newDaemonSecret as c, CALL_RATES as d, DEFAULT_RATE as f, frameSamples as g, frameBytes as h, endedUnanswered as i, proof as l, bytesToMs as m, MAX_LINE as n, HELLO as o, PlaybackQueue as p, connectDaemon as r, greeting as s, DaemonClient as t, removeDaemonSecret as u, monotonic as v };
550
+ export { frameSamples as _, endedUnsent as a, greeting as c, removeDaemonSecret as d, CALL_RATES as f, frameBytes as g, bytesToMs as h, endedUnanswered as i, newDaemonSecret as l, PlaybackQueue as m, MAX_LINE as n, isNotTheDaemon as o, DEFAULT_RATE as p, connectDaemon as r, HELLO as s, DaemonClient as t, proof as u, isCallRate as v, monotonic as y };
523
551
 
524
- //# sourceMappingURL=client-CGLuWFRV.js.map
552
+ //# sourceMappingURL=client-Ibk3-e60.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-Ibk3-e60.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * The call's own clock, in ms: monotonic, so the device's clock set back or ahead mid-call (a phone or a VM fixing its\n * time) moves the time of day, not the audio. On `Date.now()`, a clock set back held the next frame for as long as the\n * jump, and one set ahead read as that long without a packet from the contact.\n */\nexport const monotonic = (): number => performance.now();\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */\n private owed = false;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = monotonic, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n if (this.owed) {\n this.owed = false;\n chunk = chunk.subarray(1);\n }\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n // The queue ends on a whole sample here, so an odd number lost ends on half of one.\n if (lost % 2) this.owed = true;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n // Half a sample queued: its other half is the program's next byte.\n if (this.length % 2) this.owed = true;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n /**\n * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is\n * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much\n * was dropped, in milliseconds.\n */\n newWriter(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n // A flush that cut the last program's half sample owes nothing to the next program: it starts on a whole sample.\n this.owed = false;\n return ms;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n","import { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/** The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). */\nfunction notTheDaemon(socket: string): CliError {\n return new CliError(\"refused\", `What answers on ${socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\n/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */\nconst unanswered = new WeakSet<CliError>();\n\n/**\n * A call the daemon read and never answered, because it stopped (a restart, a crash): what was asked may be done, so\n * it is no plain failure a bot tries again (a send went twice). A daemon that stops answers its waits first (`serve`);\n * this is for the calls it could not.\n */\nfunction stoppedUnanswered(method: string): CliError {\n const error = new CliError(\"timeout\", `The daemon stopped before it answered ${method}, which may be done: check (\\`ghostly chat history\\` for a message) before you try again`, { method, reason: \"daemon-stopped\" });\n unanswered.add(error);\n return error;\n}\n\n/**\n * A call whose connection ended before the daemon read it, or before it proved itself: nothing was done. `leaving`: this\n * client ended it (a deadline, Ctrl-C), so it is no daemon that stopped under the call.\n */\nfunction wentAway(leaving: boolean): CliError {\n const error = new CliError(\"unavailable\", \"The daemon went away\");\n if (!leaving) unanswered.add(error);\n return error;\n}\n\n/**\n * Whether a call failed because its connection ended unanswered (the daemon stopped, restarted or crashed under it),\n * not because the daemon answered it with an error. A read that did can be asked again: it changed nothing. So may one\n * refused because the daemon's secret was gone when its greeting or its hello's answer came: a daemon that stops removes\n * it first, and the greeting it wrote just before is read after. Nothing but the hello was written to it, and a listener\n * that never proves itself is refused again on the new connection.\n */\nexport function endedUnanswered(error: unknown): boolean {\n return error instanceof CliError && unanswered.has(error);\n}\n\n/**\n * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are\n * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.\n */\nexport function endedUnsent(error: unknown): boolean {\n return endedUnanswered(error) && (error as CliError).details?.reason !== \"daemon-stopped\";\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n /** `written`: the call is on the socket, so the daemon may have acted on it. */\n private readonly pending = new Map<number, { method: string; written: boolean; resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n /** This client closed the connection: what was still unanswered is its own doing, not a daemon that stopped. */\n private leaving = false;\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(!secret); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse(!secret);\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? wentAway(this.leaving);\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(waiting.written && !this.refusal && !this.leaving ? stoppedUnanswered(waiting.method) : why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */\n private refuse(secretGone = false): void {\n this.refusal = notTheDaemon(this.address.socket);\n if (secretGone) unanswered.add(this.refusal);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? wentAway(this.leaving));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n method, written: false,\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => {\n if (!this.pending.has(id) || this.socket.destroyed) return;\n this.socket.write(line);\n settle.written = true;\n },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.leaving = true;\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.leaving = true;\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OAAQ,GAAI;AAExG,SAAgB,WAAW,OAAmC;CAC5D,OAAO,WAAW,SAAS,KAAiB;AAC9C;;AAGA,IAAa,eAAe;;;;;;AAa5B,IAAa,kBAA0B,YAAY,IAAI;;;;;AAMvD,IAAa,gBAAb,MAA2B;CAaJ;CAAiC;CAZtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAAiB;CACjB,WAAmB;;CAEnB,OAAe;CACf;CACA;CACA;;CAEA,UAAU;CAEV,YAAY,MAAyB,MAAqC,WAAW,QAAQ,cAAc;EAAtF,KAAA,OAAA;EAAiC,KAAA,MAAA;EACpD,KAAK,QAAQ,WAAW,IAAI;EAE5B,KAAK,MAAM,KAAK,MAAO,OAAO,QAAS,GAAI,IAAI;EAC/C,KAAK,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B;EACd,KAAK,UAAU;EACf,KAAK,OAAO,QAAQ;CACtB;AACF;;;;;AAMA,SAAgB,cAAc,SAAwB,YAAY,KAAO,EAAE,aAAa,gBAAyC,CAAC,GAAiC;CACjK,MAAM,OAAO,QAAQ;CAErB,IAAI,CAAC,UAAU,IAAI,GAAG,OAAO,QAAQ,QAAQ,IAAI;CACjD,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,QAAQ,IAAI;EAC3B,MAAM,QAAQ,iBAAiB;GAAE,OAAO,QAAQ;GAAG,QAAQ,IAAI;EAAG,GAAG,SAAS;EAC9E,OAAO,KAAK,iBAAiB;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI,aAAa,QAAQ,SAAS,UAAU,CAAC;EAAG,CAAC;EAC7G,OAAO,KAAK,eAAe;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI;EAAG,CAAC;CACpE,CAAC;AACH"}
@@ -1,4 +1,4 @@
1
- import "./src-BzsyAvPf.js";
1
+ import "./src-DjVj2ynY.js";
2
2
  //#region ../browser/src/backup/codec.ts
3
3
  function fromBase64Url(text) {
4
4
  if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("Invalid base64url");
@@ -10,4 +10,4 @@ function fromBase64Url(text) {
10
10
  //#endregion
11
11
  export { fromBase64Url as t };
12
12
 
13
- //# sourceMappingURL=codec-YGJDr7uH.js.map
13
+ //# sourceMappingURL=codec-DMpQqVSt.js.map