@ghostlytools/cli 1.5.2 → 1.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -11
- package/dist/assets/{api-CHD8_kcJ.js → api-BIg0Msax.js} +2 -2
- package/dist/assets/{api-CMohP9Pw.js → api-d2aXkbM5.js} +341 -114
- package/dist/assets/api-d2aXkbM5.js.map +1 -0
- package/dist/assets/{apiKit-CfwVtBcw.js → apiKit-Ba_t7MZO.js} +4 -4
- package/dist/assets/apiKit-Ba_t7MZO.js.map +1 -0
- package/dist/assets/{apps-733nXRBy.js → apps-B_F3gEI4.js} +1 -1
- package/dist/assets/{apps-LG-QOIxs.js → apps-CJo1MmSY.js} +17 -16
- package/dist/assets/apps-CJo1MmSY.js.map +1 -0
- package/dist/assets/{arkade-C8x3Efyj.js → arkade-DTne0O3Q.js} +12 -5
- package/dist/assets/arkade-DTne0O3Q.js.map +1 -0
- package/dist/assets/{backup-CfJenOQo.js → backup-BY88aZr5.js} +11 -8
- package/dist/assets/backup-BY88aZr5.js.map +1 -0
- package/dist/assets/{backup-nCbNWJ7-.js → backup-CqpDAZZG.js} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
- package/dist/assets/{blobFiles-1wUBd8ZD.js → blobFiles-B1lX6iGy.js} +3 -3
- package/dist/assets/{blobFiles-1wUBd8ZD.js.map → blobFiles-B1lX6iGy.js.map} +1 -1
- package/dist/assets/{buttons-BC0stvPg.js → buttons-B5EnA2nh.js} +23 -6
- package/dist/assets/buttons-B5EnA2nh.js.map +1 -0
- package/dist/assets/buttons-azvbN6xn.js +2 -0
- package/dist/assets/{daemonProof-CWTVNUmr.js → daemonProof-Dx3N_DLC.js} +19 -37
- package/dist/assets/daemonProof-Dx3N_DLC.js.map +1 -0
- package/dist/assets/{endpoint-Cl3cgAYl.js → endpoint-BdaeBw2L.js} +3 -3
- package/dist/assets/endpoint-BdaeBw2L.js.map +1 -0
- package/dist/assets/{envelope-BbvUBjc5.js → envelope-BU-BB1wR.js} +2 -2
- package/dist/assets/{envelope-BbvUBjc5.js.map → envelope-BU-BB1wR.js.map} +1 -1
- package/dist/assets/{errors-BLSPp0tK.js → errors-DI6Z3jTH.js} +26 -1
- package/dist/assets/errors-DI6Z3jTH.js.map +1 -0
- package/dist/assets/{fileBytes-gTd_8l-P.js → fileBytes-BMlLVdfg.js} +1 -1
- package/dist/assets/{fileBytes-uRqLyxa0.js → fileBytes-D0CYuRwZ.js} +2 -2
- package/dist/assets/{fileBytes-uRqLyxa0.js.map → fileBytes-D0CYuRwZ.js.map} +1 -1
- package/dist/assets/{fileBytes-B8eTZfAT.js → fileBytes-D85lBh-Q.js} +3 -3
- package/dist/assets/{fileBytes-B8eTZfAT.js.map → fileBytes-D85lBh-Q.js.map} +1 -1
- package/dist/assets/fileBytesIdb-Dn9levD1.js +2 -0
- package/dist/assets/{fileBytesIdb-BIFKtgln.js → fileBytesIdb-LAhH7kY2.js} +7 -7
- package/dist/assets/fileBytesIdb-LAhH7kY2.js.map +1 -0
- package/dist/assets/{fileBytesOpfs-ChrHcCVV.js → fileBytesOpfs-DjBBghvq.js} +3 -3
- package/dist/assets/{fileBytesOpfs-ChrHcCVV.js.map → fileBytesOpfs-DjBBghvq.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-BsAEFIjl.js → ghostly_iroh_web-BXCsSxxo.js} +29 -29
- package/dist/assets/{ghostly_iroh_web-BsAEFIjl.js.map → ghostly_iroh_web-BXCsSxxo.js.map} +1 -1
- package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
- package/dist/assets/{groupFiles-Bmo-SkVQ.js → groupFiles-D9k6fyhf.js} +61 -17
- package/dist/assets/groupFiles-D9k6fyhf.js.map +1 -0
- package/dist/assets/{host-DxDRCRKD.js → host-DrL7FPG4.js} +125 -47
- package/dist/assets/host-DrL7FPG4.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-CZfsPfT9.js → hyperdhtRelay-C-BsT6_V.js} +2 -2
- package/dist/assets/{hyperdhtRelay-CZfsPfT9.js.map → hyperdhtRelay-C-BsT6_V.js.map} +1 -1
- package/dist/assets/{idb-BJARz3Qi.js → idb-CWvq4HKc.js} +25 -3
- package/dist/assets/{idb-BJARz3Qi.js.map → idb-CWvq4HKc.js.map} +1 -1
- package/dist/assets/{irohWeb-BUvaADop.js → irohWeb-DdHXEwgj.js} +3 -3
- package/dist/assets/{irohWeb-BUvaADop.js.map → irohWeb-DdHXEwgj.js.map} +1 -1
- package/dist/assets/{main-BIXIs84L.js → main-xeoX7yLM.js} +160 -50
- package/dist/assets/main-xeoX7yLM.js.map +1 -0
- package/dist/assets/{mainline-HQVJ5ukA.js → mainline-CEqGvRYJ.js} +46 -16
- package/dist/assets/mainline-CEqGvRYJ.js.map +1 -0
- package/dist/assets/{networkReason-CKBiFTwt.js → networkReason-RGRU5xoa.js} +3 -3
- package/dist/assets/{networkReason-CKBiFTwt.js.map → networkReason-RGRU5xoa.js.map} +1 -1
- package/dist/assets/{nwc-Dm4RSvvF.js → nwc-s5xHLqNf.js} +3 -3
- package/dist/assets/{nwc-Dm4RSvvF.js.map → nwc-s5xHLqNf.js.map} +1 -1
- package/dist/assets/{nwcProvider-yQdL-DfC.js → nwcProvider-CfAFO5Fr.js} +2 -2
- package/dist/assets/{nwcProvider-yQdL-DfC.js.map → nwcProvider-CfAFO5Fr.js.map} +1 -1
- package/dist/assets/{profiles-BehWURA9.js → profiles-gZdQPyaz.js} +74 -13
- package/dist/assets/profiles-gZdQPyaz.js.map +1 -0
- package/dist/assets/{registry-CHVZ0Jzl.js → registry-BUhSjM-J.js} +1 -1
- package/dist/assets/{registry-C9f2Ogff.js → registry-CVUdD4bJ.js} +3 -3
- package/dist/assets/{registry-C9f2Ogff.js.map → registry-CVUdD4bJ.js.map} +1 -1
- package/dist/assets/{resolve-Cqj1jjK2.js → resolve-uZECJ3f7.js} +2 -2
- package/dist/assets/{resolve-Cqj1jjK2.js.map → resolve-uZECJ3f7.js.map} +1 -1
- package/dist/assets/{restoredRows-DGuKtIBz.js → restoredRows-D6WZUA2U.js} +2 -2
- package/dist/assets/{restoredRows-DGuKtIBz.js.map → restoredRows-D6WZUA2U.js.map} +1 -1
- package/dist/assets/{server-CcAs54Yb.js → server-DOtUKoYR.js} +776 -248
- package/dist/assets/server-DOtUKoYR.js.map +1 -0
- package/dist/assets/{src-BLHey3Q1.js → src-Dd_7Ew1X.js} +459 -129
- package/dist/assets/src-Dd_7Ew1X.js.map +1 -0
- package/dist/assets/{usdt-DMKpMhdM.js → usdt-C2Anx8p7.js} +3 -3
- package/dist/assets/{usdt-DMKpMhdM.js.map → usdt-C2Anx8p7.js.map} +1 -1
- package/dist/assets/{words-DUlvkoUT.js → words-DoLU6p8H.js} +4 -4
- package/dist/assets/words-DoLU6p8H.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/package.json +1 -1
- package/dist/assets/api-CMohP9Pw.js.map +0 -1
- package/dist/assets/apiKit-CfwVtBcw.js.map +0 -1
- package/dist/assets/apps-LG-QOIxs.js.map +0 -1
- package/dist/assets/arkade-C8x3Efyj.js.map +0 -1
- package/dist/assets/backup-CfJenOQo.js.map +0 -1
- package/dist/assets/buttons-BC0stvPg.js.map +0 -1
- package/dist/assets/buttons-BDKeKyKw.js +0 -2
- package/dist/assets/daemonProof-CWTVNUmr.js.map +0 -1
- package/dist/assets/endpoint-Cl3cgAYl.js.map +0 -1
- package/dist/assets/errors-BLSPp0tK.js.map +0 -1
- package/dist/assets/fileBytesIdb-BIFKtgln.js.map +0 -1
- package/dist/assets/fileBytesIdb-BVVr_rWX.js +0 -2
- package/dist/assets/groupFiles-Bmo-SkVQ.js.map +0 -1
- package/dist/assets/host-DxDRCRKD.js.map +0 -1
- package/dist/assets/main-BIXIs84L.js.map +0 -1
- package/dist/assets/mainline-HQVJ5ukA.js.map +0 -1
- package/dist/assets/profiles-BehWURA9.js.map +0 -1
- package/dist/assets/server-CcAs54Yb.js.map +0 -1
- package/dist/assets/src-BLHey3Q1.js.map +0 -1
- package/dist/assets/words-DUlvkoUT.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backup-BY88aZr5.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 { 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: \"end\"; files: number; bytes: number };\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 if ((await stat(path)).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): Promise<void> {\n const handle = 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.\n const store = join(paths.db, `backup-store-${process.pid}.bin`);\n await ctx.runtime.store.exportSnapshot(store);\n const light = bool(params, \"light\");\n const all = await Promise.all((await walk(paths.files)).map(async (name) => ({ name, size: (await stat(join(paths.files, name))).size })));\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 for (const file of files) {\n await put({ t: \"file\", kind: \"file\", path: file.name.split(sep).join(\"/\"), size: file.size });\n await copyIn(writer, join(paths.files, file.name), file.size);\n }\n await put({ t: \"end\", files: files.length, bytes });\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: files.length, 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 !== \"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,gBAAgB;AAAG;AAc5F,IAAM,oBAAoB,OAAO,sBAAsB;AACvD,eAAe,QAAQ,OAAmB,QAAiD,QAAQ,UAA+B;CAChI,MAAM,SAAS,IAAI,KAAK,CAAC,KAAiB,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,UAAU;CACpF,MAAM,SAAuB,CAAC;CAC9B,IAAI,OAAO;CACX,KAAK,IAAI,OAAO,MAAM,OAAO,KAAK,GAAG,CAAC,KAAK,MAAM,OAAO,MAAM,OAAO,KAAK,GAAG;EAC3E,QAAQ,KAAK,MAAM;EACnB,IAAI,OAAO,OA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GAAG;GAAE,WAAW;GAAM,MAAM;EAAM,CAAC;EAC7D,MAAM,UAAU,QAAQ,OAAO,KAAK,MAAM,MAAM,QAAQ,GAAG,EAAE,MAAM,IAAM,CAAC;CAC5E;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as backupFileProtection, r as restoreProfile } from "./backup-
|
|
1
|
+
import { n as backupFileProtection, r as restoreProfile } from "./backup-BY88aZr5.js";
|
|
2
2
|
export { backupFileProtection, restoreProfile };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bark_ffi_wasm_bg-EY2uc0Bx.js","names":["import.meta.
|
|
1
|
+
{"version":3,"file":"bark_ffi_wasm_bg-EY2uc0Bx.js","names":["import.meta.ROLLDOWN_FILE_URL_WPGYjwIlzWVNM1bYhOc83w"],"sources":["../../../../node_modules/@secondts/bark/web/bark_ffi_wasm_bg.wasm?url"],"sourcesContent":["export default import.meta.ROLLDOWN_FILE_URL_WPGYjwIlzWVNM1bYhOc83w"],"ignoreList":[0],"mappings":";AAAA,IAAA,2BAAe,IAAA,IAAA,oCAAA,YAAA,GAAmD,CAAA,CAAnDA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bitcoindevkit_bg-B-iLWrmX.js","names":["import.meta.
|
|
1
|
+
{"version":3,"file":"bitcoindevkit_bg-B-iLWrmX.js","names":["import.meta.ROLLDOWN_FILE_URL_FKNdLzKnlftW3t_gzo81yw"],"sources":["../../../../node_modules/@bitcoindevkit/bdk-wallet-web/bitcoindevkit_bg.wasm?url"],"sourcesContent":["export default import.meta.ROLLDOWN_FILE_URL_FKNdLzKnlftW3t_gzo81yw"],"ignoreList":[0],"mappings":";AAAA,IAAA,2BAAe,IAAA,IAAA,oCAAA,YAAA,GAAmD,CAAA,CAAnDA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { o as fileBytes } from "./fileBytes-
|
|
1
|
+
import { u as fileStore } from "./idb-CWvq4HKc.js";
|
|
2
|
+
import { o as fileBytes } from "./fileBytes-D85lBh-Q.js";
|
|
3
3
|
//#region src/runtime/blobFiles.ts
|
|
4
4
|
/** Files moved at once: their Blobs are in memory already, and each one is read and written a step at a time. */
|
|
5
5
|
var AT_ONCE = 4;
|
|
@@ -32,4 +32,4 @@ async function moveBlobFiles() {
|
|
|
32
32
|
//#endregion
|
|
33
33
|
export { moveBlobFiles };
|
|
34
34
|
|
|
35
|
-
//# sourceMappingURL=blobFiles-
|
|
35
|
+
//# sourceMappingURL=blobFiles-B1lX6iGy.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"blobFiles-
|
|
1
|
+
{"version":3,"file":"blobFiles-B1lX6iGy.js","names":[],"sources":["../../src/runtime/blobFiles.ts"],"sourcesContent":["import { fileBytes } from \"@ghostly/browser/shared/fileBytes\";\nimport { fileStore } from \"@ghostly/browser/shared/idb\";\n\n/** Files moved at once: their Blobs are in memory already, and each one is read and written a step at a time. */\nconst AT_ONCE = 4;\n\n/**\n * Files a profile took before every received file went to file storage (held files, hold/1, up to 1.3.0): their bytes\n * are a Blob in their record, which the store keeps in memory and writes whole into `snapshot.bin` (100 MB for 24\n * pictures), read back at every start and one-shot. Each one goes to the profile's files folder, then its record says so\n * and drops the Blob. Called before the engine starts; a file that fails stays as it was, and goes at the next start.\n * Resolves to how many moved: the caller folds the store's journal into a small snapshot then.\n */\nexport async function moveBlobFiles(): Promise<number> {\n const ids = await fileStore.blobIds();\n if (!ids.length) return 0;\n const storage = await fileBytes();\n let moved = 0;\n const move = async (id: string) => {\n const file = await fileStore.get(id);\n // Its size is read off its metadata once the Blob is gone (`storedSize`): one without stays as it is.\n if (!file?.blob || file.metadata?.size !== file.blob.size) return;\n try {\n await storage.stage(id, file.blob);\n if (await fileStore.movedToBytes(id, storage.kind)) moved++;\n else await storage.remove(id);\n } catch {\n await storage.remove(id).catch(() => {});\n }\n };\n for (let i = 0; i < ids.length; i += AT_ONCE) await Promise.all(ids.slice(i, i + AT_ONCE).map(move));\n return moved;\n}\n"],"mappings":";;;;AAIA,IAAM,UAAU;;;;;;;;AAShB,eAAsB,gBAAiC;CACrD,MAAM,MAAM,MAAM,UAAU,QAAQ;CACpC,IAAI,CAAC,IAAI,QAAQ,OAAO;CACxB,MAAM,UAAU,MAAM,UAAU;CAChC,IAAI,QAAQ;CACZ,MAAM,OAAO,OAAO,OAAe;EACjC,MAAM,OAAO,MAAM,UAAU,IAAI,EAAE;EAEnC,IAAI,CAAC,MAAM,QAAQ,KAAK,UAAU,SAAS,KAAK,KAAK,MAAM;EAC3D,IAAI;GACF,MAAM,QAAQ,MAAM,IAAI,KAAK,IAAI;GACjC,IAAI,MAAM,UAAU,aAAa,IAAI,QAAQ,IAAI,GAAG;QAC/C,MAAM,QAAQ,OAAO,EAAE;EAC9B,QAAQ;GACN,MAAM,QAAQ,OAAO,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC;EACzC;CACF;CACA,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,SAAS,MAAM,QAAQ,IAAI,IAAI,MAAM,GAAG,IAAI,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC;CACnG,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as CliError } from "./errors-
|
|
3
|
-
import { f as messageOf, h as oneOf, i as chatOrGroup, m as num, n as bool, p as node, v as str } from "./apiKit-
|
|
1
|
+
import { $a as buttonLabelClash, Xa as STATUS_CARD_LIMITS, _u as toBase64Url, gu as randomBytes, no as checkStatusCard, oi as BUTTONS_CAPABILITY } from "./src-Dd_7Ew1X.js";
|
|
2
|
+
import { t as CliError } from "./errors-DI6Z3jTH.js";
|
|
3
|
+
import { f as messageOf, h as oneOf, i as chatOrGroup, m as num, n as bool, p as node, v as str } from "./apiKit-Ba_t7MZO.js";
|
|
4
4
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
5
|
import { createBase58check } from "@scure/base";
|
|
6
6
|
import { wordlist } from "@scure/bip39/wordlists/english.js";
|
|
@@ -258,8 +258,25 @@ async function waitForGroupFrame(ctx, groupId, messageId, edit, ms) {
|
|
|
258
258
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
259
259
|
}
|
|
260
260
|
}
|
|
261
|
-
/**
|
|
261
|
+
/**
|
|
262
|
+
* A one-shot whose text went over the live link waits this long for its receipt before it leaves (`waitForMessage`).
|
|
263
|
+
* Left at `sent`, the engine stopping took the text for unconfirmed, the next start sent it again on the DHT, and that
|
|
264
|
+
* 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
|
|
265
|
+
* messages, and the last text showed "Connection closed before receipt" though the contact had it (agents#1640).
|
|
266
|
+
*/
|
|
267
|
+
var ONE_SHOT_RECEIPT_MS = 2e3;
|
|
268
|
+
/** What a timed-out wait says of what happens next: a daemon goes on, a one-shot's profile closes now. */
|
|
269
|
+
var goesOn = (ctx) => ctx.mode === "one-shot" ? "goes with this profile's next command, or keep it online with `ghostly daemon --detach`" : "still goes by itself while this profile is online";
|
|
270
|
+
/**
|
|
271
|
+
* Waits until a message of mine reached `target` (`sent`: on its way to the contact; `delivered`: acknowledged). A
|
|
272
|
+
* one-shot's text sent over the live link waits a moment more for its receipt (`ONE_SHOT_RECEIPT_MS`).
|
|
273
|
+
*/
|
|
262
274
|
async function waitForMessage(ctx, chat, messageId, target, ms) {
|
|
275
|
+
const reached = await waitForDelivery(ctx, chat, messageId, target, ms);
|
|
276
|
+
if (ctx.mode !== "one-shot" || target !== "sent" || reached.delivery !== "sent" || reached.via !== "datalink") return reached;
|
|
277
|
+
return waitForDelivery(ctx, chat, messageId, "delivered", ONE_SHOT_RECEIPT_MS).catch(async () => await node(ctx).getMessage(chat, messageId) ?? reached);
|
|
278
|
+
}
|
|
279
|
+
async function waitForDelivery(ctx, chat, messageId, target, ms) {
|
|
263
280
|
const want = DELIVERY_RANK[target];
|
|
264
281
|
const look = (message) => {
|
|
265
282
|
if (!message) return void 0;
|
|
@@ -284,7 +301,7 @@ async function waitForMessage(ctx, chat, messageId, target, ms) {
|
|
|
284
301
|
try {
|
|
285
302
|
const done = look(message);
|
|
286
303
|
if (done) finish(null, done);
|
|
287
|
-
else if (last) finish(new CliError("timeout", `Timed out after ${Math.round(ms / 1e3)} s: the message is ${message?.delivery ?? "not sent yet"} and
|
|
304
|
+
else if (last) finish(new CliError("timeout", `Timed out after ${Math.round(ms / 1e3)} s: the message is ${message?.delivery ?? "not sent yet"} and ${goesOn(ctx)}`, {
|
|
288
305
|
messageId,
|
|
289
306
|
delivery: message?.delivery ?? null
|
|
290
307
|
}));
|
|
@@ -493,4 +510,4 @@ var BUTTON_METHODS = {
|
|
|
493
510
|
//#endregion
|
|
494
511
|
export { waitForEdit as a, findSecret as c, pressable as i, buttonsCard as n, waitForGroupFrame as o, buttonsOf as r, waitForMessage as s, BUTTON_METHODS as t };
|
|
495
512
|
|
|
496
|
-
//# sourceMappingURL=buttons-
|
|
513
|
+
//# sourceMappingURL=buttons-B5EnA2nh.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buttons-B5EnA2nh.js","names":[],"sources":["../../../../apps/ui/src/lib/parse/secrets.ts","../../src/waits.ts","../../src/buttons.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { createBase58check } from \"@scure/base\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\n\n/**\n * What the composer asks about before a message goes: text that looks like a secret someone could take funds or an\n * identity with, or a Cashu token (bearer money: the text box would hand it to whoever reads the chat).\n *\n * Detection is local and synchronous, and a finding never carries the text it found: only what kind it is and, for\n * ecash, the amount decoded here. Ark, Spark and Fedimint wallets are BIP39 seeds or raw keys, caught by the rules\n * below; Fedimint ecash notes are plain base64 with no prefix, so they are not recognised.\n */\nexport type SecretFinding =\n | { kind: \"mnemonic\" | \"nsec\" | \"bitcoin-key\" | \"hex-key\" }\n | { kind: \"cashu\"; amount: number | null; unit: string };\n\nexport type SecretKind = SecretFinding[\"kind\"];\n\nconst WORD_INDEX = new Map(wordlist.map((word, index) => [word, index]));\nconst MNEMONIC_LENGTHS = [12, 15, 18, 21, 24];\n/** Checksums tried per message at most: a 16 KiB run of seed words stays a few milliseconds. */\nconst CHECKSUM_BUDGET = 4096;\n\nconst NSEC = /\\bnsec1[02-9ac-hj-np-z]{58}(?![02-9ac-hj-np-z])/i;\nconst EXTENDED_PRIVATE = /\\b[xtyzuvYZUV]prv[1-9A-HJ-NP-Za-km-z]{100,}/;\nconst WIF = /\\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\\b/g;\nconst HEX_SECRET = /\\b(?:0x)?(?:[0-9a-fA-F]{128}|[0-9a-fA-F]{64})\\b/g;\nconst SECRET_CONTEXT = /priv(?:ate)?[\\s_-]*key|secret|seed|mnemonic|nsec|xprv|\\bwif\\b|recovery|passphrase/i;\n/** How far from a 64-hex string a word like \"seed\" still counts as saying what it is. */\nconst CONTEXT_REACH = 48;\nconst CASHU_TOKEN = /\\bcashu([AB])([A-Za-z0-9_\\-+/]{20,}={0,2})/g;\n\n/**\n * Characters that take no room on screen: format characters (zero-width space, soft hyphen, word joiner, the joiners,\n * direction marks), control characters that are not white space, variation selectors, the grapheme joiner and the\n * Hangul fillers. A page, a PDF or a terminal puts some of them into long strings as places to break a line.\n */\nconst INVISIBLE = /(?![\\t\\n\\v\\f\\r\\x85])[\\p{Cc}\\p{Cf}]|\\u034f|[\\u115f\\u1160\\u3164\\uffa0]|[\\ufe00-\\ufe0f]|[\\u{e0100}-\\u{e01ef}]/gu;\n\nconst base58check = createBase58check(sha256);\n\n/**\n * The first secret in `text`, keys and seeds before ecash; null for anything else. The text is read as it is and as\n * it reads without its invisible characters: a key with one inside is whole again once the reader takes it out.\n */\nexport function findSecret(text: string): SecretFinding | null {\n const visible = text.replace(INVISIBLE, \"\");\n const readings = visible === text ? [text] : [text, visible];\n if (readings.some(hasMnemonic)) return { kind: \"mnemonic\" };\n if (readings.some((reading) => NSEC.test(reading))) return { kind: \"nsec\" };\n if (readings.some((reading) => EXTENDED_PRIVATE.test(reading) || hasWif(reading))) return { kind: \"bitcoin-key\" };\n if (readings.some(hasHexSecret)) return { kind: \"hex-key\" };\n const tokens = readings.map(findCashu);\n return tokens.find((found) => found?.kind === \"cashu\" && found.amount !== null) ?? tokens.find((found) => found) ?? null;\n}\n\n/**\n * 12 to 24 words in a row from the English BIP39 list whose checksum holds, anywhere in the text; or a message that\n * is nothing but 12, 15, 18, 21 or 24 of those words (a seed with one word mistyped is still most of a seed). Prose\n * breaks a run at once: \"the\", \"a\", \"is\", \"to\", \"and\", \"of\" and \"I\" are not on the list.\n *\n * One word said over and over is not a seed, though one in 16 such runs passes a 12-word checksum (\"word\" does): a\n * window of a single word never counts, and a window mostly of one word (\"abandon … about\") counts only when that\n * word does not go on past it on either side.\n */\nfunction hasMnemonic(text: string): boolean {\n const tokens = text.toLowerCase().match(/[a-z]+/g);\n if (!tokens || tokens.length < 12) return false;\n let budget = CHECKSUM_BUDGET;\n let run: number[] = [];\n const seedLike = (start: number, length: number) => {\n const window = run.slice(start, start + length);\n const counts = new Map<number, number>();\n for (const word of window) counts.set(word, (counts.get(word) ?? 0) + 1);\n if (counts.size === 1) return false;\n const [most, times] = [...counts].reduce((a, b) => (b[1] > a[1] ? b : a));\n if (times > length / 2 && (run[start - 1] === most || run[start + length] === most)) return false;\n return checksumHolds(window);\n };\n const check = () => {\n if (run.length >= 12) {\n for (const length of MNEMONIC_LENGTHS) {\n for (let start = 0; start + length <= run.length && budget > 0; start++, budget--) {\n if (seedLike(start, length)) return true;\n }\n }\n if (run.length === tokens.length && MNEMONIC_LENGTHS.includes(run.length) && new Set(run).size > 1) return true;\n }\n run = [];\n return false;\n };\n for (const token of tokens) {\n const index = WORD_INDEX.get(token);\n if (index !== undefined) run.push(index);\n else if (check()) return true;\n }\n return check();\n}\n\n/** BIP39: the words' 11-bit indices are the entropy followed by the first bits of its SHA-256. */\nfunction checksumHolds(indices: number[]): boolean {\n const bits = indices.length * 11, checksumBits = bits / 33, entropyBytes = (bits - checksumBits) / 8;\n const bytes = new Uint8Array(Math.ceil(bits / 8));\n indices.forEach((index, i) => {\n for (let b = 0; b < 11; b++) if (index & (1 << (10 - b))) { const at = i * 11 + b; bytes[at >> 3] |= 0x80 >> (at & 7); }\n });\n const expected = sha256(bytes.subarray(0, entropyBytes))[0] >> (8 - checksumBits);\n const got = bytes[entropyBytes] >> (8 - checksumBits);\n return expected === got;\n}\n\n/** A WIF private key: base58check with version 0x80 (mainnet) or 0xef (testnet), 32 bytes and an optional 0x01. */\nfunction hasWif(text: string): boolean {\n for (const [candidate] of text.matchAll(WIF)) {\n try {\n const payload = base58check.decode(candidate);\n if ((payload[0] === 0x80 || payload[0] === 0xef) && (payload.length === 33 || (payload.length === 34 && payload[33] === 1))) return true;\n } catch { /* not base58check: an ordinary word */ }\n }\n return false;\n}\n\n/** 64 or 128 hex digits with \"private key\", \"secret\", \"seed\" or the like close by. A bare hash is not asked about. */\nfunction hasHexSecret(text: string): boolean {\n for (const match of text.matchAll(HEX_SECRET)) {\n const before = text.slice(Math.max(0, match.index - CONTEXT_REACH), match.index);\n const after = text.slice(match.index + match[0].length, match.index + match[0].length + CONTEXT_REACH);\n if (SECRET_CONTEXT.test(before) || SECRET_CONTEXT.test(after)) return true;\n }\n return false;\n}\n\n/** Every Cashu token in the text, with their amounts added up when all of them decode and share one unit. */\nfunction findCashu(text: string): SecretFinding | null {\n const tokens = [...text.matchAll(CASHU_TOKEN)].map(([, version, body]) => decodeCashu(version as \"A\" | \"B\", body));\n if (!tokens.length) return null;\n const unit = tokens.find((token) => token)?.unit ?? \"sat\";\n const readable = tokens.every((token) => token && token.unit === unit);\n return { kind: \"cashu\", amount: readable ? tokens.reduce((sum, token) => sum + token!.amount, 0) : null, unit };\n}\n\n/** What a Cashu token is worth, read from the token itself (NUT-00): nothing is asked of the mint. */\nexport function decodeCashu(version: \"A\" | \"B\", body: string): { amount: number; unit: string } | null {\n try {\n const bytes = fromBase64(body);\n if (version === \"A\") {\n const token = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)) as { token?: { proofs?: { amount?: unknown }[] }[]; unit?: unknown };\n return total(token.token?.flatMap((entry) => entry.proofs ?? []).map((proof) => proof.amount), token.unit);\n }\n const token = decodeCbor(bytes) as { t?: { p?: { a?: unknown }[] }[]; u?: unknown } | null;\n return total(token?.t?.flatMap((entry) => entry.p ?? []).map((proof) => proof.a), token?.u);\n } catch {\n return null;\n }\n}\n\nfunction total(amounts: unknown[] | undefined, unit: unknown): { amount: number; unit: string } | null {\n if (!amounts?.length || !amounts.every((a): a is number => Number.isSafeInteger(a) && (a as number) >= 0)) return null;\n const amount = amounts.reduce((sum, a) => sum + a, 0);\n return Number.isSafeInteger(amount) ? { amount, unit: typeof unit === \"string\" && unit ? unit : \"sat\" } : null;\n}\n\nfunction fromBase64(text: string): Uint8Array {\n const standard = text.replace(/-/g, \"+\").replace(/_/g, \"/\").replace(/=+$/, \"\");\n const binary = atob(standard + \"=\".repeat((4 - (standard.length % 4)) % 4));\n return Uint8Array.from(binary, (c) => c.charCodeAt(0));\n}\n\n/** Enough CBOR (RFC 8949) for a cashuB token: definite lengths, integers, bytes, text, arrays, maps, tags, simple values. */\nfunction decodeCbor(bytes: Uint8Array): unknown {\n let at = 0, depth = 0;\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const length = (info: number): number => {\n if (info < 24) return info;\n const size = info === 24 ? 1 : info === 25 ? 2 : info === 26 ? 4 : info === 27 ? 8 : 0;\n if (!size || at + size > bytes.length) throw new Error(\"cbor\");\n let value = 0;\n for (let i = 0; i < size; i++) value = value * 256 + bytes[at + i];\n at += size;\n return value;\n };\n const item = (): unknown => {\n if (at >= bytes.length || ++depth > 32) throw new Error(\"cbor\");\n const head = bytes[at++], major = head >> 5, info = head & 31;\n try {\n if (major === 7) {\n if (info === 20) return false;\n if (info === 21) return true;\n if (info === 22 || info === 23) return null;\n if (info === 25) { at += 2; return NaN; } // a half float: never in a token\n if (info === 26) { at += 4; return view.getFloat32(at - 4); }\n if (info === 27) { at += 8; return view.getFloat64(at - 8); }\n throw new Error(\"cbor\");\n }\n const n = length(info);\n switch (major) {\n case 0: return n;\n case 1: return -1 - n;\n case 2: case 3: {\n if (at + n > bytes.length) throw new Error(\"cbor\");\n const slice = bytes.subarray(at, (at += n));\n return major === 2 ? slice : new TextDecoder(\"utf-8\", { fatal: true }).decode(slice);\n }\n case 4: {\n if (n > bytes.length - at) throw new Error(\"cbor\");\n return Array.from({ length: n }, item);\n }\n case 5: {\n if (n > bytes.length - at) throw new Error(\"cbor\");\n const map: Record<string, unknown> = Object.create(null);\n for (let i = 0; i < n; i++) { const key = item(); map[String(key)] = item(); }\n return map;\n }\n default: return item(); // a tag: the value it tags\n }\n } finally { depth--; }\n };\n return item();\n}\n","import type { StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { node, type ApiContext } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\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.\n */\n\nconst DELIVERY_RANK: Record<string, number> = { sending: 0, waiting: 1, queued: 1, held: 2, sent: 2, delivered: 3 };\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 = Date.now() + ms;\n for (;;) {\n const message = await node(ctx).getMessage(chat, messageId);\n if (!message) throw new CliError(\"not_found\", `No message ${messageId} in this chat`);\n if (!message.edit?.pending) return message;\n if (Date.now() >= until) throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: the contact has not confirmed the edit yet. It goes by itself once the chat is live and the contact's app shows edits, while this profile is online`, { messageId, edits: message.edit.seq });\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * Waits until an edge took my group message, or its edit number `edit` (WISP 902: a group has no receipts, so this is\n * as far as the author sees): a member's edge in a private group, an edge to one of my hubs in a community.\n */\nexport async function waitForGroupFrame(ctx: ApiContext, groupId: string, messageId: string, edit: number | undefined, ms: number): Promise<number> {\n const until = Date.now() + ms;\n for (;;) {\n const taken = node(ctx).groupTaken({ groupId, messageId, ...(edit ? { edit } : {}) });\n if (taken > 0) return taken;\n if (Date.now() >= until) throw new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s: no member's edge took it yet. It stays in the group and goes when one opens, while this profile is online`, { messageId, ...(edit ? { edits: edit } : {}) });\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/** What a timed-out wait says of what happens next: a daemon goes on, a one-shot's profile closes now. */\nconst goesOn = (ctx: ApiContext) => ctx.mode === \"one-shot\"\n ? \"goes with this profile's next command, or keep it online with `ghostly daemon --detach`\"\n : \"still goes by itself while this profile is online\";\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();\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\", `Timed out after ${Math.round(ms / 1000)} s: the message is ${message?.delivery ?? \"not sent yet\"} and ${goesOn(ctx)}`, { messageId, delivery: message?.delivery ?? null }));\n } catch (error) { finish(error); }\n }, finish);\n const timer = setTimeout(() => check(true), 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 check();\n });\n}\n","import { BUTTONS_CAPABILITY, 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, node, num, oneOf, str, type Method, type Params } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport { findSecret } from \"../../../apps/ui/src/lib/parse/secrets\";\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. Two labels that read the same (ignoring case and spaces at the ends), or a label that is\n * another button's id, are a usage error here; other 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 // 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 button.style = value.slice(eq + 1);\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, group: boolean): StoredMessage & { card: ButtonsCard } {\n if (!message) throw new CliError(\"not_found\", `No message ${JSON.stringify(ref)} of yours in this ${group ? \"group\" : \"chat\"}: the messageId send gave`);\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 ${secret.kind === \"cashu\" ? \"a Cashu token (money anyone who reads it can take)\" : \"a secret (a seed or a private key)\"}; 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, target.group);\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: the card's own check names only the field.\n if (chosen !== undefined && !before.buttons.some((b) => b.id === chosen))\n throw new CliError(\"bad_request\", `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 new CliError(\"not_found\", `No message ${JSON.stringify(ref)} from someone else in this ${where}: the id its event or history gave`);\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, ctx.mode === \"one-shot\" ? \"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":";;;;;;;AAkBA,IAAM,aAAa,IAAI,IAAI,SAAS,KAAK,MAAM,UAAU,CAAC,MAAM,KAAK,CAAC,CAAC;AACvE,IAAM,mBAAmB;CAAC;CAAI;CAAI;CAAI;CAAI;AAAE;;AAE5C,IAAM,kBAAkB;AAExB,IAAM,OAAO;AACb,IAAM,mBAAmB;AACzB,IAAM,MAAM;AACZ,IAAM,aAAa;AACnB,IAAM,iBAAiB;;AAEvB,IAAM,gBAAgB;AACtB,IAAM,cAAc;;;;;;AAOpB,IAAM,YAAY;AAElB,IAAM,cAAc,kBAAkB,MAAM;;;;;AAM5C,SAAgB,WAAW,MAAoC;CAC7D,MAAM,UAAU,KAAK,QAAQ,WAAW,EAAE;CAC1C,MAAM,WAAW,YAAY,OAAO,CAAC,IAAI,IAAI,CAAC,MAAM,OAAO;CAC3D,IAAI,SAAS,KAAK,WAAW,GAAG,OAAO,EAAE,MAAM,WAAW;CAC1D,IAAI,SAAS,MAAM,YAAY,KAAK,KAAK,OAAO,CAAC,GAAG,OAAO,EAAE,MAAM,OAAO;CAC1E,IAAI,SAAS,MAAM,YAAY,iBAAiB,KAAK,OAAO,KAAK,OAAO,OAAO,CAAC,GAAG,OAAO,EAAE,MAAM,cAAc;CAChH,IAAI,SAAS,KAAK,YAAY,GAAG,OAAO,EAA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AAE;CAC/I,OAAO;EAAE,GAAG;EAAQ,UAAU,OAAO,YAAY;CAAK;AACxD;AAEA,IAAa,iBAAyC;;CAEpD,gBAAgB;;CAEhB,iBAAiB;AACnB"}
|
|
@@ -1,40 +1,7 @@
|
|
|
1
|
-
import { d as lockPath } from "./profiles-
|
|
2
|
-
import {
|
|
1
|
+
import { d as lockPath } from "./profiles-gZdQPyaz.js";
|
|
2
|
+
import { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
5
|
-
//#region src/privateFolder.ts
|
|
6
|
-
/**
|
|
7
|
-
* A folder for a socket outside the profile (when the profile's path is too long for one): made owner-only, and
|
|
8
|
-
* refused when it is a link, someone else made it, or anyone else may enter it.
|
|
9
|
-
*/
|
|
10
|
-
function privateFolder(path, what) {
|
|
11
|
-
mkdirSync(path, {
|
|
12
|
-
recursive: true,
|
|
13
|
-
mode: 448
|
|
14
|
-
});
|
|
15
|
-
const info = lstatSync(path);
|
|
16
|
-
if (!info.isDirectory() || process.getuid && info.uid !== process.getuid() || (info.mode & 63) !== 0) throw new Error(`${path} is not a folder of this user's alone: ${what}`);
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* The profile's own folder, made owner-only again before the daemon's socket goes in it: a folder made by an older
|
|
20
|
-
* release, or opened up by hand, is closed rather than trusted. Refused when it is a link or someone else's.
|
|
21
|
-
*/
|
|
22
|
-
function ownFolder(path, what) {
|
|
23
|
-
const info = lstatSync(path);
|
|
24
|
-
if (!info.isDirectory() || process.getuid && info.uid !== process.getuid()) throw new Error(`${path} is not a folder of this user's: ${what}`);
|
|
25
|
-
if ((info.mode & 63) !== 0) chmodSync(path, 448);
|
|
26
|
-
}
|
|
27
|
-
/** False when `path` is there but is not a socket of this user's: nothing to connect to. */
|
|
28
|
-
function ownSocket(path) {
|
|
29
|
-
if (process.platform === "win32") return true;
|
|
30
|
-
let info;
|
|
31
|
-
try {
|
|
32
|
-
info = lstatSync(path);
|
|
33
|
-
} catch {
|
|
34
|
-
return true;
|
|
35
|
-
}
|
|
36
|
-
return info.isSocket() && (!process.getuid || info.uid === process.getuid());
|
|
37
|
-
}
|
|
38
5
|
var CALL_RATES = [
|
|
39
6
|
8e3,
|
|
40
7
|
12e3,
|
|
@@ -216,6 +183,21 @@ function provesGreeting(secret, dir, message, now = Date.now()) {
|
|
|
216
183
|
if (!timingSafeEqual(Buffer.from(given.proof, "hex"), Buffer.from(proof(secret, "greeting", `${pid}:${at}`), "hex"))) return false;
|
|
217
184
|
return holdsProfile(dir, pid);
|
|
218
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a
|
|
188
|
+
* daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is
|
|
189
|
+
* busy (its event loop held by one long task), not something else on its socket: the client waits for it.
|
|
190
|
+
*/
|
|
191
|
+
function daemonOfThisRelease(dir) {
|
|
192
|
+
if (!readDaemonSecret(dir)) return false;
|
|
193
|
+
let pid;
|
|
194
|
+
try {
|
|
195
|
+
pid = Number(readFileSync(lockPath(dir), "utf8").trim());
|
|
196
|
+
} catch {
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);
|
|
200
|
+
}
|
|
219
201
|
function holdsProfile(dir, pid) {
|
|
220
202
|
try {
|
|
221
203
|
if (readFileSync(lockPath(dir), "utf8").trim() !== String(pid)) return false;
|
|
@@ -249,6 +231,6 @@ function provesDaemon(secret, nonce, answer) {
|
|
|
249
231
|
return timingSafeEqual(Buffer.from(given, "hex"), Buffer.from(proof(secret, "daemon", nonce), "hex"));
|
|
250
232
|
}
|
|
251
233
|
//#endregion
|
|
252
|
-
export {
|
|
234
|
+
export { isCallRate as _, newNonce as a, provesGreeting as c, CALL_RATES as d, DEFAULT_RATE as f, frameSamples as g, frameBytes as h, newDaemonSecret as i, readDaemonSecret as l, bytesToMs as m, daemonOfThisRelease as n, proof as o, PlaybackQueue as p, greeting as r, provesDaemon as s, HELLO as t, removeDaemonSecret as u };
|
|
253
235
|
|
|
254
|
-
//# sourceMappingURL=daemonProof-
|
|
236
|
+
//# sourceMappingURL=daemonProof-Dx3N_DLC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"daemonProof-Dx3N_DLC.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = Date.now, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n"],"mappings":";;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OA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O,aAAa,SAAS,GAAG,GAAG,MAAM,CAAC,CAAC,KAAK,CAAC;CAAG,QAAQ;EAAE,OAAO;CAAO;CACxF,OAAO,OAAO,cAAc,GAAG,KAAK,MAAM,KAAK,aAAa,KAAK,GAAG;AACtE;AAEA,SAAS,aAAa,KAAa,KAAsB;CACvD,IAAI;EACF,IAAI,aAAa,SAAS,GAAG,GAAG,MAAM,CAAC,CAAC,KAAK,MAAM,OAAO,GAAG,GAAG,OAAO;EACvE,QAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,QAAQ;EAAE,OAAO;CAAO;AAC1B;;;;;;AAOA,SAAgB,iBAAiB,KAA4B;CAC3D,MAAM,OAAO,iBAAiB,GAAG;CACjC,IAAI;EACF,MAAM,OAAO,UAAU,IAAI;EAC3B,IAAI,CAAC,KAAK,OAAO,GAAG,OAAO;EAC3B,IAAI,QAAQ,aAAa,YAAa,QAAQ,UAAU,KAAK,QAAQ,QAAQ,OAAO,MAAO,KAAK,OAAO,QAAW,IAAI,OAAO;EAC7H,MAAM,OAAO,aAAa,MAAM,MAAM,CAAC,CAAC,KAAK;EAC7C,OAAO,iBAAiB,KAAK,IAAI,IAAI,OAAO,KAAK,MAAM,KAAK,IAAI;CAClE,QAAQ;EAAE,OAAO;CAAM;AACzB;;AAGA,SAAgB,aAAa,QAAgB,OAAe,QAA0B;CACpF,MAAM,QAAS,QAAuC;CACtD,IAAI,OAAO,UAAU,YAAY,CAAC,iBAAiB,KAAK,KAAK,GAAG,OAAO;CACvE,OAAO,gBAAgB,OAAO,KAAK,OAAO,KAAK,GAAG,OAAO,KAAK,MAAM,QAAQ,UAAU,KAAK,GAAG,KAAK,CAAC;AACtG"}
|
|
@@ -89,8 +89,8 @@ var PREFACE = "ghostly/paired-chat/1";
|
|
|
89
89
|
var CLOSE_FLUSH_MS = 300;
|
|
90
90
|
/**
|
|
91
91
|
* Bytes a channel may hold before `send` throws: above what every sender here lets itself queue (the CLI's 1 MiB high
|
|
92
|
-
* water mark and an app's quarter above it; the Desktop page
|
|
93
|
-
* trips only for one that ignores its own line.
|
|
92
|
+
* water mark and an app's quarter above it; the Desktop page, which stops a file once the sidecar says `full` past its
|
|
93
|
+
* `SEND_ROOM`), so it trips only for one that ignores its own line.
|
|
94
94
|
*/
|
|
95
95
|
var MAX_BUFFERED = 2097152;
|
|
96
96
|
/**
|
|
@@ -331,4 +331,4 @@ async function createHyperEndpoint(seed, options = {}) {
|
|
|
331
331
|
//#endregion
|
|
332
332
|
export { MAX_FRAME, createHyperEndpoint };
|
|
333
333
|
|
|
334
|
-
//# sourceMappingURL=endpoint-
|
|
334
|
+
//# sourceMappingURL=endpoint-BdaeBw2L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoint-BdaeBw2L.js","names":[],"sources":["../../../../native/transports/hyperdht/redial.mjs","../../../../native/transports/hyperdht/endpoint.mjs"],"sourcesContent":["/**\n * How long a HyperDHT dial whose stream opened may go without the contact's preface before it is dialled again.\n *\n * The first connection a freshly started process makes sometimes opens (the handshake went through the DHT and the\n * stream is connected to the right address) and then carries nothing: the contact never sees it, and UDX gives up\n * only after 13 s. A connection made again at once goes through in milliseconds. Found as a chat moved to HyperDHT\n * right after the contact's app restarted taking about 28 s in CI (the move's 8 s, then its 20 s retry), 1 run in 6;\n * reproduced with hyperdht alone under load (bug hunt r11h). On loopback the preface comes within milliseconds of\n * the stream opening, one round trip on the internet.\n */\nexport const PREFACE_WAIT_MS = 2000\n\n/**\n * The longest a stream that opened waits for the preface on a slow path: the 8 s a chat's move gives its dial. Past\n * it nobody is waiting for the dial made again, and UDX gives a silent stream up at 13 s anyway.\n */\nexport const PREFACE_MAX_WAIT_MS = 8000\n\n/**\n * How many of the stream's smoothed round trips the preface may take. A contact that waits for our first packet\n * before its side of the stream connects (we are behind a firewall) writes its preface one round trip after our\n * stream opened; a lost packet adds a retransmission timeout (at least one round trip more). Three keep a slow path's\n * preface from being dialled again for nothing (a fixed 2 s on a 3 s path made three dials) and leave every path\n * under 667 ms on the 2 s.\n */\nexport const RTT_FACTOR = 3\n\n/**\n * Before the stream has its first RTT sample, how many times the dial's own opening (from the dial to the stream\n * open) the preface may take. The opening is the DHT lookup plus the handshake through a DHT node, so it took at\n * least two round trips of the path, and the preface comes one round trip after the stream opened: once covers it\n * (on a 3 s path the first sample comes only 3 s after the stream opened, past the 2 s). It is not more because a\n * stalled stream never gets a sample, and its opening is mostly the lookup (1-3 s on the public DHT even for a near\n * contact): twice a 2.5 s opening would dial again only 7.5 s after the dial, past the move's 8 s once the second\n * dial's own opening is added. A dial that opened in milliseconds (loopback, a near contact) stays on the 2 s.\n */\nexport const OPENING_FACTOR = 1\n\n/**\n * The preface wait for a stream whose smoothed RTT is `rtt` ms and whose dial took `opening` ms to open: three round\n * trips once there is a sample, the opening itself before, between `floor` and `ceiling`.\n */\nexport function prefaceWait(rtt, opening = 0, floor = PREFACE_WAIT_MS, ceiling = PREFACE_MAX_WAIT_MS) {\n const wait = rtt > 0 ? RTT_FACTOR * rtt : OPENING_FACTOR * (opening || 0)\n return Math.min(ceiling, Math.max(floor, wait))\n}\n\n/**\n * At most this many dials for one `connect`: the first, and two more if they stalled, 2 s apart, all within the 8 s a\n * chat's move gives its dial. Under load a dial made again stalled too about once in 20 (bug hunt r11h).\n */\nexport const MAX_DIALS = 3\n\n/**\n * Dials with `dialOnce` until one brings the contact's preface. `dialOnce()` starts a connection and returns\n * `{ opened, ready, close }`: `opened` resolves true once the stream is open (the handshake is done), `ready` with the\n * bound channel once the contact's preface came, and `close()` drops it; `rtt()`, if given, is the stream's smoothed\n * RTT in ms so far, 0 before its first sample (UDX's `rawStream.rtt`). A dial that opened and brought no preface\n * within `waitMs`, or longer on a slow path (`prefaceWait`, at most `maxWaitMs`), is closed and made again, up to\n * `maxDials` in all. The RTT is read again whenever the wait would end, so a sample taken after the stream opened\n * counts. A dial that fails before it opened (the contact not found, refused) fails the whole connect at once, as\n * before: there is nothing to wait for.\n */\nexport function redial(dialOnce, { waitMs = PREFACE_WAIT_MS, maxWaitMs = PREFACE_MAX_WAIT_MS, maxDials = MAX_DIALS } = {}) {\n return new Promise((resolve, reject) => {\n let settled = false\n let dials = 0\n const attempt = () => {\n dials++\n const dialledAt = Date.now()\n const dial = dialOnce()\n let timer = null\n let stalled = false\n dial.opened.then(open => {\n if (!open || settled) return\n const openedAt = Date.now()\n const check = () => {\n if (settled) return\n const left = openedAt + prefaceWait(dial.rtt?.(), openedAt - dialledAt, waitMs, maxWaitMs) - Date.now()\n if (left > 0) { timer = setTimeout(check, left); return }\n if (dials >= maxDials) return\n stalled = true\n dial.close()\n attempt()\n }\n timer = setTimeout(check, waitMs)\n }, () => {})\n dial.ready.then(bound => {\n clearTimeout(timer)\n if (settled || stalled) { bound.channel.close(); return }\n settled = true\n resolve(bound)\n }, error => {\n clearTimeout(timer)\n // A dial closed here for stalling ends as closed: the next one carries the connect.\n if (settled || stalled) return\n settled = true\n reject(error)\n })\n }\n attempt()\n })\n}\n","import DHT from 'hyperdht'\nimport { redial } from './redial.mjs'\n\nexport const MAX_FRAME = 60 * 1024\n/** The top bit of a frame's length word: the frame is a binary message, not UTF-8 text (WISP 103). */\nconst BINARY = 0x80000000\nconst PREFACE = 'ghostly/paired-chat/1'\n/** How long a closing channel waits for what it sent last to go out before the stream is destroyed anyway. */\nconst CLOSE_FLUSH_MS = 300\n/**\n * Bytes a channel may hold before `send` throws: above what every sender here lets itself queue (the CLI's 1 MiB high\n * water mark and an app's quarter above it; the Desktop page, which stops a file once the sidecar says `full` past its\n * `SEND_ROOM`), so it trips only for one that ignores its own line.\n */\nconst MAX_BUFFERED = 2 * 1024 * 1024\n/**\n * `drained()` resolves once a channel holds no more than this: no more than the sidecar's `SEND_ROOM`, so its wait for\n * room never spins on a `drained()` that resolves at once.\n */\nconst DRAINED_AT = 64 * 1024\n/**\n * How often a wait in `drained()` looks again. Each stream says `drain` only once its own queue is empty, which on a fast\n * link comes first; on a slow one this finds the queue at `DRAINED_AT` before it runs dry.\n */\nconst DRAIN_POLL_MS = 10\n\n/**\n * What a connection's stream still holds: secret-stream's queue and the UDX stream's under it. Both are streamx\n * streams, which count it in `_writableState.buffered` (hyperdht is pinned; hyperdhtEndpointBuffered.test.ts reads it).\n * secret-stream has no `writableLength`: read from there, it was always 0.\n */\nfunction held(socket) {\n return (socket._writableState?.buffered ?? 0) + (socket.rawStream?._writableState?.buffered ?? 0)\n}\n\n/** Native UDP + NoiseSecretStream. The binding comes from the authenticated\n * stream itself, never from an application frame supplied by the other peer. */\nexport async function createHyperEndpoint(seed, options = {}) {\n if (!(seed instanceof Uint8Array) || seed.length !== 32) throw new Error('Invalid HyperDHT seed')\n const keyPair = DHT.keyPair(Buffer.from(seed))\n // A chat's listener is a DHT client for good: an adaptive node turns persistent after ~20 min wherever its UDP port is\n // reachable, and then joins the routing table and keeps strangers' records and values. Ephemeral, it still listens\n // (announced through other nodes) and holepunches.\n const node = new DHT({ ...options, keyPair, ephemeral: true })\n const channels = new Set()\n let stopped = false\n let incomingHandler = null\n const waiting = []\n const descriptor = { publicKey: keyPair.publicKey.toString('hex') }\n\n /** `onChannel`: hears the channel as soon as it counts against the limit (a dial that stalls is dropped from it). */\n async function attach(socket, onChannel) {\n if (stopped || channels.size >= 2) { socket.destroy(); throw new Error('Native connection limit reached') }\n let reader = null\n let closeHandler = null\n let closed = false\n let ending = null\n let pending = []\n let buffer = Buffer.alloc(0)\n let preface = false\n let resolveOpen, rejectOpen\n const ready = new Promise((resolve, reject) => { resolveOpen = resolve; rejectOpen = reject })\n const timer = setTimeout(() => { socket.destroy(new Error('HyperDHT handshake timed out')) }, 20000)\n const channel = {\n // It carries binary messages (WISP 100 § Text and binary messages): a capability that needs them may be offered.\n binary: true,\n get bufferedAmount() { return held(socket) },\n get onMessage() { return reader },\n set onMessage(value) { reader = value; if (value) for (const text of pending.splice(0)) value(text) },\n get onClose() { return closeHandler },\n set onClose(value) { closeHandler = value; if (closed) value?.() },\n send(data) {\n const binary = data instanceof Uint8Array\n if (closed || !(binary || typeof data === 'string') || !data.length || (binary ? data.length : Buffer.byteLength(data)) > MAX_FRAME || this.bufferedAmount > MAX_BUFFERED)\n throw new Error('Native channel is closed or exceeds its frame budget')\n const payload = binary ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : Buffer.from(data)\n const header = Buffer.alloc(4); header.writeUInt32BE((binary ? BINARY : 0) + payload.length)\n socket.write(Buffer.concat([header, payload]))\n },\n drained() {\n if (this.bufferedAmount <= DRAINED_AT) return Promise.resolve()\n if (closed) return Promise.reject(new Error('Native channel closed'))\n return new Promise((resolve, reject) => {\n const raw = socket.rawStream\n const check = () => { if (this.bufferedAmount <= DRAINED_AT) finish(resolve) }\n const gone = () => finish(() => reject(new Error('Native channel closed')))\n const poll = setInterval(check, DRAIN_POLL_MS)\n poll.unref?.()\n function finish(settle) {\n clearInterval(poll); socket.off('drain', check); raw?.off('drain', check); socket.off('close', gone); settle()\n }\n socket.on('drain', check); raw?.on('drain', check); socket.once('close', gone)\n })\n },\n // What was sent last (a goodbye, as an app stops) goes out before the stream ends: destroyed at once, it was\n // dropped unsent. A contact that never finishes the stream has CLOSE_FLUSH_MS.\n close() {\n if (closed || ending) return ending ?? Promise.resolve()\n ending = new Promise(resolve => { socket.once('close', resolve) })\n const timer = setTimeout(() => socket.destroy(), CLOSE_FLUSH_MS)\n timer.unref?.()\n socket.end()\n return ending\n },\n }\n channels.add(channel)\n onChannel?.(channel)\n socket.on('error', error => rejectOpen(error))\n // The contact ended its side (its channel closed): this one ends too, so the stream closes now, not on its timer.\n socket.on('end', () => socket.end())\n socket.on('close', () => {\n closed = true; pending = []; clearTimeout(timer); channels.delete(channel)\n rejectOpen(new Error('Native channel closed')); closeHandler?.()\n })\n const opened = () => {\n if (socket.handshakeHash?.length !== 64 || socket.publicKey?.length !== 32 || socket.remotePublicKey?.length !== 32) {\n socket.destroy(new Error('Noise session binding unavailable')); return\n }\n channel.send(PREFACE)\n }\n socket.on('data', chunk => {\n // Secretstream chunks are bounded by its record layer. Process all frames\n // before retaining a partial one; never allocate based on an unchecked size.\n buffer = Buffer.concat([buffer, chunk])\n while (buffer.length >= 4) {\n const word = buffer.readUInt32BE(0)\n const binary = word >= BINARY, length = word % BINARY\n // A binary frame before the preface is another protocol.\n if (length === 0 || length > MAX_FRAME || (binary && !preface)) { socket.destroy(new Error('Invalid frame length')); return }\n if (buffer.length < 4 + length) break\n let text\n if (binary) text = new Uint8Array(buffer.subarray(4, 4 + length))\n else {\n try { text = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(4, 4 + length)) }\n catch { socket.destroy(new Error('Invalid UTF-8 frame')); return }\n }\n buffer = buffer.subarray(4 + length)\n if (!preface) {\n if (text !== PREFACE) { socket.destroy(new Error('Unexpected application protocol')); return }\n preface = true; clearTimeout(timer)\n resolveOpen({ channel, binding: { transport: 'hyperdht/1', context: socket.handshakeHash.toString('hex'),\n identities: [socket.publicKey.toString('hex'), socket.remotePublicKey.toString('hex')].sort() } })\n } else if (reader) reader(text)\n else if (pending.length < 64) pending.push(text)\n else { socket.destroy(new Error('Receive queue exceeded')); return }\n }\n })\n void socket.opened.then(ok => { if (ok) opened(); else rejectOpen(new Error('Noise handshake failed')) })\n return ready\n }\n\n const server = node.createServer(socket => {\n void attach(socket).then(bound => {\n if (stopped) bound.channel.close()\n else if (incomingHandler) incomingHandler(bound)\n else waiting.push(bound)\n }).catch(() => {})\n })\n try { await server.listen(keyPair) }\n catch (error) { await node.destroy(); throw error }\n return {\n transport: 'hyperdht/1', descriptor, onDescriptor: null,\n get onConnection() { return incomingHandler },\n set onConnection(value) { incomingHandler = value; if (value) for (const bound of waiting.splice(0)) value(bound) },\n async connect(address) {\n if (stopped || !address || !/^[a-f0-9]{64}$/.test(address.publicKey)) throw new Error('Invalid HyperDHT endpoint')\n const remote = Buffer.from(address.publicKey, 'hex')\n // A dial whose stream opened and carried nothing is made again (`redial.mjs`): it is dropped from the limit at\n // once, so the next one has its place even while another channel is live. The wait follows the stream's RTT.\n return redial(() => {\n const socket = node.connect(remote, { keyPair })\n let counted = null\n const ready = attach(socket, channel => { counted = channel })\n return { opened: socket.opened, ready, rtt: () => socket.rawStream?.rtt ?? 0,\n close() { if (counted) channels.delete(counted); socket.destroy() } }\n })\n },\n // The channels end first (their last frames out, CLOSE_FLUSH_MS at most): the node's socket goes with it.\n async close() { stopped = true; const ended = [...channels].map(channel => channel.close()); waiting.length = 0; await Promise.all(ended); await server.close(); await node.destroy() },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAUA,IAAa,kBAAkB;;;;;AAM/B,IAAa,sBAAsB;;;;;AA0BnC,SAAgB,YAAY,KAAK,UAAU,GAAG,QAAQ,iBAAiB,UAAU,qBAAqB;CACpG,MAAM,OAAO,MAAM,IAAA,IAAiB,MAAA,KAAwB,WAAW;CACvE,OAAO,KAAK,IAAI,SAAS,KAAK,IAAI,OAAO,IAAI,CAAC;AAChD;;;;;;;;;;;AAkBA,SAAgB,OAAO,UAAU,EAAE,SAAS,iBAAiB,YAAY,qBAAqB,WAAA,MAAyB,CAAC,GAAG;CACzH,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,UAAU;EACd,IAAI,QAAQ;EACZ,MAAM,gBAAgB;GACpB;GACA,MAAM,YAAY,KAAK,IAAI;GAC3B,MAAM,OAAO,SAAS;GACtB,IAAI,QAAQ;GACZ,IAAI,UAAU;GACd,KAAK,OAAO,MAAK,SAAQ;IACvB,IAAI,CAAC,QAAQ,SAAS;IACtB,MAAM,WAAW,KAAK,IAAI;IAC1B,MAAM,cAAc;KAClB,IAAI,SAAS;KACb,MAAM,OAAO,WAAW,YAAY,KAAK,MAAM,GAAG,WAAW,WAAW,QAAQ,SAAS,IAAI,KAAK,IAAI;KACtG,IAAI,OAAO,GAAG;MAAE,QAAQ,WAAW,OAAO,IAAI;MAAG;KAAO;KACxD,IAAI,SAAS,UAAU;KACvB,UAAU;KACV,KAAK,MAAM;KACX,QAAQ;IACV;IACA,QAAQ,WAAW,OAAO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1,4 +1,4 @@
|
|
|
1
|
-
import "./src-
|
|
1
|
+
import "./src-Dd_7Ew1X.js";
|
|
2
2
|
//#region ../browser/src/backup/codec.ts
|
|
3
3
|
function fromBase64Url(text) {
|
|
4
4
|
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("Invalid base64url");
|
|
@@ -87,4 +87,4 @@ async function open(text, passphrase) {
|
|
|
87
87
|
//#endregion
|
|
88
88
|
export { fromBase64Url as i, MAX_BACKUP_BYTES as n, open as r, BACKUP_MEDIA_TYPE as t };
|
|
89
89
|
|
|
90
|
-
//# sourceMappingURL=envelope-
|
|
90
|
+
//# sourceMappingURL=envelope-BU-BB1wR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envelope-BbvUBjc5.js","names":[],"sources":["../../../browser/src/backup/codec.ts","../../../browser/src/backup/envelope.ts"],"sourcesContent":["import { toBase64Url } from \"@ghostly/core\";\n\n/**\n * Base64url without padding. Core's encoder, not `btoa`: every picture, voice note and kept file (up to 16 MiB each)\n * goes through it on the page's thread, where `btoa` spends over a second per 16 MiB.\n */\nexport { toBase64Url };\nexport function fromBase64Url(text: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error(\"Invalid base64url\");\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (text.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\ntype Tagged = { $ghostly: \"bigint\" | \"bytes\" | \"blob\"; value: string; type?: string };\n/** Data that happens to look like a tag (a contact can send anything) travels as its entries instead. */\ntype Escaped = { $ghostly: \"object\"; entries: [string, unknown][] };\n\n/**\n * Blobs cannot be read synchronously: turn them into tagged values first, everywhere in the tree. An\n * object of the data's own with a `$ghostly` key is escaped, so it comes back as it was and not as a tag.\n */\nasync function inlineBlobs(value: unknown): Promise<unknown> {\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return { $ghostly: \"blob\", type: value.type, value: toBase64Url(new Uint8Array(await value.arrayBuffer())) } satisfies Tagged;\n if (Array.isArray(value)) return Promise.all(value.map(inlineBlobs));\n if (value && typeof value === \"object\" && !(value instanceof Uint8Array) && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) out[k] = await inlineBlobs(v);\n return Object.prototype.hasOwnProperty.call(out, \"$ghostly\") ? ({ $ghostly: \"object\", entries: Object.entries(out) } satisfies Escaped) : out;\n }\n return value;\n}\n\n/** JSON that also carries what IndexedDB holds: bigints, bytes and blobs (WISP 05). */\nexport async function encode(value: unknown): Promise<string> {\n return JSON.stringify(await inlineBlobs(value), (_key, v) => {\n if (typeof v === \"bigint\") return { $ghostly: \"bigint\", value: String(v) } satisfies Tagged;\n if (v instanceof Uint8Array) return { $ghostly: \"bytes\", value: toBase64Url(v) } satisfies Tagged;\n if (v instanceof ArrayBuffer) return { $ghostly: \"bytes\", value: toBase64Url(new Uint8Array(v)) } satisfies Tagged;\n return v;\n });\n}\n/** Never throws on a tag it cannot read: that value stays as it is, and the rest of the backup restores. */\nexport function decode(text: string): unknown {\n return JSON.parse(text, (_key, v) => {\n const escaped = v as Partial<Escaped> | null;\n if (escaped && typeof escaped === \"object\" && escaped.$ghostly === \"object\" && Array.isArray(escaped.entries)) {\n const out: Record<string, unknown> = {};\n for (const entry of escaped.entries) if (Array.isArray(entry) && typeof entry[0] === \"string\") Object.defineProperty(out, entry[0], { value: entry[1], enumerable: true, writable: true, configurable: true });\n return out;\n }\n const tag = v as Partial<Tagged> | null;\n if (!tag || typeof tag !== \"object\" || typeof tag.$ghostly !== \"string\" || typeof tag.value !== \"string\") return v;\n if (tag.$ghostly === \"bigint\") return /^-?\\d+$/.test(tag.value) ? BigInt(tag.value) : v;\n if (!/^[A-Za-z0-9_-]*$/.test(tag.value)) return v;\n if (tag.$ghostly === \"bytes\") return fromBase64Url(tag.value);\n if (tag.$ghostly === \"blob\") return new Blob([fromBase64Url(tag.value) as BlobPart], { type: typeof tag.type === \"string\" ? tag.type : \"\" });\n return v;\n });\n}\n","import { fromBase64Url, toBase64Url } from \"./codec\";\n\n/** The clear part of a bundle (WISP 05): only what decryption needs. */\nexport interface Envelope {\n format: \"ghostly-backup\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n compression: \"gzip\" | \"none\";\n ciphertext: string;\n}\nexport const BACKUP_MEDIA_TYPE = \"application/vnd.ghostly.backup+json\";\nconst ITERATIONS = 600_000;\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}\n/** A profile with years of files is large, but not this large: past it, a bundle is refused, not read. */\nexport const MAX_BACKUP_BYTES = 1024 * 1024 * 1024;\n\nasync function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): 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 > MAX_BACKUP_BYTES) { await reader.cancel(); throw new Error(\"This backup is too large to restore\"); }\n chunks.push(next.value);\n }\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\n/**\n * The clear header is authenticated with the ciphertext (AES-GCM associated data): changing any of it,\n * the compression included, makes the bundle fail to open instead of being read differently.\n */\nconst header = (e: Pick<Envelope, \"format\" | \"version\" | \"kdf\" | \"cipher\" | \"compression\">) =>\n new TextEncoder().encode([e.format, e.version, e.kdf.name, e.kdf.iterations, e.kdf.salt, e.cipher.name, e.cipher.iv, e.compression].join(\"\\n\"));\nconst canCompress = () => typeof CompressionStream !== \"undefined\";\n\n/** Compresses and encrypts a payload under a passphrase the person chose. */\nexport async function seal(payload: string, passphrase: string): Promise<string> {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the backup passphrase\");\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const plain = new TextEncoder().encode(payload);\n const compression = canCompress() ? \"gzip\" : \"none\";\n const body = compression === \"gzip\" ? await through(plain, new CompressionStream(\"gzip\")) : plain;\n const clear = { format: \"ghostly-backup\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, compression } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await keyFrom(passphrase, salt, ITERATIONS), body as BufferSource));\n const envelope: Envelope = { ...clear, ciphertext: toBase64Url(ciphertext) };\n return JSON.stringify(envelope);\n}\n\n/** Checks, decrypts and decompresses a bundle. Nothing from a bundle is used before this succeeds. */\nexport async function open(text: string, passphrase: string): Promise<string> {\n if (text.length > MAX_BACKUP_BYTES * 1.4) throw new Error(\"This backup is too large to restore\");\n let envelope: Envelope;\n try { envelope = JSON.parse(text) as Envelope; } catch { throw new Error(\"This is not a Ghostly backup\"); }\n if (envelope?.format !== \"ghostly-backup\") throw new Error(\"This is not a Ghostly backup\");\n if (envelope.version !== 1) throw new Error(\"This backup comes from a newer Ghostly; update to restore it\");\n if (envelope.kdf?.name !== \"PBKDF2-SHA256\" || !(envelope.kdf.iterations >= ITERATIONS) || envelope.kdf.iterations > 10_000_000 || envelope.cipher?.name !== \"AES-256-GCM\" || ![\"gzip\", \"none\"].includes(envelope.compression)) throw new Error(\"Unsupported backup encryption\");\n let body: Uint8Array;\n try {\n body = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: fromBase64Url(envelope.cipher.iv) as BufferSource, additionalData: header(envelope) as BufferSource }, await keyFrom(passphrase, fromBase64Url(envelope.kdf.salt), envelope.kdf.iterations), fromBase64Url(envelope.ciphertext) as BufferSource));\n } catch { throw new Error(\"Wrong passphrase, or the backup was changed\"); }\n const plain = envelope.compression === \"gzip\" ? await through(body, new DecompressionStream(\"gzip\")) : body;\n return new TextDecoder().decode(plain);\n}\n"],"mappings":";;AAOA,SAAgB,cAAc,MAA0B;CACtD,IAAI,CAAC,mBAAmB,KAAK,IAAI,GAAG,MAAM,IAAI,MAAM,mBAAmB;CACvE,MAAM,SAAS,KAAK,KAAK,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,IAAI,IAAI,QAAQ,IAAK,KAAK,SAAS,KAAM,CAAC,CAAC;CACxG,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO;AACT;;;ACFA,IAAa,oBAAoB;AACjC,IAAM,aAAa;AAEnB,eAAe,QAAQ,YAAoB,MAAkB,YAAwC;CACnG,MAAM,WAAW,MAAM,OAAO,OAAO,UAAU,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU,GAAG,UAAU,OAAO,CAAC,WAAW,CAAC;CAC1H,OAAO,OAAO,OAAO,UAAU;EAAE,MAAM;EAAU,MAAM;EAAiB;EAAsB;CAAW,GAAG,UAAU;EAAE,MAAM;EAAW,QAAQ;CAAI,GAAG,OAAO,CAAC,WAAW,SAAS,CAAC;AACvL;;AAEA,IAAa,mBAAmB;AAEhC,eAAe,QAAQ,OAAmB,QAAsE;CAC9G,MAAM,SAAS,IAAI,KAAK,CAAC,KAAiB,CAAC,CAAC,CAAC,OAAO,CA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AA+B;CAC9Q,IAAI;CACJ,IAAI;EACF,OAAO,IAAI,WAAW,MAAM,OAAO,OAAO,QAAQ;GAAE,MAAM;GAAW,IAAI,cAAc,SAAS,OAAO,EAAE;GAAmB,gBAAgB,OAAO,QAAQ;EAAkB,GAAG,MAAM,QAAQ,YAAY,cAAc,SAAS,IAAI,IAAI,GAAG,SAAS,IAAI,UAAU,GAAG,cAAc,SAAS,UAAU,CAAiB,CAAC;CAC3T,QAAQ;EAAE,MAAM,IAAI,MAAM,6CAA6C;CAAG;CAC1E,MAAM,QAAQ,SAAS,gBAAgB,SAAS,MAAM,QAAQ,MAAM,IAAI,oBAAoB,MAAM,CAAC,IAAI;CACvG,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;AACvC"}
|
|
1
|
+
{"version":3,"file":"envelope-BU-BB1wR.js","names":[],"sources":["../../../browser/src/backup/codec.ts","../../../browser/src/backup/envelope.ts"],"sourcesContent":["import { toBase64Url } from \"@ghostly/core\";\n\n/**\n * Base64url without padding. Core's encoder, not `btoa`: every picture, voice note and kept file (up to 16 MiB each)\n * goes through it on the page's thread, where `btoa` spends over a second per 16 MiB.\n */\nexport { toBase64Url };\nexport function fromBase64Url(text: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error(\"Invalid base64url\");\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (text.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\ntype Tagged = { $ghostly: \"bigint\" | \"bytes\" | \"blob\"; value: string; type?: string };\n/** Data that happens to look like a tag (a contact can send anything) travels as its entries instead. */\ntype Escaped = { $ghostly: \"object\"; entries: [string, unknown][] };\n\n/**\n * Blobs cannot be read synchronously: turn them into tagged values first, everywhere in the tree. An\n * object of the data's own with a `$ghostly` key is escaped, so it comes back as it was and not as a tag.\n */\nasync function inlineBlobs(value: unknown): Promise<unknown> {\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return { $ghostly: \"blob\", type: value.type, value: toBase64Url(new Uint8Array(await value.arrayBuffer())) } satisfies Tagged;\n if (Array.isArray(value)) return Promise.all(value.map(inlineBlobs));\n if (value && typeof value === \"object\" && !(value instanceof Uint8Array) && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) out[k] = await inlineBlobs(v);\n return Object.prototype.hasOwnProperty.call(out, \"$ghostly\") ? ({ $ghostly: \"object\", entries: Object.entries(out) } satisfies Escaped) : out;\n }\n return value;\n}\n\n/** JSON that also carries what IndexedDB holds: bigints, bytes and blobs (WISP 05). */\nexport async function encode(value: unknown): Promise<string> {\n return JSON.stringify(await inlineBlobs(value), (_key, v) => {\n if (typeof v === \"bigint\") return { $ghostly: \"bigint\", value: String(v) } satisfies Tagged;\n if (v instanceof Uint8Array) return { $ghostly: \"bytes\", value: toBase64Url(v) } satisfies Tagged;\n if (v instanceof ArrayBuffer) return { $ghostly: \"bytes\", value: toBase64Url(new Uint8Array(v)) } satisfies Tagged;\n return v;\n });\n}\n/** Never throws on a tag it cannot read: that value stays as it is, and the rest of the backup restores. */\nexport function decode(text: string): unknown {\n return JSON.parse(text, (_key, v) => {\n const escaped = v as Partial<Escaped> | null;\n if (escaped && typeof escaped === \"object\" && escaped.$ghostly === \"object\" && Array.isArray(escaped.entries)) {\n const out: Record<string, unknown> = {};\n for (const entry of escaped.entries) if (Array.isArray(entry) && typeof entry[0] === \"string\") Object.defineProperty(out, entry[0], { value: entry[1], enumerable: true, writable: true, configurable: true });\n return out;\n }\n const tag = v as Partial<Tagged> | null;\n if (!tag || typeof tag !== \"object\" || typeof tag.$ghostly !== \"string\" || typeof tag.value !== \"string\") return v;\n if (tag.$ghostly === \"bigint\") return /^-?\\d+$/.test(tag.value) ? BigInt(tag.value) : v;\n if (!/^[A-Za-z0-9_-]*$/.test(tag.value)) return v;\n if (tag.$ghostly === \"bytes\") return fromBase64Url(tag.value);\n if (tag.$ghostly === \"blob\") return new Blob([fromBase64Url(tag.value) as BlobPart], { type: typeof tag.type === \"string\" ? tag.type : \"\" });\n return v;\n });\n}\n","import { fromBase64Url, toBase64Url } from \"./codec\";\n\n/** The clear part of a bundle (WISP 05): only what decryption needs. */\nexport interface Envelope {\n format: \"ghostly-backup\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n compression: \"gzip\" | \"none\";\n ciphertext: string;\n}\nexport const BACKUP_MEDIA_TYPE = \"application/vnd.ghostly.backup+json\";\nconst ITERATIONS = 600_000;\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}\n/** A profile with years of files is large, but not this large: past it, a bundle is refused, not read. */\nexport const MAX_BACKUP_BYTES = 1024 * 1024 * 1024;\n\nasync function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): 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 > MAX_BACKUP_BYTES) { await reader.cancel(); throw new Error(\"This backup is too large to restore\"); }\n chunks.push(next.value);\n }\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\n/**\n * The clear header is authenticated with the ciphertext (AES-GCM associated data): changing any of it,\n * the compression included, makes the bundle fail to open instead of being read differently.\n */\nconst header = (e: Pick<Envelope, \"format\" | \"version\" | \"kdf\" | \"cipher\" | \"compression\">) =>\n new TextEncoder().encode([e.format, e.version, e.kdf.name, e.kdf.iterations, e.kdf.salt, e.cipher.name, e.cipher.iv, e.compression].join(\"\\n\"));\nconst canCompress = () => typeof CompressionStream !== \"undefined\";\n\n/** Compresses and encrypts a payload under a passphrase the person chose. */\nexport async function seal(payload: string, passphrase: string): Promise<string> {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the backup passphrase\");\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const plain = new TextEncoder().encode(payload);\n const compression = canCompress() ? \"gzip\" : \"none\";\n const body = compression === \"gzip\" ? await through(plain, new CompressionStream(\"gzip\")) : plain;\n const clear = { format: \"ghostly-backup\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, compression } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await keyFrom(passphrase, salt, ITERATIONS), body as BufferSource));\n const envelope: Envelope = { ...clear, ciphertext: toBase64Url(ciphertext) };\n return JSON.stringify(envelope);\n}\n\n/** Checks, decrypts and decompresses a bundle. Nothing from a bundle is used before this succeeds. */\nexport async function open(text: string, passphrase: string): Promise<string> {\n if (text.length > MAX_BACKUP_BYTES * 1.4) throw new Error(\"This backup is too large to restore\");\n let envelope: Envelope;\n try { envelope = JSON.parse(text) as Envelope; } catch { throw new Error(\"This is not a Ghostly backup\"); }\n if (envelope?.format !== \"ghostly-backup\") throw new Error(\"This is not a Ghostly backup\");\n if (envelope.version !== 1) throw new Error(\"This backup comes from a newer Ghostly; update to restore it\");\n if (envelope.kdf?.name !== \"PBKDF2-SHA256\" || !(envelope.kdf.iterations >= ITERATIONS) || envelope.kdf.iterations > 10_000_000 || envelope.cipher?.name !== \"AES-256-GCM\" || ![\"gzip\", \"none\"].includes(envelope.compression)) throw new Error(\"Unsupported backup encryption\");\n let body: Uint8Array;\n try {\n body = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: fromBase64Url(envelope.cipher.iv) as BufferSource, additionalData: header(envelope) as BufferSource }, await keyFrom(passphrase, fromBase64Url(envelope.kdf.salt), envelope.kdf.iterations), fromBase64Url(envelope.ciphertext) as BufferSource));\n } catch { throw new Error(\"Wrong passphrase, or the backup was changed\"); }\n const plain = envelope.compression === \"gzip\" ? await through(body, new DecompressionStream(\"gzip\")) : body;\n return new TextDecoder().decode(plain);\n}\n"],"mappings":";;AAOA,SAAgB,cAAc,MAA0B;CACtD,IAAI,CAAC,mBAAmB,KAAK,IAAI,GAAG,MAAM,IAAI,MAAM,mBAAmB;CACvE,MAAM,SAAS,KAAK,KAAK,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,IAAI,IAAI,QAAQ,IAAK,KAAK,SAAS,KAAM,CAAC,CAAC;CACxG,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO;AACT;;;ACFA,IAAa,oBAAoB;AACjC,IAAM,aAAa;AAEnB,eAAe,QAAQ,YAAoB,MAAkB,YAAwC;CACnG,MAAM,WAAW,MAAM,OAAO,OAAO,UAAU,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU,GAAG,UAAU,OAAO,CAAC,WAAW,CAAC;CAC1H,OAAO,OAAO,OAAO,UAAU;EAAE,MAAM;EAAU,MAAM;EAAiB;EAAsB;CAAW,GAAG,UAAU;EAAE,MAAM;EAAW,QAAQ;CAAI,GAAG,OAAO,CAAC,WAAW,SAAS,CAAC;AACvL;;AAEA,IAAa,mBAAmB;AAEhC,eAAe,QAAQ,OAAmB,QAAsE;CAC9G,MAAM,SAAS,IAAI,KAAK,CAAC,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