@ghostlytools/cli 1.13.0 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +13 -10
  2. package/dist/assets/api-DV52o7A8.js +3 -0
  3. package/dist/assets/{api-CjOaoG-v.js → api-O57SNJcb.js} +495 -99
  4. package/dist/assets/api-O57SNJcb.js.map +1 -0
  5. package/dist/assets/{apiKit-BAGvlQtm.js → apiKit-CPTFJHA7.js} +40 -8
  6. package/dist/assets/{apiKit-BAGvlQtm.js.map → apiKit-CPTFJHA7.js.map} +1 -1
  7. package/dist/assets/{appFetch-BwJd-kNq.js → appFetch-Ca9DNQQ2.js} +2 -2
  8. package/dist/assets/{appFetch-BwJd-kNq.js.map → appFetch-Ca9DNQQ2.js.map} +1 -1
  9. package/dist/assets/{apps-Cuk45sz5.js → apps-gXpGFPiv.js} +16 -14
  10. package/dist/assets/apps-gXpGFPiv.js.map +1 -0
  11. package/dist/assets/{apps-DjY095Af.js → apps-uZTu5FlR.js} +1 -1
  12. package/dist/assets/{arkade-DryM-q5n.js → arkade-B6UNf5HI.js} +2 -2
  13. package/dist/assets/{arkade-DryM-q5n.js.map → arkade-B6UNf5HI.js.map} +1 -1
  14. package/dist/assets/{backup-DekVCDWv.js → backup-CxH3auHB.js} +9 -7
  15. package/dist/assets/backup-CxH3auHB.js.map +1 -0
  16. package/dist/assets/{backup-B56sQqoQ.js → backup-Di2U6QVH.js} +1 -1
  17. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
  18. package/dist/assets/{bitcoind-B2bbVSzh.js → bitcoind-BpZn3bRN.js} +2 -2
  19. package/dist/assets/{bitcoind-B2bbVSzh.js.map → bitcoind-BpZn3bRN.js.map} +1 -1
  20. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
  21. package/dist/assets/{buttons-BGxzOtrq.js → buttons-D4udKEvT.js} +8 -8
  22. package/dist/assets/buttons-D4udKEvT.js.map +1 -0
  23. package/dist/assets/buttons-YTYEqvGC.js +1 -0
  24. package/dist/assets/{client-DcQAfc3h.js → client-DGx7E8b3.js} +3 -3
  25. package/dist/assets/{client-DcQAfc3h.js.map → client-DGx7E8b3.js.map} +1 -1
  26. package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
  27. package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
  28. package/dist/assets/{engineErrors--9hfgKlK.js → engineErrors-wWlLy54D.js} +11 -3
  29. package/dist/assets/engineErrors-wWlLy54D.js.map +1 -0
  30. package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
  31. package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
  32. package/dist/assets/{fixedHosts-C3hBliM9.js → fixedHosts-CODN2pTL.js} +3 -3
  33. package/dist/assets/{fixedHosts-C3hBliM9.js.map → fixedHosts-CODN2pTL.js.map} +1 -1
  34. package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
  35. package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
  36. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  37. package/dist/assets/{groupMeta-goASqzOt.js → groupMeta-CeZpqVVC.js} +174 -37
  38. package/dist/assets/groupMeta-CeZpqVVC.js.map +1 -0
  39. package/dist/assets/{host-C2WRKj3g.js → host-CRA7h5A2.js} +270 -64
  40. package/dist/assets/host-CRA7h5A2.js.map +1 -0
  41. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-B34Zhz4P.js} +2 -2
  42. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-B34Zhz4P.js.map} +1 -1
  43. package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-DDwU5b4P.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-DDwU5b4P.js.map} +1 -1
  45. package/dist/assets/{identityProofs-Cksc_K7_.js → identityProofs-B8zCp5_0.js} +140 -27
  46. package/dist/assets/identityProofs-B8zCp5_0.js.map +1 -0
  47. package/dist/assets/{irohWeb-NfthOL98.js → irohWeb-mnOi2Jp7.js} +10838 -4837
  48. package/dist/assets/irohWeb-mnOi2Jp7.js.map +1 -0
  49. package/dist/assets/{linkPreview-DdMf-YAc.js → linkPreview-5kHmKUTN.js} +20 -8
  50. package/dist/assets/linkPreview-5kHmKUTN.js.map +1 -0
  51. package/dist/assets/{main-Dh7fePd8.js → main-Chc871HV.js} +119 -81
  52. package/dist/assets/main-Chc871HV.js.map +1 -0
  53. package/dist/assets/{mainline-DY95WbuK.js → mainline-CDUXtV-I.js} +2 -2
  54. package/dist/assets/{mainline-DY95WbuK.js.map → mainline-CDUXtV-I.js.map} +1 -1
  55. package/dist/assets/{networkReason-Be-hMghr.js → networkReason-DYlPZS5M.js} +2 -2
  56. package/dist/assets/{networkReason-Be-hMghr.js.map → networkReason-DYlPZS5M.js.map} +1 -1
  57. package/dist/assets/{ownDid-BErplN7N.js → ownDid-BOuSlDv-.js} +10 -6
  58. package/dist/assets/ownDid-BOuSlDv-.js.map +1 -0
  59. package/dist/assets/{ownStatus-ClrFjd7h.js → ownStatus-CLA1VPkL.js} +6 -6
  60. package/dist/assets/{ownStatus-ClrFjd7h.js.map → ownStatus-CLA1VPkL.js.map} +1 -1
  61. package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-DAzupLYo.js} +23 -17
  62. package/dist/assets/pairedTransports-DAzupLYo.js.map +1 -0
  63. package/dist/assets/{paymentIntent-DySU3Ajm.js → paymentIntent-Cr3uZa_0.js} +2 -2
  64. package/dist/assets/{paymentIntent-DySU3Ajm.js.map → paymentIntent-Cr3uZa_0.js.map} +1 -1
  65. package/dist/assets/{profiles-B8xO8-oj.js → profiles-BH1bH9aE.js} +3 -3
  66. package/dist/assets/{profiles-B8xO8-oj.js.map → profiles-BH1bH9aE.js.map} +1 -1
  67. package/dist/assets/{registry--Rg2YvOH.js → registry-DAq16T-V.js} +1 -1
  68. package/dist/assets/{registry-CU8PevhI.js → registry-DP_-RA-v.js} +11 -7
  69. package/dist/assets/registry-DP_-RA-v.js.map +1 -0
  70. package/dist/assets/{relay-CHWg5hpZ.js → relay-gJTOYQJZ.js} +93 -7
  71. package/dist/assets/relay-gJTOYQJZ.js.map +1 -0
  72. package/dist/assets/{resolve-B1upovPM.js → resolve-B1eQ4dVQ.js} +10 -5
  73. package/dist/assets/resolve-B1eQ4dVQ.js.map +1 -0
  74. package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
  75. package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
  76. package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
  77. package/dist/assets/{server-Dgxx_DaN.js → server-Bd2ofxc1.js} +1283 -6628
  78. package/dist/assets/server-Bd2ofxc1.js.map +1 -0
  79. package/dist/assets/{sshForges-BnvwmNj-.js → sshForges-As7dbGXM.js} +2 -2
  80. package/dist/assets/{sshForges-BnvwmNj-.js.map → sshForges-As7dbGXM.js.map} +1 -1
  81. package/dist/assets/{translate-BcbSWkuq.js → translate-DnuQMfj0.js} +22 -11
  82. package/dist/assets/translate-DnuQMfj0.js.map +1 -0
  83. package/dist/assets/{usdt-CBJ4Q5Ji.js → usdt-DLmtf8F9.js} +4 -4
  84. package/dist/assets/{usdt-CBJ4Q5Ji.js.map → usdt-DLmtf8F9.js.map} +1 -1
  85. package/dist/assets/{waitNotice-ylU3XwjO.js → waitNotice-BHuMofaH.js} +57 -3
  86. package/dist/assets/waitNotice-BHuMofaH.js.map +1 -0
  87. package/dist/ghostly.mjs +1 -1
  88. package/npm-shrinkwrap.json +2 -2
  89. package/package.json +1 -1
  90. package/dist/assets/api-CVtg7MpI.js +0 -3
  91. package/dist/assets/api-CjOaoG-v.js.map +0 -1
  92. package/dist/assets/apps-Cuk45sz5.js.map +0 -1
  93. package/dist/assets/backup-DekVCDWv.js.map +0 -1
  94. package/dist/assets/buttons-BGxzOtrq.js.map +0 -1
  95. package/dist/assets/buttons-CsN2WJOf.js +0 -1
  96. package/dist/assets/engineErrors--9hfgKlK.js.map +0 -1
  97. package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
  98. package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
  99. package/dist/assets/groupMeta-goASqzOt.js.map +0 -1
  100. package/dist/assets/host-C2WRKj3g.js.map +0 -1
  101. package/dist/assets/identityProofs-Cksc_K7_.js.map +0 -1
  102. package/dist/assets/irohWeb-NfthOL98.js.map +0 -1
  103. package/dist/assets/linkPreview-DdMf-YAc.js.map +0 -1
  104. package/dist/assets/main-Dh7fePd8.js.map +0 -1
  105. package/dist/assets/ownDid-BErplN7N.js.map +0 -1
  106. package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
  107. package/dist/assets/registry-CU8PevhI.js.map +0 -1
  108. package/dist/assets/relay-CHWg5hpZ.js.map +0 -1
  109. package/dist/assets/resolve-B1upovPM.js.map +0 -1
  110. package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
  111. package/dist/assets/server-Dgxx_DaN.js.map +0 -1
  112. package/dist/assets/translate-BcbSWkuq.js.map +0 -1
  113. package/dist/assets/waitNotice-ylU3XwjO.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buttons-D4udKEvT.js","names":["goesOnIn"],"sources":["../../src/waits.ts","../../src/textSize.ts","../../src/buttons.ts"],"sourcesContent":["import type { GroupView, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { groupById, noMessage, nobodyJoinedChat, node, type ApiContext, type Method } 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. */\nexport const 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/** How long `purgeMessage` waits for the engine to take the message's row out: it does so in a few milliseconds. */\nconst PURGE_WAIT_MS = 5_000;\n\n/**\n * `message delete --purge`: once the message's row is gone (the engine takes it out on later turns, its files first),\n * the replies that quote it lose its line (a delete here leaves it in their rows, one for everyone to a sweep within\n * 10 s), then the store's journal is folded into a fresh snapshot now, not within the hour of the fold that comes by\n * itself: what the message said leaves rows.db, `db/journal.bin` and rows.db's WAL before the command answers. For a\n * secret pasted into a chat; every delete folding would rewrite the snapshot each time. `message`: its row, read\n * before the delete.\n */\nexport async function purgeMessage(ctx: ApiContext, message: StoredMessage): Promise<void> {\n const { linkId: chat, id: messageId } = message;\n const until = performance.now() + PURGE_WAIT_MS;\n let gone = !(await node(ctx).getMessage(chat, messageId));\n while (!gone && performance.now() < until) {\n await new Promise((resolve) => setTimeout(resolve, 20));\n gone = !(await node(ctx).getMessage(chat, messageId));\n }\n if (gone) await node(ctx).forgetQuotesOf(message);\n await ctx.runtime.store.compact({ scrub: true });\n if (!gone) throw new CliError(\"timeout\", `Timed out after ${PURGE_WAIT_MS / 1000} s: the message is deleted, but what it said may stay in the profile's store until its next fold (within the hour)`, { messageId, deleted: messageId });\n}\n\n/**\n * `message delete --purge` that the delete answers no to (`not_found`, `refused`): the store folds all the same, so\n * the error says so in its words and `details.purged`. A message no longer here (the contact deleted it for everyone,\n * or a delete here without `--purge` took it) and another member's group message (only its author deletes it, and\n * once they do it is gone here) answered no and folded nothing: what a deleted copy said stayed in `db/journal.bin`\n * and rows.db's WAL until the fold within the hour. A usage mistake (`bad_request`) folds nothing.\n */\nexport function foldsAnyway(method: Method): Method {\n return async (ctx, params, call) => {\n try { return await method(ctx, params, call); } catch (error) {\n if (params.purge !== true || !(error instanceof CliError) || (error.code !== \"not_found\" && error.code !== \"refused\")) throw error;\n await ctx.runtime.store.compact({ scrub: true });\n // Said first: a refusal may end in a command to paste (`... is a group, not a chat: ghostly message delete ...`).\n throw new CliError(error.code, `The store was folded anyway, so a deleted copy of it is gone from the profile's folder. ${error.message}`, { ...error.details, purged: true });\n }\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 => alone(groupIn(ctx, groupId));\n\n/** A group as the engine shows it, built alone: `getState()` builds a view of every chat, once per poll. */\nconst groupIn = (ctx: ApiContext, groupId: string): GroupView | undefined => groupById(ctx, groupId);\n\nconst alone = (group: GroupView | undefined): boolean => group?.profile === \"mesh\" && !group.members.some((m) => !m.me);\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 */\nexport const outOf = (group: GroupView | undefined): string | null =>\n group?.status && group.status !== \"active\" && group.status !== \"lost\" ? group.statusReason ?? \"You are not in this group\" : null;\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) return taken;\n const group = groupIn(ctx, groupId);\n if (alone(group)) return taken;\n const out = outOf(group);\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, shownValue } 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 ${shownValue(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 ${shownValue(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,IAAa,SAAS,KAAiB,OAAe,QAAQ,GAAG,IAAI,6CAA6C,mBAAmB,KAAK,MAAM,KAAK,GAAI,EAAE;;AAG3J,IAAM,SAAS,KAAiB,YAAqC,QAAQ,GAAG,IAAI;CA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E,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"}
@@ -0,0 +1 @@
1
+ export { r as buttonsOf } from "./buttons-D4udKEvT.js";
@@ -1,5 +1,5 @@
1
- import { t as CliError } from "./errors-DDLFO4Gf.js";
2
- import { T as ownSocket, h as lockPath } from "./profiles-B8xO8-oj.js";
1
+ import { t as CliError } from "./errors-JVJsO8Iu.js";
2
+ import { T as ownSocket, h as lockPath } from "./profiles-BH1bH9aE.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";
@@ -566,4 +566,4 @@ function connectDaemon(address, timeoutMs = 2e3, { greetingMs = GREETING_MS } =
566
566
  }
567
567
  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 };
568
568
 
569
- //# sourceMappingURL=client-DcQAfc3h.js.map
569
+ //# sourceMappingURL=client-DGx7E8b3.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-DcQAfc3h.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,IAA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AC3B,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
+ {"version":3,"file":"client-DGx7E8b3.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;GACZ,QAAQ,MAAM,SAAS,CAAC;EAC1B;EACA,MAAM,OAAO,KAAK,MAAM,KAAK;EAC7B,MAAM,OAAO,MAAM,UAAU,OAAO,QAAQ,MAAM,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,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"}
@@ -256,7 +256,8 @@ function txtValue(rdata) {
256
256
  return new TextDecoder("utf-8", { fatal: true }).decode(concatBytes(...parts));
257
257
  }
258
258
  /** False for loopback, private, link-local, shared (CGNAT), multicast, reserved
259
- * and unspecified addresses, including IPv4 embedded in IPv6. */
259
+ * and unspecified addresses, including IPv4 embedded in IPv6, and for 6to4, Teredo and documentation IPv6, as
260
+ * Desktop's link_preview::is_public and apps/ui/src/lib/localHost.ts refuse them. */
260
261
  function isPublicAddress(address) {
261
262
  if (address.length === 4) {
262
263
  const [a, b, c] = address;
@@ -273,8 +274,11 @@ function isPublicAddress(address) {
273
274
  if (address[0] === 254 && (address[1] & 192) === 192) return false;
274
275
  if (address[0] === 255) return false;
275
276
  if (address[0] === 1 && address.subarray(1, 8).every((x) => x === 0)) return false;
277
+ if (address[0] === 32 && address[1] === 2) return false;
278
+ if (address[0] === 32 && address[1] === 1 && address[2] === 0 && address[3] === 0) return false;
279
+ if (address[0] === 32 && address[1] === 1 && address[2] === 13 && address[3] === 184) return false;
276
280
  return (address[0] & 224) === 32;
277
281
  }
278
282
  export { domainWellKnownFile as a, nip05RootKey as c, recordsFromWellKnown as d, recordsName as f, domainTxtRecord as i, normalizeDomain as l, wellKnownUrl as m, decodeDnsResponse as n, encodeDnsQuery as o, txtValue as p, dnsProofName as r, isPublicAddress as s, DOMAIN_FILE_MAX_BYTES as t, recordsFromTxt as u };
279
283
 
280
- //# sourceMappingURL=domainProofs-BDNP1dIy.js.map
284
+ //# sourceMappingURL=domainProofs-b3Y1Gj9g.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"domainProofs-BDNP1dIy.js","names":[],"sources":["../../../core/src/domainProofs.ts"],"sourcesContent":["import { concatBytes, fromZ32, toZ32, utf8Decode, utf8Encode } from './bytes';\n\n/**\n * Domain identity proofs (draft WISP 304, docs/wisps/304-domain.md), the pure half.\n *\n * Under WISP 300 a proof authorizes a fresh Ed25519 *proof key* that only this\n * profile holds, through a statement the external identity vouches for. A\n * domain vouches by publishing: a DNS TXT record at `_ghostly.<domain>` or a\n * `/.well-known/ghostly.json` file names the proof key **and the statement id**\n * (SHA-256 of the statement), so the record commits to the exact binding —\n * subject, key, dates and nonce — not just to a key. Sharing with a contact is\n * then the contract's per-contact presentation, signed by the proof key.\n *\n * People who already run NIP-05 can use `/.well-known/nostr.json` instead: its\n * root name `_` must be the very Nostr key that signed the statement.\n *\n * The record names no participation key and no contact. Fetching, DNS over\n * HTTPS and caching live in `@ghostly/browser/proofs/domain`.\n */\n\nexport type DomainMethod = 'dns' | 'https' | 'nip05';\n/** What a record says: this Ghostly proof key, for this statement. */\nexport interface DomainRecord { key: string; proof: string }\n\nexport const DOMAIN_METHODS: readonly DomainMethod[] = ['dns', 'https', 'nip05'];\nexport const DNS_LABEL = '_ghostly';\nexport const WELL_KNOWN_PATH = '/.well-known/ghostly.json';\nexport const NIP05_PATH = '/.well-known/nostr.json?name=_';\n/** Everything read from a domain is bounded; these match the fetch limits. */\nexport const DOMAIN_FILE_MAX_BYTES = 16 * 1024;\nexport const DOMAIN_TXT_MAX_BYTES = 1024;\nexport const DOMAIN_MAX_RECORDS = 8;\n\nconst z32 = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\nconst hex64 = /^[a-f0-9]{64}$/;\n\n// ---------------------------------------------------------------------------\n// Domain names\n\n/** Names that never resolve publicly (RFC 6761, 6762, 7686, 8375, 9476) or that\n * only ever mean a private network. A proof for them could only point inward. */\nconst SPECIAL_USE = ['localhost', 'local', 'internal', 'lan', 'home', 'corp', 'intranet', 'private',\n 'test', 'example', 'invalid', 'onion', 'alt', 'arpa'];\n\n/**\n * Normalizes what a person typed (\"Example.COM.\", \"https://example.com/\") into\n * a lowercase ASCII host name, or throws with a message fit for the UI.\n * Internationalized names become punycode (xn--), the form DNS carries.\n */\nexport function normalizeDomain(input: string): string {\n if (typeof input !== 'string') throw new Error('Enter a domain name, like example.com');\n let value = input.trim();\n if (!value || value.length > 300) throw new Error('Enter a domain name, like example.com');\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n let url: URL;\n try { url = new URL(value); } catch { throw new Error('Enter a domain name, like example.com'); }\n if (url.protocol !== 'https:' || url.username || url.password || url.port || (url.pathname !== '/' && url.pathname !== '') || url.search || url.hash)\n throw new Error('Enter only the domain name, without a path or port');\n value = url.hostname;\n } else {\n if (/[/:@?#\\s\\\\]/.test(value)) throw new Error('Enter only the domain name, without a path or port');\n try { value = new URL(`https://${value}`).hostname; } catch { throw new Error('That is not a valid domain name'); }\n }\n value = value.toLowerCase().replace(/\\.$/, '');\n if (value.length > 253 - DNS_LABEL.length - 1) throw new Error('That domain name is too long');\n const labels = value.split('.');\n if (labels.length < 2) throw new Error('Use a full domain name, like example.com');\n for (const label of labels) {\n if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) throw new Error('That is not a valid domain name');\n }\n const tld = labels[labels.length - 1];\n if (/^[0-9]+$/.test(tld) || /^\\[/.test(value)) throw new Error('Use a domain name, not an IP address');\n if (SPECIAL_USE.includes(tld) || (labels.length >= 2 && labels.slice(-2).join('.') === 'home.arpa'))\n throw new Error('That name only works on private networks');\n return value;\n}\n\nexport const dnsProofName = (domain: string) => `${DNS_LABEL}.${normalizeDomain(domain)}`;\nexport const wellKnownUrl = (domain: string, method: 'https' | 'nip05' = 'https') =>\n `https://${normalizeDomain(domain)}${method === 'nip05' ? NIP05_PATH : WELL_KNOWN_PATH}`;\n\n// ---------------------------------------------------------------------------\n// Records\n\nexport function validDomainRecord(r: DomainRecord): boolean {\n if (!r || typeof r.key !== 'string' || typeof r.proof !== 'string' || !z32.test(r.key) || !hex64.test(r.proof)) return false;\n try { return toZ32(fromZ32(r.key)) === r.key; } catch { return false; }\n}\n\n/** The TXT record value, in the `tag=value; …` style people know from DKIM. */\nexport function domainTxtRecord(r: DomainRecord): string {\n if (!validDomainRecord(r)) throw new Error('Invalid domain record');\n return `v=ghostly1; key=${r.key}; proof=${r.proof}`;\n}\n\n/** Parses one TXT string. Undefined for anything that is not ours or not exactly\n * well-formed; unknown extra tags are ignored for forward compatibility. */\nexport function parseDomainTxt(value: string): DomainRecord | undefined {\n if (typeof value !== 'string' || utf8Encode(value).length > DOMAIN_TXT_MAX_BYTES) return;\n const tags = new Map<string, string>();\n const parts = value.split(';').map(p => p.trim()).filter(Boolean);\n for (const part of parts) {\n const eq = part.indexOf('=');\n if (eq < 1) return;\n const name = part.slice(0, eq).trim().toLowerCase();\n if (tags.has(name)) return;\n tags.set(name, part.slice(eq + 1).trim());\n }\n if (!parts[0]?.toLowerCase().startsWith('v=') || tags.get('v') !== 'ghostly1') return;\n const r = { key: tags.get('key'), proof: tags.get('proof') } as DomainRecord;\n return validDomainRecord(r) ? r : undefined;\n}\n\nconst addRecord = (list: DomainRecord[], r: DomainRecord) => {\n if (!list.some(x => x.key === r.key && x.proof === r.proof)) list.push(r);\n};\n\n/** All records among the first 32 TXT strings of `_ghostly.<domain>`; other strings are skipped. A TXT set has\n * no order, so every record is kept: the one a proof needs may come in any position. */\nexport function recordsFromTxt(values: string[]): DomainRecord[] {\n const out: DomainRecord[] = [];\n for (const value of values.slice(0, 32)) { const r = parseDomainTxt(value); if (r) addRecord(out, r); }\n return out;\n}\n\n/** The body of `/.well-known/ghostly.json`. */\nexport function domainWellKnownFile(records: DomainRecord[]): string {\n if (!records.length || records.length > DOMAIN_MAX_RECORDS || !records.every(validDomainRecord)) throw new Error('Invalid domain records');\n return JSON.stringify({ ghostly: 1, proofs: records.map(r => ({ key: r.key, proof: r.proof })) }, null, 2) + '\\n';\n}\n\nfunction parseJson(text: string): unknown {\n if (typeof text !== 'string' || utf8Encode(text).length > DOMAIN_FILE_MAX_BYTES) throw new Error('File too large');\n return JSON.parse(text);\n}\n\n/** Records from the first 32 entries of `ghostly.json`. Throws on a malformed file; [] when it names none. */\nexport function recordsFromWellKnown(text: string): DomainRecord[] {\n const body = parseJson(text) as { ghostly?: unknown; proofs?: unknown };\n if (!body || typeof body !== 'object' || Array.isArray(body) || body.ghostly !== 1 || !Array.isArray(body.proofs))\n throw new Error('Not a Ghostly domain file');\n const out: DomainRecord[] = [];\n for (const entry of body.proofs.slice(0, 32) as { key?: unknown; proof?: unknown }[]) {\n if (!entry || typeof entry !== 'object') continue;\n const r = { key: entry.key, proof: entry.proof } as DomainRecord;\n if (validDomainRecord(r)) addRecord(out, r);\n }\n return out;\n}\n\n/** NIP-05: only the root name `_` speaks for the domain itself. Undefined when absent. */\nexport function nip05RootKey(text: string): string | undefined {\n const body = parseJson(text) as { names?: unknown };\n if (!body || typeof body !== 'object' || !body.names || typeof body.names !== 'object' || Array.isArray(body.names))\n throw new Error('Not a NIP-05 file');\n const root = (body.names as Record<string, unknown>)['_'];\n return typeof root === 'string' && hex64.test(root) ? root : undefined;\n}\n\nexport const recordsName = (records: DomainRecord[], r: DomainRecord) => records.some(x => x.key === r.key && x.proof === r.proof);\n\n// ---------------------------------------------------------------------------\n// DNS over HTTPS (RFC 8484) wire messages\n\nexport const DNS_TYPE = { A: 1, CNAME: 5, TXT: 16, AAAA: 28 } as const;\nexport type DnsType = keyof typeof DNS_TYPE;\nexport interface DnsAnswer { name: string; type: number; ttl: number; data: Uint8Array }\nexport interface DnsResponse {\n /** 0 = NOERROR, 3 = NXDOMAIN; anything else is a failed lookup. */\n rcode: number;\n /** The resolver reports it validated the answer with DNSSEC. */\n authenticated: boolean;\n answers: DnsAnswer[];\n}\n\n/**\n * EDNS0 OPT record (RFC 6891) with one Client Subnet option of source prefix 0 (RFC 7871 §7.1.2): a resolver must\n * not add this device's subnet to its queries to the name's servers, as Google Public DNS otherwise does.\n */\nconst NO_CLIENT_SUBNET = Uint8Array.of(0, 0, 41, 1232 >> 8, 1232 & 0xff, 0, 0, 0, 0, 0, 8, 0, 8, 0, 4, 0, 1, 0, 0);\n\n/** A recursive query for one name and type. ID 0, as RFC 8484 recommends for caching;\n * the AD bit asks the resolver to report DNSSEC validation (RFC 6840 §5.7). */\nexport function encodeDnsQuery(name: string, type: DnsType): Uint8Array {\n const labels = name.replace(/\\.$/, '').split('.');\n const parts: Uint8Array[] = [Uint8Array.of(0, 0, 0x01, 0x20, 0, 1, 0, 0, 0, 0, 0, 1)];\n for (const label of labels) {\n const bytes = utf8Encode(label);\n if (!bytes.length || bytes.length > 63) throw new Error('Invalid DNS name');\n parts.push(Uint8Array.of(bytes.length), bytes);\n }\n const code = DNS_TYPE[type];\n parts.push(Uint8Array.of(0, code >> 8, code & 0xff, 0, 1), NO_CLIENT_SUBNET);\n return concatBytes(...parts);\n}\n\nfunction readName(data: Uint8Array, start: number): { name: string; next: number } {\n const labels: string[] = [];\n let pos = start, next = -1, jumps = 0, length = 0;\n for (;;) {\n if (pos >= data.length) throw new Error('DNS name out of bounds');\n const len = data[pos];\n if ((len & 0xc0) === 0xc0) {\n if (pos + 1 >= data.length) throw new Error('DNS pointer out of bounds');\n if (next < 0) next = pos + 2;\n pos = ((len & 0x3f) << 8) | data[pos + 1];\n if (++jumps > 32) throw new Error('DNS name loops');\n continue;\n }\n if (len & 0xc0) throw new Error('Unsupported DNS label');\n pos += 1;\n if (len === 0) break;\n if (pos + len > data.length) throw new Error('DNS label out of bounds');\n length += len + 1;\n if (length > 255) throw new Error('DNS name too long');\n labels.push(utf8Decode(data.subarray(pos, pos + len)).toLowerCase());\n pos += len;\n }\n return { name: labels.join('.'), next: next < 0 ? pos : next };\n}\n\n/**\n * Decodes a resolver's answer to `encodeDnsQuery(name, type)`. Refuses a reply\n * to another question or a truncated one, and keeps only records of the asked\n * type owned by the name or by the CNAME chain the answer itself follows.\n */\nexport function decodeDnsResponse(data: Uint8Array, name: string, type: DnsType): DnsResponse {\n if (data.length < 12) throw new Error('DNS response too short');\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const flags = view.getUint16(2);\n if (!(flags & 0x8000) || (flags & 0x7800) || (flags & 0x0200)) throw new Error('Unusable DNS response');\n const questions = view.getUint16(4), count = view.getUint16(6);\n const want = name.replace(/\\.$/, '').toLowerCase(), code = DNS_TYPE[type];\n if (questions !== 1) throw new Error('DNS response is for another question');\n const q = readName(data, 12);\n if (q.name !== want || q.next + 4 > data.length || view.getUint16(q.next) !== code) throw new Error('DNS response is for another question');\n let pos = q.next + 4;\n const all: DnsAnswer[] = [];\n for (let i = 0; i < count && i < 64; i++) {\n const owner = readName(data, pos);\n pos = owner.next;\n if (pos + 10 > data.length) throw new Error('DNS record out of bounds');\n const rtype = view.getUint16(pos), ttl = view.getUint32(pos + 4), len = view.getUint16(pos + 8);\n pos += 10;\n if (pos + len > data.length) throw new Error('DNS record out of bounds');\n const rdata = rtype === DNS_TYPE.CNAME ? utf8Encode(readName(data, pos).name) : data.slice(pos, pos + len);\n all.push({ name: owner.name, type: rtype, ttl, data: rdata });\n pos += len;\n }\n const owners = new Set([want]);\n for (let hop = 0; hop < 8; hop++) {\n const cname = all.find(a => a.type === DNS_TYPE.CNAME && owners.has(a.name) && !owners.has(utf8Decode(a.data)));\n if (!cname) break;\n owners.add(utf8Decode(cname.data));\n }\n return { rcode: flags & 0x000f, authenticated: !!(flags & 0x0020), answers: all.filter(a => a.type === code && owners.has(a.name)) };\n}\n\n/** The TXT character-strings of one record, joined as RFC 7208 §3.3 does. */\nexport function txtValue(rdata: Uint8Array): string {\n const parts: Uint8Array[] = [];\n for (let p = 0; p < rdata.length;) {\n const len = rdata[p];\n if (p + 1 + len > rdata.length) throw new Error('DNS text out of bounds');\n parts.push(rdata.subarray(p + 1, p + 1 + len));\n p += 1 + len;\n }\n return new TextDecoder('utf-8', { fatal: true }).decode(concatBytes(...parts));\n}\n\n// ---------------------------------------------------------------------------\n// Addresses: a proof may only make a contact's app fetch from the public Internet\n\n/** False for loopback, private, link-local, shared (CGNAT), multicast, reserved\n * and unspecified addresses, including IPv4 embedded in IPv6. */\nexport function isPublicAddress(address: Uint8Array): boolean {\n if (address.length === 4) {\n const [a, b, c] = address;\n return !(a === 0 || a === 10 || a === 127 || a >= 224 ||\n (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) || (a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19)));\n }\n if (address.length !== 16) return false;\n const zeroTo = (n: number) => address.subarray(0, n).every(x => x === 0);\n if (zeroTo(15) && (address[15] === 0 || address[15] === 1)) return false; // :: and ::1\n if (zeroTo(10) && address[10] === 0xff && address[11] === 0xff) return isPublicAddress(address.subarray(12)); // ::ffff:a.b.c.d\n if (address[0] === 0x00 && address[1] === 0x64 && address[2] === 0xff && address[3] === 0x9b && address.subarray(4, 12).every(x => x === 0))\n return isPublicAddress(address.subarray(12)); // 64:ff9b::/96 NAT64\n if (zeroTo(12)) return false; // deprecated IPv4-compatible\n if ((address[0] & 0xfe) === 0xfc) return false; // fc00::/7 unique local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0x80) return false; // fe80::/10 link-local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0xc0) return false; // fec0::/10 site-local\n if (address[0] === 0xff) return false; // multicast\n if (address[0] === 0x01 && address.subarray(1, 8).every(x => x === 0)) return false; // 100::/64 discard\n return (address[0] & 0xe0) === 0x20; // only 2000::/3 is global unicast\n}\n"],"mappings":";;AAyBA,IAAa,YAAY;AACzB,IAAa,kBAAkB;AAC/B,IAAa,aAAa;;AAE1B,IAAa,wBAAwB;AAIrC,IAAM,MAAM;AACZ,IAAM,QAAQ;;;AAOd,IAAM,cAAc;CAAC;CAAa;CAAS;CAAY;CAAO;CAAQ;CAAQ;CAAY;CACxF;CAAQ;CAAW;CAAW;CAAS;CAAO;AAAM;;;;;;AAOtD,SAAgB,gBAAgB,OAAuB;CACrD,IAAI,OAAO,UAAU,UAAU,MAAM,IAAI,MAAM,uCAAuC;CACtF,IAAI,QAAQ,MAAM,KAAK;CACvB,IAAI,CAAC,SAAS,MAAM,SAAS,KAAK,MAAM,IAAI,MAAM,uCAAuC;CACzF,IAAI,2BAA2B,KAAK,KAAK,GAAG;EAC1C,IAAI;EACJ,IAAI;GAAE,MAAM,IAAI,IAAI,KAAK;EAAG,QAAQ;GAAE,MAAM,IAAI,MAAM,uCAAuC;EAAG;EAChG,IAAI,IAAI,aAAa,YAAY,IAAI,YAAY,IAAI,YAAY,IAAI,QAAS,IAAI,aAAa,OAAO,IAAI,aAAa,MAAO,IAAI,UAAU,IAAI,MAC9I,MAAM,IAAI,MAAM,oDAAoD;EACtE,QAAQ,IAAI;CACd,OAAO;EACL,IAAI,cAAc,KAAK,KAAK,GAAG,MAAM,IAAI,MAAM,oDAAoD;EACnG,IAAI;GAAE,QAAQ,IAAI,IAAI,WAAW,OAAO,CAAC,CAAC;EAAU,QAAQ;GAAE,MAAM,IAAI,MAAM,iCAAiC;EAAG;CACpH;CACA,QAAQ,MAAM,YAAY,CAAC,CAAC,QAAQ,OAAO,EAAE;CAC7C,IAAI,MAAM,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1Gj9g.js","names":[],"sources":["../../../core/src/domainProofs.ts"],"sourcesContent":["import { concatBytes, fromZ32, toZ32, utf8Decode, utf8Encode } from './bytes';\n\n/**\n * Domain identity proofs (draft WISP 304, docs/wisps/304-domain.md), the pure half.\n *\n * Under WISP 300 a proof authorizes a fresh Ed25519 *proof key* that only this\n * profile holds, through a statement the external identity vouches for. A\n * domain vouches by publishing: a DNS TXT record at `_ghostly.<domain>` or a\n * `/.well-known/ghostly.json` file names the proof key **and the statement id**\n * (SHA-256 of the statement), so the record commits to the exact binding —\n * subject, key, dates and nonce — not just to a key. Sharing with a contact is\n * then the contract's per-contact presentation, signed by the proof key.\n *\n * People who already run NIP-05 can use `/.well-known/nostr.json` instead: its\n * root name `_` must be the very Nostr key that signed the statement.\n *\n * The record names no participation key and no contact. Fetching, DNS over\n * HTTPS and caching live in `@ghostly/browser/proofs/domain`.\n */\n\nexport type DomainMethod = 'dns' | 'https' | 'nip05';\n/** What a record says: this Ghostly proof key, for this statement. */\nexport interface DomainRecord { key: string; proof: string }\n\nexport const DOMAIN_METHODS: readonly DomainMethod[] = ['dns', 'https', 'nip05'];\nexport const DNS_LABEL = '_ghostly';\nexport const WELL_KNOWN_PATH = '/.well-known/ghostly.json';\nexport const NIP05_PATH = '/.well-known/nostr.json?name=_';\n/** Everything read from a domain is bounded; these match the fetch limits. */\nexport const DOMAIN_FILE_MAX_BYTES = 16 * 1024;\nexport const DOMAIN_TXT_MAX_BYTES = 1024;\nexport const DOMAIN_MAX_RECORDS = 8;\n\nconst z32 = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\nconst hex64 = /^[a-f0-9]{64}$/;\n\n// ---------------------------------------------------------------------------\n// Domain names\n\n/** Names that never resolve publicly (RFC 6761, 6762, 7686, 8375, 9476) or that\n * only ever mean a private network. A proof for them could only point inward. */\nconst SPECIAL_USE = ['localhost', 'local', 'internal', 'lan', 'home', 'corp', 'intranet', 'private',\n 'test', 'example', 'invalid', 'onion', 'alt', 'arpa'];\n\n/**\n * Normalizes what a person typed (\"Example.COM.\", \"https://example.com/\") into\n * a lowercase ASCII host name, or throws with a message fit for the UI.\n * Internationalized names become punycode (xn--), the form DNS carries.\n */\nexport function normalizeDomain(input: string): string {\n if (typeof input !== 'string') throw new Error('Enter a domain name, like example.com');\n let value = input.trim();\n if (!value || value.length > 300) throw new Error('Enter a domain name, like example.com');\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n let url: URL;\n try { url = new URL(value); } catch { throw new Error('Enter a domain name, like example.com'); }\n if (url.protocol !== 'https:' || url.username || url.password || url.port || (url.pathname !== '/' && url.pathname !== '') || url.search || url.hash)\n throw new Error('Enter only the domain name, without a path or port');\n value = url.hostname;\n } else {\n if (/[/:@?#\\s\\\\]/.test(value)) throw new Error('Enter only the domain name, without a path or port');\n try { value = new URL(`https://${value}`).hostname; } catch { throw new Error('That is not a valid domain name'); }\n }\n value = value.toLowerCase().replace(/\\.$/, '');\n if (value.length > 253 - DNS_LABEL.length - 1) throw new Error('That domain name is too long');\n const labels = value.split('.');\n if (labels.length < 2) throw new Error('Use a full domain name, like example.com');\n for (const label of labels) {\n if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) throw new Error('That is not a valid domain name');\n }\n const tld = labels[labels.length - 1];\n if (/^[0-9]+$/.test(tld) || /^\\[/.test(value)) throw new Error('Use a domain name, not an IP address');\n if (SPECIAL_USE.includes(tld) || (labels.length >= 2 && labels.slice(-2).join('.') === 'home.arpa'))\n throw new Error('That name only works on private networks');\n return value;\n}\n\nexport const dnsProofName = (domain: string) => `${DNS_LABEL}.${normalizeDomain(domain)}`;\nexport const wellKnownUrl = (domain: string, method: 'https' | 'nip05' = 'https') =>\n `https://${normalizeDomain(domain)}${method === 'nip05' ? NIP05_PATH : WELL_KNOWN_PATH}`;\n\n// ---------------------------------------------------------------------------\n// Records\n\nexport function validDomainRecord(r: DomainRecord): boolean {\n if (!r || typeof r.key !== 'string' || typeof r.proof !== 'string' || !z32.test(r.key) || !hex64.test(r.proof)) return false;\n try { return toZ32(fromZ32(r.key)) === r.key; } catch { return false; }\n}\n\n/** The TXT record value, in the `tag=value; …` style people know from DKIM. */\nexport function domainTxtRecord(r: DomainRecord): string {\n if (!validDomainRecord(r)) throw new Error('Invalid domain record');\n return `v=ghostly1; key=${r.key}; proof=${r.proof}`;\n}\n\n/** Parses one TXT string. Undefined for anything that is not ours or not exactly\n * well-formed; unknown extra tags are ignored for forward compatibility. */\nexport function parseDomainTxt(value: string): DomainRecord | undefined {\n if (typeof value !== 'string' || utf8Encode(value).length > DOMAIN_TXT_MAX_BYTES) return;\n const tags = new Map<string, string>();\n const parts = value.split(';').map(p => p.trim()).filter(Boolean);\n for (const part of parts) {\n const eq = part.indexOf('=');\n if (eq < 1) return;\n const name = part.slice(0, eq).trim().toLowerCase();\n if (tags.has(name)) return;\n tags.set(name, part.slice(eq + 1).trim());\n }\n if (!parts[0]?.toLowerCase().startsWith('v=') || tags.get('v') !== 'ghostly1') return;\n const r = { key: tags.get('key'), proof: tags.get('proof') } as DomainRecord;\n return validDomainRecord(r) ? r : undefined;\n}\n\nconst addRecord = (list: DomainRecord[], r: DomainRecord) => {\n if (!list.some(x => x.key === r.key && x.proof === r.proof)) list.push(r);\n};\n\n/** All records among the first 32 TXT strings of `_ghostly.<domain>`; other strings are skipped. A TXT set has\n * no order, so every record is kept: the one a proof needs may come in any position. */\nexport function recordsFromTxt(values: string[]): DomainRecord[] {\n const out: DomainRecord[] = [];\n for (const value of values.slice(0, 32)) { const r = parseDomainTxt(value); if (r) addRecord(out, r); }\n return out;\n}\n\n/** The body of `/.well-known/ghostly.json`. */\nexport function domainWellKnownFile(records: DomainRecord[]): string {\n if (!records.length || records.length > DOMAIN_MAX_RECORDS || !records.every(validDomainRecord)) throw new Error('Invalid domain records');\n return JSON.stringify({ ghostly: 1, proofs: records.map(r => ({ key: r.key, proof: r.proof })) }, null, 2) + '\\n';\n}\n\nfunction parseJson(text: string): unknown {\n if (typeof text !== 'string' || utf8Encode(text).length > DOMAIN_FILE_MAX_BYTES) throw new Error('File too large');\n return JSON.parse(text);\n}\n\n/** Records from the first 32 entries of `ghostly.json`. Throws on a malformed file; [] when it names none. */\nexport function recordsFromWellKnown(text: string): DomainRecord[] {\n const body = parseJson(text) as { ghostly?: unknown; proofs?: unknown };\n if (!body || typeof body !== 'object' || Array.isArray(body) || body.ghostly !== 1 || !Array.isArray(body.proofs))\n throw new Error('Not a Ghostly domain file');\n const out: DomainRecord[] = [];\n for (const entry of body.proofs.slice(0, 32) as { key?: unknown; proof?: unknown }[]) {\n if (!entry || typeof entry !== 'object') continue;\n const r = { key: entry.key, proof: entry.proof } as DomainRecord;\n if (validDomainRecord(r)) addRecord(out, r);\n }\n return out;\n}\n\n/** NIP-05: only the root name `_` speaks for the domain itself. Undefined when absent. */\nexport function nip05RootKey(text: string): string | undefined {\n const body = parseJson(text) as { names?: unknown };\n if (!body || typeof body !== 'object' || !body.names || typeof body.names !== 'object' || Array.isArray(body.names))\n throw new Error('Not a NIP-05 file');\n const root = (body.names as Record<string, unknown>)['_'];\n return typeof root === 'string' && hex64.test(root) ? root : undefined;\n}\n\nexport const recordsName = (records: DomainRecord[], r: DomainRecord) => records.some(x => x.key === r.key && x.proof === r.proof);\n\n// ---------------------------------------------------------------------------\n// DNS over HTTPS (RFC 8484) wire messages\n\nexport const DNS_TYPE = { A: 1, CNAME: 5, TXT: 16, AAAA: 28 } as const;\nexport type DnsType = keyof typeof DNS_TYPE;\nexport interface DnsAnswer { name: string; type: number; ttl: number; data: Uint8Array }\nexport interface DnsResponse {\n /** 0 = NOERROR, 3 = NXDOMAIN; anything else is a failed lookup. */\n rcode: number;\n /** The resolver reports it validated the answer with DNSSEC. */\n authenticated: boolean;\n answers: DnsAnswer[];\n}\n\n/**\n * EDNS0 OPT record (RFC 6891) with one Client Subnet option of source prefix 0 (RFC 7871 §7.1.2): a resolver must\n * not add this device's subnet to its queries to the name's servers, as Google Public DNS otherwise does.\n */\nconst NO_CLIENT_SUBNET = Uint8Array.of(0, 0, 41, 1232 >> 8, 1232 & 0xff, 0, 0, 0, 0, 0, 8, 0, 8, 0, 4, 0, 1, 0, 0);\n\n/** A recursive query for one name and type. ID 0, as RFC 8484 recommends for caching;\n * the AD bit asks the resolver to report DNSSEC validation (RFC 6840 §5.7). */\nexport function encodeDnsQuery(name: string, type: DnsType): Uint8Array {\n const labels = name.replace(/\\.$/, '').split('.');\n const parts: Uint8Array[] = [Uint8Array.of(0, 0, 0x01, 0x20, 0, 1, 0, 0, 0, 0, 0, 1)];\n for (const label of labels) {\n const bytes = utf8Encode(label);\n if (!bytes.length || bytes.length > 63) throw new Error('Invalid DNS name');\n parts.push(Uint8Array.of(bytes.length), bytes);\n }\n const code = DNS_TYPE[type];\n parts.push(Uint8Array.of(0, code >> 8, code & 0xff, 0, 1), NO_CLIENT_SUBNET);\n return concatBytes(...parts);\n}\n\nfunction readName(data: Uint8Array, start: number): { name: string; next: number } {\n const labels: string[] = [];\n let pos = start, next = -1, jumps = 0, length = 0;\n for (;;) {\n if (pos >= data.length) throw new Error('DNS name out of bounds');\n const len = data[pos];\n if ((len & 0xc0) === 0xc0) {\n if (pos + 1 >= data.length) throw new Error('DNS pointer out of bounds');\n if (next < 0) next = pos + 2;\n pos = ((len & 0x3f) << 8) | data[pos + 1];\n if (++jumps > 32) throw new Error('DNS name loops');\n continue;\n }\n if (len & 0xc0) throw new Error('Unsupported DNS label');\n pos += 1;\n if (len === 0) break;\n if (pos + len > data.length) throw new Error('DNS label out of bounds');\n length += len + 1;\n if (length > 255) throw new Error('DNS name too long');\n labels.push(utf8Decode(data.subarray(pos, pos + len)).toLowerCase());\n pos += len;\n }\n return { name: labels.join('.'), next: next < 0 ? pos : next };\n}\n\n/**\n * Decodes a resolver's answer to `encodeDnsQuery(name, type)`. Refuses a reply\n * to another question or a truncated one, and keeps only records of the asked\n * type owned by the name or by the CNAME chain the answer itself follows.\n */\nexport function decodeDnsResponse(data: Uint8Array, name: string, type: DnsType): DnsResponse {\n if (data.length < 12) throw new Error('DNS response too short');\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const flags = view.getUint16(2);\n if (!(flags & 0x8000) || (flags & 0x7800) || (flags & 0x0200)) throw new Error('Unusable DNS response');\n const questions = view.getUint16(4), count = view.getUint16(6);\n const want = name.replace(/\\.$/, '').toLowerCase(), code = DNS_TYPE[type];\n if (questions !== 1) throw new Error('DNS response is for another question');\n const q = readName(data, 12);\n if (q.name !== want || q.next + 4 > data.length || view.getUint16(q.next) !== code) throw new Error('DNS response is for another question');\n let pos = q.next + 4;\n const all: DnsAnswer[] = [];\n for (let i = 0; i < count && i < 64; i++) {\n const owner = readName(data, pos);\n pos = owner.next;\n if (pos + 10 > data.length) throw new Error('DNS record out of bounds');\n const rtype = view.getUint16(pos), ttl = view.getUint32(pos + 4), len = view.getUint16(pos + 8);\n pos += 10;\n if (pos + len > data.length) throw new Error('DNS record out of bounds');\n const rdata = rtype === DNS_TYPE.CNAME ? utf8Encode(readName(data, pos).name) : data.slice(pos, pos + len);\n all.push({ name: owner.name, type: rtype, ttl, data: rdata });\n pos += len;\n }\n const owners = new Set([want]);\n for (let hop = 0; hop < 8; hop++) {\n const cname = all.find(a => a.type === DNS_TYPE.CNAME && owners.has(a.name) && !owners.has(utf8Decode(a.data)));\n if (!cname) break;\n owners.add(utf8Decode(cname.data));\n }\n return { rcode: flags & 0x000f, authenticated: !!(flags & 0x0020), answers: all.filter(a => a.type === code && owners.has(a.name)) };\n}\n\n/** The TXT character-strings of one record, joined as RFC 7208 §3.3 does. */\nexport function txtValue(rdata: Uint8Array): string {\n const parts: Uint8Array[] = [];\n for (let p = 0; p < rdata.length;) {\n const len = rdata[p];\n if (p + 1 + len > rdata.length) throw new Error('DNS text out of bounds');\n parts.push(rdata.subarray(p + 1, p + 1 + len));\n p += 1 + len;\n }\n return new TextDecoder('utf-8', { fatal: true }).decode(concatBytes(...parts));\n}\n\n// ---------------------------------------------------------------------------\n// Addresses: a proof may only make a contact's app fetch from the public Internet\n\n/** False for loopback, private, link-local, shared (CGNAT), multicast, reserved\n * and unspecified addresses, including IPv4 embedded in IPv6, and for 6to4, Teredo and documentation IPv6, as\n * Desktop's link_preview::is_public and apps/ui/src/lib/localHost.ts refuse them. */\nexport function isPublicAddress(address: Uint8Array): boolean {\n if (address.length === 4) {\n const [a, b, c] = address;\n return !(a === 0 || a === 10 || a === 127 || a >= 224 ||\n (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) || (a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19)));\n }\n if (address.length !== 16) return false;\n const zeroTo = (n: number) => address.subarray(0, n).every(x => x === 0);\n if (zeroTo(15) && (address[15] === 0 || address[15] === 1)) return false; // :: and ::1\n if (zeroTo(10) && address[10] === 0xff && address[11] === 0xff) return isPublicAddress(address.subarray(12)); // ::ffff:a.b.c.d\n if (address[0] === 0x00 && address[1] === 0x64 && address[2] === 0xff && address[3] === 0x9b && address.subarray(4, 12).every(x => x === 0))\n return isPublicAddress(address.subarray(12)); // 64:ff9b::/96 NAT64\n if (zeroTo(12)) return false; // deprecated IPv4-compatible\n if ((address[0] & 0xfe) === 0xfc) return false; // fc00::/7 unique local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0x80) return false; // fe80::/10 link-local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0xc0) return false; // fec0::/10 site-local\n if (address[0] === 0xff) return false; // multicast\n if (address[0] === 0x01 && address.subarray(1, 8).every(x => x === 0)) return false; // 100::/64 discard\n if (address[0] === 0x20 && address[1] === 0x02) return false; // 2002::/16 6to4: carries an IPv4 address a gateway may reach\n if (address[0] === 0x20 && address[1] === 0x01 && address[2] === 0x00 && address[3] === 0x00) return false; // 2001::/32 Teredo, the same\n if (address[0] === 0x20 && address[1] === 0x01 && address[2] === 0x0d && address[3] === 0xb8) return false; // 2001:db8::/32 documentation\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AAQ,OAAO,KAAM,OAAO;CACrG,QAAQ,QAAQ,KAAK,SAAU;AACjC"}
@@ -31,6 +31,7 @@ var ENGINE_ERRORS = {
31
31
  ecashBeingReceived: "This ecash is already being received",
32
32
  ecashFeeTakesAll: "The mint keeps all {amount} sats of this ecash as its fee to take it in: nothing was redeemed, and its sender can still take it back",
33
33
  ecashOtherUnit: "This ecash is in {unit}: only sat ecash can be redeemed here",
34
+ ecashUnnamedUnit: "This ecash is in another unit: only sat ecash can be redeemed here",
34
35
  reviewedEcashSpent: "The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.",
35
36
  reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.",
36
37
  mintFailedQuote: "{host} could not take this payment right now, and no sats left your wallet: try again later. The mint said: {reason}",
@@ -106,12 +107,19 @@ function engineText(code, values = {}) {
106
107
  return ENGINE_ERRORS[code].replace(/\{(\w+)\}/g, (_, name) => name in values ? String(values[name]) : `{${name}}`);
107
108
  }
108
109
  var engineError = (code, values) => new EngineError(code, values);
110
+ /** A unit as the app names it: a unit's shape (`frames.ts` `isUnit`, in any case), never a token sender's other text. */
111
+ var NAMED_UNIT = "[A-Za-z0-9]{1,12}";
112
+ /**
113
+ * Why ecash of `unit` is not redeemed here. The unit is named only when it looks like one: a token's unit is whatever
114
+ * its sender wrote, and the line is the app's own (a contact's payment's refusal row, the CLI's answer).
115
+ */
116
+ var ecashUnitError = (unit) => new RegExp(`^${NAMED_UNIT}$`).test(unit) ? engineError("ecashOtherUnit", { unit }) : engineError("ecashUnnamedUnit");
109
117
  /** What each kind of value looks like in a text: never a space in a host, a network by its name, an amount as digits. */
110
118
  var VALUE = {
111
119
  host: "(\\S+)",
112
120
  domain: "(\\S+)",
113
121
  chain: "(\\S+)",
114
- unit: "(\\S+)",
122
+ unit: `(${NAMED_UNIT})`,
115
123
  network: "(Mainnet|Testnet)",
116
124
  amount: "(\\d[\\d.,\\u00a0\\u202f' ]*?)",
117
125
  fee: "(\\d[\\d.,\\u00a0\\u202f' ]*?)",
@@ -145,6 +153,6 @@ function parseEngineError(text) {
145
153
  }
146
154
  return null;
147
155
  }
148
- export { parseEngineError as i, engineError as n, engineText as r, EngineError as t };
156
+ export { parseEngineError as a, engineText as i, ecashUnitError as n, engineError as r, EngineError as t };
149
157
 
150
- //# sourceMappingURL=engineErrors--9hfgKlK.js.map
158
+ //# sourceMappingURL=engineErrors-wWlLy54D.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineErrors-wWlLy54D.js","names":[],"sources":["../../../core/src/engineErrors.ts"],"sourcesContent":["/**\n * The engine's known errors: a stable code each, and its English text with the values in it. The engine throws\n * `engineError(code, values)`; the text is the one it always wrote, so the CLI and every log keep printing the same.\n * The app's pages get only the text (it crosses the engine's RPC and is kept on payments and operations as a string),\n * and `parseEngineError` finds the code and the values back in it, to say it in the app's language. A text that is\n * none of these (a mint's own words, a provider's) stays as it is.\n *\n * `{name}` in a template is a value: a host or domain (no spaces), a network (\"Mainnet\" or \"Testnet\"), a chain's name,\n * an ecash unit (\"usd\"), an amount (digits, with the separators of whatever locale wrote it), or a server's own `{reason}`\n * (one line, last in its text).\n */\nexport const ENGINE_ERRORS = {\n // Reaching a mint, a server, the network.\n mintUnreachable: \"Could not reach {host}. Check the address: it should be a Cashu mint.\",\n lnurlUnreachable: \"Could not reach {host}. It may be down, or not allow web apps to read it (CORS).\",\n hostUnreachable: \"Could not reach {host}\",\n networkUnreachable: \"Could not reach the network\",\n hostTimedOut: \"{host} did not answer in time\",\n networkTimedOut: \"The network did not answer in time\",\n // Cashu mints.\n testMintOnMainnet: \"This is a test mint, and its sats are worth nothing: add it to a Testnet Cashu wallet\",\n realMintOnTestnet: \"This mint holds real sats: add it to a Mainnet Cashu wallet\",\n mintHoldsSats: \"Move your sats out of this mint before removing it\",\n lastMint: \"This is the last mint of your {network} Cashu wallet: remove the wallet to remove it\",\n invalidMintUrl: \"That is not a valid mint URL\",\n mintNotHttps: \"Mints must use https\",\n notEnoughSats: \"Not enough sats in your wallet\",\n notEnoughForFee: \"Not enough sats in your wallet: {amount} sats leave room for the fee\",\n mintsNoAnyAmount: \"None of your mints can pay an invoice with no amount\",\n noSharedMint: \"You share no mint with this contact\",\n ecashAlreadySpent: \"This ecash was already spent somewhere else\",\n ecashBeingReceived: \"This ecash is already being received\",\n ecashFeeTakesAll: \"The mint keeps all {amount} sats of this ecash as its fee to take it in: nothing was redeemed, and its sender can still take it back\",\n ecashOtherUnit: \"This ecash is in {unit}: only sat ecash can be redeemed here\",\n // A token's unit is its sender's free text: one that does not look like a unit is not named (`ecashUnitError`).\n ecashUnnamedUnit: \"This ecash is in another unit: only sat ecash can be redeemed here\",\n reviewedEcashSpent: \"The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.\",\n reviewedSatsGone: \"The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.\",\n // A mint that failed (a server error, a closed connection), not refused: nothing happened, and it may work later.\n mintFailedQuote: \"{host} could not take this payment right now, and no sats left your wallet: try again later. The mint said: {reason}\",\n mintFailedFaucet: \"{host} could not give test coins right now: try again later. The mint said: {reason}\",\n mintFailedInvoice: \"{host} could not create an invoice right now: try again later. The mint said: {reason}\",\n // Lightning.\n lightningFeeTooHigh: \"The Lightning fee ({fee} sats) is too high\",\n lightningRefused: \"The mint refused this Lightning payment, and no sats left your wallet: it is safe to try again. The mint said: {reason}\",\n invoiceExpired: \"That invoice has expired\",\n lnurlExactly: \"{domain} asks for exactly {amount} sats\",\n lnurlRange: \"{domain} takes between {min} and {max} sats\",\n // A reviewed payment, from its review to its outcome (paymentAdapters/coordinator.ts, persistence.ts, node.ts).\n feeAboveLimit: \"The fee exceeds your limit\",\n cashuFeeAboveLimit: \"Cashu fee exceeds your limit\",\n invalidMaxFee: \"Invalid maximum fee\",\n methodUnavailable: \"This payment method is unavailable\",\n unknownPaymentIntent: \"Unknown payment intent\",\n paymentExpired: \"Payment request expired or has an invalid expiry\",\n requestHasPayment: \"This request already has a payment. Reconcile it before trying again.\",\n requestPaymentInFlight: \"This request already has a payment; reconcile it instead\",\n requestNotAwaiting: \"This request is no longer awaiting payment. Check its status before spending.\",\n reconnectBeforeApprove: \"Reconnect the data link before approving. Your review was saved.\",\n cannotSubmitAgain: \"This payment cannot be submitted again. Reconcile its existing transaction.\",\n alreadySubmitted: \"This payment was already submitted or could not be saved\",\n sentAfterReview: \"A payment from this wallet was sent after this review was made. Create a new review\",\n cannotCancelSubmitted: \"A submitted payment cannot be cancelled; reconcile it instead\",\n outcomeUnknown: \"Outcome unknown. Check the existing payment; do not send another.\",\n notYetConfirmed: \"Not yet confirmed. No second payment was sent.\",\n couldNotVerify: \"Could not verify this payment yet. No second payment was sent.\",\n paymentTakenBack: \"This payment was taken back. The sats are in your wallet.\",\n parkedSigned: \"Needs your decision: this payment was signed before this copy of your profile took over. It is never sent again from here. Check it before you pay again.\",\n // Paying in a chat.\n contactAway: \"Your contact is offline. Nothing was sent: pay once the chat is live.\",\n contactNoWallet: \"Your contact has no wallet yet: they need one to pay or be paid\",\n contactNoPayments: \"Your contact has payments off in this chat, or needs an updated Ghostly\",\n // Real money and test coins.\n realMoneyUnconfirmed: \"This pays with real money: confirm it with Send real money first. Nothing was sent.\",\n mainnetPaymentOnTestnet: \"This is a Mainnet payment (real money): a Testnet wallet never pays it. Use a Mainnet wallet.\",\n testnetPaymentOnMainnet: \"This is a Testnet payment (test coins): a Mainnet wallet never pays it. Use a Testnet wallet.\",\n // USDT.\n usdtRpcUnavailable: \"USDT RPC unavailable\",\n usdtNotEnoughTokens: \"Insufficient token balance\",\n usdtNotEnoughGas: \"Insufficient ETH for gas\",\n usdtGasAboveLimit: \"Estimated maximum gas exceeds your limit\",\n usdtNeedsSepoliaGas: \"This needs a little Sepolia ETH for gas first\",\n // Fedimint.\n fedimintNotInvite: \"That is not a Fedimint invite code: it starts with fed1\",\n fedimintAlreadyJoined: \"You already joined this federation\",\n fedimintConnecting: \"Wait for the federation to connect\",\n fedimintNotEnough: \"Not enough in this federation\",\n fedimintRedeemUnheard: \"Could not hear from the federation about these notes: if they don't show in your balance soon, paste them again\",\n fedimintRealOnTestnet: \"This federation holds real bitcoin: it belongs in a Mainnet Fedimint wallet\",\n fedimintTestOnMainnet: \"This federation is on {chain}, a test network: it belongs in a Testnet Fedimint wallet\",\n walletAway: \"{wallet} can't be used here. Use it on {device}.\",\n walletAwayUnnamed: \"{wallet} can't be used here: its home is another device.\",\n // Web apps shared with a contact.\n serviceShareFull: \"A contact can reach at most {max} of your apps: take one back from them before sharing another\",\n // One profile on several devices (WISP 06).\n groupTurnUnconfirmed: \"Can't check which device is active, so the group was not changed. Try again in a moment.\",\n // Group calls through the group's node (WISP 602).\n groupNoCall: \"This group has no calls: its admin has not set a call server\",\n groupCallNotMember: \"You are not in this group, so you can't join its call\",\n groupCallRefused: \"{host} did not let you into the group's call. Try again in a minute.\",\n groupCallBusy: \"{host} is busy. Try the call again in a minute.\",\n groupCallFailed: \"{host} could not start the group's call. Try again later.\",\n} as const;\n\nexport type EngineErrorCode = keyof typeof ENGINE_ERRORS;\nexport type EngineErrorValues = Record<string, string | number>;\n\n/**\n * An error the engine knows: `engineCode` travels with it inside the engine, the text everywhere. Not `code`: the\n * CLI reads a `code` as its own exit code, and Node's errors carry one of theirs.\n */\nexport class EngineError extends Error {\n constructor(readonly engineCode: EngineErrorCode, readonly values: EngineErrorValues = {}) {\n super(engineText(engineCode, values));\n }\n}\n\n/** The English text of `code` with its values in it, exactly as the engine writes it. */\nexport function engineText(code: EngineErrorCode, values: EngineErrorValues = {}): string {\n return ENGINE_ERRORS[code].replace(/\\{(\\w+)\\}/g, (_, name: string) => (name in values ? String(values[name]) : `{${name}}`));\n}\n\nexport const engineError = (code: EngineErrorCode, values?: EngineErrorValues): EngineError => new EngineError(code, values);\n\n/** A unit as the app names it: a unit's shape (`frames.ts` `isUnit`, in any case), never a token sender's other text. */\nconst NAMED_UNIT = \"[A-Za-z0-9]{1,12}\";\n\n/**\n * Why ecash of `unit` is not redeemed here. The unit is named only when it looks like one: a token's unit is whatever\n * its sender wrote, and the line is the app's own (a contact's payment's refusal row, the CLI's answer).\n */\nexport const ecashUnitError = (unit: string): EngineError =>\n new RegExp(`^${NAMED_UNIT}$`).test(unit) ? engineError(\"ecashOtherUnit\", { unit }) : engineError(\"ecashUnnamedUnit\");\n\n/** What each kind of value looks like in a text: never a space in a host, a network by its name, an amount as digits. */\nconst VALUE: Record<string, string> = {\n host: \"(\\\\S+)\", domain: \"(\\\\S+)\", chain: \"(\\\\S+)\", unit: `(${NAMED_UNIT})`, network: \"(Mainnet|Testnet)\",\n amount: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\", fee: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\", min: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\", max: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\",\n};\nconst escape = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst PATTERNS = (Object.keys(ENGINE_ERRORS) as EngineErrorCode[]).map((code) => {\n const names: string[] = [];\n const source = ENGINE_ERRORS[code].split(/(\\{\\w+\\})/).map((part) => {\n const value = /^\\{(\\w+)\\}$/.exec(part);\n if (!value) return escape(part);\n names.push(value[1]);\n return VALUE[value[1]] ?? \"(.+?)\";\n }).join(\"\");\n return { code, names, pattern: new RegExp(`^${source}$`) };\n});\n\n/** The code and values of a text the engine wrote, or null for any other text (it is then shown as it is). */\nexport function parseEngineError(text: string): { code: EngineErrorCode; values: Record<string, string> } | null {\n const trimmed = text.trim();\n for (const { code, names, pattern } of PATTERNS) {\n const match = pattern.exec(trimmed);\n if (match) return { code, values: Object.fromEntries(names.map((name, i) => [name, match[i + 1]])) };\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;AAWA,IAAa,gBAAgB;CAE3B,iBAAiB;CACjB,kBAAkB;CAClB,iBAAiB;C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AM,MAAM,IAAI,EAAE,CAAC,CAAC;EAAE;CACrG;CACA,OAAO;AACT"}
@@ -30,6 +30,22 @@ var CliError = class extends Error {
30
30
  };
31
31
  }
32
32
  };
33
+ /**
34
+ * A value as a refusal quotes it (`--limit takes a number, not "x"`): a word with a line break or longer than 40
35
+ * characters is described, not printed, as an unknown option is (docs/CLI.md "Secrets stay hidden"). A Cashu token, a
36
+ * wallet connection link, an nsec, a seed or a hex key typed in the wrong place is that long, and bots keep the output.
37
+ */
38
+ function shownValue(value) {
39
+ if (typeof value !== "string") return JSON.stringify(value);
40
+ return secretValue(value) ?? JSON.stringify(value);
41
+ }
42
+ /** What `shownValue` says in place of a long or secret-looking word, else undefined (the word may be printed). */
43
+ function secretValue(value) {
44
+ if (/^cashu[AB]/.test(value)) return "(a Cashu token)";
45
+ if (/^nostr\+walletconnect:/i.test(value)) return "(a wallet connection link)";
46
+ if (/^nsec1/.test(value)) return "(a private key)";
47
+ return value.length > 40 || /[\r\n]/.test(value) ? `(a ${value.length}-character word)` : void 0;
48
+ }
33
49
  /** Anything thrown, as the error a bot sees: the engine's own refusals keep their words. */
34
50
  function asCliError(error) {
35
51
  if (error instanceof CliError) return error;
@@ -172,6 +188,6 @@ function localFileError(error, file) {
172
188
  });
173
189
  }
174
190
  }
175
- export { localFileError as i, EXIT as n, asCliError as r, CliError as t };
191
+ export { secretValue as a, localFileError as i, EXIT as n, shownValue as o, asCliError as r, CliError as t };
176
192
 
177
- //# sourceMappingURL=errors-DDLFO4Gf.js.map
193
+ //# sourceMappingURL=errors-JVJsO8Iu.js.map