@ghostlytools/cli 1.11.0 → 1.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -16
- package/dist/assets/{api-CTqIcdu7.js → api-BM3PsXbB.js} +372 -123
- package/dist/assets/api-BM3PsXbB.js.map +1 -0
- package/dist/assets/{api-B-52sVYp.js → api-CtXgscmK.js} +2 -2
- package/dist/assets/{apiKit-CZq4Lq4f.js → apiKit-lCTQ0EBG.js} +17 -7
- package/dist/assets/apiKit-lCTQ0EBG.js.map +1 -0
- package/dist/assets/appFetch-BKHy5H8J.js +194 -0
- package/dist/assets/appFetch-BKHy5H8J.js.map +1 -0
- package/dist/assets/{apps-kRsY9S2S.js → apps-DO_gAZgm.js} +1 -1
- package/dist/assets/{apps-C_X0zgSG.js → apps-Do26w3c7.js} +44 -40
- package/dist/assets/apps-Do26w3c7.js.map +1 -0
- package/dist/assets/{arkade-_aaB7VbW.js → arkade-CZrLbz-M.js} +2 -2
- package/dist/assets/{arkade-_aaB7VbW.js.map → arkade-CZrLbz-M.js.map} +1 -1
- package/dist/assets/{backup-DBg388Ke.js → backup-D21x1f5P.js} +1 -1
- package/dist/assets/{backup-OTvrmk-w.js → backup-j47AzDvG.js} +84 -33
- package/dist/assets/backup-j47AzDvG.js.map +1 -0
- package/dist/assets/{bitcoind-CZchoh43.js → bitcoind-CdSmvy2y.js} +3 -3
- package/dist/assets/{bitcoind-CZchoh43.js.map → bitcoind-CdSmvy2y.js.map} +1 -1
- package/dist/assets/{bitcoindProvider-DGw3xBSa.js → bitcoindProvider-BvoRh0D5.js} +2 -2
- package/dist/assets/{bitcoindProvider-DGw3xBSa.js.map → bitcoindProvider-BvoRh0D5.js.map} +1 -1
- package/dist/assets/{buttons-DUu7hxxT.js → buttons-CiGlBVBT.js} +18 -7
- package/dist/assets/buttons-CiGlBVBT.js.map +1 -0
- package/dist/assets/buttons-D2l2bVCG.js +2 -0
- package/dist/assets/{childEnv-BVOQK9EA.js → childEnv-K_IzUqQx.js} +4 -3
- package/dist/assets/childEnv-K_IzUqQx.js.map +1 -0
- package/dist/assets/{client-DDpZP1R1.js → client-raIncVtF.js} +31 -3
- package/dist/assets/client-raIncVtF.js.map +1 -0
- package/dist/assets/{codec-DrryGcPT.js → codec-DcG2AeyE.js} +2 -2
- package/dist/assets/{codec-DrryGcPT.js.map → codec-DcG2AeyE.js.map} +1 -1
- package/dist/assets/endpoint-DarqblYE.js +5052 -0
- package/dist/assets/endpoint-DarqblYE.js.map +1 -0
- package/dist/assets/{envelope-Q_rMgoE9.js → envelope-Dud6lntA.js} +2 -2
- package/dist/assets/{envelope-Q_rMgoE9.js.map → envelope-Dud6lntA.js.map} +1 -1
- package/dist/assets/{fedimintSdk-CqTeMdF0.js → fedimintSdk-DRKRSw14.js} +6 -3
- package/dist/assets/fedimintSdk-DRKRSw14.js.map +1 -0
- package/dist/assets/{fixedHosts-BV5GDiTU.js → fixedHosts-CNX7QiUD.js} +3 -3
- package/dist/assets/{fixedHosts-BV5GDiTU.js.map → fixedHosts-CNX7QiUD.js.map} +1 -1
- package/dist/assets/{host-BlUzZgQL.js → host-8RskzQgB.js} +306 -84
- package/dist/assets/host-8RskzQgB.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-BvI_uNZO.js → hyperdhtRelay-uAThbFub.js} +2 -2
- package/dist/assets/{hyperdhtRelay-BvI_uNZO.js.map → hyperdhtRelay-uAThbFub.js.map} +1 -1
- package/dist/assets/{irohWeb-CqPN8VPY.js → irohWeb-DGelfgDJ.js} +695 -40
- package/dist/assets/irohWeb-DGelfgDJ.js.map +1 -0
- package/dist/assets/jsonOut-POtMBS_V.js +16 -0
- package/dist/assets/jsonOut-POtMBS_V.js.map +1 -0
- package/dist/assets/{main-vQjlgEnt.js → main-BC33ooYg.js} +175 -107
- package/dist/assets/main-BC33ooYg.js.map +1 -0
- package/dist/assets/{mainline-p6HOW7sb.js → mainline-DYrjsS1t.js} +27 -8
- package/dist/assets/mainline-DYrjsS1t.js.map +1 -0
- package/dist/assets/{networkReason-DMffkiJ6.js → networkReason-n2oBs4by.js} +3 -3
- package/dist/assets/{networkReason-DMffkiJ6.js.map → networkReason-n2oBs4by.js.map} +1 -1
- package/dist/assets/{nwc-2vH18oNy.js → nwc-Do3VSlIS.js} +6 -5
- package/dist/assets/nwc-Do3VSlIS.js.map +1 -0
- package/dist/assets/{nwcProvider-DpeDy0bV.js → nwcProvider-Du5aWNIn.js} +6 -3
- package/dist/assets/{nwcProvider-DpeDy0bV.js.map → nwcProvider-Du5aWNIn.js.map} +1 -1
- package/dist/assets/{ownDid-iKz8u_fM.js → ownDid-CwwYu8s2.js} +3 -3
- package/dist/assets/{ownDid-iKz8u_fM.js.map → ownDid-CwwYu8s2.js.map} +1 -1
- package/dist/assets/{ownStatus-BlRKnM5F.js → ownStatus-D7dB4zJB.js} +4 -3
- package/dist/assets/{ownStatus-BlRKnM5F.js.map → ownStatus-D7dB4zJB.js.map} +1 -1
- package/dist/assets/{profiles-B5e0TyvS.js → profiles-NyF5FnYF.js} +82 -6
- package/dist/assets/profiles-NyF5FnYF.js.map +1 -0
- package/dist/assets/{registry-Cc_PQb3k.js → registry-C734VrO9.js} +1 -1
- package/dist/assets/{registry-CnFO2Pp5.js → registry-DKDInr0A.js} +75 -23
- package/dist/assets/registry-DKDInr0A.js.map +1 -0
- package/dist/assets/{resolve-DI8uAM_Y.js → resolve-3Tqh9AWQ.js} +4 -3
- package/dist/assets/resolve-3Tqh9AWQ.js.map +1 -0
- package/dist/assets/{server-DdtPxkqI.js → server-B6PQ6iae.js} +430 -868
- package/dist/assets/server-B6PQ6iae.js.map +1 -0
- package/dist/assets/{src-BnpEQqzk.js → src-ChJijTlM.js} +1139 -243
- package/dist/assets/src-ChJijTlM.js.map +1 -0
- package/dist/assets/{sshForges-cdIAraDw.js → sshForges-Brf0fslM.js} +2 -2
- package/dist/assets/{sshForges-cdIAraDw.js.map → sshForges-Brf0fslM.js.map} +1 -1
- package/dist/assets/{translate-kNopA04L.js → translate-xLme9Rdh.js} +10 -8
- package/dist/assets/translate-xLme9Rdh.js.map +1 -0
- package/dist/assets/{types-C4_KafL_.js → types-Clyb52K2.js} +2 -1
- package/dist/assets/types-Clyb52K2.js.map +1 -0
- package/dist/assets/{usdt-CDaLhEYh.js → usdt-CSU5KzTV.js} +3 -3
- package/dist/assets/{usdt-CDaLhEYh.js.map → usdt-CSU5KzTV.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +3592 -0
- package/package.json +5 -3
- package/dist/assets/api-CTqIcdu7.js.map +0 -1
- package/dist/assets/apiKit-CZq4Lq4f.js.map +0 -1
- package/dist/assets/apps-C_X0zgSG.js.map +0 -1
- package/dist/assets/backup-OTvrmk-w.js.map +0 -1
- package/dist/assets/buttons-4EKtQl-7.js +0 -2
- package/dist/assets/buttons-DUu7hxxT.js.map +0 -1
- package/dist/assets/childEnv-BVOQK9EA.js.map +0 -1
- package/dist/assets/client-DDpZP1R1.js.map +0 -1
- package/dist/assets/endpoint-DWHkXWVM.js +0 -419
- package/dist/assets/endpoint-DWHkXWVM.js.map +0 -1
- package/dist/assets/fedimintSdk-CqTeMdF0.js.map +0 -1
- package/dist/assets/host-BlUzZgQL.js.map +0 -1
- package/dist/assets/irohWeb-CqPN8VPY.js.map +0 -1
- package/dist/assets/main-vQjlgEnt.js.map +0 -1
- package/dist/assets/mainline-p6HOW7sb.js.map +0 -1
- package/dist/assets/nwc-2vH18oNy.js.map +0 -1
- package/dist/assets/profiles-B5e0TyvS.js.map +0 -1
- package/dist/assets/registry-CnFO2Pp5.js.map +0 -1
- package/dist/assets/resolve-DI8uAM_Y.js.map +0 -1
- package/dist/assets/server-DdtPxkqI.js.map +0 -1
- package/dist/assets/src-BnpEQqzk.js.map +0 -1
- package/dist/assets/translate-kNopA04L.js.map +0 -1
- package/dist/assets/types-C4_KafL_.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backup-j47AzDvG.js","names":["join","openEnvelope"],"sources":["../../../browser/src/backup/stream.ts","../../../browser/src/backup/light.ts","../../src/backup.ts"],"sourcesContent":["import { fromBase64Url, toBase64Url } from \"./codec\";\n\n/**\n * A backup written and read a piece at a time (WISP 05, envelope version 2), so a profile with years of files never\n * has to fit in memory. The file is one line of clear JSON (the header), then frames:\n *\n * header line: {\"format\":\"ghostly-backup\",\"version\":2,\"protection\":\"passphrase\"|\"none\",...}\\n\n * frame: kind (1 byte) | length (4 bytes, big endian) | body\n *\n * A frame carries one record: a piece of JSON (gzip or plain) or a piece of a file's bytes, at most `FRAME_BYTES`\n * of them. The last frame is the final marker; a file that ends without it was cut short and is refused.\n *\n * - `passphrase`: the key comes from the passphrase as in version 1 (PBKDF2-SHA256, 600 000 rounds, 16 byte salt).\n * Every frame is sealed alone with AES-256-GCM: its nonce is the header's 7 random bytes, the frame's number\n * (4 bytes) and its kind (1 byte), and the SHA-256 of the header line is its associated data. A frame changed,\n * moved, dropped or retyped, a changed header, or a missing final marker fails to open.\n * - `none`: nothing is encrypted. A SHA-256 chain runs over the header line and every frame, and the final marker\n * holds its last value, so a damaged or cut file is refused. It proves nothing about who made the file.\n */\nexport const FRAME_BYTES = 1024 * 1024;\n/** No frame is larger than this: a reader refuses one that says it is, before reading it. */\nconst MAX_FRAME_BYTES = 64 * 1024 * 1024;\n/** One piece of JSON, decompressed: past it the backup is refused, not read. */\nconst MAX_JSON_BYTES = 256 * 1024 * 1024;\nconst MAX_HEADER_BYTES = 4096;\nconst ITERATIONS = 600_000;\nconst TAG_BYTES = 16;\n\nconst KIND = { gzipJson: 1, json: 2, bytes: 3, final: 255 } as const;\n\n/**\n * The envelope version of a bundle that carries a device set (WISP 06 § Compatibility and rollout): an app from before\n * WISP 06 refuses it with \"This backup comes from a newer Ghostly\", rather than restoring a copy that stops nothing.\n * WISP 06 names it version 2, but WISP 05's streamed bundle took 2 first; every other bundle is still 2.\n */\nexport const DEVICE_SET_BACKUP_VERSION = 3;\n\nexport interface BackupHeader {\n format: \"ghostly-backup\";\n version: 2 | 3;\n protection: \"passphrase\" | \"none\";\n kdf?: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher?: { name: \"AES-256-GCM\"; nonce: string };\n check?: { name: \"SHA-256-chain\" };\n}\n\n/** Where a backup is written: in order, a piece at a time. */\nexport interface BackupSink { write(bytes: Uint8Array): Promise<void> }\n/** Where a backup is read from: any range, so nothing is read before it is needed. */\nexport interface BackupSource { readonly size: number; read(offset: number, length: number): Promise<Uint8Array> }\n/** One record of a backup: JSON text, or a piece of the bytes of the file the JSON before it announced. */\nexport type BackupRecord = { json: string; bytes?: undefined } | { bytes: Uint8Array; json?: undefined };\n\n/** Thrown when the work was cancelled (`AbortSignal`): nothing is wrong with the backup. */\nexport class BackupCancelled extends Error {\n constructor() { super(\"Cancelled\"); this.name = \"AbortError\"; }\n}\nexport const isCancelled = (error: unknown) => (error as { name?: string })?.name === \"AbortError\";\nconst check = (signal?: AbortSignal) => { if (signal?.aborted) throw new BackupCancelled(); };\n\n/** A Blob (a picked file) as a source, read in slices: never `stream()`, which WebKit fails on for some stored Blobs. */\nexport const blobSource = (blob: Blob): BackupSource => ({ size: blob.size, read: async (offset, length) => new Uint8Array(await blob.slice(offset, offset + length).arrayBuffer()) });\nexport const bytesSource = (bytes: Uint8Array): BackupSource => ({ size: bytes.length, read: async (offset, length) => bytes.subarray(offset, offset + length) });\n/** A sink that keeps what is written (tests, and a backup small enough to hand over whole). */\nexport function memorySink(): BackupSink & { bytes(): Uint8Array } {\n const parts: Uint8Array[] = [];\n return {\n write: async (bytes) => { parts.push(bytes.slice()); },\n bytes: () => { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let at = 0; for (const p of parts) { out.set(p, at); at += p.length; } return out; },\n };\n}\n\nconst canCompress = () => typeof CompressionStream !== \"undefined\";\nasync function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream, limit = Infinity): Promise<Uint8Array> {\n const reader = new Blob([bytes as BlobPart]).stream().pipeThrough(stream).getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (let next = await reader.read(); !next.done; next = await reader.read()) {\n size += next.value.length;\n if (size > limit) { await reader.cancel(); throw new Error(\"This backup is too large to restore\"); }\n chunks.push(next.value);\n }\n if (chunks.length === 1) return chunks[0];\n const out = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) { out.set(chunk, at); at += chunk.length; }\n return out;\n}\n\nasync function keyFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\nconst sha256 = async (...parts: Uint8Array[]) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", join(parts) as BufferSource));\nfunction join(parts: Uint8Array[]): Uint8Array {\n if (parts.length === 1) return parts[0];\n const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n let at = 0;\n for (const part of parts) { out.set(part, at); at += part.length; }\n return out;\n}\nfunction prefix(kind: number, length: number): Uint8Array {\n const out = new Uint8Array(5);\n out[0] = kind;\n new DataView(out.buffer).setUint32(1, length);\n return out;\n}\nfunction nonce(base: Uint8Array, frame: number, kind: number): Uint8Array {\n const out = new Uint8Array(12);\n out.set(base, 0);\n new DataView(out.buffer).setUint32(7, frame);\n out[11] = kind;\n return out;\n}\n\n/** Writes a backup: `json` and `bytes` in the order they are to be read, then `finish`. */\nexport class BackupWriter {\n private frame = 0;\n /** Bytes handed to the sink so far. */\n written = 0;\n private finished = false;\n /** Set once the sink refused a frame: the error it gave, thrown again at every later write. */\n private failed: { error: unknown } | null = null;\n\n private constructor(private readonly sink: BackupSink, private readonly key: CryptoKey | null, private readonly base: Uint8Array, private chain: Uint8Array, private readonly signal?: AbortSignal) {}\n\n /** `passphrase` null: a backup anyone can read (the caller has made sure that is what the person chose). */\n static async start(sink: BackupSink, passphrase: string | null, signal?: AbortSignal, version: 2 | 3 = 2): Promise<BackupWriter> {\n if (passphrase !== null && passphrase.length < 12) throw new Error(\"Use at least 12 characters for the backup passphrase\");\n check(signal);\n const salt = crypto.getRandomValues(new Uint8Array(16)), base = crypto.getRandomValues(new Uint8Array(7));\n const header: BackupHeader = passphrase === null\n ? { format: \"ghostly-backup\", version, protection: \"none\", check: { name: \"SHA-256-chain\" } }\n : { format: \"ghostly-backup\", version, protection: \"passphrase\", kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", nonce: toBase64Url(base) } };\n const line = new TextEncoder().encode(`${JSON.stringify(header)}\\n`);\n const key = passphrase === null ? null : await keyFrom(passphrase, salt, ITERATIONS);\n const writer = new BackupWriter(sink, key, base, await sha256(line), signal);\n await sink.write(line);\n writer.written = line.length;\n return writer;\n }\n\n private async put(kind: number, plain: Uint8Array): Promise<void> {\n check(this.signal);\n if (this.failed) throw this.failed.error;\n if (this.finished) throw new Error(\"This backup is already finished\");\n if (this.frame >= 0xffffffff) throw new Error(\"This backup is too large\");\n // What a reader refuses is not written: found out now, not when the backup is needed.\n if (plain.length > MAX_FRAME_BYTES) throw new Error(\"A record of this profile is too large for a backup\");\n let out: Uint8Array;\n if (this.key) {\n // The header's digest is every frame's associated data: a frame of another backup, or under a changed header, fails.\n const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce(this.base, this.frame, kind) as BufferSource, additionalData: this.chain as BufferSource }, this.key, plain as BufferSource));\n out = join([prefix(kind, sealed.length), sealed]);\n } else {\n const head = prefix(kind, kind === KIND.final ? 32 : plain.length);\n if (kind === KIND.final) out = join([head, this.chain]);\n else { out = join([head, plain]); this.chain = await sha256(this.chain, out); }\n }\n this.frame += 1;\n // A frame the sink did not take (no room left, say) is the end of this backup: every frame after it would be\n // numbered past a gap, and the file would never open. Nothing more is written, whatever the caller does next.\n try { await this.sink.write(out); } catch (error) { this.failed = { error }; throw error; }\n this.written += out.length;\n }\n\n /** One piece of JSON, compressed where the platform can. */\n async json(text: string): Promise<void> {\n const plain = new TextEncoder().encode(text);\n if (plain.length > MAX_JSON_BYTES) throw new Error(\"A record of this profile is too large for a backup\");\n if (canCompress()) await this.put(KIND.gzipJson, await through(plain, new CompressionStream(\"gzip\")));\n else await this.put(KIND.json, plain);\n }\n\n /** Bytes of the file the last JSON announced, cut into frames. */\n async bytes(chunk: Uint8Array): Promise<void> {\n for (let at = 0; at < chunk.length; at += FRAME_BYTES) await this.put(KIND.bytes, chunk.subarray(at, Math.min(chunk.length, at + FRAME_BYTES)));\n }\n\n /** The final marker: without it a reader refuses the backup. Resolves to the size of the whole backup. */\n async finish(): Promise<number> {\n await this.put(KIND.final, new Uint8Array());\n this.finished = true;\n return this.written;\n }\n}\n\n/** The first line of a version 2 backup, or null when this is not one (version 1 is one JSON object with no line end). */\nexport async function readBackupHeader(source: BackupSource): Promise<{ header: BackupHeader; line: Uint8Array } | null> {\n const start = await source.read(0, Math.min(MAX_HEADER_BYTES, source.size));\n const end = start.indexOf(10);\n if (end < 0) return null;\n let header: BackupHeader;\n try { header = JSON.parse(new TextDecoder().decode(start.subarray(0, end))) as BackupHeader; } catch { return null; }\n if (header?.format !== \"ghostly-backup\" || typeof header.version !== \"number\" || header.version < 2) return null;\n if (header.version !== 2 && header.version !== DEVICE_SET_BACKUP_VERSION) throw new Error(\"This backup comes from a newer Ghostly; update to restore it\");\n if (header.protection === \"none\") {\n if (header.check?.name !== \"SHA-256-chain\") throw new Error(\"Unsupported backup format\");\n } else if (header.protection === \"passphrase\") {\n if (header.kdf?.name !== \"PBKDF2-SHA256\" || !(header.kdf.iterations >= ITERATIONS) || header.kdf.iterations > 10_000_000 || header.cipher?.name !== \"AES-256-GCM\") throw new Error(\"Unsupported backup encryption\");\n } else throw new Error(\"Unsupported backup format\");\n return { header, line: start.slice(0, end + 1) };\n}\n\n/** How a backup is protected, read from its clear header without opening it: version 1 is always sealed. */\nexport async function backupProtection(source: BackupSource): Promise<\"passphrase\" | \"none\"> {\n return (await readBackupHeader(source))?.header.protection ?? \"passphrase\";\n}\n\nconst DAMAGED = \"This backup is damaged: it was changed or cut short\";\n\n/** Reads a version 2 backup record by record. Nothing of a frame is handed out before it passed its check. */\nexport class BackupReader {\n private frame = 0;\n private at: number;\n private block: Uint8Array = new Uint8Array();\n private blockAt = 0;\n private done = false;\n\n private constructor(private readonly source: BackupSource, private readonly key: CryptoKey | null, private readonly base: Uint8Array, private chain: Uint8Array, start: number, private readonly signal?: AbortSignal) { this.at = start; }\n\n get protection(): \"passphrase\" | \"none\" { return this.key ? \"passphrase\" : \"none\"; }\n\n /** Null when `source` is not a version 2 backup. `passphrase` is needed, and used, only for a sealed one. */\n static async open(source: BackupSource, passphrase?: string, signal?: AbortSignal): Promise<BackupReader | null> {\n const found = await readBackupHeader(source);\n if (!found) return null;\n check(signal);\n const { header, line } = found;\n if (header.protection === \"none\") return new BackupReader(source, null, new Uint8Array(), await sha256(line), line.length, signal);\n let key: CryptoKey, base: Uint8Array;\n try {\n base = fromBase64Url(header.cipher!.nonce);\n if (base.length !== 7) throw new Error(\"nonce\");\n key = await keyFrom(passphrase ?? \"\", fromBase64Url(header.kdf!.salt), header.kdf!.iterations);\n } catch { throw new Error(\"Unsupported backup encryption\"); }\n return new BackupReader(source, key, base, await sha256(line), line.length, signal);\n }\n\n /** Bytes of the source read so far (for progress). */\n get position(): number { return this.at; }\n\n /** `length` bytes at the reading point, through a read-ahead block so a source is asked a few times per megabyte, not per frame. */\n private async take(length: number): Promise<Uint8Array> {\n if (this.at + length > this.source.size) throw new Error(DAMAGED);\n const from = this.at - this.blockAt;\n if (from < 0 || from + length > this.block.length) {\n this.block = await this.source.read(this.at, Math.min(this.source.size - this.at, Math.max(length, 4 * FRAME_BYTES)));\n this.blockAt = this.at;\n if (this.block.length < length) throw new Error(DAMAGED);\n }\n const out = this.block.subarray(this.at - this.blockAt, this.at - this.blockAt + length);\n this.at += length;\n return out;\n }\n\n /** The next record, or null at the end: only then is the backup known to be whole. */\n async next(): Promise<BackupRecord | null> {\n check(this.signal);\n if (this.done) return null;\n const head = await this.take(5);\n const kind = head[0], length = new DataView(head.buffer, head.byteOffset, 5).getUint32(1);\n if (length > MAX_FRAME_BYTES + TAG_BYTES || !Object.values(KIND).includes(kind as never)) throw new Error(DAMAGED);\n const headCopy = head.slice();\n const body = await this.take(length);\n let plain: Uint8Array;\n if (this.key) {\n try {\n plain = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce(this.base, this.frame, kind) as BufferSource, additionalData: this.chain as BufferSource }, this.key, body as BufferSource));\n } catch { throw new Error(this.frame === 0 ? \"Wrong passphrase, or the backup was changed\" : DAMAGED); }\n } else if (kind === KIND.final) {\n if (body.length !== 32 || body.some((byte, i) => byte !== this.chain[i])) throw new Error(DAMAGED);\n plain = new Uint8Array();\n } else {\n this.chain = await sha256(this.chain, headCopy, body);\n plain = body.slice();\n }\n this.frame += 1;\n if (kind === KIND.final) {\n if (plain.length || this.at !== this.source.size) throw new Error(DAMAGED);\n this.done = true;\n return null;\n }\n if (kind === KIND.bytes) return { bytes: plain };\n const text = kind === KIND.gzipJson ? await through(plain, new DecompressionStream(\"gzip\"), MAX_JSON_BYTES).catch((error: unknown) => { throw error instanceof Error && error.message.startsWith(\"This backup is too large\") ? error : new Error(DAMAGED); }) : plain;\n return { json: new TextDecoder().decode(text) };\n }\n}\n","/**\n * A light backup (WISP 05 § Light backups): everything of a profile but the bytes of its larger files. Their messages\n * and records stay; after a restore they show as not in this backup.\n *\n * The cut: a file of at most 1 MiB keeps its bytes (a short clip, a sticker, a screenshot, a document), and so does a\n * voice message of at most 4 MiB. Voice messages are part of the conversation, and the longest one the apps record\n * (15 minutes at 32 kbit/s, `VOICE_LIMITS`) is about 3.6 MB, so every recorded one stays. Photos from a camera\n * (usually 2 to 8 MB), videos and large files are what is left out.\n */\nexport const LIGHT_FILE_BYTES = 1024 * 1024;\nexport const LIGHT_VOICE_BYTES = 4 * 1024 * 1024;\n\n/** What a light bundle says of itself in its first record: its cut, and what it left out. */\nexport interface LightMark {\n maxFileBytes: number;\n maxVoiceBytes: number;\n /** How many files were left out, and their bytes. */\n files: number;\n bytes: number;\n}\n\n/** Whether a file of this size keeps its bytes in a light backup. */\nexport const keptInLight = (size: number, voice: boolean): boolean => size <= (voice ? LIGHT_VOICE_BYTES : LIGHT_FILE_BYTES);\n","import { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { link, mkdir, open, readdir, readFile, rename, rm, stat, writeFile, type FileHandle } from \"node:fs/promises\";\nimport { basename, dirname, join, relative, resolve, sep } from \"node:path\";\nimport { open as openEnvelope } from \"@ghostly/browser/backup/envelope\";\nimport { BackupReader, BackupWriter, FRAME_BYTES, readBackupHeader, type BackupSource } from \"@ghostly/browser/backup/stream\";\nimport { LIGHT_FILE_BYTES, LIGHT_VOICE_BYTES, keptInLight, type LightMark } from \"@ghostly/browser/backup/light\";\nimport { fileStore } from \"@ghostly/browser/shared/idb\";\nimport { bool, str, type Method } from \"./apiKit\";\nimport { CliError, localFileError } from \"./errors\";\nimport { RESTORED_MARK, profileExists, profilePaths, type ProfilePaths } from \"./profiles\";\n\n/**\n * A headless profile's backup: the WISP 05 envelope around the profile itself, its store and its files, written and\n * read a piece at a time (envelope version 2), so a profile with large files never has to fit in memory. It restores\n * into a new headless profile; the app's own backups are made from its page's storage and are not this format\n * (WISP 1100 § Parity). A backup an older CLI made (version 1: everything in one sealed JSON document) still restores.\n */\nconst FORMAT = \"ghostly-cli-profile/2\";\nconst FORMAT_1 = \"ghostly-cli-profile/1\";\n\n/** Version 1: the store and every file as base64 in one document. */\ninterface Payload1 { format: typeof FORMAT_1; createdAt: number; store: string; files: { path: string; data: string }[] }\n/** Version 2, in order: the head, then each file (the store first) followed by its bytes, then the end. */\n/**\n * `light`: a light backup (WISP 05 § Light backups) left the bytes of these files out. Their records are in the store;\n * the restored profile marks them when it first starts (`markLeftOutFiles`).\n */\ntype BackupRecord =\n | { t: \"profile\"; format: typeof FORMAT; createdAt: number; files: number; bytes: number; light?: LightMark & { ids: string[] } }\n | { t: \"file\"; kind: \"store\" | \"file\"; path?: string; size: number }\n | { t: \"setting\"; name: string; text: string }\n | { t: \"end\"; files: number; bytes: number };\n\n/**\n * The profile's settings kept beside its store, which name its chats and their contacts' keys: auto-join (`groups.json`),\n * auto-answer (`calls.json`) and the chats held off their direct link (`holds.json`, `chat disconnect --hold`: the\n * store has such a chat on DHT only, and only this file says it comes back; the restored daemon ends a hold whose time\n * passed meanwhile at its start). Each travels as a `setting` record (an older CLI skips it); a backup without them\n * restores with auto-join and auto-answer off and no hold.\n */\nconst HOLDS = \"holds.json\";\nconst SETTINGS = [\"groups.json\", \"calls.json\", HOLDS];\n\n/** A setting's text, or null for one the profile never wrote. */\nconst readSetting = (dir: string, name: string) => readFile(join(dir, name), \"utf8\").catch(unlessGone);\n\n/** The holds a read of holds.json names (`holds.ts`), none for a file that does not parse, as the daemon reads it. */\nfunction parseHolds(text: string | undefined): Record<string, unknown> {\n try {\n const holds: unknown = JSON.parse(text ?? \"{}\");\n return holds && typeof holds === \"object\" && !Array.isArray(holds) ? holds as Record<string, unknown> : {};\n } catch { return {}; }\n}\n\n/**\n * Null for a file the profile removed since it was named (a deleted or disappearing message's, a group's files): the\n * daemon goes on while a backup runs, and such a file is left out of it, as one the profile no longer has.\n */\nconst unlessGone = (error: NodeJS.ErrnoException) => { if (error.code === \"ENOENT\") return null; throw error; };\n\nasync function walk(root: string, dir = root, out: string[] = []): Promise<string[]> {\n let names: string[];\n try { names = await readdir(dir); } catch { return out; }\n for (const name of names) {\n const path = join(dir, name);\n const found = await stat(path).catch(unlessGone);\n if (!found) continue;\n if (found.isDirectory()) await walk(root, path, out);\n else out.push(relative(root, path));\n }\n return out;\n}\n\n/** A file's first `size` bytes into the backup, a frame at a time. One that got shorter meanwhile stops the backup. */\nasync function copyIn(writer: BackupWriter, path: string, size: number, opened?: FileHandle): Promise<void> {\n const handle = opened ?? await open(path, \"r\");\n try {\n const buffer = new Uint8Array(FRAME_BYTES);\n for (let at = 0; at < size;) {\n const { bytesRead } = await handle.read(buffer, 0, Math.min(FRAME_BYTES, size - at), at);\n if (!bytesRead) throw new CliError(\"unavailable\", `${path} changed while it was backed up: try again`);\n await writer.bytes(buffer.subarray(0, bytesRead));\n at += bytesRead;\n }\n } finally { await handle.close(); }\n}\n\nexport const BACKUP_METHODS: Record<string, Method> = {\n /**\n * Writes the backup to `path` (resolved by the command), sealed with `passphrase`, or not encrypted when\n * `noPassphrase` is true: one of the two, never a guess. The store is written whole for it, every value inline. It is\n * written beside `path` and only takes its name once it is complete: a backup that fails leaves no file. `light`:\n * the files over the cut (`keptInLight`) are left out, their records kept.\n */\n async \"profile.backup\"(ctx, params) {\n const path = resolve(str(params, \"path\", true));\n // `refused`, not `confirm` (exit 5, \"pass --force\"): backup takes no flag that writes over a file.\n if (existsSync(path)) throw new CliError(\"refused\", `${path} exists: choose another name`);\n const passphrase = str(params, \"passphrase\"), unsealed = bool(params, \"noPassphrase\");\n if (!passphrase && !unsealed) throw new CliError(\"bad_request\", \"passphrase is required (or noPassphrase: true for a backup anyone can read)\");\n if (passphrase && unsealed) throw new CliError(\"bad_request\", \"Give a passphrase or noPassphrase, not both\");\n // The folder it goes in, checked first: a missing one is named, not the file written beside `path`.\n const folder = dirname(path);\n if (!(await stat(folder)).isDirectory()) throw new CliError(\"not_found\", `No such file or folder: ${folder}`);\n const paths = ctx.runtime.paths;\n // The store as one snapshot with every value in it (the messages too, which the profile keeps in rows.db): a backup\n // any ghostly restores, this one or an older one. Its name is this backup's own: two at once in one daemon shared\n // one by the process id, and the first packed the other's store as its own, or removed it under the other.\n const store = join(paths.db, `backup-store-${process.pid}-${randomBytes(6).toString(\"hex\")}.bin`);\n // The settings before the store, and the holds again after it, the backup keeping both reads' holds: a hold that\n // ends in between is in the backup with its chat already back on its live link (the restored daemon ends it,\n // nothing more), and one that starts in between (`holdChat` writes it before the chat goes on DHT only) is in it\n // too. Never the chat on DHT only with no hold to end.\n const settings: { name: string; text: string }[] = [];\n for (const name of SETTINGS) {\n const text = await readSetting(paths.dir, name);\n if (text !== null) settings.push({ name, text });\n }\n await ctx.runtime.store.exportSnapshot(store);\n const holds = settings.find((setting) => setting.name === HOLDS), after = await readSetting(paths.dir, HOLDS);\n if (after !== null && after !== holds?.text) {\n const text = JSON.stringify({ ...parseHolds(holds?.text), ...parseHolds(after) }) + \"\\n\";\n if (holds) holds.text = text; else settings.push({ name: HOLDS, text });\n }\n const light = bool(params, \"light\");\n const found = await Promise.all((await walk(paths.files)).map(async (name) => {\n const file = await stat(join(paths.files, name)).catch(unlessGone);\n return file && { name, size: file.size };\n }));\n const all = found.filter((file) => file !== null);\n // A file's name is its id: only one that could be a voice message under its larger cut is looked up.\n const kept = async (file: { name: string; size: number }) => keptInLight(file.size, false) || (file.size <= LIGHT_VOICE_BYTES && !!(await fileStore.get(basename(file.name)).catch(() => undefined))?.metadata?.voice);\n const files: typeof all = [], leftOut: typeof all = [];\n for (const file of all) (!light || (await kept(file)) ? files : leftOut).push(file);\n const storeSize = (await stat(store)).size, bytes = files.reduce((sum, file) => sum + file.size, 0);\n const leftOutBytes = leftOut.reduce((sum, file) => sum + file.size, 0);\n\n const partial = `${path}.partial-${process.pid}`;\n let out: FileHandle | null = null;\n try {\n out = await openFile(partial);\n const handle = out;\n let writer: BackupWriter;\n try { writer = await BackupWriter.start({ write: async (chunk) => { await handle.write(chunk); } }, unsealed ? null : passphrase!); } catch (error) { throw localFileError(error, path) ?? new CliError(\"bad_request\", error instanceof Error ? error.message : String(error)); }\n const put = (record: BackupRecord) => writer.json(JSON.stringify(record));\n await put({ t: \"profile\", format: FORMAT, createdAt: Date.now(), files: files.length, bytes, ...(light && { light: { maxFileBytes: LIGHT_FILE_BYTES, maxVoiceBytes: LIGHT_VOICE_BYTES, files: leftOut.length, bytes: leftOutBytes, ids: leftOut.map((file) => basename(file.name)) } }) });\n await put({ t: \"file\", kind: \"store\", size: storeSize });\n await copyIn(writer, store, storeSize);\n // Each file opened before its record: one removed since the walk is left out, and the end counts what went in.\n let copied = 0, copiedBytes = 0;\n for (const file of files) {\n const path = join(paths.files, file.name), handle = await open(path, \"r\").catch(unlessGone);\n if (!handle) continue;\n await put({ t: \"file\", kind: \"file\", path: file.name.split(sep).join(\"/\"), size: file.size });\n await copyIn(writer, path, file.size, handle);\n copied++;\n copiedBytes += file.size;\n }\n for (const { name, text } of settings) await put({ t: \"setting\", name, text });\n await put({ t: \"end\", files: copied, bytes: copiedBytes });\n const written = await writer.finish();\n await handle.sync();\n await handle.close();\n out = null;\n // Its name only now, and never over a file that appeared meanwhile.\n try { await link(partial, path); } catch (error) { throw (error as NodeJS.ErrnoException).code === \"EEXIST\" ? new CliError(\"refused\", `${path} exists: choose another name`) : error; }\n return { path, bytes: written, files: copied, protection: unsealed ? \"none\" : \"passphrase\", ...(light && { light: true, leftOut: leftOut.length, leftOutBytes }) };\n } catch (error) {\n // A write into the backup that found its disk full names the backup, not Node's bare \"write\".\n if ((error as NodeJS.ErrnoException)?.code === \"ENOSPC\" || (error as NodeJS.ErrnoException)?.code === \"EDQUOT\") throw localFileError(error, path) ?? error;\n throw error;\n } finally {\n await out?.close().catch(() => {});\n await rm(partial, { force: true });\n await rm(store, { force: true });\n }\n },\n};\n\nasync function openFile(path: string): Promise<FileHandle> {\n try { return await open(path, \"wx\", 0o600); } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") { await rm(path, { force: true }); return open(path, \"wx\", 0o600); }\n throw error;\n }\n}\n\n/** A file on disk as a backup's source: read in ranges, never whole. A folder opens, and is refused as one here. */\nasync function fileSource(path: string): Promise<BackupSource & { close(): Promise<void> }> {\n const handle = await open(path, \"r\");\n const found = await handle.stat();\n if (found.isDirectory()) { await handle.close(); throw new CliError(\"bad_request\", `${path} is a folder: name a file`); }\n const { size } = found;\n return {\n size,\n read: async (offset, length) => {\n const buffer = new Uint8Array(Math.max(0, Math.min(length, size - offset)));\n let got = 0;\n while (got < buffer.length) { const { bytesRead } = await handle.read(buffer, got, buffer.length - got, offset + got); if (!bytesRead) break; got += bytesRead; }\n return buffer.subarray(0, got);\n },\n close: () => handle.close(),\n };\n}\n\n/** A version 1 backup is one JSON object, and `seal` writes its format first. */\nconst VERSION_1_START = /^\\s*\\{\\s*\"format\"\\s*:\\s*\"ghostly-backup\"/;\n\n/**\n * Whether the backup at `file` is sealed with a passphrase or was made without one, read from its clear header.\n * A file that is neither version is refused here, before any passphrase is asked for: the path is what is wrong.\n */\nexport async function backupFileProtection(file: string): Promise<\"passphrase\" | \"none\"> {\n const source = await fileSource(file);\n try {\n let found: Awaited<ReturnType<typeof readBackupHeader>>;\n try { found = await readBackupHeader(source); } catch (error) { throw new CliError(\"refused\", error instanceof Error ? error.message : String(error)); }\n if (found) return found.header.protection;\n if (!VERSION_1_START.test(new TextDecoder().decode(await source.read(0, 256)))) throw new CliError(\"refused\", \"This is not a Ghostly backup\");\n return \"passphrase\";\n } finally { await source.close(); }\n}\n\n/** Where a path named by a backup lands inside the new profile's files folder; never outside it. */\nfunction inside(root: string, path: unknown): string {\n const target = typeof path === \"string\" && path ? resolve(root, path) : \"\";\n if (!target.startsWith(resolve(root) + sep)) throw new CliError(\"refused\", \"The backup names a file outside its folder\");\n return target;\n}\n\n/** While a restore writes it, the profile's folder is not a profile: no profile name starts with a dot (`listProfiles`). */\nconst RESTORING = /^\\.restoring-(.+)-(\\d+)$/;\n\n/**\n * The folder a restore writes into, beside the profiles: it takes the profile's name only once everything is in it,\n * so a restore that is stopped at any moment (Ctrl-C, a kill, the power) leaves no profile, whole or half-made.\n * What an earlier restore that was stopped left behind is removed here, once the process that made it is gone.\n */\nasync function restoringFolder(home: string, name: string): Promise<ProfilePaths> {\n const root = join(home, \"profiles\");\n await mkdir(root, { recursive: true, mode: 0o700 });\n for (const entry of await readdir(root)) {\n const pid = Number(RESTORING.exec(entry)?.[2]);\n if (!pid) continue;\n let alive = pid === process.pid;\n if (!alive) try { process.kill(pid, 0); alive = true; } catch (error) { alive = (error as NodeJS.ErrnoException).code === \"EPERM\"; }\n if (!alive) await rm(join(root, entry), { recursive: true, force: true });\n }\n const dir = join(root, `.restoring-${name}-${process.pid}`);\n await rm(dir, { recursive: true, force: true });\n await mkdir(dir, { mode: 0o700 });\n return { ...profilePaths(home, name), dir, db: join(dir, \"db\"), files: join(dir, \"files\") };\n}\n\n/**\n * The folder is whole: marked as a restored copy (`RESTORED_MARK`, which names the files a light backup left out),\n * then given the profile's name. Never over a profile.\n */\nasync function finishRestore(home: string, name: string, work: ProfilePaths, leftOut: string[] = []): Promise<ProfilePaths> {\n const paths = profilePaths(home, name);\n await writeFile(join(work.dir, RESTORED_MARK), leftOut.length ? JSON.stringify({ leftOut }) : \"\", { mode: 0o600 });\n if (existsSync(paths.dir)) throw new CliError(\"refused\", `Profile ${name} exists: restore into a new name`);\n await rename(work.dir, paths.dir);\n return paths;\n}\n\n/**\n * Opens the backup at `file` into a new profile (never over an existing one), with its passphrase when it has one.\n * Runs with no engine: nothing is open yet. A backup that is refused, damaged or cut short leaves no profile behind,\n * and neither does a restore that is stopped while it runs (`restoringFolder`). The profile is marked as a restored\n * copy: its engine, the first time it starts, treats the money in it as a restore does (`RESTORED_MARK`).\n */\nexport async function restoreProfile(home: string, name: string, file: string, passphrase?: string): Promise<ProfilePaths> {\n if (profileExists(home, name)) throw new CliError(\"refused\", `Profile ${name} exists: restore into a new name`);\n const source = await fileSource(file);\n let work: ProfilePaths | null = null;\n try {\n let reader: BackupReader | null;\n try { reader = await BackupReader.open(source, passphrase); } catch (error) { throw new CliError(\"refused\", error instanceof Error ? error.message : String(error)); }\n if (!reader) {\n const payload = await readWhole(file, passphrase ?? \"\");\n work = await restoringFolder(home, name);\n await writeWhole(work, payload);\n return await finishRestore(home, name, work);\n }\n const next = async () => { try { return await reader.next(); } catch (error) { throw new CliError(\"refused\", error instanceof Error ? error.message : String(error)); } };\n const parse = (json: string) => { try { return JSON.parse(json) as BackupRecord; } catch { throw new CliError(\"refused\", \"This backup is damaged: it was changed or cut short\"); } };\n\n // The first record is read (and with it the passphrase checked) before any folder is made.\n const first = await next();\n const head = first?.json === undefined ? null : parse(first.json);\n if (head?.t !== \"profile\" || head.format !== FORMAT) throw new CliError(\"refused\", \"This backup is not a headless Ghostly profile\");\n const leftOut = Array.isArray(head.light?.ids) ? head.light.ids.filter((id): id is string => typeof id === \"string\") : [];\n work = await restoringFolder(home, name);\n const paths = work;\n await mkdir(paths.db, { recursive: true, mode: 0o700 });\n let out: { handle: FileHandle; left: number } | null = null, files = 0, bytes = 0, ended = false, stored = false;\n try {\n for (let record = await next(); record; record = await next()) {\n if (ended) throw new CliError(\"refused\", \"This backup is damaged: it was changed or cut short\");\n if (record.bytes) {\n if (!out || record.bytes.length > out.left) throw new CliError(\"refused\", \"This backup is damaged: it was changed or cut short\");\n await out.handle.write(record.bytes);\n out.left -= record.bytes.length;\n continue;\n }\n if (out) { if (out.left) throw new CliError(\"refused\", \"This backup is damaged: it was changed or cut short\"); await out.handle.close(); out = null; }\n const value = parse(record.json);\n if (value.t === \"end\") { ended = value.files === files && value.bytes === bytes; if (!ended) throw new CliError(\"refused\", \"This backup is damaged: it was changed or cut short\"); continue; }\n if (value.t === \"setting\") {\n if (SETTINGS.includes(value.name) && typeof value.text === \"string\") {\n try { await writeFile(join(paths.dir, value.name), value.text, { mode: 0o600, flag: \"wx\" }); } catch (error) { throw (error as NodeJS.ErrnoException).code === \"EEXIST\" ? new CliError(\"refused\", \"This backup is damaged: it was changed or cut short\") : error; }\n }\n continue;\n }\n if (value.t !== \"file\" || !Number.isSafeInteger(value.size) || value.size < 0) continue;\n let target: string;\n if (value.kind === \"store\") { target = join(paths.db, \"snapshot.bin\"); stored = true; }\n else { target = inside(paths.files, value.path); await mkdir(dirname(target), { recursive: true, mode: 0o700 }); files += 1; bytes += value.size; }\n out = { handle: await open(target, \"wx\", 0o600), left: value.size };\n }\n if (out || !ended || !stored) throw new CliError(\"refused\", \"This backup is damaged: it was changed or cut short\");\n } finally { await out?.handle.close().catch(() => {}); }\n return await finishRestore(home, name, work, leftOut);\n } catch (error) {\n if (work) await rm(work.dir, { recursive: true, force: true });\n throw error;\n } finally {\n await source.close();\n }\n}\n\n/** A version 1 backup: one sealed JSON document, read whole. */\nasync function readWhole(file: string, passphrase: string): Promise<Payload1> {\n let payload: Payload1;\n try { payload = JSON.parse(await openEnvelope(await readFile(file, \"utf8\"), passphrase)) as Payload1; } catch (error) { throw new CliError(\"refused\", error instanceof Error ? error.message : String(error)); }\n if (payload?.format !== FORMAT_1 || typeof payload.store !== \"string\" || !Array.isArray(payload.files)) throw new CliError(\"refused\", \"This backup is not a headless Ghostly profile\");\n return payload;\n}\n\nasync function writeWhole(paths: ProfilePaths, payload: Payload1): Promise<void> {\n await mkdir(paths.db, { recursive: true, mode: 0o700 });\n await writeFile(join(paths.db, \"snapshot.bin\"), Buffer.from(payload.store, \"base64\"), { mode: 0o600 });\n for (const entry of payload.files) {\n const target = inside(paths.files, entry.path);\n await mkdir(dirname(target), { recursive: true, mode: 0o700 });\n await writeFile(target, Buffer.from(entry.data, \"base64\"), { mode: 0o600 });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,cAAc;;AAE3B,IAAM,kBAAkB;;AAExB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AACzB,IAAM,aAAa;AAGnB,IAAM,OAAO;CAAE,UAAU;CAAG,MAAM;CAAG,OAAO;CAAG,OAAO;AAAI;;AA0B1D,IAAa,kBAAb,cAAqC,MAAM;CACzC,cAAc;EAAE,MAAM,WAAW;EAAG,KAAK,OAAO;CAAc;AAChE;AAEA,IAAM,SAAS,WAAyB;CAAE,IAAI,QAAQ,SAAS,MAAM,IAAI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D,OAAO,MAAM,cAAc,MAAM,MAAM,MAAM,OAAO;CACtD,SAAS,OAAO;EACd,IAAI,MAAM,MAAM,GAAG,KAAK,KAAK;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;EAC7D,MAAM;CACR,UAAU;EACR,MAAM,OAAO,MAAM;CACrB;AACF;;AAGA,eAAe,UAAU,MAAc,YAAuC;CAC5E,IAAI;CACJ,IAAI;EAAE,UAAU,KAAK,MAAM,MAAMC,OAAa,MAAM,SAAS,MAAM,MAAM,GAAG,UAAU,CAAC;CAAe,SAAS,OAAO;EAAE,MAAM,IAAI,SAAS,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CAAG;CAC/M,IAAI,SAAS,WAAW,YAAY,OAAO,QAAQ,UAAU,YAAY,CAAC,MAAM,QAAQ,QAAQ,KAAK,GAAG,MAAM,IAAI,SAAS,WAAW,+CAA+C;CACrL,OAAO;AACT;AAEA,eAAe,WAAW,OAAqB,SAAkC;CAC/E,MAAM,MAAM,MAAM,IAAI;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CACtD,MAAM,UAAU,KAAK,MAAM,IAAI,cAAc,GAAG,OAAO,KAAK,QAAQ,OAAO,QAAQ,GAAG,EAAE,MAAM,IAAM,CAAC;CACrG,KAAK,MAAM,SAAS,QAAQ,OAAO;EACjC,MAAM,SAAS,OAAO,MAAM,OAAO,MAAM,IAAI;EAC7C,MAAM,MAAM,QAAQ,MAAM,GAAG;GAAE,WAAW;GAAM,MAAM;EAAM,CAAC;EAC7D,MAAM,UAAU,QAAQ,OAAO,KAAK,MAAM,MAAM,QAAQ,GAAG,EAAE,MAAM,IAAM,CAAC;CAC5E;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { s as networkMode, t as NothingSpentError } from "./types-
|
|
2
|
-
import "./bitcoindProvider-
|
|
1
|
+
import { s as networkMode, t as NothingSpentError } from "./types-Clyb52K2.js";
|
|
2
|
+
import "./bitcoindProvider-BvoRh0D5.js";
|
|
3
3
|
import { base64, hex } from "@scure/base";
|
|
4
4
|
import { Address, OutScript, Transaction } from "@scure/btc-signer";
|
|
5
5
|
//#region ../browser/src/engine/paymentAdapters/providers/bitcoind.ts
|
|
@@ -346,4 +346,4 @@ var BitcoindOnchain = class BitcoindOnchain {
|
|
|
346
346
|
//#endregion
|
|
347
347
|
export { BitcoindOnchain, tauriTransport };
|
|
348
348
|
|
|
349
|
-
//# sourceMappingURL=bitcoind-
|
|
349
|
+
//# sourceMappingURL=bitcoind-CdSmvy2y.js.map
|
|
@@ -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.amount);\n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AAY,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-
|
|
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-
|
|
97
|
+
//# sourceMappingURL=bitcoindProvider-BvoRh0D5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bitcoindProvider-
|
|
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() ?? \"\", ...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,7 +1,7 @@
|
|
|
1
|
-
import { Ao as
|
|
1
|
+
import { Ao as STATUS_CARD_LIMITS, Co as BUTTON_STYLES, Lo as checkStatusCard, Mi as BUTTONS_CAPABILITY, Po as buttonLabelClash, bd as toBase64Url, yd as randomBytes } from "./src-ChJijTlM.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,
|
|
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-lCTQ0EBG.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,20 @@ 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
|
+
/**
|
|
63
72
|
* Waits until an edge took my group message, or its edit number `edit`, or my reaction to it numbered `reaction`, or my
|
|
64
73
|
* 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.
|
|
74
|
+
* 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
|
|
75
|
+
* edge will ever take it, and the wait sat its whole time, then said "it goes when one opens" and exited 4, which a
|
|
76
|
+
* bot retries, sending it again each time.
|
|
66
77
|
*/
|
|
67
78
|
async function waitForGroupFrame(ctx, groupId, messageId, edit, ms) {
|
|
68
79
|
const until = performance.now() + ms;
|
|
@@ -73,7 +84,7 @@ async function waitForGroupFrame(ctx, groupId, messageId, edit, ms) {
|
|
|
73
84
|
messageId,
|
|
74
85
|
...which
|
|
75
86
|
});
|
|
76
|
-
if (taken > 0) return taken;
|
|
87
|
+
if (taken > 0 || nobodyElseIn(ctx, groupId)) return taken;
|
|
77
88
|
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
89
|
messageId,
|
|
79
90
|
..."edit" in which ? { edits: which.edit } : which
|
|
@@ -261,7 +272,7 @@ async function updateButtons(ctx, params) {
|
|
|
261
272
|
edits: message.edit.seq
|
|
262
273
|
});
|
|
263
274
|
const before = message.card;
|
|
264
|
-
if (chosen !== void 0 && !before.buttons.some((b) => b.id === chosen)) throw new CliError("
|
|
275
|
+
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
276
|
const card = checked({
|
|
266
277
|
...before,
|
|
267
278
|
...chosen !== void 0 && { chosen },
|
|
@@ -358,6 +369,6 @@ var BUTTON_METHODS = {
|
|
|
358
369
|
"button.update": updateButtons
|
|
359
370
|
};
|
|
360
371
|
//#endregion
|
|
361
|
-
export { goesOn as a,
|
|
372
|
+
export { goesOn as a, waitForEdit as c, waitForRemoval as d, pressable as i, waitForGroupFrame as l, buttonsCard as n, nobodyElseIn as o, buttonsOf as r, waitForConfirmed as s, BUTTON_METHODS as t, waitForMessage as u };
|
|
362
373
|
|
|
363
|
-
//# sourceMappingURL=buttons-
|
|
374
|
+
//# sourceMappingURL=buttons-CiGlBVBT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buttons-CiGlBVBT.js","names":["goesOnIn"],"sources":["../../src/waits.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 * 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.\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 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 { 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 { 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 guard as `send` and `edit`.\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,SAAkB,SAAS,KAAA,KAAa,iBAAiB,KAAK,IAAI,IACtG,yDAAyD,IAAI,SAAS,aAAa,8DAA8D,OACjJ,IAAI,SAAS,YAAY,QAAQ,GAAG,IAAI,qDAAqDA,SAAS,IAAI,IAAI;;;;;;AAOlH,IAAM,WAAW,QAAoB,IAAI,UAAU,YAAY;;A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
|
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
|
|
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-
|
|
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 {
|
|
2
|
+
import { m as lockPath, w as ownSocket } from "./profiles-NyF5FnYF.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 {
|
|
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-
|
|
552
|
+
//# sourceMappingURL=client-raIncVtF.js.map
|