@ghostlytools/cli 1.11.2 → 1.11.4
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 +34 -28
- package/SKILL.md +4 -2
- package/dist/assets/{api-CtXgscmK.js → api-BwyFq4lA.js} +2 -2
- package/dist/assets/{api-BM3PsXbB.js → api-MYc6QNRs.js} +306 -114
- package/dist/assets/api-MYc6QNRs.js.map +1 -0
- package/dist/assets/{apiKit-lCTQ0EBG.js → apiKit-CfsNx9ZR.js} +62 -16
- package/dist/assets/apiKit-CfsNx9ZR.js.map +1 -0
- package/dist/assets/{appFetch-BKHy5H8J.js → appFetch-DVYZOZFw.js} +3 -3
- package/dist/assets/{appFetch-BKHy5H8J.js.map → appFetch-DVYZOZFw.js.map} +1 -1
- package/dist/assets/{apps-DO_gAZgm.js → apps-Dbw2Hcko.js} +1 -1
- package/dist/assets/{apps-Do26w3c7.js → apps-h12II1us.js} +150 -57
- package/dist/assets/apps-h12II1us.js.map +1 -0
- package/dist/assets/{arkade-CZrLbz-M.js → arkade-Bw_4PZRG.js} +2 -2
- package/dist/assets/{arkade-CZrLbz-M.js.map → arkade-Bw_4PZRG.js.map} +1 -1
- package/dist/assets/{backup-D21x1f5P.js → backup-CdEzTq5C.js} +1 -1
- package/dist/assets/{backup-j47AzDvG.js → backup-Chvy79SN.js} +60 -55
- package/dist/assets/backup-Chvy79SN.js.map +1 -0
- 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/{buttons-CiGlBVBT.js → buttons-BgoExb4E.js} +37 -7
- package/dist/assets/buttons-BgoExb4E.js.map +1 -0
- package/dist/assets/buttons-DK2aAGat.js +2 -0
- package/dist/assets/{client-raIncVtF.js → client-DY8tZZWi.js} +28 -8
- package/dist/assets/client-DY8tZZWi.js.map +1 -0
- package/dist/assets/{codec-DcG2AeyE.js → codec-BnMg-Grj.js} +2 -2
- package/dist/assets/{codec-DcG2AeyE.js.map → codec-BnMg-Grj.js.map} +1 -1
- package/dist/assets/{envelope-Dud6lntA.js → envelope-CdV7vHVZ.js} +2 -2
- package/dist/assets/{envelope-Dud6lntA.js.map → envelope-CdV7vHVZ.js.map} +1 -1
- package/dist/assets/{errors-Dt-ZnyOX.js → errors-CAh6GLJZ.js} +27 -2
- package/dist/assets/errors-CAh6GLJZ.js.map +1 -0
- package/dist/assets/{fedimintSdk-DRKRSw14.js → fedimintSdk-CPFfVK-G.js} +2 -2
- package/dist/assets/{fedimintSdk-DRKRSw14.js.map → fedimintSdk-CPFfVK-G.js.map} +1 -1
- package/dist/assets/{fixedHosts-CNX7QiUD.js → fixedHosts-CbgqrIKs.js} +3 -3
- package/dist/assets/{fixedHosts-CNX7QiUD.js.map → fixedHosts-CbgqrIKs.js.map} +1 -1
- package/dist/assets/{host-8RskzQgB.js → host-C0NMNQLl.js} +702 -143
- package/dist/assets/host-C0NMNQLl.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-uAThbFub.js → hyperdhtRelay-Dz7pvcBA.js} +2 -2
- package/dist/assets/{hyperdhtRelay-uAThbFub.js.map → hyperdhtRelay-Dz7pvcBA.js.map} +1 -1
- package/dist/assets/{irohWeb-DGelfgDJ.js → irohWeb-caAj4Dms.js} +19 -12
- package/dist/assets/irohWeb-caAj4Dms.js.map +1 -0
- package/dist/assets/{main-BC33ooYg.js → main-C6t5zrD5.js} +383 -110
- package/dist/assets/main-C6t5zrD5.js.map +1 -0
- package/dist/assets/{mainline-DYrjsS1t.js → mainline-DCuGUSZF.js} +35 -18
- package/dist/assets/mainline-DCuGUSZF.js.map +1 -0
- package/dist/assets/{networkReason-n2oBs4by.js → networkReason-BbQW1Xpc.js} +3 -3
- package/dist/assets/{networkReason-n2oBs4by.js.map → networkReason-BbQW1Xpc.js.map} +1 -1
- package/dist/assets/{nwc-Do3VSlIS.js → nwc-CSDRMZ0e.js} +3 -3
- package/dist/assets/{nwc-Do3VSlIS.js.map → nwc-CSDRMZ0e.js.map} +1 -1
- package/dist/assets/{nwcProvider-Du5aWNIn.js → nwcProvider-PE0wli8n.js} +2 -2
- package/dist/assets/{nwcProvider-Du5aWNIn.js.map → nwcProvider-PE0wli8n.js.map} +1 -1
- package/dist/assets/{ownDid-CwwYu8s2.js → ownDid-C1R5Kd8q.js} +2 -2
- package/dist/assets/{ownDid-CwwYu8s2.js.map → ownDid-C1R5Kd8q.js.map} +1 -1
- package/dist/assets/{ownStatus-D7dB4zJB.js → ownStatus-BoTf5WqQ.js} +27 -9
- package/dist/assets/ownStatus-BoTf5WqQ.js.map +1 -0
- package/dist/assets/{profiles-NyF5FnYF.js → profiles-DszHjEJi.js} +25 -10
- package/dist/assets/profiles-DszHjEJi.js.map +1 -0
- package/dist/assets/{registry-DKDInr0A.js → registry-Da-r6eC3.js} +30 -12
- package/dist/assets/registry-Da-r6eC3.js.map +1 -0
- package/dist/assets/{registry-C734VrO9.js → registry-zUZBSHYv.js} +1 -1
- package/dist/assets/{resolve-3Tqh9AWQ.js → resolve-tUzh4lHh.js} +2 -2
- package/dist/assets/{resolve-3Tqh9AWQ.js.map → resolve-tUzh4lHh.js.map} +1 -1
- package/dist/assets/{secretGuard-B7Hj0Kvz.js → secretGuard-CsVHDdYk.js} +68 -6
- package/dist/assets/{secretGuard-B7Hj0Kvz.js.map → secretGuard-CsVHDdYk.js.map} +1 -1
- package/dist/assets/secretGuard-DCb1I0_B.js +2 -0
- package/dist/assets/{server-B6PQ6iae.js → server-C1jZZ61O.js} +896 -277
- package/dist/assets/server-C1jZZ61O.js.map +1 -0
- package/dist/assets/{src-ChJijTlM.js → src-DJe-OYxd.js} +1010 -236
- package/dist/assets/src-DJe-OYxd.js.map +1 -0
- package/dist/assets/{sshForges-Brf0fslM.js → sshForges-C9zTO72R.js} +4 -3
- package/dist/assets/sshForges-C9zTO72R.js.map +1 -0
- package/dist/assets/{translate-xLme9Rdh.js → translate-CUuC5szR.js} +36 -15
- package/dist/assets/translate-CUuC5szR.js.map +1 -0
- package/dist/assets/{usdt-CSU5KzTV.js → usdt-DI51znt-.js} +3 -3
- package/dist/assets/{usdt-CSU5KzTV.js.map → usdt-DI51znt-.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/assets/api-BM3PsXbB.js.map +0 -1
- package/dist/assets/apiKit-lCTQ0EBG.js.map +0 -1
- package/dist/assets/apps-Do26w3c7.js.map +0 -1
- package/dist/assets/backup-j47AzDvG.js.map +0 -1
- package/dist/assets/buttons-CiGlBVBT.js.map +0 -1
- package/dist/assets/buttons-D2l2bVCG.js +0 -2
- package/dist/assets/client-raIncVtF.js.map +0 -1
- package/dist/assets/errors-Dt-ZnyOX.js.map +0 -1
- package/dist/assets/host-8RskzQgB.js.map +0 -1
- package/dist/assets/irohWeb-DGelfgDJ.js.map +0 -1
- package/dist/assets/main-BC33ooYg.js.map +0 -1
- package/dist/assets/mainline-DYrjsS1t.js.map +0 -1
- package/dist/assets/ownStatus-D7dB4zJB.js.map +0 -1
- package/dist/assets/profiles-NyF5FnYF.js.map +0 -1
- package/dist/assets/registry-DKDInr0A.js.map +0 -1
- package/dist/assets/secretGuard-DUr6bgKc.js +0 -2
- package/dist/assets/server-B6PQ6iae.js.map +0 -1
- package/dist/assets/src-ChJijTlM.js.map +0 -1
- package/dist/assets/sshForges-Brf0fslM.js.map +0 -1
- package/dist/assets/translate-xLme9Rdh.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buttons-BgoExb4E.js","names":["goesOnIn"],"sources":["../../src/waits.ts","../../src/textSize.ts","../../src/buttons.ts"],"sourcesContent":["import type { StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { noMessage, nobodyJoinedChat, node, state, type ApiContext } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { goesOn as goesOnIn } from \"./waitNotice\";\n\n/*\n * Waiting on what a command sent (WISP 1100): a message's delivery, an edit's confirmation, a group frame taken by an\n * edge. Shared by the chat, group and status card methods. A deadline counts on `performance.now()`: on `Date.now()`\n * a wall clock set back while a wait ran (NTP, a person fixing the time) stretched it by as much, past the client's\n * own deadline, which told the bot to restart a sound daemon.\n */\n\nconst DELIVERY_RANK: Record<string, number> = { sending: 0, waiting: 1, queued: 1, held: 2, sent: 2, delivered: 3 };\n\n/**\n * What a timed-out wait says of what happens next: a daemon goes on, a one-shot's profile closes now. A one-shot's\n * `edit` and `group edit` said \"while this profile is online\" too, as it was about to leave. Ctrl-C says the same.\n * On a chat nobody joined yet nothing goes before they do: it said \"goes with this profile's next command\".\n */\nexport const goesOn = (ctx: ApiContext, chat?: string) => chat !== undefined && nobodyJoinedChat(ctx, chat)\n ? `goes once the contact joins this chat (nobody has yet)${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}`\n : ctx.mode === \"daemon\" && stopped(ctx) ? \"goes by itself once this profile is online again\" : goesOnIn(ctx.mode);\n\n/**\n * A daemon that stops (`ApiContext.stopping`) ends every wait still open at once, with what it knows, as a timeout:\n * what was asked is done and goes on by itself. Its connections ended under the waits before, and the command failed\n * as `unavailable` \"The daemon went away\" with no `messageId`: a bot that sent again sent the message twice.\n */\nconst stopped = (ctx: ApiContext) => ctx.stopping?.aborted === true;\n\n/** How a wait that ends short of its aim begins: its time ran out, or the daemon stopped under it. */\nconst ended = (ctx: ApiContext, ms: number) => stopped(ctx) ? \"The daemon stopped before the wait ended\" : `Timed out after ${Math.round(ms / 1000)} s`;\n\n/** A timed-out wait's details, and `reason: \"daemon-stopped\"` when the daemon's stop ended it. */\nconst known = (ctx: ApiContext, details: Record<string, unknown>) => stopped(ctx) ? { ...details, reason: \"daemon-stopped\" } : details;\n\n/** Waits until the contact confirmed the latest edit of one of my messages (it is no longer pending). */\nexport async function waitForEdit(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<StoredMessage> {\n const until = performance.now() + ms;\n for (;;) {\n const message = await node(ctx).getMessage(chat, messageId);\n if (!message) throw noMessage(messageId, { group: false, ref: chat });\n if (!message.edit?.pending) return message;\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the contact has not confirmed the edit yet (it needs a live chat and a contact's app that shows edits). It ${goesOn(ctx, chat)}`, known(ctx, { messageId, edits: message.edit.seq }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/** Waits until the contact confirmed my removal of a message, which is already gone here. */\nexport async function waitForRemoval(ctx: ApiContext, chat: string, messageId: string, ms: number): Promise<void> {\n const until = performance.now() + ms;\n while (node(ctx).removalPending({ linkId: chat, messageId })) {\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the message is gone here and the contact has not confirmed yet. Its removal ${goesOn(ctx, chat)}`, known(ctx, { messageId }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * A private group with no member but me (they all left, or nobody accepted an invitation yet): what I send there now\n * reaches nobody, not even a member who joins later (a joiner reads nothing from before). A community's roster may not\n * list every member yet, so only a private group counts.\n */\nexport const nobodyElseIn = (ctx: ApiContext, groupId: string): boolean => {\n const group = state(ctx).groups?.find((g) => g.id === groupId);\n return group?.profile === \"mesh\" && !group.members.some((m) => !m.me);\n};\n\n/**\n * Why I am no longer in a group (removed, say), or null while I am. A member removed while away learns it only after\n * it is back, so what it sent in between is never taken, and from then on nothing goes. A community's `lost` is not\n * out: it asks to be let in again by itself.\n */\nconst outOf = (ctx: ApiContext, groupId: string): string | null => {\n const group = state(ctx).groups?.find((g) => g.id === groupId);\n return group?.status && group.status !== \"active\" && group.status !== \"lost\" ? group.statusReason ?? \"You are not in this group\" : null;\n};\n\n/**\n * Waits until an edge took my group message, or its edit number `edit`, or my reaction to it numbered `reaction`, or my\n * pin numbered `pin` (WISP 902: a group has no receipts, so this is as far as the author sees): a member's edge in a\n * private group, an edge to one of my hubs in a community. In a private group with nobody else in it, 0 at once: no\n * edge will ever take it, and the wait sat its whole time, then said \"it goes when one opens\" and exited 4, which a\n * bot retries, sending it again each time. Refused as soon as I learn I am out of the group: it sat its whole time\n * there too and said the same, though nothing goes any more.\n */\nexport async function waitForGroupFrame(ctx: ApiContext, groupId: string, messageId: string, edit: number | { reaction: number } | { pin: number } | undefined, ms: number): Promise<number> {\n const until = performance.now() + ms;\n const which = typeof edit === \"object\" ? edit : edit ? { edit } : {};\n for (;;) {\n const taken = node(ctx).groupTaken({ groupId, messageId, ...which });\n if (taken > 0 || nobodyElseIn(ctx, groupId)) return taken;\n const out = outOf(ctx, groupId);\n if (out) throw new CliError(\"refused\", `${out}: no member took it, and it no longer goes`, { messageId, ...(\"edit\" in which ? { edits: which.edit } : which) });\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: no member's edge took it yet (it stays in the group and goes when one opens). It ${goesOn(ctx)}`, known(ctx, { messageId, ...(\"edit\" in which ? { edits: which.edit } : which) }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * A one-shot whose text went over the live link waits this long for its receipt before it leaves (`waitForMessage`).\n * Left at `sent`, the engine stopping took the text for unconfirmed, the next start sent it again on the DHT, and that\n * copy took the chat's one DHT text awaiting a receipt: a script's next one-shot send waited 30 s behind it, every 5-8\n * messages, and the last text showed \"Connection closed before receipt\" though the contact had it (agents#1640).\n */\nexport const ONE_SHOT_RECEIPT_MS = 2_000;\n\n/**\n * Waits until the contact confirmed my reaction or pin in a 1:1 chat (WISP 401): until `pending` no longer finds it in\n * what the contact has not confirmed (`chatUnconfirmed`). It goes on the live session, a reaction also on the DHT\n * envelopes; one not confirmed in time is kept and said again.\n */\nexport async function waitForConfirmed(ctx: ApiContext, chat: string, what: \"reaction\" | \"pin\", pending: (left: { reactions: number[]; pin: number | null }) => boolean, ms: number): Promise<void> {\n const until = performance.now() + ms;\n while (pending(node(ctx).chatUnconfirmed({ linkId: chat }))) {\n if (performance.now() >= until || stopped(ctx)) throw new CliError(\"timeout\", `${ended(ctx, ms)}: the contact has not confirmed the ${what} yet. It is kept here and ${goesOn(ctx, chat)}`, known(ctx, { chat }));\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n}\n\n/**\n * Waits until a message of mine reached `target` (`sent`: on its way to the contact; `delivered`: acknowledged). A\n * one-shot's text sent over the live link waits a moment more for its receipt (`ONE_SHOT_RECEIPT_MS`).\n */\nexport async function waitForMessage(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const reached = await waitForDelivery(ctx, chat, messageId, target, ms);\n if (ctx.mode !== \"one-shot\" || target !== \"sent\" || reached.delivery !== \"sent\" || reached.via !== \"datalink\") return reached;\n return waitForDelivery(ctx, chat, messageId, \"delivered\", ONE_SHOT_RECEIPT_MS).catch(async () => (await node(ctx).getMessage(chat, messageId)) ?? reached);\n}\n\nasync function waitForDelivery(ctx: ApiContext, chat: string, messageId: string, target: \"sent\" | \"delivered\", ms: number): Promise<StoredMessage> {\n const want = DELIVERY_RANK[target];\n const look = (message: StoredMessage | undefined) => {\n if (!message) return undefined;\n const delivery = message.delivery ?? \"sent\";\n if (delivery === \"failed\") throw new CliError(\"engine\", message.deliveryError ?? \"The message could not be sent\", { messageId, delivery });\n return (DELIVERY_RANK[delivery] ?? 0) >= want ? message : undefined;\n };\n return new Promise<StoredMessage>((resolve, reject) => {\n let settled = false;\n const finish = (error: unknown, message?: StoredMessage) => {\n if (settled) return;\n settled = true; clearTimeout(timer); off(); ctx.stopping?.removeEventListener(\"abort\", giveUp);\n if (error) reject(error); else resolve(message!);\n };\n const check = (last = false) => void node(ctx).getMessage(chat, messageId).then((message) => {\n try {\n const done = look(message);\n if (done) finish(null, done);\n else if (last) finish(new CliError(\"timeout\", `${ended(ctx, ms)}: the message is ${message?.delivery ?? \"not sent yet\"} and ${goesOn(ctx, chat)}`, known(ctx, { messageId, delivery: message?.delivery ?? null })));\n } catch (error) { finish(error); }\n }, finish);\n const giveUp = () => check(true);\n const timer = setTimeout(giveUp, ms);\n // Any event naming the message: a message first seen already delivered comes as `message.sent`, never as\n // `message.delivery`. Listening before the first read leaves no gap for a change to slip through.\n const off = ctx.hub.onEvent((event: GhostlyEvent) => {\n if (event.chat === chat && (event.messageId === messageId || (event.message as { id?: string } | undefined)?.id === messageId)) check();\n });\n if (stopped(ctx)) giveUp();\n else { ctx.stopping?.addEventListener(\"abort\", giveUp, { once: true }); check(); }\n });\n}\n","import { LIMITS } from \"@ghostly/core\";\nimport { CliError } from \"./errors\";\n\n/**\n * A text past what a chat or a group carries (16 KiB of UTF-8, as the engine counts it: trimmed) is refused before the\n * secret guard reads it and before the engine is asked, with its size and the bound, as `send` and `edit` refuse it.\n */\nexport function checkTextSize(text: string): void {\n const bytes = new TextEncoder().encode(text.trim()).length;\n if (bytes > LIMITS.maxChatMessageBytes) throw new CliError(\"bad_request\", `Message exceeds ${LIMITS.maxChatMessageBytes} UTF-8 bytes (${bytes}): shorten it, or send it as a file`, { bytes, max: LIMITS.maxChatMessageBytes });\n}\n","import { BUTTONS_CAPABILITY, BUTTON_STYLES, STATUS_CARD_LIMITS, buttonLabelClash, checkStatusCard, randomBytes, toBase64Url, type ButtonsCard } from \"@ghostly/core\";\nimport type { LinkView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport type { Parsed } from \"./args\";\nimport { bool, chatOrGroup, messageOf, noMessage, node, num, oneOf, oneShotWaits, str, type Method, type Params, type RefPlace } from \"./apiKit\";\nimport { CliError } from \"./errors\";\nimport { findSecret, secretWords } from \"./secretGuard\";\nimport { checkTextSize } from \"./textSize\";\nimport { waitForEdit, waitForGroupFrame, waitForMessage } from \"./waits\";\n\n/*\n * Message buttons (WISP 406 · Message Buttons), the bot's side: a message whose text is the question, with up to six\n * buttons under it (`send --button yes:Yes`). A press comes back as a reply whose text is the button's label; the\n * engine marks it (`press`) and `listen` says `button.pressed`. `button update` then shows the answer (`chosen`) and\n * closes the buttons, by editing the message with the same buttons.\n */\n\n/**\n * `--button id:Label` (again for each, 1 to 6), `--style id=primary|neutral|danger`, `--once` and `--id`, as the\n * method's parameters: `buttons` and `buttonsId`. Nothing when no `--button` is given. The label may hold colons: the\n * id ends at the first one. An id given twice, two labels that read the same (ignoring case and spaces at the ends), a\n * label that is another button's id, or a style not listed are a usage error here, before the profile opens; other\n * bounds (ids, labels, how many) are the card's, checked when it is sent.\n */\nexport function buttonsOf(options: Parsed[\"options\"]): { buttons: Record<string, unknown>[]; buttonsId?: string } | undefined {\n const given = Array.isArray(options.button) ? options.button as string[] : [];\n if (!given.length) {\n for (const flag of [\"style\", \"once\", \"id\"] as const)\n if (options[flag] !== undefined) throw new CliError(\"usage\", `--${flag} goes with --button id:Label`);\n return undefined;\n }\n const buttons: Record<string, unknown>[] = given.map((value) => {\n const colon = value.indexOf(\":\");\n if (colon < 1 || colon === value.length - 1) throw new CliError(\"usage\", `--button takes id:Label, like yes:Yes, not ${JSON.stringify(value)}`);\n return { id: value.slice(0, colon), label: value.slice(colon + 1).trim() };\n });\n const twice = buttons.findIndex((button, at) => buttons.findIndex((other) => other.id === button.id) !== at);\n if (twice !== -1) throw new CliError(\"usage\", `--button ${JSON.stringify(given[twice])} repeats the id ${JSON.stringify(buttons[twice].id)}: each button takes its own`);\n // Two buttons a typed answer could not tell apart: the same label, or a label that is another's id (ignoring case).\n const clash = buttonLabelClash(buttons);\n if (clash) {\n const [at, other] = [JSON.stringify(given[clash.at]), JSON.stringify(given[clash.with])];\n throw new CliError(\"usage\", clash.kind === \"label\"\n ? `--button ${at} repeats the label of --button ${other} (ignoring case and spaces): a typed answer could not tell them apart`\n : `--button ${at} has a label that is the id of --button ${other}: a typed answer could not tell them apart`);\n }\n for (const value of Array.isArray(options.style) ? options.style as string[] : []) {\n const eq = value.indexOf(\"=\");\n const button = eq > 0 ? buttons.find((b) => b.id === value.slice(0, eq)) : undefined;\n if (!button) throw new CliError(\"usage\", `--style takes id=primary|neutral|danger for one of the buttons, not ${JSON.stringify(value)}`);\n const style = value.slice(eq + 1);\n if (!(BUTTON_STYLES as readonly string[]).includes(style)) throw new CliError(\"usage\", `--style ${JSON.stringify(value)}: a button's style is ${BUTTON_STYLES.join(\", \")}`);\n button.style = style;\n }\n if (options.once === true) for (const button of buttons) button.once = true;\n return { buttons, ...(options.id !== undefined && { buttonsId: String(options.id) }) };\n}\n\n/** A buttons card checked by the sender's rule, or a `bad_request` that says what is wrong. */\nfunction checked(card: Record<string, unknown>): ButtonsCard {\n const result = checkStatusCard(card);\n if (\"error\" in result) throw new CliError(\"bad_request\", `Buttons: ${result.error}`, { card });\n return result.card as ButtonsCard;\n}\n\n/**\n * The card a send's `buttons` (and `buttonsId`) make, or undefined when it names none. `buttons` is a list of\n * `{id, label, style?, once?}`; the id of the question is made up (`ask-…`) unless given.\n */\nexport function buttonsCard(params: Params): ButtonsCard | undefined {\n const buttons = params.buttons;\n if (buttons === undefined || buttons === null) {\n if (params.buttonsId !== undefined) throw new CliError(\"bad_request\", \"buttonsId goes with buttons\");\n return undefined;\n }\n if (!Array.isArray(buttons)) throw new CliError(\"bad_request\", \"buttons must be a list of {id, label, style?, once?}\");\n const id = str(params, \"buttonsId\") ?? `ask-${toBase64Url(randomBytes(6))}`;\n return checked({ kind: \"buttons\", id, buttons });\n}\n\n/** Whether a 1:1 contact's app shows and presses buttons: null until its app said what it offers. */\nexport function pressable(link: LinkView): boolean | null {\n const peer = link.sessionOffers?.peer;\n return peer ? peer.includes(BUTTONS_CAPABILITY) : null;\n}\n\n/** The message of mine with buttons that `button update` names, by its id here (or the id both sides know). */\nfunction buttonsMessage(message: StoredMessage | undefined, ref: string, place: RefPlace): StoredMessage & { card: ButtonsCard } {\n if (!message) throw noMessage(ref, place, { whose: \"of yours\" });\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons: send one with send --button id:Label\");\n return message as StoredMessage & { card: ButtonsCard };\n}\n\n/**\n * `button update`: the answer shown on a question's buttons (`chosen`), the buttons closed (`close`), or a new text\n * (`text`), by editing the message with the same buttons. What is not given stays as it was.\n */\nasync function updateButtons(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const chosen = str(params, \"chosen\");\n const close = bool(params, \"close\");\n const newText = str(params, \"text\");\n if (chosen === undefined && !close && newText === undefined) throw new CliError(\"bad_request\", \"Nothing to update: give chosen, close or text\");\n // The engine fills a card's blank text with its fallback line (\"Reply: Yes / No\"): the question's words were lost.\n if (newText !== undefined && !newText.trim()) throw new CliError(\"bad_request\", \"The new text is blank: give the question's new words, or leave text out to keep them\");\n // A new text is a message like any other: the same size check and guard as `send` and `edit`.\n if (newText !== undefined) checkTextSize(newText);\n if (newText !== undefined && !bool(params, \"force\")) {\n const secret = findSecret(newText);\n if (secret) throw new CliError(\"confirm\", `The text looks like ${secretWords(secret)}; update with --force if you mean to`, { kind: secret.kind });\n }\n const message = buttonsMessage(await messageOf(ctx, target.linkId, ref, (m) => m.sender === \"me\"), ref, { group: target.group, ref: str(params, \"chat\", true) });\n if ((message.edit?.seq ?? 0) >= STATUS_CARD_LIMITS.edits)\n throw new CliError(\"refused\", `This message took ${STATUS_CARD_LIMITS.edits} updates, the most one takes: ask again with a new send`, { messageId: message.id, edits: message.edit!.seq });\n const before = message.card;\n // Said here, with the buttons it has, as a press says it (not_found, exit 3): the card's own check names only the field.\n if (chosen !== undefined && !before.buttons.some((b) => b.id === chosen))\n throw new CliError(\"not_found\", `That message has no button ${JSON.stringify(chosen)}; its buttons: ${before.buttons.map((b) => b.id).join(\", \")}`, { card: before });\n const card = checked({ ...before, ...(chosen !== undefined && { chosen }), ...((close || before.closed) && { closed: true }) });\n const text = newText ?? message.text;\n const wait = oneOf(params, \"wait\", target.group ? [\"none\", \"sent\"] as const : [\"none\", \"confirmed\"] as const, \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).editMessage({ linkId: target.linkId, messageId: message.id, text, card });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error);\n let edited = await node(ctx).getMessage(target.linkId, message.id);\n if (wait === \"confirmed\" && edited?.edit?.pending) edited = await waitForEdit(ctx, target.linkId, message.id, ms);\n const edges = wait === \"sent\" && edited?.edit ? await waitForGroupFrame(ctx, target.id, message.id, edited.edit.seq, ms) : undefined;\n return {\n [target.group ? \"group\" : \"chat\"]: target.id, buttons: card.id, messageId: message.id, card, edits: edited?.edit?.seq ?? 0,\n ...(target.group ? { ...(edges !== undefined && { edges }) } : { confirmed: !!edited && !edited.edit?.pending }),\n };\n}\n\n/**\n * `button press`: the other side of a question, as the app's tap: a press on a button of someone else's message, by\n * its id here (or the id both sides know). The engine sends a reply whose text is the button's label, and refuses what\n * an app would: a button the message does not have, closed buttons, a second answer past `once`, a second press\n * within a second. A one-shot in a chat waits until the press went out, as `send` does.\n */\nasync function pressButton(ctx: Parameters<Method>[0], params: Params): Promise<Record<string, unknown>> {\n const target = chatOrGroup(ctx, str(params, \"chat\", true));\n const ref = str(params, \"message\", true);\n const buttonId = str(params, \"button\", true);\n const where = target.group ? \"group\" : \"chat\";\n const message = await messageOf(ctx, target.linkId, ref, (m) => m.sender !== \"me\");\n if (!message) throw noMessage(ref, { group: target.group, ref: str(params, \"chat\", true) }, { whose: \"from someone else\" });\n if (message.card?.kind !== \"buttons\") throw new CliError(\"bad_request\", \"That message has no buttons\");\n const button = message.card.buttons.find((b) => b.id === buttonId);\n if (!button) throw new CliError(\"not_found\", `That message has no button ${JSON.stringify(buttonId)}; its buttons: ${message.card.buttons.map((b) => b.id).join(\", \")}`);\n const wait = target.group\n ? oneOf(params, \"wait\", [\"none\", \"sent\"] as const, \"none\")\n : oneOf(params, \"wait\", [\"none\", \"sent\", \"delivered\"] as const, oneShotWaits(ctx, target.linkId) ? \"sent\" : \"none\");\n const ms = num(params, \"timeout\", 30, { min: 1, max: 3600 }) * 1000;\n const result = await node(ctx).pressButton({ linkId: target.linkId, messageId: message.id, buttonId });\n if (result.error) throw new CliError(result.refused ? \"refused\" : \"unavailable\", result.error, result.paced ? { paced: true } : undefined);\n const replyId = result.messageId ?? null;\n const answer = { [where]: target.id, messageId: message.id, button: button.id, label: button.label, replyId };\n if (!replyId) return answer;\n if (target.group) {\n const edges = wait === \"sent\" ? await waitForGroupFrame(ctx, target.id, replyId, undefined, ms) : node(ctx).groupTaken({ groupId: target.id, messageId: replyId });\n return { ...answer, edges };\n }\n const reply = wait === \"none\" ? await node(ctx).getMessage(target.linkId, replyId) : await waitForMessage(ctx, target.linkId, replyId, wait, ms);\n return { ...answer, delivery: reply?.delivery ?? null };\n}\n\nexport const BUTTON_METHODS: Record<string, Method> = {\n /** WISP 406 · Message Buttons: a press on a button of someone else's message, as the app's tap. */\n \"button.press\": pressButton,\n /** WISP 406 · Message Buttons: the answer chosen on a question of mine, its buttons closed, or its text changed. */\n \"button.update\": updateButtons,\n};\n"],"mappings":";;;;;;AAaA,IAAM,gBAAwC;CAAE,SAAS;CAAG,SAAS;CAAG,QAAQ;CAAG,MAAM;CAAG,MAAM;CAAG,WAAW;AAAE;;;;;;AAOlH,IAAa,UAAU,KAAiB,SAAkB,SAAS,KAAA,KAAa,iBAAiB,KAAK,IAAI,IACtG,yDAAyD,IAAI,SAAS,aAAa,8DAA8D,OACjJ,IAAI,SAAS,YAAY,QAAQ,GAAG,IAAI,qDAAqDA,SAAS,IAAI,IAAI;;;;;;AAOlH,IAAM,WAAW,QAAoB,IAAI,UAAU,YAAY;;AAG/D,IAAM,SAAS,KAAiB,OAAe,QAAQ,GAAG,IAAI,6CAA6C,mBAAmB,KAAK,MAAM,KAAK,GAAI,EAAE;;AAGpJ,IAAM,SAAS,KAAiB,YAAqC,QAAQ,GAAG,IAAI;CAAE,GAAG;CAAS,QAAQ;AAAiB,IAAI;;AAG/H,eAAsB,YAAY,KAAiB,MAAc,WAAmB,IAAoC;CAC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AAO;CACrB,IAAI,OAAO,OAAO;EAChB,MAAM,QAAQ,SAAS,SAAS,MAAM,kBAAkB,KAAK,OAAO,IAAI,SAAS,KAAA,GAAW,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC,WAAW;GAAE,SAAS,OAAO;GAAI,WAAW;EAAQ,CAAC;EACjK,OAAO;GAAE,GAAG;GAAQ;EAAM;CAC5B;CACA,MAAM,QAAQ,SAAS,SAAS,MAAM,KAAK,GAAG,CAAC,CAAC,WAAW,OAAO,QAAQ,OAAO,IAAI,MAAM,eAAe,KAAK,OAAO,QAAQ,SAAS,MAAM,EAAE;CAC/I,OAAO;EAAE,GAAG;EAAQ,UAAU,OAAO,YAAY;CAAK;AACxD;AAEA,IAAa,iBAAyC;;CAEpD,gBAAgB;;CAEhB,iBAAiB;AACnB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as CliError } from "./errors-
|
|
2
|
-
import {
|
|
1
|
+
import { t as CliError } from "./errors-CAh6GLJZ.js";
|
|
2
|
+
import { T as ownSocket, h as lockPath } from "./profiles-DszHjEJi.js";
|
|
3
3
|
import { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
@@ -274,9 +274,29 @@ var HELLO_ID = "hello";
|
|
|
274
274
|
var GREETING_MS = 2e3;
|
|
275
275
|
/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */
|
|
276
276
|
var MAX_LINE = 16777216;
|
|
277
|
-
/**
|
|
278
|
-
|
|
279
|
-
|
|
277
|
+
/**
|
|
278
|
+
* The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody
|
|
279
|
+
* holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,
|
|
280
|
+
* which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether
|
|
281
|
+
* a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.
|
|
282
|
+
*/
|
|
283
|
+
function notTheDaemon(address, held = profileHeld(address.dir)) {
|
|
284
|
+
if (!held) return new CliError("refused", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, {
|
|
285
|
+
reason: "not-the-daemon",
|
|
286
|
+
socket: address.socket
|
|
287
|
+
});
|
|
288
|
+
return new CliError("refused", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \`ghostly daemon restart\` starts this one's`, { reason: "not-the-daemon" });
|
|
289
|
+
}
|
|
290
|
+
/** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */
|
|
291
|
+
function profileHeld(dir) {
|
|
292
|
+
try {
|
|
293
|
+
const pid = Number(readFileSync(lockPath(dir), "utf8").trim());
|
|
294
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
295
|
+
process.kill(pid, 0);
|
|
296
|
+
return true;
|
|
297
|
+
} catch {
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
280
300
|
}
|
|
281
301
|
/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */
|
|
282
302
|
var unanswered = /* @__PURE__ */ new WeakSet();
|
|
@@ -429,7 +449,7 @@ var DaemonClient = class {
|
|
|
429
449
|
}
|
|
430
450
|
/** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */
|
|
431
451
|
refuse(secretGone = false) {
|
|
432
|
-
this.refusal = notTheDaemon(this.address
|
|
452
|
+
this.refusal = notTheDaemon(this.address);
|
|
433
453
|
if (secretGone) unanswered.add(this.refusal);
|
|
434
454
|
this.settle.reject(this.refusal);
|
|
435
455
|
this.socket.destroy();
|
|
@@ -547,6 +567,6 @@ function connectDaemon(address, timeoutMs = 2e3, { greetingMs = GREETING_MS } =
|
|
|
547
567
|
});
|
|
548
568
|
}
|
|
549
569
|
//#endregion
|
|
550
|
-
export {
|
|
570
|
+
export { frameBytes as _, endedUnsent as a, monotonic as b, HELLO as c, proof as d, removeDaemonSecret as f, bytesToMs as g, PlaybackQueue as h, endedUnanswered as i, greeting as l, DEFAULT_RATE as m, MAX_LINE as n, isNotTheDaemon as o, CALL_RATES as p, connectDaemon as r, notTheDaemon as s, DaemonClient as t, newDaemonSecret as u, frameSamples as v, isCallRate as y };
|
|
551
571
|
|
|
552
|
-
//# sourceMappingURL=client-
|
|
572
|
+
//# sourceMappingURL=client-DY8tZZWi.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-DY8tZZWi.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * The call's own clock, in ms: monotonic, so the device's clock set back or ahead mid-call (a phone or a VM fixing its\n * time) moves the time of day, not the audio. On `Date.now()`, a clock set back held the next frame for as long as the\n * jump, and one set ahead read as that long without a packet from the contact.\n */\nexport const monotonic = (): number => performance.now();\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */\n private owed = false;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = monotonic, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n if (this.owed) {\n this.owed = false;\n chunk = chunk.subarray(1);\n }\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n // The queue ends on a whole sample here, so an odd number lost ends on half of one.\n if (lost % 2) this.owed = true;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n // Half a sample queued: its other half is the program's next byte.\n if (this.length % 2) this.owed = true;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n /**\n * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is\n * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much\n * was dropped, in milliseconds.\n */\n newWriter(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n // A flush that cut the last program's half sample owes nothing to the next program: it starts on a whole sample.\n this.owed = false;\n return ms;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n","import { readFileSync } from \"node:fs\";\nimport { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\nimport { lockPath } from \"./profiles\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/**\n * The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody\n * holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,\n * which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether\n * a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.\n */\nexport function notTheDaemon(address: DaemonAddress, held = profileHeld(address.dir)): CliError {\n if (!held) {\n return new CliError(\"refused\", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, { reason: \"not-the-daemon\", socket: address.socket });\n }\n return new CliError(\"refused\", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\n/** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */\nfunction profileHeld(dir: string): boolean {\n try {\n const pid = Number(readFileSync(lockPath(dir), \"utf8\").trim());\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */\nconst unanswered = new WeakSet<CliError>();\n\n/**\n * A call the daemon read and never answered, because it stopped (a restart, a crash): what was asked may be done, so\n * it is no plain failure a bot tries again (a send went twice). A daemon that stops answers its waits first (`serve`);\n * this is for the calls it could not.\n */\nfunction stoppedUnanswered(method: string): CliError {\n const error = new CliError(\"timeout\", `The daemon stopped before it answered ${method}, which may be done: check (\\`ghostly chat history\\` for a message) before you try again`, { method, reason: \"daemon-stopped\" });\n unanswered.add(error);\n return error;\n}\n\n/**\n * A call whose connection ended before the daemon read it, or before it proved itself: nothing was done. `leaving`: this\n * client ended it (a deadline, Ctrl-C), so it is no daemon that stopped under the call.\n */\nfunction wentAway(leaving: boolean): CliError {\n const error = new CliError(\"unavailable\", \"The daemon went away\");\n if (!leaving) unanswered.add(error);\n return error;\n}\n\n/**\n * Whether a call failed because its connection ended unanswered (the daemon stopped, restarted or crashed under it),\n * not because the daemon answered it with an error. A read that did can be asked again: it changed nothing. So may one\n * refused because the daemon's secret was gone when its greeting or its hello's answer came: a daemon that stops removes\n * it first, and the greeting it wrote just before is read after. Nothing but the hello was written to it, and a listener\n * that never proves itself is refused again on the new connection.\n */\nexport function endedUnanswered(error: unknown): boolean {\n return error instanceof CliError && unanswered.has(error);\n}\n\n/**\n * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are\n * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.\n */\nexport function endedUnsent(error: unknown): boolean {\n return endedUnanswered(error) && (error as CliError).details?.reason !== \"daemon-stopped\";\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n /** `written`: the call is on the socket, so the daemon may have acted on it. */\n private readonly pending = new Map<number, { method: string; written: boolean; resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n /** This client closed the connection: what was still unanswered is its own doing, not a daemon that stopped. */\n private leaving = false;\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(!secret); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse(!secret);\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? wentAway(this.leaving);\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(waiting.written && !this.refusal && !this.leaving ? stoppedUnanswered(waiting.method) : why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */\n private refuse(secretGone = false): void {\n this.refusal = notTheDaemon(this.address);\n if (secretGone) unanswered.add(this.refusal);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? wentAway(this.leaving));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n method, written: false,\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => {\n if (!this.pending.has(id) || this.socket.destroyed) return;\n this.socket.write(line);\n settle.written = true;\n },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.leaving = true;\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.leaving = true;\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OAAQ,GAAI;AAExG,SAAgB,WAAW,OAAmC;CAC5D,OAAO,WAAW,SAAS,KAAiB;AAC9C;;AAGA,IAAa,eAAe;;;;;;AAa5B,IAAa,kBAA0B,YAAY,IAAI;;;;;AAMvD,IAAa,gBAAb,MAA2B;CAaJ;CAAiC;CAZtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAAiB;CACjB,WAAmB;;CAEnB,OAAe;CACf;CACA;CACA;;CAEA,UAAU;CAEV,YAAY,MAAyB,MAAqC,WAAW,QAAQ,cAAc;EAAtF,KAAA,OAAA;EAAiC,KAAA,MAAA;EACpD,KAAK,QAAQ,WAAW,IAAI;EAE5B,KAAK,MAAM,KAAK,MAAO,OAAO,QAAS,GAAI,IAAI;EAC/C,KAAK,UAAU,OAAO,MAAM,KAAK,KAAK;CACxC;;CAGA,KAAK,OAAuB;EAC1B,IAAI,CAAC,MAAM,QAAQ,OAAO;EAC1B,KAAK,WAAW,KAAK,IAAI;EACzB,IAAI,KAAK,MAAM;GACb,KAAK,OAAO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,QAAQ,KAAK;GACpC,KAAK,gBAAgB,KAAK,EAAE;GAC5B,IAAI,KAAK,MAAM;IAAE,KAAM,KAAwB,QAAQ,GAAG,KAAK,MAAM,IAAI,CAAC,CAAC;IAAG;GAAQ;EACxF;EACA,KAAK,OAAO,OAAO;CACrB;CAEA,QAAc;EACZ,KAAK,UAAU;EACf,KAAK,OAAO,IAAI;CAClB;;CAGA,UAAgB;EACd,KAAK,UAAU;EACf,KAAK,OAAO,QAAQ;CACtB;AACF;;;;;AAMA,SAAgB,cAAc,SAAwB,YAAY,KAAO,EAAE,aAAa,gBAAyC,CAAC,GAAiC;CACjK,MAAM,OAAO,QAAQ;CAErB,IAAI,CAAC,UAAU,IAAI,GAAG,OAAO,QAAQ,QAAQ,IAAI;CACjD,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,QAAQ,IAAI;EAC3B,MAAM,QAAQ,iBAAiB;GAAE,OAAO,QAAQ;GAAG,QAAQ,IAAI;EAAG,GAAG,SAAS;EAC9E,OAAO,KAAK,iBAAiB;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI,aAAa,QAAQ,SAAS,UAAU,CAAC;EAAG,CAAC;EAC7G,OAAO,KAAK,eAAe;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI;EAAG,CAAC;CACpE,CAAC;AACH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./src-
|
|
1
|
+
import "./src-DJe-OYxd.js";
|
|
2
2
|
//#region ../browser/src/backup/codec.ts
|
|
3
3
|
function fromBase64Url(text) {
|
|
4
4
|
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("Invalid base64url");
|
|
@@ -10,4 +10,4 @@ function fromBase64Url(text) {
|
|
|
10
10
|
//#endregion
|
|
11
11
|
export { fromBase64Url as t };
|
|
12
12
|
|
|
13
|
-
//# sourceMappingURL=codec-
|
|
13
|
+
//# sourceMappingURL=codec-BnMg-Grj.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec-
|
|
1
|
+
{"version":3,"file":"codec-BnMg-Grj.js","names":[],"sources":["../../../browser/src/backup/codec.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"],"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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as fromBase64Url } from "./codec-
|
|
1
|
+
import { t as fromBase64Url } from "./codec-BnMg-Grj.js";
|
|
2
2
|
//#region ../browser/src/backup/envelope.ts
|
|
3
3
|
var BACKUP_MEDIA_TYPE = "application/vnd.ghostly.backup+json";
|
|
4
4
|
var ITERATIONS = 6e5;
|
|
@@ -78,4 +78,4 @@ async function open(text, passphrase) {
|
|
|
78
78
|
//#endregion
|
|
79
79
|
export { MAX_BACKUP_BYTES as n, open as r, BACKUP_MEDIA_TYPE as t };
|
|
80
80
|
|
|
81
|
-
//# sourceMappingURL=envelope-
|
|
81
|
+
//# sourceMappingURL=envelope-CdV7vHVZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envelope-
|
|
1
|
+
{"version":3,"file":"envelope-CdV7vHVZ.js","names":[],"sources":["../../../browser/src/backup/envelope.ts"],"sourcesContent":["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":";;AAWA,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,WA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AI,cAAc,eAAe,SAAS,IAAI,aAAa,OAAc,SAAS,QAAQ,SAAS,iBAAiB,CAAC,CAAC,QAAQ,MAAM,CAAC,CAAC,SAAS,SAAS,WAAW,GAAG,MAAM,IAAI,MAAM,+BAA+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"}
|
|
@@ -35,7 +35,7 @@ function asCliError(error) {
|
|
|
35
35
|
if (error instanceof CliError) return error;
|
|
36
36
|
if (error && typeof error === "object" && "code" in error && "message" in error && typeof error.code === "string" && Object.hasOwn(EXIT, error.code)) return new CliError(error.code, String(error.message));
|
|
37
37
|
if (error instanceof Error && error.code === "unreachable") return new CliError("unavailable", error.message);
|
|
38
|
-
const known = engineKnown(error);
|
|
38
|
+
const known = engineKnown(error) ?? contactNoRail(error);
|
|
39
39
|
if (known) return known;
|
|
40
40
|
const full = noRoomError(error);
|
|
41
41
|
if (full) return full;
|
|
@@ -92,6 +92,29 @@ function engineKnown(error) {
|
|
|
92
92
|
if (engineCode === "contactNoWallet") return new CliError("refused", `${error.message} (on a CLI: ghostly wallet create cashu)`, details);
|
|
93
93
|
return new CliError(ENGINE_CODES[engineCode], error.message, details);
|
|
94
94
|
}
|
|
95
|
+
/** The engine's names of the ways of paying (payments.ts `METHOD_NAME`), as `wallet create` takes them; Bark is the app's only. */
|
|
96
|
+
var RAILS = {
|
|
97
|
+
Cashu: "cashu",
|
|
98
|
+
Lightning: "lightning",
|
|
99
|
+
Ark: "arkade",
|
|
100
|
+
USDT: "usdt",
|
|
101
|
+
Bark: null,
|
|
102
|
+
"on-chain Bitcoin": "bitcoin",
|
|
103
|
+
Fedimint: "fedimint",
|
|
104
|
+
Spark: "spark"
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* A contact with no wallet of the way of paying or the network asked (`chat request --method arkade`, a Mainnet `chat
|
|
108
|
+
* pay` to a contact with Testnet Cashu only): the engine says it in words alone. `refused` with `contact_no_wallet` and
|
|
109
|
+
* the contact's next step, as a contact with no wallet at all is said. Before, `engine`, which a bot may retry.
|
|
110
|
+
*/
|
|
111
|
+
function contactNoRail(error) {
|
|
112
|
+
const said = error instanceof Error ? /^Your contact has no (Mainnet|Testnet) (.+) wallet$/.exec(error.message) : null;
|
|
113
|
+
if (!said || !Object.hasOwn(RAILS, said[2])) return void 0;
|
|
114
|
+
const type = RAILS[said[2]];
|
|
115
|
+
const step = type ? ` (on a CLI: ghostly wallet create ${type}${said[1] === "Mainnet" ? " --network mainnet" : ""})` : "";
|
|
116
|
+
return new CliError("refused", `${said[0]}${step}`, { reason: "contact_no_wallet" });
|
|
117
|
+
}
|
|
95
118
|
/**
|
|
96
119
|
* A change the profile's store could not put on disk (`storage.ts` refuses its transaction with a QuotaExceededError;
|
|
97
120
|
* the engine's `committed` wraps it in its own words, the store's as the cause): `unavailable`, try again once there is
|
|
@@ -133,8 +156,10 @@ function localFileError(error, file) {
|
|
|
133
156
|
const { code, path } = error;
|
|
134
157
|
const where = typeof path === "string" ? path : file ?? "the path";
|
|
135
158
|
if (code === "ENOENT" || code === "ENOTDIR") return new CliError("not_found", `No such file or folder: ${where}`);
|
|
159
|
+
if (code === "ELOOP") return new CliError("not_found", `No such file or folder: ${where} (its symbolic links go round in a loop)`);
|
|
136
160
|
if (code === "EACCES" || code === "EPERM" || code === "EROFS") return new CliError("refused", `Not allowed to write or read ${where}`);
|
|
137
161
|
if (code === "EISDIR") return new CliError("bad_request", `${where} is a folder: name a file`);
|
|
162
|
+
if (code === "EEXIST" && error.syscall === "mkdir") return new CliError("not_found", `${where} is a file, not a folder`);
|
|
138
163
|
if (code === "ENAMETOOLONG") return new CliError("bad_request", `A name in ${where} is too long for this file system (at most 255 bytes)`);
|
|
139
164
|
if (code === "ENOSPC" || code === "EDQUOT") {
|
|
140
165
|
const at = typeof path === "string" ? path : file;
|
|
@@ -148,4 +173,4 @@ function localFileError(error, file) {
|
|
|
148
173
|
//#endregion
|
|
149
174
|
export { localFileError as i, EXIT as n, asCliError as r, CliError as t };
|
|
150
175
|
|
|
151
|
-
//# sourceMappingURL=errors-
|
|
176
|
+
//# sourceMappingURL=errors-CAh6GLJZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-CAh6GLJZ.js","names":[],"sources":["../../src/errors.ts"],"sourcesContent":["/**\n * Errors that reach a bot: a stable `code` to branch on, a message for people, and the exit status the CLI\n * leaves with (WISP 1100 § Exit codes). The daemon sends `{code, message}` over the socket; the CLI prints\n * `{\"error\": {code, message}}` on stdout and exits with `exit`.\n */\nexport type ErrorCode =\n | \"bad_request\" | \"usage\" | \"not_found\" | \"refused\" | \"unavailable\" | \"confirm\" | \"timeout\"\n | \"engine\" | \"busy\" | \"internal\" | \"interrupted\";\n\n/** `interrupted`: Ctrl-C (SIGINT) ended the command, 128 + 2 as a shell says of a command its signal ended. */\nexport const EXIT: Record<ErrorCode, number> = {\n engine: 1, refused: 1, unavailable: 1, bad_request: 1, busy: 1, internal: 1,\n usage: 2, not_found: 3, timeout: 4, confirm: 5, interrupted: 130,\n};\n\nexport class CliError extends Error {\n constructor(readonly code: ErrorCode, message: string, readonly details?: Record<string, unknown>) {\n super(message);\n this.name = \"CliError\";\n }\n toJSON(): { code: ErrorCode; message: string; details?: Record<string, unknown> } {\n return { code: this.code, message: this.message, ...(this.details ? { details: this.details } : {}) };\n }\n}\n\n/** Anything thrown, as the error a bot sees: the engine's own refusals keep their words. */\nexport function asCliError(error: unknown): CliError {\n if (error instanceof CliError) return error;\n if (error && typeof error === \"object\" && \"code\" in error && \"message\" in error && typeof (error as { code: unknown }).code === \"string\"\n && Object.hasOwn(EXIT, (error as { code: string }).code)) return new CliError((error as { code: ErrorCode }).code, String((error as { message: unknown }).message));\n // A contact the chat's link could not reach (its `GhostlyHttpError` \"unreachable\"): not there now, not the engine failing.\n if (error instanceof Error && (error as { code?: unknown }).code === \"unreachable\") return new CliError(\"unavailable\", error.message);\n const known = engineKnown(error) ?? contactNoRail(error);\n if (known) return known;\n const full = noRoomError(error);\n if (full) return full;\n const local = localFileError(error);\n if (local) return local;\n const unopened = profileOpenError(error);\n if (unopened) return unopened;\n const message = error instanceof Error ? error.message : String(error);\n if (/real money|confirmedReal|Mainnet/i.test(message) && /confirm/i.test(message)) return new CliError(\"confirm\", message);\n if (/other network|cross-network|network does not match/i.test(message)) return new CliError(\"refused\", message);\n // A member asking for a group's admin-only change, one removed from the group (or gone) asking for any, an invitation\n // already answered: not allowed, not the engine failing.\n if (/^Only the admin |^You are no longer in this group$|^No invitation to (accept|decline)$/.test(message)) return new CliError(\"refused\", message);\n // `group invite` to a contact whose app is closed: try again once they are online.\n if (message === \"This contact is not connected right now. Invite them when they are online.\") return new CliError(\"unavailable\", message);\n // `group invite` the group or the contact's app cannot take: one already in, a full group, an app too old for it.\n if (/^This contact is already a member$|^A group holds \\d+ members at most$|^A group grows past \\d+ only when |^Their app (does not take part in groups|takes groups of \\d+ at most)|^This group runs through hubs, which their app /.test(message)) return new CliError(\"refused\", message);\n // `group invite` into a community: it has no invitations, its link is how people join.\n if (message === \"Share the group's link with them: anyone who opens it joins\") return new CliError(\"bad_request\", message);\n return new CliError(\"engine\", message);\n}\n\n/**\n * The engine's known errors (`EngineError`, packages/core engineErrors.ts) a bot branches on, by their `engineCode`: a\n * host or the network not answering is `unavailable` (try again later), one too slow `timeout`, a value the person gave\n * `bad_request`, money that is not there `refused`, a contact that offers no way of paying `refused` with its reason in\n * `details.reason`. Any other keeps `engine`. Read by its shape, as `profileOpenError`.\n */\nconst ENGINE_CODES: Record<string, ErrorCode> = {\n mintUnreachable: \"unavailable\", lnurlUnreachable: \"unavailable\", hostUnreachable: \"unavailable\", networkUnreachable: \"unavailable\", usdtRpcUnavailable: \"unavailable\",\n hostTimedOut: \"timeout\", networkTimedOut: \"timeout\",\n invalidMintUrl: \"bad_request\", mintNotHttps: \"bad_request\", invalidMaxFee: \"bad_request\",\n notEnoughSats: \"refused\", notEnoughForFee: \"refused\", mintsNoAnyAmount: \"refused\", ecashAlreadySpent: \"refused\", ecashFeeTakesAll: \"refused\", lightningRefused: \"refused\", contactNoWallet: \"refused\", contactNoPayments: \"refused\",\n};\n/** `details.reason` of an engine error a bot tells apart from others of its code. */\nconst ENGINE_REASONS: Record<string, string> = { contactNoWallet: \"contact_no_wallet\", contactNoPayments: \"contact_payments_off\" };\n\nfunction engineKnown(error: unknown): CliError | undefined {\n if (!(error instanceof Error)) return undefined;\n const { engineCode, values } = error as { engineCode?: unknown; values?: { host?: unknown } };\n if (typeof engineCode !== \"string\" || !Object.hasOwn(ENGINE_CODES, engineCode)) return undefined;\n // The app's reason for a Lightning address it could not read (a browser's CORS) is no reason in a terminal.\n if (engineCode === \"lnurlUnreachable\" && typeof values?.host === \"string\") return new CliError(\"unavailable\", `Could not reach ${values.host}`);\n const details = Object.hasOwn(ENGINE_REASONS, engineCode) ? { reason: ENGINE_REASONS[engineCode] } : undefined;\n // The contact's next step, for a contact that is a bot too.\n if (engineCode === \"contactNoWallet\") return new CliError(\"refused\", `${error.message} (on a CLI: ghostly wallet create cashu)`, details);\n return new CliError(ENGINE_CODES[engineCode], error.message, details);\n}\n\n/** The engine's names of the ways of paying (payments.ts `METHOD_NAME`), as `wallet create` takes them; Bark is the app's only. */\nconst RAILS: Record<string, string | null> = { Cashu: \"cashu\", Lightning: \"lightning\", Ark: \"arkade\", USDT: \"usdt\", Bark: null, \"on-chain Bitcoin\": \"bitcoin\", Fedimint: \"fedimint\", Spark: \"spark\" };\n\n/**\n * A contact with no wallet of the way of paying or the network asked (`chat request --method arkade`, a Mainnet `chat\n * pay` to a contact with Testnet Cashu only): the engine says it in words alone. `refused` with `contact_no_wallet` and\n * the contact's next step, as a contact with no wallet at all is said. Before, `engine`, which a bot may retry.\n */\nfunction contactNoRail(error: unknown): CliError | undefined {\n const said = error instanceof Error ? /^Your contact has no (Mainnet|Testnet) (.+) wallet$/.exec(error.message) : null;\n if (!said || !Object.hasOwn(RAILS, said[2])) return undefined;\n const type = RAILS[said[2]];\n const step = type ? ` (on a CLI: ghostly wallet create ${type}${said[1] === \"Mainnet\" ? \" --network mainnet\" : \"\"})` : \"\";\n return new CliError(\"refused\", `${said[0]}${step}`, { reason: \"contact_no_wallet\" });\n}\n\n/**\n * A change the profile's store could not put on disk (`storage.ts` refuses its transaction with a QuotaExceededError;\n * the engine's `committed` wraps it in its own words, the store's as the cause): `unavailable`, try again once there is\n * room, in the store's words, which name the profile's folder. Before, a daemon on a full disk answered done.\n */\nfunction noRoomError(error: unknown): CliError | undefined {\n let said: string | undefined, found = false;\n for (let at = error, depth = 0; at && typeof at === \"object\" && depth < 4; at = (at as { cause?: unknown }).cause, depth++) {\n if ((at as { name?: unknown }).name !== \"QuotaExceededError\") continue;\n found = true;\n const message = (at as { message?: unknown }).message;\n if (typeof message === \"string\" && message.startsWith(\"No room left\")) said = message;\n }\n return found ? new CliError(\"unavailable\", said ?? \"No room left on the disk: free some space, then try again\") : undefined;\n}\n\n/**\n * The profile's database did not open (the engine's `ProfileOpenError`, packages/browser/src/shared/idb.ts): `engine`\n * (exit 1) with the engine's own words, which name the versions when a newer ghostly stored it, and the reason and\n * the versions in `details` for a bot. Read by its shape: this module is also the thin client's, which loads no engine.\n */\nfunction profileOpenError(error: unknown): CliError | undefined {\n if (!(error instanceof Error) || error.name !== \"ProfileOpenError\") return undefined;\n const failure = (error as { failure?: { reason?: unknown; storedVersion?: unknown; supportedVersion?: unknown } }).failure;\n if (!failure || typeof failure.reason !== \"string\") return undefined;\n return new CliError(\"engine\", error.message, {\n reason: failure.reason === \"newer\" ? \"newer_profile\" : `profile_${failure.reason}`,\n ...(typeof failure.storedVersion === \"number\" ? { storedVersion: failure.storedVersion } : {}),\n ...(typeof failure.supportedVersion === \"number\" ? { supportedVersion: failure.supportedVersion } : {}),\n });\n}\n\n/**\n * A file or folder on this machine the command could not open (`file save --dir`, `profile backup --out`): the\n * person's path, not the engine refusing, so it says so with the code a bot branches on. Before, a folder that did\n * not exist was `engine` (exit 1) with Node's `ENOENT: no such file or directory, open '…'`. `file`: the path read, for\n * an error that names none (a folder read as a file).\n */\nexport function localFileError(error: unknown, file?: string): CliError | undefined {\n if (!error || typeof error !== \"object\" || typeof (error as { syscall?: unknown }).syscall !== \"string\") return undefined;\n const { code, path } = error as { code?: unknown; path?: unknown };\n const where = typeof path === \"string\" ? path : file ?? \"the path\";\n if (code === \"ENOENT\" || code === \"ENOTDIR\") return new CliError(\"not_found\", `No such file or folder: ${where}`);\n // A symbolic link to itself (or a ring of them) leads nowhere: before, Node's raw \"ELOOP: …, stat\" as `engine`.\n if (code === \"ELOOP\") return new CliError(\"not_found\", `No such file or folder: ${where} (its symbolic links go round in a loop)`);\n if (code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\") return new CliError(\"refused\", `Not allowed to write or read ${where}`);\n if (code === \"EISDIR\") return new CliError(\"bad_request\", `${where} is a folder: name a file`);\n // A file where a folder is to be made (`store sign --out`, `app publish --key`/`--out`): Node's \"EEXIST: file already\n // exists, mkdir '…'\" was `engine`. Named as `file save --dir` names one.\n if (code === \"EEXIST\" && (error as { syscall: string }).syscall === \"mkdir\") return new CliError(\"not_found\", `${where} is a file, not a folder`);\n if (code === \"ENAMETOOLONG\") return new CliError(\"bad_request\", `A name in ${where} is too long for this file system (at most 255 bytes)`);\n // A full disk (or a quota) answered Node's raw \"ENOSPC: no space left on device, write\" as `engine`, naming nothing\n // (agents#1710). `unavailable`: it works again once there is room, with nothing lost.\n if (code === \"ENOSPC\" || code === \"EDQUOT\") {\n const at = typeof path === \"string\" ? path : file;\n return new CliError(\"unavailable\", at ? `No room left for ${at}: free some space, then try again` : \"No room left on the disk: free some space, then try again\", { reason: \"no_space\", errno: code, ...(at && { path: at }) });\n }\n return undefined;\n}\n"],"mappings":";;AAUA,IAAa,OAAkC;CAC7C,QAAQ;CAAG,SAAS;CAAG,aAAa;CAAG,aAAa;CAAG,MAAM;CAAG,UAAU;CAC1E,OAAO;CAAG,WAAW;CAAG,SAAS;CAAG,SAAS;CAAG,aAAa;AAC/D;AAEA,IAAa,WAAb,cAA8B,MAAM;CACb;CAA2C;CAAhE,YAAY,MAA0B,SAAiB,SAA4C;EACjG,MAAM,OAAO;EADM,KAAA,OAAA;EAA2C,KAAA,UAAA;EAE9D,KAAK,OAAO;CACd;CACA,SAAkF;EAChF,OAAO;GAAE,MAAM,KAAK;GAAM,SAAS,KAAK;GAAS,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;EAAG;CACtG;AACF;;AAGA,SAAgB,WAAW,OAA0B;CACnD,IAAI,iBAAiB,UAAU,OAAO;CACtC,IAAI,SAAS,OAAO,UAAU,YAAY,UAAU,SAAS,aAAa,SAAS,OAAQ,MAA4B,SAAS,YAC3H,OAAO,OAAO,MAAO,MAA2B,IAAI,GAAG,OAAO,IAAI,SAAU,MAA8B,MAAM,OAAQ,MAA+B,OAAO,CAAC;CAEpK,IAAI,iBAAiB,SAAU,MAA6B,SAAS,eAAe,OAAO,IAAI,SAAS,eAAe,MAAM,OAAO;CACpI,MAAM,QAAQ,YAAY,KAAK,KAAK,cAAc,KAAK;CACvD,IAAI,OAAO,OAAO;CAClB,MAAM,OAAO,YAAY,KAAK;CAC9B,IAAI,MAAM,OAAO;CACjB,MAAM,QAAQ,eAAe,KAAK;CAClC,IAAI,OAAO,OAAO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,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { yd as stripHidden } from "./src-DJe-OYxd.js";
|
|
2
2
|
//#region ../browser/src/engine/paymentAdapters/fedimintSdk.ts
|
|
3
3
|
var fedimintDatabase = (id) => `ghostly-fedimint-${id}.db`;
|
|
4
4
|
var MODULE_WASM = () => import("./fedimint_client_wasm_bg-BtHHlFpp.js");
|
|
@@ -349,4 +349,4 @@ async function fedimintSdkOn(platform) {
|
|
|
349
349
|
//#endregion
|
|
350
350
|
export { fedimintSdkOn as n, loadFedimintSdk as r, fedimintDatabase as t };
|
|
351
351
|
|
|
352
|
-
//# sourceMappingURL=fedimintSdk-
|
|
352
|
+
//# sourceMappingURL=fedimintSdk-CPFfVK-G.js.map
|