@ghostlytools/cli 1.12.0 → 1.12.1

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 (63) hide show
  1. package/README.md +5 -5
  2. package/dist/assets/{api-DLzCtePC.js → api-BwEgbvvK.js} +49 -23
  3. package/dist/assets/api-BwEgbvvK.js.map +1 -0
  4. package/dist/assets/{api-DYMKyb1k.js → api-jRUXnBdX.js} +2 -2
  5. package/dist/assets/{apiKit-CVaEzKWQ.js → apiKit-BlsNk-Cx.js} +2 -2
  6. package/dist/assets/{apiKit-CVaEzKWQ.js.map → apiKit-BlsNk-Cx.js.map} +1 -1
  7. package/dist/assets/{appFetch-D56GsYuq.js → appFetch-CW9fJPHh.js} +2 -2
  8. package/dist/assets/{appFetch-D56GsYuq.js.map → appFetch-CW9fJPHh.js.map} +1 -1
  9. package/dist/assets/{apps-BPFW19Wc.js → apps-BcG4u6SM.js} +1 -1
  10. package/dist/assets/{apps-XnZ8VEuj.js → apps-CL8TXHhu.js} +6 -6
  11. package/dist/assets/{apps-XnZ8VEuj.js.map → apps-CL8TXHhu.js.map} +1 -1
  12. package/dist/assets/{backup-DpyvT9Z6.js → backup-BA41EDvh.js} +47 -8
  13. package/dist/assets/backup-BA41EDvh.js.map +1 -0
  14. package/dist/assets/{backup-COX6j1_W.js → backup-xZfV-ytw.js} +1 -1
  15. package/dist/assets/{bitcoind-DTsrd7TF.js → bitcoind-Dh7n9amb.js} +2 -2
  16. package/dist/assets/{bitcoind-DTsrd7TF.js.map → bitcoind-Dh7n9amb.js.map} +1 -1
  17. package/dist/assets/buttons-CsGdQNnR.js +1 -0
  18. package/dist/assets/{buttons-BvWqHJeh.js → buttons-SH1tNRh7.js} +6 -6
  19. package/dist/assets/buttons-SH1tNRh7.js.map +1 -0
  20. package/dist/assets/{client-kGZ3ZdUW.js → client-DGS-atRu.js} +2 -2
  21. package/dist/assets/{client-kGZ3ZdUW.js.map → client-DGS-atRu.js.map} +1 -1
  22. package/dist/assets/{endpoint-B0vE5ojY.js → endpoint-Cvu-taMs.js} +42 -5
  23. package/dist/assets/{endpoint-B0vE5ojY.js.map → endpoint-Cvu-taMs.js.map} +1 -1
  24. package/dist/assets/{groupMeta-DTQAJG50.js → groupMeta-DxuJzko_.js} +49 -28
  25. package/dist/assets/groupMeta-DxuJzko_.js.map +1 -0
  26. package/dist/assets/{host-z0FAHP9Z.js → host-BxM-HMr0.js} +62 -9
  27. package/dist/assets/host-BxM-HMr0.js.map +1 -0
  28. package/dist/assets/{hyperdhtRelay-CvsAfQRQ.js → hyperdhtRelay-DLUiwfnt.js} +32 -4
  29. package/dist/assets/hyperdhtRelay-DLUiwfnt.js.map +1 -0
  30. package/dist/assets/{irohWeb-CLBx5MIv.js → irohWeb-CbnGtUo6.js} +175 -6
  31. package/dist/assets/irohWeb-CbnGtUo6.js.map +1 -0
  32. package/dist/assets/{main-CVqkvuIo.js → main-CwTaepxR.js} +48 -31
  33. package/dist/assets/main-CwTaepxR.js.map +1 -0
  34. package/dist/assets/{ownStatus-DMEhrpkd.js → ownStatus-DtzIllg2.js} +4 -3
  35. package/dist/assets/ownStatus-DtzIllg2.js.map +1 -0
  36. package/dist/assets/{profiles-BFSGqDFC.js → profiles-BOYGlmu2.js} +2 -2
  37. package/dist/assets/{profiles-BFSGqDFC.js.map → profiles-BOYGlmu2.js.map} +1 -1
  38. package/dist/assets/{registry-B15Yg_1C.js → registry-4W1LGlCF.js} +1 -1
  39. package/dist/assets/{registry-rXgaZeNn.js → registry-Bep4umOM.js} +36 -28
  40. package/dist/assets/registry-Bep4umOM.js.map +1 -0
  41. package/dist/assets/secretGuard-Bm6nci0I.js +1 -0
  42. package/dist/assets/{secretGuard-B4-LlMjv.js → secretGuard-BrATm_gl.js} +33 -9
  43. package/dist/assets/{secretGuard-B4-LlMjv.js.map → secretGuard-BrATm_gl.js.map} +1 -1
  44. package/dist/assets/{server-CQR7NLCz.js → server-D4gf-LnD.js} +257 -43
  45. package/dist/assets/server-D4gf-LnD.js.map +1 -0
  46. package/dist/assets/{waitNotice-BGM0QOS2.js → waitNotice-DQvZgz2T.js} +2 -2
  47. package/dist/assets/{waitNotice-BGM0QOS2.js.map → waitNotice-DQvZgz2T.js.map} +1 -1
  48. package/dist/ghostly.mjs +1 -1
  49. package/npm-shrinkwrap.json +2 -2
  50. package/package.json +1 -1
  51. package/dist/assets/api-DLzCtePC.js.map +0 -1
  52. package/dist/assets/backup-DpyvT9Z6.js.map +0 -1
  53. package/dist/assets/buttons-Bq7pTXqF.js +0 -1
  54. package/dist/assets/buttons-BvWqHJeh.js.map +0 -1
  55. package/dist/assets/groupMeta-DTQAJG50.js.map +0 -1
  56. package/dist/assets/host-z0FAHP9Z.js.map +0 -1
  57. package/dist/assets/hyperdhtRelay-CvsAfQRQ.js.map +0 -1
  58. package/dist/assets/irohWeb-CLBx5MIv.js.map +0 -1
  59. package/dist/assets/main-CVqkvuIo.js.map +0 -1
  60. package/dist/assets/ownStatus-DMEhrpkd.js.map +0 -1
  61. package/dist/assets/registry-rXgaZeNn.js.map +0 -1
  62. package/dist/assets/secretGuard-BmmnEbYf.js +0 -1
  63. package/dist/assets/server-CQR7NLCz.js.map +0 -1
@@ -1,3 +1,3 @@
1
- import { F as startNamedChats, l as findGroup, s as findChat } from "./apiKit-CVaEzKWQ.js";
2
- import { a as hideStateSecrets, c as settingsInEffect, i as groupSendRefused, n as SETTABLE, o as mentionsFor, r as callApi, s as redactSettings, t as API_METHODS } from "./api-DLzCtePC.js";
1
+ import { F as startNamedChats, l as findGroup, s as findChat } from "./apiKit-BlsNk-Cx.js";
2
+ import { a as hideStateSecrets, c as settingsInEffect, i as groupSendRefused, n as SETTABLE, o as mentionsFor, r as callApi, s as redactSettings, t as API_METHODS } from "./api-BwEgbvvK.js";
3
3
  export { API_METHODS, SETTABLE, callApi, findChat, findGroup, groupSendRefused, hideStateSecrets, mentionsFor, redactSettings, settingsInEffect, startNamedChats };
@@ -1,4 +1,4 @@
1
- import { u as groupName, x as INVITE_TAKEN } from "./groupMeta-DTQAJG50.js";
1
+ import { u as groupName, x as INVITE_TAKEN } from "./groupMeta-DxuJzko_.js";
2
2
  import { o as isZ32Key } from "./bytes-C1DNGY18.js";
3
3
  import { r as sanitizeDisplayText } from "./text-li76pThX.js";
4
4
  import { t as CliError } from "./errors-DDLFO4Gf.js";
@@ -546,4 +546,4 @@ function waitForState(ctx, check, ms, what, stopping) {
546
546
  }
547
547
  export { sentAt as A, shellWord as B, nobodyJoined as C, oneOf as D, num as E, startNamedChats as F, state as I, str as L, shownName as M, sinceSeq as N, oneShotWaits as O, somebodyJoined as P, transportOffered as R, noMessage as S, node as T, jsonOut as V, list as _, contactKeyOf as a, namedByThem as b, findChatOrGroup as c, groupById as d, groupNameOf as f, keptForJoin as g, inviteTaken as h, cleanName as i, settingsOf as j, ownChatOf as k, findGroup as l, groupPrefixed as m, chatOf as n, dhtOnly as o, groupOf as p, chatOrGroup as r, findChat as s, bool as t, findOwnNamedChat as u, messageOf as v, nobodyJoinedChat as w, noFile as x, nameKey as y, waitForState as z };
548
548
 
549
- //# sourceMappingURL=apiKit-CVaEzKWQ.js.map
549
+ //# sourceMappingURL=apiKit-BlsNk-Cx.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"apiKit-CVaEzKWQ.js","names":[],"sources":["../../src/jsonOut.ts","../../src/shellWord.ts","../../src/apiKit.ts"],"sourcesContent":["/**\n * What `JSON.stringify` leaves raw and a terminal may act on: DEL and the C1 controls (CSI, OSC, ST, NEL... in UTF-8),\n * the line and paragraph separators, and the bidi marks, embeddings, overrides and isolates that reorder a line. Only\n * a string holds them, and a peer writes some of those strings (a message's text), so the CLI's output writes them as\n * `\\uXXXX`: the same JSON value for every reader, nothing a terminal acts on. What is stored stays whole.\n */\nconst RAW = /[\\u007f-\\u009f\\u061c\\u200e\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]/g;\n\n/** `value` as the JSON the CLI prints: `JSON.stringify`, with `RAW` escaped. */\nexport function jsonOut(value: unknown, space?: number): string {\n return JSON.stringify(value, null, space)?.replace(RAW, (char) => \"\\\\u\" + char.charCodeAt(0).toString(16).padStart(4, \"0\"));\n}\n","import { jsonOut } from \"./jsonOut\";\n\n/**\n * A word as a hint offers it to be pasted into a shell: as it is when plain, else single-quoted. JSON's double quotes\n * are no shell quoting: `\"$5 lunch\"` pasted names ` lunch`, and a backtick in it runs a command. A leading `=` stays\n * quoted too (zsh expands `=word` to a command's path). Every \"<name> (2)\" a keep-both hint names has a `(` in it, a\n * syntax error in bash and zsh unquoted.\n *\n * The CLI prints every answer, an error too, as JSON, and a hint is pasted as the terminal shows it: a `'` quoted as\n * `'\\''` read `'\\\\''` there, which ended the quote, and the rest of the word ran as commands (a group's name is its\n * inviter's, a kept-both file's its sender's). A `\"` or a `\\` came out doubled the same way. No shell quoting survives\n * that, so such a word is not offered: `instead` is said, an id that names the same thing or where the details hold it.\n */\nexport function shellWord(word: string, instead: string): string {\n if (/^[\\w@%+:,./-][\\w@%+=:,./-]*$/.test(word)) return word;\n return word.includes(\"'\") || jsonOut(word) !== `\"${word}\"` ? instead : `'${word}'`;\n}\n","import { groupName, INVITE_TAKEN, isZ32Key, MAX_GROUP_NAME_BYTES, MAX_GROUP_NAME_LENGTH, sanitizeDisplayText, type PairedTransport } from \"@ghostly/core\";\nimport type { GhostlyNode } from \"@ghostly/browser/engine/node\";\nimport type { EngineState, GroupView, LinkView, Settings, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { CliError } from \"./errors\";\nimport { shellWord } from \"./shellWord\";\nimport type { CallManager } from \"./calls/manager\";\nimport type { EventHub } from \"./events\";\nimport type { GroupAutoJoin } from \"./groupAuto\";\nimport type { Runtime } from \"./runtime/engine\";\n\n/**\n * The methods of the local control API (WISP 1100): the daemon answers them over its socket, and a one-shot\n * command calls them in its own process. Parameters come from JSON: every one is checked here.\n */\nexport interface ApiContext {\n runtime: Runtime;\n hub: EventHub;\n /** Voice calls (WISP 1100 § Calls). */\n calls: CallManager;\n /** Group invitations accepted by themselves (`group auto`). */\n groupAuto: GroupAutoJoin;\n /** How the host runs: a daemon stays; a one-shot leaves when its command is done. */\n mode: \"daemon\" | \"one-shot\";\n version: string;\n /** The daemon asks to stop (answered first). */\n stop?: () => void;\n /**\n * Aborted when the daemon stops (`serve().close`): a wait still open answers with what it knows (`waits.ts`), as a\n * timeout with `details.reason: \"daemon-stopped\"`, before the connections end.\n */\n stopping?: AbortSignal;\n /** The daemon is a `listen` that found none and runs the profile itself: a stop ends that listen too. */\n listen?: true;\n}\n\nexport type Params = Record<string, unknown>;\n/** What a call knows of who asked it. */\nexport interface CallScope {\n /**\n * Aborted when the daemon's connection the call came on closes (Ctrl-C on the command, its process gone): nobody\n * reads the answer any more. A call that leaves something behind for its answer (`profile.backup`) stops on it.\n */\n gone?: AbortSignal;\n}\n\nexport type Method = (ctx: ApiContext, params: Params, call?: CallScope) => Promise<unknown>;\n\nexport const node = (ctx: ApiContext): GhostlyNode => ctx.runtime.server.node;\nexport const state = (ctx: ApiContext): EngineState => node(ctx).getState();\n/** The engine's settings, without building `state` (a view of every chat). */\nexport const settingsOf = (ctx: ApiContext): Settings => node(ctx).getSettings();\n\n/**\n * The time of a send the engine names its row after (`me_<timestamp>`: a file, a payment, a request), its own even\n * within one millisecond (a bot paying or sending several times at once over the socket, `file send` run in\n * parallel), or the chat keeps only one. One clock for all of them: they share the row names. A file's resend after a\n * drop finds its row by it, as a forward does.\n */\nlet lastSentAt = 0;\nexport const sentAt = () => (lastSentAt = Math.max(Date.now(), lastSentAt + 1));\n\n// ---------- parameters ----------\n\nexport function str(params: Params, name: string, required: true): string;\nexport function str(params: Params, name: string, required?: false): string | undefined;\nexport function str(params: Params, name: string, required = false): string | undefined {\n const value = params[name];\n if (value === undefined || value === null || value === \"\") {\n if (required) throw new CliError(\"bad_request\", `${name} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") throw new CliError(\"bad_request\", `${name} must be a string`);\n return value;\n}\n/** A number in `[min, max]`; `whole` takes only whole ones (a count of messages), as the engine needs them. */\nexport function num(params: Params, name: string, fallback: number, { min = 0, max = Number.MAX_SAFE_INTEGER, whole = false } = {}): number {\n const value = params[name];\n if (value === undefined || value === null) return fallback;\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) throw new CliError(\"bad_request\", `${name} must be a ${whole ? \"whole \" : \"\"}number from ${min} to ${max}`);\n if (whole && !Number.isSafeInteger(value)) throw new CliError(\"bad_request\", `${name} must be a whole number from ${min} to ${max}`);\n return value;\n}\n/**\n * The seq `events.replay` and `events.subscribe` start after: whole, from 0; `fallback` when left out. A cursor sent as\n * text (\"412\") was a stream from now on the socket with no error, and a negative one a gap of seqs that never were.\n */\nexport function sinceSeq(params: Params, fallback: number): number {\n return num(params, \"since\", fallback, { whole: true });\n}\nexport function bool(params: Params, name: string): boolean {\n const value = params[name];\n if (value === undefined || value === null) return false;\n if (typeof value !== \"boolean\") throw new CliError(\"bad_request\", `${name} must be true or false`);\n return value;\n}\nexport function list(params: Params, name: string): string[] {\n const value = params[name];\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) throw new CliError(\"bad_request\", `${name} must be a list of strings`);\n return value as string[];\n}\n/**\n * One of `values`; `fallback` when it was left out. Given empty (an unset variable in a script: `wallet remove \"\"`), it\n * is refused like any other wrong choice, never read as left out: that acted on the default (the Cashu wallet).\n */\nexport function oneOf<T extends string>(params: Params, name: string, values: readonly T[], fallback: T): T {\n const value = params[name] === \"\" ? \"\" : str(params, name) ?? fallback;\n if (!values.includes(value as T)) throw new CliError(\"bad_request\", `${name} must be one of ${values.join(\", \")}`);\n return value as T;\n}\n\n// ---------- finding things ----------\n\nconst KEY_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\n/**\n * A chat's id as the engine makes it (the first 16 characters of a z-base-32 key) and the CLI prints it as `chat`. A ref\n * so shaped is only ever an id: tested on its `nameKey`, so that a case, a space or an invisible character more is too.\n */\nconst CHAT_ID_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{16}$/;\n/**\n * A contact key as chats show it (`peer`): 52 characters of z-base-32, in its one canonical spelling. The same 52\n * characters with the last one respelled decode to the same bytes but are no key (WISP 02): refused here, so that\n * they never fall through to a chat's name, which its contact chooses.\n */\nexport const CONTACT_KEY = {\n test(ref: string): boolean {\n if (isZ32Key(ref)) return true;\n if (KEY_SHAPED.test(ref)) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} is not a contact key: a key has one spelling, and its last character is not this one`);\n return false;\n },\n};\n\n/**\n * The contact key `ref` is once read as a name is (`nameKey`: trimmed, invisible characters dropped, one case), or\n * undefined for a ref not shaped as one. A key a script or a paste left a line break, a space or capitals on is still\n * that key, and only ever names by key: never a chat, a group or a member by a name someone else chose. Every ref that\n * may be a key is read here, so no caller tests the raw string.\n */\nexport function contactKeyOf(ref: string): string | undefined {\n const key = nameKey(ref);\n return CONTACT_KEY.test(key) ? key : undefined;\n}\n\n/**\n * A chat's label, its contact's name or a group's name as a ref is compared with it: cleaned as the engine cleans a name\n * it stores (`renameLink`, `groupName`: any run of whitespace one space, invisible and direction-changing characters\n * dropped, trimmed), in one Unicode form (NFC) and one case. The string given to `chat rename` or `group create` finds\n * what it named, though what was stored is the cleaned one. Empty when nothing visible is left: that names nothing.\n */\nexport function nameKey(name: string | null | undefined): string {\n if (!name) return \"\";\n return (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\").toLowerCase();\n}\n\n/**\n * A name this side writes (a chat's label, the profile's name, a group's name) cleaned as the engine stores a name\n * (`renameLink`, `groupName`): any run of whitespace (a tab, a line break) one space, invisible and direction-changing\n * characters dropped, trimmed, in NFC: `nameKey` without the case. Counted after that, in code points as the engine\n * counts: undefined past `max`, \"\" when nothing visible is left. Every command that writes a name checks it here, so a\n * tab is a space and not a second line, and a name is never refused at a length it does not have once stored.\n */\nexport function cleanName(name: string, max: number): string | undefined {\n const clean = (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\");\n return [...clean].length > max ? undefined : clean;\n}\n\n/**\n * `name` as `cleanName` stores it, or the one refusal every name kind gives (`bad_request`), so a chat's, the profile's\n * and a group's name read alike. `subject` starts the sentence (\"A chat's name\", \"nick\"); `empty` follows \"needs a\n * character that shows\" (what an empty name does instead, when it does something). Too long says the count as stored,\n * in code points as the engine counts, and the largest character of several code points in it (a joined emoji or a\n * flag counts as several): the person sees what to cut, and a bot reads `details.length` and `details.max`.\n */\nexport function shownName(name: string, max: number, subject: string, empty = \"\"): string {\n const clean = cleanName(name, Infinity) ?? \"\";\n const length = [...clean].length;\n if (length > max) {\n const widest = [...new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(clean)]\n .map(({ segment }) => segment).reduce((a, b) => ([...b].length > [...a].length ? b : a), \"\");\n const several = [...widest].length > 1 ? `: ${widest} counts as ${[...widest].length}` : \"\";\n throw new CliError(\"bad_request\", `${subject} is up to ${max} characters as stored (this one is ${length}${several})`, { length, max });\n }\n if (!clean) throw new CliError(\"bad_request\", `${subject} needs a character that shows${empty}`);\n return clean;\n}\n\n/**\n * The `name` param of `group create` and `group rename`, refused as a chat's or the profile's name is (`shownName`),\n * then as the engine takes it (`groupName`: the same cleaning, 64 code points, 256 bytes; 64 code points never pass\n * 256 bytes, so its refusal is only a guard). Said here, before anything is made.\n */\nexport function groupNameOf(params: Params): string {\n const name = groupName(shownName(str(params, \"name\", true), MAX_GROUP_NAME_LENGTH, \"A group's name\"));\n if (!name) throw new CliError(\"bad_request\", `A group's name is up to ${MAX_GROUP_NAME_BYTES} bytes as stored`);\n return name;\n}\n\n/** Whether `name` is the one `key` (a ref's `nameKey`) names. */\nconst namedAs = (key: string, name: string | null | undefined) => key !== \"\" && nameKey(name) === key;\n\n/**\n * A chat by its id; by its contact's key (only by the key: a name is never taken for one); by the label this side gave\n * it; and only when no label matches, by a unique prefix of its id or the name the contact gave itself. The contact\n * controls both of those (a joiner's chat id is made from the inviter's code), so neither wins over a label, and a ref\n * that fits one chat's prefix and another's name is refused. A ref shaped as a chat's id is only ever an id, or a label\n * given here. `group:<ref>` is never a chat (a group, as everywhere). A ref\n * that names no chat but one of `groups` says it is a group (see `noChat`).\n */\nexport function findChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n return chatBy(links, ref, groups).link;\n}\n\n/**\n * No chat by `ref`. A group's id, prefix or name (or `group:<id>`) says it is a group, as `groupOf` says a chat is one:\n * `chat connect`, `identity share`, `call start` and the other commands that take only a 1:1 chat read `No chat \"Crew\"`,\n * as if nothing had that name.\n */\nfunction noChat(ref: string, groups: readonly GroupView[]): CliError {\n const group = groupNamed(ref, groups);\n if (group) return new CliError(\"not_found\", `${JSON.stringify(ref)} is a group, not a chat (ghostly chat list)`, { group: group.id });\n return new CliError(\"not_found\", `No chat ${JSON.stringify(ref)} (ghostly chat list)`);\n}\n\n/** A chat or group ref as a next step shows it: as given, quoted only when it holds more than a word (see `shellWord`). */\nconst shownRef = (place: RefPlace) => shellWord(place.ref, place.group ? \"<group>\" : \"<chat>\");\n\n/** The chat or the group a message or a file was looked for in, as the command was given it (`ref`). */\nexport type RefPlace = { group: boolean; ref: string };\n\n/**\n * No message by `id` in a chat or a group, said one way by every command that takes one, as `noChat` says a chat: the id\n * quoted as given, and where the ids are. `whose` (\"of yours\", \"from someone else\") is what it had to be; `tail` what\n * else it may have failed for (\", or it takes no reaction\", \": only your own messages are sent again\").\n */\nexport function noMessage(id: string, place: RefPlace, { whose, tail }: { whose?: string; tail?: string } = {}): CliError {\n const history = `ghostly ${place.group ? \"group\" : \"chat\"} history ${shownRef(place)}`;\n return new CliError(\"not_found\", `No message ${JSON.stringify(id)}${whose ? ` ${whose}` : \"\"} in this ${place.group ? \"group\" : \"chat\"}${tail ?? \"\"} (${history})`);\n}\n\n/** No file by `id`, as `noMessage` says a message: in the chat or group named (`place`), or in none when none was. */\nexport function noFile(id: string, place?: RefPlace): CliError {\n const where = place ? ` in this ${place.group ? \"group\" : \"chat\"}` : \"\";\n return new CliError(\"not_found\", `No file ${JSON.stringify(id)}${where} (ghostly file list ${place ? shownRef(place) : \"<chat|group>\"})`);\n}\n\n/** The one group `ref` names, if any (none, or more than one: undefined). */\nfunction groupNamed(ref: string, groups: readonly GroupView[]): GroupView | undefined {\n try { return findGroup(groups, ref); } catch { return undefined; }\n}\n\n/** `findChat`, and whether only what the contact controls (`theirName`: a prefix of the id, its own name) found the chat. */\nfunction chatBy(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): { link: LinkView; theirName: boolean } {\n // \"\" (an unset variable in a script) is a prefix of every id: it took the only chat.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names no chat`);\n const exact = links.find((link) => link.id === ref);\n if (exact) return { link: exact, theirName: false };\n const contact = contactKeyOf(ref);\n if (contact !== undefined) {\n const byKey = links.filter((link) => link.peerPubKeyZ32 === contact);\n if (byKey.length === 1) return { link: byKey[0], theirName: false };\n if (byKey.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: byKey.map((link) => link.id) });\n throw new CliError(\"not_found\", `No chat with ${JSON.stringify(ref)} (ghostly chat list)`);\n }\n const key = nameKey(ref);\n const named = (name: string | null | undefined) => namedAs(key, name);\n const byLabel = links.filter((link) => named(link.label));\n // `group:<ref>` names a group (`groupPrefixed`), never a chat: not by a name its contact chose, nor by a label given\n // here (a chat labelled `group:Crew` was that chat for `chat show` and the group Crew for `send`). A chat labelled so\n // before labels were refused (`chatName`) is named by its id.\n if (groupPrefixed(ref) !== null) {\n if (byLabel.length && !groupNamed(ref, groups)) throw new CliError(\"not_found\", `${JSON.stringify(ref)} names a group, never a chat: name the chat labelled so by its id, and give it another name (ghostly chat rename <chat> <name>)`, { matches: byLabel.map((link) => link.id) });\n throw noChat(ref, groups);\n }\n // A chat's id no chat has (one removed since: a bot kept it from an event) is no chat. Its contact and whoever saw its\n // invite know it, so another contact could call itself that and take every later command sent by it. A label given\n // here still names the chat: only this side chooses it.\n if (!byLabel.length && CHAT_ID_SHAPED.test(key)) throw noChat(ref, groups);\n const found = byLabel.length ? byLabel : [...new Set([...links.filter((link) => link.id.startsWith(ref)), ...links.filter((link) => named(link.peerNick))])];\n if (found.length === 1) return { link: found[0], theirName: !byLabel.length };\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: found.map((link) => link.id) });\n throw noChat(ref, groups);\n}\n\n/**\n * `findChat` for a grant the daemon keeps acting on (`call auto on --from`): only the chat's id, its contact's key or the\n * label this side gave it name the chat. A prefix of its id or the name its contact gave itself is refused, with the\n * chat it found: the contact chose those, so another contact could take the grant by calling itself that name.\n */\nexport function findOwnNamedChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n const chat = chatBy(links, ref, groups);\n if (chat.theirName) throw namedByThem(ref, { chat: chat.link.id, name: chat.link.peerNick ?? null, contact: chat.link.peerPubKeyZ32 });\n return chat.link;\n}\n\n/** `findOwnNamedChat`'s refusal: `ref` found `chat` only by what its contact chose. */\nexport function namedByThem(ref: string, chat: { chat: string; name: string | null; contact: string | undefined }): CliError {\n return new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat only by what its contact chose (a prefix of its id, its own name): use the chat's id, its contact's key or a label given here (ghostly chat rename <chat> <name>)`, chat);\n}\n\n/**\n * `group:<ref>`, the form that names a group wherever a group is taken (docs/CLI.md § What it does): `<ref>`, read as any\n * other ref (`findGroup`: an id, a prefix of it or a name). Null for a ref without it. `findGroup` and `findChatOrGroup`\n * both read the prefix here, so a group command and a command that takes a chat or a group never read it apart.\n */\nexport const groupPrefixed = (ref: string): string | null => (ref.startsWith(\"group:\") ? ref.slice(\"group:\".length) : null);\n\n/** Only an invitation so far: this profile is not in the group (yet), and whoever invited chose its name. */\nconst invitedOnly = (group: GroupView) => group.status === undefined && !!group.invitation;\n\n/**\n * A group by its id, by its name, or by a unique prefix of its id. Whoever created a group chose its id and its admin\n * chooses its name, so neither wins over the other: a ref that is one group's name and another's prefix is refused,\n * with both ids, as `chatBy` does for chats. A group this profile is in wins over an invitation with the same name or\n * prefix (the one who invites chooses those); an invitation is still found by its id, and by name or prefix where no\n * group of this profile has it. `group:<ref>` is `<ref>` (`groupPrefixed`); before, only the commands that take a chat\n * or a group read it, and every group command and `listen --group` answered it `No group`.\n */\nexport function findGroup(groups: readonly GroupView[], given: string): GroupView {\n const ref = groupPrefixed(given) ?? given;\n // Each refusal echoes the ref as given (`\"group:k86q\"`), not the part after `group:`: what the person typed.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names no group`);\n const exact = groups.find((group) => group.id === ref);\n if (exact) return exact;\n const key = nameKey(ref);\n for (const among of [groups.filter((group) => !invitedOnly(group)), groups.filter(invitedOnly)]) {\n const found = among.filter((group) => namedAs(key, group.name) || group.id.startsWith(ref));\n if (found.length === 1) return found[0];\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names more than one group: use its id`, { matches: found.map((group) => group.id) });\n }\n throw new CliError(\"not_found\", `No group ${JSON.stringify(given)} (ghostly group list)`);\n}\n\n/**\n * A chat or a group, where a command takes either: `group:<id>` is a group; anything else a chat first (`findChat`),\n * then a group. A chat found only by what its contact chose (a prefix of its id, its own name) never takes what also\n * names a group: a group's\n * own id is that group, and a prefix or the name of a group this profile is in is refused, with both ids. With neither,\n * one `not_found` names both and where to look (a contact's key: no chat with it); a name that matches more than one\n * chat or group stays that error.\n */\nexport function findChatOrGroup(links: readonly LinkView[], groups: readonly GroupView[], ref: string): { link: LinkView } | { group: GroupView } {\n if (groupPrefixed(ref) !== null) return { group: findGroup(groups, ref) };\n let chat: ReturnType<typeof chatBy>;\n try {\n chat = chatBy(links, ref);\n } catch (error) {\n if (!(error instanceof CliError) || error.code !== \"not_found\") throw error;\n // Nor is it a group's name or a prefix of a group's id (its admin and its creator chose those; a group's own id is\n // longer), nor is a contact's key with no chat: `group:<ref>` names a group.\n if (CHAT_ID_SHAPED.test(nameKey(ref)) || contactKeyOf(ref) !== undefined) throw error;\n try { return { group: findGroup(groups, ref) }; } catch (inner) {\n if (!(inner instanceof CliError) || inner.code !== \"not_found\") throw inner;\n throw new CliError(\"not_found\", `No chat or group ${JSON.stringify(ref)} (ghostly chat list, ghostly group list)`);\n }\n }\n if (!chat.theirName) return { link: chat.link };\n const exact = groups.find((group) => group.id === ref);\n if (exact) return { group: exact };\n const key = nameKey(ref);\n const also = groups.filter((group) => !invitedOnly(group) && (group.id.startsWith(ref) || namedAs(key, group.name)));\n if (also.length) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat (by what its contact chose) and a group: use the chat's id or group:<id>`, { chat: chat.link.id, groups: also.map((group) => group.id) });\n return { link: chat.link };\n}\n\n/**\n * Starts the chats and groups a call names (its `chat`, a forward's `to`, its `group`) in a runtime that left the saved\n * chats and the groups' edges unstarted (`RuntimeOptions.deferChats`). A ref that names nothing starts nothing: the\n * call says so itself.\n */\nexport async function startNamedChats(ctx: ApiContext, params: Params): Promise<void> {\n const { links, groups } = state(ctx);\n for (const ref of [params.chat, ...(Array.isArray(params.to) ? params.to : [])]) {\n if (typeof ref !== \"string\") continue;\n let found: ReturnType<typeof findChatOrGroup>;\n try { found = findChatOrGroup(links, groups, ref); } catch { continue; }\n if (\"link\" in found) await node(ctx).startDeferredChat(found.link.id);\n else node(ctx).startDeferredGroup(found.group.id);\n }\n if (typeof params.group === \"string\") {\n try { node(ctx).startDeferredGroup(findGroup(groups, params.group).id); } catch { /* the call says so itself */ }\n }\n}\n\n/**\n * The chat a call names. `s`: a state the call built already. Each build is a view of every chat (about 15-20 µs a\n * chat, on the daemon's one thread): one lookup builds one, never one per list it reads.\n */\nexport function chatOf(ctx: ApiContext, params: Params, s?: EngineState): LinkView {\n const ref = str(params, \"chat\", true);\n if (!s) { const chat = byId(ctx, ref); if (chat) return chat; }\n const { links, groups } = s ?? state(ctx);\n return findChat(links, ref, groups);\n}\n/** `findOwnNamedChat` for the chat a call names, as `chatOf`. */\nexport function ownChatOf(ctx: ApiContext, params: Params, s?: EngineState): LinkView {\n const ref = str(params, \"chat\", true);\n if (!s) { const chat = byId(ctx, ref); if (chat) return chat; }\n const { links, groups } = s ?? state(ctx);\n return findOwnNamedChat(links, ref, groups);\n}\n/**\n * The chat whose id `ref` is, built alone: a chat's own id names it before anything else does (`chatBy`), and a bot\n * names its chats by the ids its events give. Undefined for any other ref, which the whole list is read for.\n */\nconst byId = (ctx: ApiContext, ref: string): LinkView | undefined => node(ctx).chatView(ref);\n\n/** A chat of mine whose invite nobody took yet: no contact's key, so nothing goes out until they join. */\nexport const nobodyJoined = (link: LinkView): boolean => !!(link.profile && link.inviteCode && !link.peerParticipationKey);\n\n/**\n * `nobodyJoined` by the chat's id: a group's (`group:<id>`) is never one. That chat's view alone: every card send or\n * update, `file send` and unconfirmed edit asks it, and built every chat for it (once in a daemon, up to three times\n * in a one-shot `usage send`).\n */\nexport const nobodyJoinedChat = (ctx: ApiContext, chat: string): boolean => {\n const link = byId(ctx, chat);\n return !!link && nobodyJoined(link);\n};\n\n/**\n * Whether a one-shot waits by default on what it did in a 1:1 chat: it leaves with its process, so it stays until that\n * went out or the contact confirmed it. Not on a chat nobody joined yet: there is no one to wait for, and `edit`, `react`,\n * `pin`, a card or a file sat their whole wait (a file 300 s), then failed `timeout`, exit 4, which a bot retries: one\n * more card or file each time. What was done is kept and goes once they join; the answer says so (`keptForJoin`).\n */\nexport const oneShotWaits = (ctx: ApiContext, chat: string): boolean => ctx.mode === \"one-shot\" && !nobodyJoinedChat(ctx, chat);\n\n/** An answer's `note` on a chat nobody joined yet: `what` is kept and goes once they join. Nothing on any other chat. */\nexport const keptForJoin = (ctx: ApiContext, chat: string, what: string): { note?: string } => nobodyJoinedChat(ctx, chat)\n ? { note: `Nobody joined this chat yet: ${what} goes once they join${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}` }\n : {};\n\n/**\n * A chat whose invite nobody took yet has no session to close either: `chat disconnect` answered done with the chat at\n * `connecting`, and `--hold` put the waiting invite on DHT only (a one-shot answered `pairing: error`).\n */\nexport function somebodyJoined(link: LinkView): void {\n if (nobodyJoined(link)) throw new CliError(\"unavailable\", \"Nobody joined this chat yet: its invite is still waiting to be taken\");\n}\n\n/**\n * A chat whose invite nobody took yet: nobody is there to pay or to dial, and its stage says so. Before, `chat pay`\n * waited 15 s and `chat connect` 25 s for the contact, then answered `engine`. A chat whose invite someone else used\n * first is refused too, with the sentence `send` gives: its contact seals everything to them (`connect` waited 120 s,\n * then answered `timeout`, a code a bot retries).\n */\nexport function inviteTaken(link: LinkView): void {\n somebodyJoined(link);\n if (link.dhtDelivery?.inviteTaken && link.textDelivery !== \"stream\") throw new CliError(\"refused\", INVITE_TAKEN);\n}\n\n/**\n * A chat on DHT only opens no live session: the engine refused `chat connect` as `engine`, \"Both peers must choose a\n * live method first\", which read as if this side had to change something. Refused instead, naming whose choice it is\n * (`details.reason`): the contact's (`peer-dht-only`, nothing to do here but wait), or this side's (`dht-only`).\n */\nexport function dhtOnly(link: LinkView): void {\n if (link.deliveryMode === \"dht\") throw new CliError(\"refused\", \"This chat is on DHT only on this side: choose a live method first (chat transport auto)\", { reason: \"dht-only\" });\n if (link.dhtDelivery?.peerMode === \"dht\") throw new CliError(\"refused\", \"Your contact keeps this chat on DHT only: it goes live once they choose a live method. Short texts still go on the DHT\", { reason: \"peer-dht-only\" });\n}\n\nconst TRANSPORT_TITLES: Record<PairedTransport, string> = { \"webrtc/1\": \"WebRTC\", \"iroh/1\": \"Iroh\", \"hyperdht/1\": \"HyperDHT\" };\n\n/**\n * A transport the chat's Connection menu offers: one this app runs (on DHT only, one it can start), and the contact's\n * app too, by its last word. `chat transport` took any: toward a contact with no WebRTC (`GHOSTLY_WEBRTC=0`) the choice\n * was kept and the chat stayed where it was, saying nothing; for one this app lacks, the engine answered `engine`,\n * \"Transport unavailable\". Refused instead, saying whose app lacks it (`details.reason`, as a chat's wait says it).\n */\nexport function transportOffered(link: LinkView, transport: PairedTransport): void {\n const mine = (link.deliveryMode === \"dht\" ? link.runnableTransports : undefined) ?? link.availableTransports;\n const title = TRANSPORT_TITLES[transport], error = link.transportErrors?.[transport];\n if (mine && !mine.includes(transport)) throw new CliError(\"refused\", `This app has no ${title} running${error ? `: ${error}` : \"\"}`, { reason: \"app-lacks\", transport });\n if (link.peerTransports?.length && !link.peerTransports.includes(transport)) throw new CliError(\"refused\", `Your contact's app doesn't have ${title}: choose another, or auto`, { reason: \"contact-lacks\", transport });\n}\n\n/** A chat or a group as `findChatOrGroup` reads it. `linkId` is what the engine calls it. `s`: as for `chatOf`. */\nexport function chatOrGroup(ctx: ApiContext, ref: string, s?: EngineState): { id: string; linkId: string; group: boolean } {\n const chat = s ? undefined : byId(ctx, ref);\n if (chat) return { id: chat.id, linkId: chat.id, group: false };\n const { links, groups } = s ?? state(ctx);\n const found = findChatOrGroup(links, groups, ref);\n return \"group\" in found ? { id: found.group.id, linkId: `group:${found.group.id}`, group: true } : { id: found.link.id, linkId: found.link.id, group: false };\n}\n\n/**\n * The group a group command names. A chat's id, key or name says it is a chat, with `twin`, the chat command that takes\n * it (`group send` on a chat, where `send` is meant; `<chat>` stands for the ref), else where the groups are listed.\n * It read \"No group\" before. A name nothing has stays that error.\n */\nexport function groupOf(ctx: ApiContext, params: Params, twin?: string): GroupView {\n const ref = str(params, \"group\", true);\n const byId = groupById(ctx, groupPrefixed(ref) ?? ref);\n if (byId) return byId;\n const { links, groups } = state(ctx);\n try { return findGroup(groups, ref); } catch (error) {\n // `group:<ref>` names a group only: never a chat, as in `findChatOrGroup`.\n if (!(error instanceof CliError) || error.code !== \"not_found\" || groupPrefixed(ref) !== null) throw error;\n let chat: LinkView;\n try { chat = findChat(links, ref); } catch { throw error; }\n const shown = shellWord(ref, chat.id);\n throw new CliError(\"not_found\", `${JSON.stringify(ref)} is a chat, not a group${twin ? `: ghostly ${twin.replace(\"<chat>\", shown)}` : \" (ghostly group list)\"}`, { chat: chat.id });\n }\n}\n\n/**\n * The group whose id `id` is, built alone with its members' edges, as `byId` builds a chat: a group's own id names it\n * before anything else does (`findGroup`), and a bot names a group by the id its events give. Undefined for any other\n * ref, which the whole list is read for.\n */\nexport const groupById = (ctx: ApiContext, id: string): GroupView | undefined => node(ctx).groupView(id);\n\n/**\n * A message of a chat or a group (`group:<id>`) named by its id here, read as one row; only a name that is no such\n * row's key (the id both sides know, `wireId`) reads the whole history. `keep`: only a message it accepts (mine, or\n * someone else's). The history is synchronous work on the daemon's one thread, about 120 ms at 10,000 messages.\n */\nexport async function messageOf(ctx: ApiContext, linkId: string, ref: string, keep: (message: StoredMessage) => boolean = () => true): Promise<StoredMessage | undefined> {\n const found = await node(ctx).getMessage(linkId, ref);\n if (found && keep(found)) return found;\n const all = linkId.startsWith(\"group:\") ? await node(ctx).groupMessages({ groupId: linkId.slice(\"group:\".length) }) : await node(ctx).getMessages(linkId);\n return all.find((m) => keep(m) && m.wireId === ref);\n}\n\n// ---------- waiting ----------\n\n/**\n * Resolves with `check`'s first defined answer: now, or on a later state; `timeout` error after `ms`. A check that\n * throws on a later state (`chat wait`'s chat removed) ends the wait with its error: the hub swallows what its\n * listeners throw, and the wait went on to its timeout.\n *\n * `stopping` (a daemon's `ctx.stopping`): the daemon's stop ends it too, as a timeout with `details.reason:\n * \"daemon-stopped\"`, for a wait whose command did something (`file send --wait`) and answers with what it knows. A\n * wait that changes nothing is left to its connection's end, and its client asks it again (main.ts `READ_WAITS`).\n */\nexport function waitForState<T>(ctx: ApiContext, check: (state: EngineState) => T | undefined, ms: number, what: string, stopping?: AbortSignal): Promise<T> {\n const now = check(state(ctx));\n if (now !== undefined) return Promise.resolve(now);\n return new Promise<T>((resolve, reject) => {\n const end = (error: unknown) => { clearTimeout(timer); off(); stopping?.removeEventListener(\"abort\", stopped); if (error) reject(error); };\n const stopped = () => end(new CliError(\"timeout\", `The daemon stopped before the wait ended, waiting for ${what}`, { reason: \"daemon-stopped\" }));\n const timer = setTimeout(() => end(new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s waiting for ${what}`)), ms);\n const off = ctx.hub.onState((next) => {\n let value: T | undefined;\n try { value = check(next); } catch (error) { end(error); return; }\n if (value === undefined) return;\n end(null);\n resolve(value);\n });\n if (stopping?.aborted) stopped();\n else stopping?.addEventListener(\"abort\", stopped, { once: true });\n });\n}\n\n"],"mappings":";;;;;;;;;;;AAMA,IAAM,MAAM;;AAGZ,SAAgB,QAAQ,OAAgB,OAAwB;CAC9D,OAAO,KAAK,UAAU,OAAO,MAAM,KAAK,CAAC,EAAE,QAAQ,MAAM,SAAS,QAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC;AAC5H;;;;;;;;;;;;;ACEA,SAAgB,UAAU,MAAc,SAAyB;CAC/D,IAAI,+BAA+B,KAAK,IAAI,GAAG,OAAO;CACtD,OAAO,KAAK,SAAS,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,KAAK,KAAK,UAAU,IAAI,KAAK;AAClF;;AC+BA,IAAa,QAAQ,QAAiC,IAAI,QAAQ,OAAO;AACzE,IAAa,SAAS,QAAiC,KAAK,GAAG,CAAC,CAAC,SAAS;;AAE1E,IAAa,cAAc,QAA8B,KAAK,GAAG,CAAC,CAAC,YAAY;;;;;;;AAQ/E,IAAI,aAAa;AACjB,IAAa,eAAgB,aAAa,KAAK,IAAI,KAAK,IAAI,GAAG,aAAa,CAAC;AAM7E,SAAgB,IAAI,QAAgB,MAAc,WAAW,OAA2B;CACtF,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,IAAI;EACzD,IAAI,UAAU,MAAM,IAAI,SAAS,eAAe,GAAG,KAAK,aAAa;EACrE;CACF;CACA,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a terminal may act on: DEL and the C1 controls (CSI, OSC, ST, NEL... in UTF-8),\n * the line and paragraph separators, and the bidi marks, embeddings, overrides and isolates that reorder a line. Only\n * a string holds them, and a peer writes some of those strings (a message's text), so the CLI's output writes them as\n * `\\uXXXX`: the same JSON value for every reader, nothing a terminal acts on. What is stored stays whole.\n */\nconst RAW = /[\\u007f-\\u009f\\u061c\\u200e\\u200f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069]/g;\n\n/** `value` as the JSON the CLI prints: `JSON.stringify`, with `RAW` escaped. */\nexport function jsonOut(value: unknown, space?: number): string {\n return JSON.stringify(value, null, space)?.replace(RAW, (char) => \"\\\\u\" + char.charCodeAt(0).toString(16).padStart(4, \"0\"));\n}\n","import { jsonOut } from \"./jsonOut\";\n\n/**\n * A word as a hint offers it to be pasted into a shell: as it is when plain, else single-quoted. JSON's double quotes\n * are no shell quoting: `\"$5 lunch\"` pasted names ` lunch`, and a backtick in it runs a command. A leading `=` stays\n * quoted too (zsh expands `=word` to a command's path). Every \"<name> (2)\" a keep-both hint names has a `(` in it, a\n * syntax error in bash and zsh unquoted.\n *\n * The CLI prints every answer, an error too, as JSON, and a hint is pasted as the terminal shows it: a `'` quoted as\n * `'\\''` read `'\\\\''` there, which ended the quote, and the rest of the word ran as commands (a group's name is its\n * inviter's, a kept-both file's its sender's). A `\"` or a `\\` came out doubled the same way. No shell quoting survives\n * that, so such a word is not offered: `instead` is said, an id that names the same thing or where the details hold it.\n */\nexport function shellWord(word: string, instead: string): string {\n if (/^[\\w@%+:,./-][\\w@%+=:,./-]*$/.test(word)) return word;\n return word.includes(\"'\") || jsonOut(word) !== `\"${word}\"` ? instead : `'${word}'`;\n}\n","import { groupName, INVITE_TAKEN, isZ32Key, MAX_GROUP_NAME_BYTES, MAX_GROUP_NAME_LENGTH, sanitizeDisplayText, type PairedTransport } from \"@ghostly/core\";\nimport type { GhostlyNode } from \"@ghostly/browser/engine/node\";\nimport type { EngineState, GroupView, LinkView, Settings, StoredMessage } from \"@ghostly/browser/shared/types\";\nimport { CliError } from \"./errors\";\nimport { shellWord } from \"./shellWord\";\nimport type { CallManager } from \"./calls/manager\";\nimport type { EventHub } from \"./events\";\nimport type { GroupAutoJoin } from \"./groupAuto\";\nimport type { Runtime } from \"./runtime/engine\";\n\n/**\n * The methods of the local control API (WISP 1100): the daemon answers them over its socket, and a one-shot\n * command calls them in its own process. Parameters come from JSON: every one is checked here.\n */\nexport interface ApiContext {\n runtime: Runtime;\n hub: EventHub;\n /** Voice calls (WISP 1100 § Calls). */\n calls: CallManager;\n /** Group invitations accepted by themselves (`group auto`). */\n groupAuto: GroupAutoJoin;\n /** How the host runs: a daemon stays; a one-shot leaves when its command is done. */\n mode: \"daemon\" | \"one-shot\";\n version: string;\n /** The daemon asks to stop (answered first). */\n stop?: () => void;\n /**\n * Aborted when the daemon stops (`serve().close`): a wait still open answers with what it knows (`waits.ts`), as a\n * timeout with `details.reason: \"daemon-stopped\"`, before the connections end.\n */\n stopping?: AbortSignal;\n /** The daemon is a `listen` that found none and runs the profile itself: a stop ends that listen too. */\n listen?: true;\n}\n\nexport type Params = Record<string, unknown>;\n/** What a call knows of who asked it. */\nexport interface CallScope {\n /**\n * Aborted when the daemon's connection the call came on closes (Ctrl-C on the command, its process gone): nobody\n * reads the answer any more. A call that leaves something behind for its answer (`profile.backup`) stops on it.\n */\n gone?: AbortSignal;\n}\n\nexport type Method = (ctx: ApiContext, params: Params, call?: CallScope) => Promise<unknown>;\n\nexport const node = (ctx: ApiContext): GhostlyNode => ctx.runtime.server.node;\nexport const state = (ctx: ApiContext): EngineState => node(ctx).getState();\n/** The engine's settings, without building `state` (a view of every chat). */\nexport const settingsOf = (ctx: ApiContext): Settings => node(ctx).getSettings();\n\n/**\n * The time of a send the engine names its row after (`me_<timestamp>`: a file, a payment, a request), its own even\n * within one millisecond (a bot paying or sending several times at once over the socket, `file send` run in\n * parallel), or the chat keeps only one. One clock for all of them: they share the row names. A file's resend after a\n * drop finds its row by it, as a forward does.\n */\nlet lastSentAt = 0;\nexport const sentAt = () => (lastSentAt = Math.max(Date.now(), lastSentAt + 1));\n\n// ---------- parameters ----------\n\nexport function str(params: Params, name: string, required: true): string;\nexport function str(params: Params, name: string, required?: false): string | undefined;\nexport function str(params: Params, name: string, required = false): string | undefined {\n const value = params[name];\n if (value === undefined || value === null || value === \"\") {\n if (required) throw new CliError(\"bad_request\", `${name} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") throw new CliError(\"bad_request\", `${name} must be a string`);\n return value;\n}\n/** A number in `[min, max]`; `whole` takes only whole ones (a count of messages), as the engine needs them. */\nexport function num(params: Params, name: string, fallback: number, { min = 0, max = Number.MAX_SAFE_INTEGER, whole = false } = {}): number {\n const value = params[name];\n if (value === undefined || value === null) return fallback;\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) throw new CliError(\"bad_request\", `${name} must be a ${whole ? \"whole \" : \"\"}number from ${min} to ${max}`);\n if (whole && !Number.isSafeInteger(value)) throw new CliError(\"bad_request\", `${name} must be a whole number from ${min} to ${max}`);\n return value;\n}\n/**\n * The seq `events.replay` and `events.subscribe` start after: whole, from 0; `fallback` when left out. A cursor sent as\n * text (\"412\") was a stream from now on the socket with no error, and a negative one a gap of seqs that never were.\n */\nexport function sinceSeq(params: Params, fallback: number): number {\n return num(params, \"since\", fallback, { whole: true });\n}\nexport function bool(params: Params, name: string): boolean {\n const value = params[name];\n if (value === undefined || value === null) return false;\n if (typeof value !== \"boolean\") throw new CliError(\"bad_request\", `${name} must be true or false`);\n return value;\n}\nexport function list(params: Params, name: string): string[] {\n const value = params[name];\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) throw new CliError(\"bad_request\", `${name} must be a list of strings`);\n return value as string[];\n}\n/**\n * One of `values`; `fallback` when it was left out. Given empty (an unset variable in a script: `wallet remove \"\"`), it\n * is refused like any other wrong choice, never read as left out: that acted on the default (the Cashu wallet).\n */\nexport function oneOf<T extends string>(params: Params, name: string, values: readonly T[], fallback: T): T {\n const value = params[name] === \"\" ? \"\" : str(params, name) ?? fallback;\n if (!values.includes(value as T)) throw new CliError(\"bad_request\", `${name} must be one of ${values.join(\", \")}`);\n return value as T;\n}\n\n// ---------- finding things ----------\n\nconst KEY_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\n/**\n * A chat's id as the engine makes it (the first 16 characters of a z-base-32 key) and the CLI prints it as `chat`. A ref\n * so shaped is only ever an id: tested on its `nameKey`, so that a case, a space or an invisible character more is too.\n */\nconst CHAT_ID_SHAPED = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{16}$/;\n/**\n * A contact key as chats show it (`peer`): 52 characters of z-base-32, in its one canonical spelling. The same 52\n * characters with the last one respelled decode to the same bytes but are no key (WISP 02): refused here, so that\n * they never fall through to a chat's name, which its contact chooses.\n */\nexport const CONTACT_KEY = {\n test(ref: string): boolean {\n if (isZ32Key(ref)) return true;\n if (KEY_SHAPED.test(ref)) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} is not a contact key: a key has one spelling, and its last character is not this one`);\n return false;\n },\n};\n\n/**\n * The contact key `ref` is once read as a name is (`nameKey`: trimmed, invisible characters dropped, one case), or\n * undefined for a ref not shaped as one. A key a script or a paste left a line break, a space or capitals on is still\n * that key, and only ever names by key: never a chat, a group or a member by a name someone else chose. Every ref that\n * may be a key is read here, so no caller tests the raw string.\n */\nexport function contactKeyOf(ref: string): string | undefined {\n const key = nameKey(ref);\n return CONTACT_KEY.test(key) ? key : undefined;\n}\n\n/**\n * A chat's label, its contact's name or a group's name as a ref is compared with it: cleaned as the engine cleans a name\n * it stores (`renameLink`, `groupName`: any run of whitespace one space, invisible and direction-changing characters\n * dropped, trimmed), in one Unicode form (NFC) and one case. The string given to `chat rename` or `group create` finds\n * what it named, though what was stored is the cleaned one. Empty when nothing visible is left: that names nothing.\n */\nexport function nameKey(name: string | null | undefined): string {\n if (!name) return \"\";\n return (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\").toLowerCase();\n}\n\n/**\n * A name this side writes (a chat's label, the profile's name, a group's name) cleaned as the engine stores a name\n * (`renameLink`, `groupName`): any run of whitespace (a tab, a line break) one space, invisible and direction-changing\n * characters dropped, trimmed, in NFC: `nameKey` without the case. Counted after that, in code points as the engine\n * counts: undefined past `max`, \"\" when nothing visible is left. Every command that writes a name checks it here, so a\n * tab is a space and not a second line, and a name is never refused at a length it does not have once stored.\n */\nexport function cleanName(name: string, max: number): string | undefined {\n const clean = (sanitizeDisplayText(name.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \") ?? \"\").normalize(\"NFC\");\n return [...clean].length > max ? undefined : clean;\n}\n\n/**\n * `name` as `cleanName` stores it, or the one refusal every name kind gives (`bad_request`), so a chat's, the profile's\n * and a group's name read alike. `subject` starts the sentence (\"A chat's name\", \"nick\"); `empty` follows \"needs a\n * character that shows\" (what an empty name does instead, when it does something). Too long says the count as stored,\n * in code points as the engine counts, and the largest character of several code points in it (a joined emoji or a\n * flag counts as several): the person sees what to cut, and a bot reads `details.length` and `details.max`.\n */\nexport function shownName(name: string, max: number, subject: string, empty = \"\"): string {\n const clean = cleanName(name, Infinity) ?? \"\";\n const length = [...clean].length;\n if (length > max) {\n const widest = [...new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(clean)]\n .map(({ segment }) => segment).reduce((a, b) => ([...b].length > [...a].length ? b : a), \"\");\n const several = [...widest].length > 1 ? `: ${widest} counts as ${[...widest].length}` : \"\";\n throw new CliError(\"bad_request\", `${subject} is up to ${max} characters as stored (this one is ${length}${several})`, { length, max });\n }\n if (!clean) throw new CliError(\"bad_request\", `${subject} needs a character that shows${empty}`);\n return clean;\n}\n\n/**\n * The `name` param of `group create` and `group rename`, refused as a chat's or the profile's name is (`shownName`),\n * then as the engine takes it (`groupName`: the same cleaning, 64 code points, 256 bytes; 64 code points never pass\n * 256 bytes, so its refusal is only a guard). Said here, before anything is made.\n */\nexport function groupNameOf(params: Params): string {\n const name = groupName(shownName(str(params, \"name\", true), MAX_GROUP_NAME_LENGTH, \"A group's name\"));\n if (!name) throw new CliError(\"bad_request\", `A group's name is up to ${MAX_GROUP_NAME_BYTES} bytes as stored`);\n return name;\n}\n\n/** Whether `name` is the one `key` (a ref's `nameKey`) names. */\nconst namedAs = (key: string, name: string | null | undefined) => key !== \"\" && nameKey(name) === key;\n\n/**\n * A chat by its id; by its contact's key (only by the key: a name is never taken for one); by the label this side gave\n * it; and only when no label matches, by a unique prefix of its id or the name the contact gave itself. The contact\n * controls both of those (a joiner's chat id is made from the inviter's code), so neither wins over a label, and a ref\n * that fits one chat's prefix and another's name is refused. A ref shaped as a chat's id is only ever an id, or a label\n * given here. `group:<ref>` is never a chat (a group, as everywhere). A ref\n * that names no chat but one of `groups` says it is a group (see `noChat`).\n */\nexport function findChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n return chatBy(links, ref, groups).link;\n}\n\n/**\n * No chat by `ref`. A group's id, prefix or name (or `group:<id>`) says it is a group, as `groupOf` says a chat is one:\n * `chat connect`, `identity share`, `call start` and the other commands that take only a 1:1 chat read `No chat \"Crew\"`,\n * as if nothing had that name.\n */\nfunction noChat(ref: string, groups: readonly GroupView[]): CliError {\n const group = groupNamed(ref, groups);\n if (group) return new CliError(\"not_found\", `${JSON.stringify(ref)} is a group, not a chat (ghostly chat list)`, { group: group.id });\n return new CliError(\"not_found\", `No chat ${JSON.stringify(ref)} (ghostly chat list)`);\n}\n\n/** A chat or group ref as a next step shows it: as given, quoted only when it holds more than a word (see `shellWord`). */\nconst shownRef = (place: RefPlace) => shellWord(place.ref, place.group ? \"<group>\" : \"<chat>\");\n\n/** The chat or the group a message or a file was looked for in, as the command was given it (`ref`). */\nexport type RefPlace = { group: boolean; ref: string };\n\n/**\n * No message by `id` in a chat or a group, said one way by every command that takes one, as `noChat` says a chat: the id\n * quoted as given, and where the ids are. `whose` (\"of yours\", \"from someone else\") is what it had to be; `tail` what\n * else it may have failed for (\", or it takes no reaction\", \": only your own messages are sent again\").\n */\nexport function noMessage(id: string, place: RefPlace, { whose, tail }: { whose?: string; tail?: string } = {}): CliError {\n const history = `ghostly ${place.group ? \"group\" : \"chat\"} history ${shownRef(place)}`;\n return new CliError(\"not_found\", `No message ${JSON.stringify(id)}${whose ? ` ${whose}` : \"\"} in this ${place.group ? \"group\" : \"chat\"}${tail ?? \"\"} (${history})`);\n}\n\n/** No file by `id`, as `noMessage` says a message: in the chat or group named (`place`), or in none when none was. */\nexport function noFile(id: string, place?: RefPlace): CliError {\n const where = place ? ` in this ${place.group ? \"group\" : \"chat\"}` : \"\";\n return new CliError(\"not_found\", `No file ${JSON.stringify(id)}${where} (ghostly file list ${place ? shownRef(place) : \"<chat|group>\"})`);\n}\n\n/** The one group `ref` names, if any (none, or more than one: undefined). */\nfunction groupNamed(ref: string, groups: readonly GroupView[]): GroupView | undefined {\n try { return findGroup(groups, ref); } catch { return undefined; }\n}\n\n/** `findChat`, and whether only what the contact controls (`theirName`: a prefix of the id, its own name) found the chat. */\nfunction chatBy(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): { link: LinkView; theirName: boolean } {\n // \"\" (an unset variable in a script) is a prefix of every id: it took the only chat.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names no chat`);\n const exact = links.find((link) => link.id === ref);\n if (exact) return { link: exact, theirName: false };\n const contact = contactKeyOf(ref);\n if (contact !== undefined) {\n const byKey = links.filter((link) => link.peerPubKeyZ32 === contact);\n if (byKey.length === 1) return { link: byKey[0], theirName: false };\n if (byKey.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: byKey.map((link) => link.id) });\n throw new CliError(\"not_found\", `No chat with ${JSON.stringify(ref)} (ghostly chat list)`);\n }\n const key = nameKey(ref);\n const named = (name: string | null | undefined) => namedAs(key, name);\n const byLabel = links.filter((link) => named(link.label));\n // `group:<ref>` names a group (`groupPrefixed`), never a chat: not by a name its contact chose, nor by a label given\n // here (a chat labelled `group:Crew` was that chat for `chat show` and the group Crew for `send`). A chat labelled so\n // before labels were refused (`chatName`) is named by its id.\n if (groupPrefixed(ref) !== null) {\n if (byLabel.length && !groupNamed(ref, groups)) throw new CliError(\"not_found\", `${JSON.stringify(ref)} names a group, never a chat: name the chat labelled so by its id, and give it another name (ghostly chat rename <chat> <name>)`, { matches: byLabel.map((link) => link.id) });\n throw noChat(ref, groups);\n }\n // A chat's id no chat has (one removed since: a bot kept it from an event) is no chat. Its contact and whoever saw its\n // invite know it, so another contact could call itself that and take every later command sent by it. A label given\n // here still names the chat: only this side chooses it.\n if (!byLabel.length && CHAT_ID_SHAPED.test(key)) throw noChat(ref, groups);\n const found = byLabel.length ? byLabel : [...new Set([...links.filter((link) => link.id.startsWith(ref)), ...links.filter((link) => named(link.peerNick))])];\n if (found.length === 1) return { link: found[0], theirName: !byLabel.length };\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names more than one chat: use its id`, { matches: found.map((link) => link.id) });\n throw noChat(ref, groups);\n}\n\n/**\n * `findChat` for a grant the daemon keeps acting on (`call auto on --from`): only the chat's id, its contact's key or the\n * label this side gave it name the chat. A prefix of its id or the name its contact gave itself is refused, with the\n * chat it found: the contact chose those, so another contact could take the grant by calling itself that name.\n */\nexport function findOwnNamedChat(links: readonly LinkView[], ref: string, groups: readonly GroupView[] = []): LinkView {\n const chat = chatBy(links, ref, groups);\n if (chat.theirName) throw namedByThem(ref, { chat: chat.link.id, name: chat.link.peerNick ?? null, contact: chat.link.peerPubKeyZ32 });\n return chat.link;\n}\n\n/** `findOwnNamedChat`'s refusal: `ref` found `chat` only by what its contact chose. */\nexport function namedByThem(ref: string, chat: { chat: string; name: string | null; contact: string | undefined }): CliError {\n return new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat only by what its contact chose (a prefix of its id, its own name): use the chat's id, its contact's key or a label given here (ghostly chat rename <chat> <name>)`, chat);\n}\n\n/**\n * `group:<ref>`, the form that names a group wherever a group is taken (docs/CLI.md § What it does): `<ref>`, read as any\n * other ref (`findGroup`: an id, a prefix of it or a name). Null for a ref without it. `findGroup` and `findChatOrGroup`\n * both read the prefix here, so a group command and a command that takes a chat or a group never read it apart.\n */\nexport const groupPrefixed = (ref: string): string | null => (ref.startsWith(\"group:\") ? ref.slice(\"group:\".length) : null);\n\n/** Only an invitation so far: this profile is not in the group (yet), and whoever invited chose its name. */\nconst invitedOnly = (group: GroupView) => group.status === undefined && !!group.invitation;\n\n/**\n * A group by its id, by its name, or by a unique prefix of its id. Whoever created a group chose its id and its admin\n * chooses its name, so neither wins over the other: a ref that is one group's name and another's prefix is refused,\n * with both ids, as `chatBy` does for chats. A group this profile is in wins over an invitation with the same name or\n * prefix (the one who invites chooses those); an invitation is still found by its id, and by name or prefix where no\n * group of this profile has it. `group:<ref>` is `<ref>` (`groupPrefixed`); before, only the commands that take a chat\n * or a group read it, and every group command and `listen --group` answered it `No group`.\n */\nexport function findGroup(groups: readonly GroupView[], given: string): GroupView {\n const ref = groupPrefixed(given) ?? given;\n // Each refusal echoes the ref as given (`\"group:k86q\"`), not the part after `group:`: what the person typed.\n if (!ref.trim()) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names no group`);\n const exact = groups.find((group) => group.id === ref);\n if (exact) return exact;\n const key = nameKey(ref);\n for (const among of [groups.filter((group) => !invitedOnly(group)), groups.filter(invitedOnly)]) {\n const found = among.filter((group) => namedAs(key, group.name) || group.id.startsWith(ref));\n if (found.length === 1) return found[0];\n if (found.length > 1) throw new CliError(\"bad_request\", `${JSON.stringify(given)} names more than one group: use its id`, { matches: found.map((group) => group.id) });\n }\n throw new CliError(\"not_found\", `No group ${JSON.stringify(given)} (ghostly group list)`);\n}\n\n/**\n * A chat or a group, where a command takes either: `group:<id>` is a group; anything else a chat first (`findChat`),\n * then a group. A chat found only by what its contact chose (a prefix of its id, its own name) never takes what also\n * names a group: a group's\n * own id is that group, and a prefix or the name of a group this profile is in is refused, with both ids. With neither,\n * one `not_found` names both and where to look (a contact's key: no chat with it); a name that matches more than one\n * chat or group stays that error.\n */\nexport function findChatOrGroup(links: readonly LinkView[], groups: readonly GroupView[], ref: string): { link: LinkView } | { group: GroupView } {\n if (groupPrefixed(ref) !== null) return { group: findGroup(groups, ref) };\n let chat: ReturnType<typeof chatBy>;\n try {\n chat = chatBy(links, ref);\n } catch (error) {\n if (!(error instanceof CliError) || error.code !== \"not_found\") throw error;\n // Nor is it a group's name or a prefix of a group's id (its admin and its creator chose those; a group's own id is\n // longer), nor is a contact's key with no chat: `group:<ref>` names a group.\n if (CHAT_ID_SHAPED.test(nameKey(ref)) || contactKeyOf(ref) !== undefined) throw error;\n try { return { group: findGroup(groups, ref) }; } catch (inner) {\n if (!(inner instanceof CliError) || inner.code !== \"not_found\") throw inner;\n throw new CliError(\"not_found\", `No chat or group ${JSON.stringify(ref)} (ghostly chat list, ghostly group list)`);\n }\n }\n if (!chat.theirName) return { link: chat.link };\n const exact = groups.find((group) => group.id === ref);\n if (exact) return { group: exact };\n const key = nameKey(ref);\n const also = groups.filter((group) => !invitedOnly(group) && (group.id.startsWith(ref) || namedAs(key, group.name)));\n if (also.length) throw new CliError(\"bad_request\", `${JSON.stringify(ref)} names a chat (by what its contact chose) and a group: use the chat's id or group:<id>`, { chat: chat.link.id, groups: also.map((group) => group.id) });\n return { link: chat.link };\n}\n\n/**\n * Starts the chats and groups a call names (its `chat`, a forward's `to`, its `group`) in a runtime that left the saved\n * chats and the groups' edges unstarted (`RuntimeOptions.deferChats`). A ref that names nothing starts nothing: the\n * call says so itself.\n */\nexport async function startNamedChats(ctx: ApiContext, params: Params): Promise<void> {\n const { links, groups } = state(ctx);\n for (const ref of [params.chat, ...(Array.isArray(params.to) ? params.to : [])]) {\n if (typeof ref !== \"string\") continue;\n let found: ReturnType<typeof findChatOrGroup>;\n try { found = findChatOrGroup(links, groups, ref); } catch { continue; }\n if (\"link\" in found) await node(ctx).startDeferredChat(found.link.id);\n else node(ctx).startDeferredGroup(found.group.id);\n }\n if (typeof params.group === \"string\") {\n try { node(ctx).startDeferredGroup(findGroup(groups, params.group).id); } catch { /* the call says so itself */ }\n }\n}\n\n/**\n * The chat a call names. `s`: a state the call built already. Each build is a view of every chat (about 15-20 µs a\n * chat, on the daemon's one thread): one lookup builds one, never one per list it reads.\n */\nexport function chatOf(ctx: ApiContext, params: Params, s?: EngineState): LinkView {\n const ref = str(params, \"chat\", true);\n if (!s) { const chat = byId(ctx, ref); if (chat) return chat; }\n const { links, groups } = s ?? state(ctx);\n return findChat(links, ref, groups);\n}\n/** `findOwnNamedChat` for the chat a call names, as `chatOf`. */\nexport function ownChatOf(ctx: ApiContext, params: Params, s?: EngineState): LinkView {\n const ref = str(params, \"chat\", true);\n if (!s) { const chat = byId(ctx, ref); if (chat) return chat; }\n const { links, groups } = s ?? state(ctx);\n return findOwnNamedChat(links, ref, groups);\n}\n/**\n * The chat whose id `ref` is, built alone: a chat's own id names it before anything else does (`chatBy`), and a bot\n * names its chats by the ids its events give. Undefined for any other ref, which the whole list is read for.\n */\nconst byId = (ctx: ApiContext, ref: string): LinkView | undefined => node(ctx).chatView(ref);\n\n/** A chat of mine whose invite nobody took yet: no contact's key, so nothing goes out until they join. */\nexport const nobodyJoined = (link: LinkView): boolean => !!(link.profile && link.inviteCode && !link.peerParticipationKey);\n\n/**\n * `nobodyJoined` by the chat's id: a group's (`group:<id>`) is never one. That chat's view alone: every card send or\n * update, `file send` and unconfirmed edit asks it, and built every chat for it (once in a daemon, up to three times\n * in a one-shot `usage send`).\n */\nexport const nobodyJoinedChat = (ctx: ApiContext, chat: string): boolean => {\n const link = byId(ctx, chat);\n return !!link && nobodyJoined(link);\n};\n\n/**\n * Whether a one-shot waits by default on what it did in a 1:1 chat: it leaves with its process, so it stays until that\n * went out or the contact confirmed it. Not on a chat nobody joined yet: there is no one to wait for, and `edit`, `react`,\n * `pin`, a card or a file sat their whole wait (a file 300 s), then failed `timeout`, exit 4, which a bot retries: one\n * more card or file each time. What was done is kept and goes once they join; the answer says so (`keptForJoin`).\n */\nexport const oneShotWaits = (ctx: ApiContext, chat: string): boolean => ctx.mode === \"one-shot\" && !nobodyJoinedChat(ctx, chat);\n\n/** An answer's `note` on a chat nobody joined yet: `what` is kept and goes once they join. Nothing on any other chat. */\nexport const keptForJoin = (ctx: ApiContext, chat: string, what: string): { note?: string } => nobodyJoinedChat(ctx, chat)\n ? { note: `Nobody joined this chat yet: ${what} goes once they join${ctx.mode === \"one-shot\" ? \" while this profile is online (`ghostly daemon --detach`)\" : \"\"}` }\n : {};\n\n/**\n * A chat whose invite nobody took yet has no session to close either: `chat disconnect` answered done with the chat at\n * `connecting`, and `--hold` put the waiting invite on DHT only (a one-shot answered `pairing: error`).\n */\nexport function somebodyJoined(link: LinkView): void {\n if (nobodyJoined(link)) throw new CliError(\"unavailable\", \"Nobody joined this chat yet: its invite is still waiting to be taken\");\n}\n\n/**\n * A chat whose invite nobody took yet: nobody is there to pay or to dial, and its stage says so. Before, `chat pay`\n * waited 15 s and `chat connect` 25 s for the contact, then answered `engine`. A chat whose invite someone else used\n * first is refused too, with the sentence `send` gives: its contact seals everything to them (`connect` waited 120 s,\n * then answered `timeout`, a code a bot retries).\n */\nexport function inviteTaken(link: LinkView): void {\n somebodyJoined(link);\n if (link.dhtDelivery?.inviteTaken && link.textDelivery !== \"stream\") throw new CliError(\"refused\", INVITE_TAKEN);\n}\n\n/**\n * A chat on DHT only opens no live session: the engine refused `chat connect` as `engine`, \"Both peers must choose a\n * live method first\", which read as if this side had to change something. Refused instead, naming whose choice it is\n * (`details.reason`): the contact's (`peer-dht-only`, nothing to do here but wait), or this side's (`dht-only`).\n */\nexport function dhtOnly(link: LinkView): void {\n if (link.deliveryMode === \"dht\") throw new CliError(\"refused\", \"This chat is on DHT only on this side: choose a live method first (chat transport auto)\", { reason: \"dht-only\" });\n if (link.dhtDelivery?.peerMode === \"dht\") throw new CliError(\"refused\", \"Your contact keeps this chat on DHT only: it goes live once they choose a live method. Short texts still go on the DHT\", { reason: \"peer-dht-only\" });\n}\n\nconst TRANSPORT_TITLES: Record<PairedTransport, string> = { \"webrtc/1\": \"WebRTC\", \"iroh/1\": \"Iroh\", \"hyperdht/1\": \"HyperDHT\" };\n\n/**\n * A transport the chat's Connection menu offers: one this app runs (on DHT only, one it can start), and the contact's\n * app too, by its last word. `chat transport` took any: toward a contact with no WebRTC (`GHOSTLY_WEBRTC=0`) the choice\n * was kept and the chat stayed where it was, saying nothing; for one this app lacks, the engine answered `engine`,\n * \"Transport unavailable\". Refused instead, saying whose app lacks it (`details.reason`, as a chat's wait says it).\n */\nexport function transportOffered(link: LinkView, transport: PairedTransport): void {\n const mine = (link.deliveryMode === \"dht\" ? link.runnableTransports : undefined) ?? link.availableTransports;\n const title = TRANSPORT_TITLES[transport], error = link.transportErrors?.[transport];\n if (mine && !mine.includes(transport)) throw new CliError(\"refused\", `This app has no ${title} running${error ? `: ${error}` : \"\"}`, { reason: \"app-lacks\", transport });\n if (link.peerTransports?.length && !link.peerTransports.includes(transport)) throw new CliError(\"refused\", `Your contact's app doesn't have ${title}: choose another, or auto`, { reason: \"contact-lacks\", transport });\n}\n\n/** A chat or a group as `findChatOrGroup` reads it. `linkId` is what the engine calls it. `s`: as for `chatOf`. */\nexport function chatOrGroup(ctx: ApiContext, ref: string, s?: EngineState): { id: string; linkId: string; group: boolean } {\n const chat = s ? undefined : byId(ctx, ref);\n if (chat) return { id: chat.id, linkId: chat.id, group: false };\n const { links, groups } = s ?? state(ctx);\n const found = findChatOrGroup(links, groups, ref);\n return \"group\" in found ? { id: found.group.id, linkId: `group:${found.group.id}`, group: true } : { id: found.link.id, linkId: found.link.id, group: false };\n}\n\n/**\n * The group a group command names. A chat's id, key or name says it is a chat, with `twin`, the chat command that takes\n * it (`group send` on a chat, where `send` is meant; `<chat>` stands for the ref), else where the groups are listed.\n * It read \"No group\" before. A name nothing has stays that error.\n */\nexport function groupOf(ctx: ApiContext, params: Params, twin?: string): GroupView {\n const ref = str(params, \"group\", true);\n const byId = groupById(ctx, groupPrefixed(ref) ?? ref);\n if (byId) return byId;\n const { links, groups } = state(ctx);\n try { return findGroup(groups, ref); } catch (error) {\n // `group:<ref>` names a group only: never a chat, as in `findChatOrGroup`.\n if (!(error instanceof CliError) || error.code !== \"not_found\" || groupPrefixed(ref) !== null) throw error;\n let chat: LinkView;\n try { chat = findChat(links, ref); } catch { throw error; }\n const shown = shellWord(ref, chat.id);\n throw new CliError(\"not_found\", `${JSON.stringify(ref)} is a chat, not a group${twin ? `: ghostly ${twin.replace(\"<chat>\", shown)}` : \" (ghostly group list)\"}`, { chat: chat.id });\n }\n}\n\n/**\n * The group whose id `id` is, built alone with its members' edges, as `byId` builds a chat: a group's own id names it\n * before anything else does (`findGroup`), and a bot names a group by the id its events give. Undefined for any other\n * ref, which the whole list is read for.\n */\nexport const groupById = (ctx: ApiContext, id: string): GroupView | undefined => node(ctx).groupView(id);\n\n/**\n * A message of a chat or a group (`group:<id>`) named by its id here, read as one row; only a name that is no such\n * row's key (the id both sides know, `wireId`) reads the whole history. `keep`: only a message it accepts (mine, or\n * someone else's). The history is synchronous work on the daemon's one thread, about 120 ms at 10,000 messages.\n */\nexport async function messageOf(ctx: ApiContext, linkId: string, ref: string, keep: (message: StoredMessage) => boolean = () => true): Promise<StoredMessage | undefined> {\n const found = await node(ctx).getMessage(linkId, ref);\n if (found && keep(found)) return found;\n const all = linkId.startsWith(\"group:\") ? await node(ctx).groupMessages({ groupId: linkId.slice(\"group:\".length) }) : await node(ctx).getMessages(linkId);\n return all.find((m) => keep(m) && m.wireId === ref);\n}\n\n// ---------- waiting ----------\n\n/**\n * Resolves with `check`'s first defined answer: now, or on a later state; `timeout` error after `ms`. A check that\n * throws on a later state (`chat wait`'s chat removed) ends the wait with its error: the hub swallows what its\n * listeners throw, and the wait went on to its timeout.\n *\n * `stopping` (a daemon's `ctx.stopping`): the daemon's stop ends it too, as a timeout with `details.reason:\n * \"daemon-stopped\"`, for a wait whose command did something (`file send --wait`) and answers with what it knows. A\n * wait that changes nothing is left to its connection's end, and its client asks it again (main.ts `READ_WAITS`).\n */\nexport function waitForState<T>(ctx: ApiContext, check: (state: EngineState) => T | undefined, ms: number, what: string, stopping?: AbortSignal): Promise<T> {\n const now = check(state(ctx));\n if (now !== undefined) return Promise.resolve(now);\n return new Promise<T>((resolve, reject) => {\n const end = (error: unknown) => { clearTimeout(timer); off(); stopping?.removeEventListener(\"abort\", stopped); if (error) reject(error); };\n const stopped = () => end(new CliError(\"timeout\", `The daemon stopped before the wait ended, waiting for ${what}`, { reason: \"daemon-stopped\" }));\n const timer = setTimeout(() => end(new CliError(\"timeout\", `Timed out after ${Math.round(ms / 1000)} s waiting for ${what}`)), ms);\n const off = ctx.hub.onState((next) => {\n let value: T | undefined;\n try { value = check(next); } catch (error) { end(error); return; }\n if (value === undefined) return;\n end(null);\n resolve(value);\n });\n if (stopping?.aborted) stopped();\n else stopping?.addEventListener(\"abort\", stopped, { once: true });\n });\n}\n\n"],"mappings":";;;;;;;;;;;AAMA,IAAM,MAAM;;AAGZ,SAAgB,QAAQ,OAAgB,OAAwB;CAC9D,OAAO,KAAK,UAAU,OAAO,MAAM,KAAK,CAAC,EAAE,QAAQ,MAAM,SAAS,QAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC;AAC5H;;;;;;;;;;;;;ACEA,SAAgB,UAAU,MAAc,SAAyB;CAC/D,IAAI,+BAA+B,KAAK,IAAI,GAAG,OAAO;CACtD,OAAO,KAAK,SAAS,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,KAAK,KAAK,UAAU,IAAI,KAAK;AAClF;;AC+BA,IAAa,QAAQ,QAAiC,IAAI,QAAQ,OAAO;AACzE,IAAa,SAAS,QAAiC,KAAK,GAAG,CAAC,CAAC,SAAS;;AAE1E,IAAa,cAAc,QA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KAAK;IAAG;GAAQ;GACjE,IAAI,UAAU,KAAA,GAAW;GACzB,IAAI,IAAI;GACR,QAAQ,KAAK;EACf,CAAC;EACD,IAAI,UAAU,SAAS,QAAQ;OAC1B,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAClE,CAAC;AACH"}
@@ -1,6 +1,6 @@
1
1
  import { l as toBase64Url, u as toZ32 } from "./bytes-C1DNGY18.js";
2
2
  import { x as sign } from "./pkarr-BQo4PcCg.js";
3
- import { Ba as readAppSignature, Da as APP_PREFIXES, Fa as isAppLine, Ga as verifyAppSignature, Ha as signAppObject, Ia as isAppRef, Na as isAppHash, Pa as isAppKey, Ra as readAppRevocationShape, Sa as isAppUrl, Wa as verifyAppRevocation, Xa as canonicalJsonBytes, Za as readCanonicalJson, ja as appRefPublisher, xa as findAppForbiddenKey } from "./groupMeta-DTQAJG50.js";
3
+ import { Ca as isAppUrl, Fa as isAppKey, Ga as verifyAppRevocation, Ia as isAppLine, Ka as verifyAppSignature, La as isAppRef, Ma as appRefPublisher, Oa as APP_PREFIXES, Pa as isAppHash, Qa as readCanonicalJson, Sa as findAppForbiddenKey, Ua as signAppObject, Va as readAppSignature, Za as canonicalJsonBytes, za as readAppRevocationShape } from "./groupMeta-DxuJzko_.js";
4
4
  import { ed25519 } from "@noble/curves/ed25519.js";
5
5
  import { sha256 } from "@noble/hashes/sha2.js";
6
6
  // ../core/src/signer.ts
@@ -599,4 +599,4 @@ function besideUrl(url, name) {
599
599
  }
600
600
  export { webCryptoSigner as S, readAppStore as _, besideUrl as a, signAppStore as b, isGitHubPage as c, appStoreDecision as d, appUpdateDecision as f, checkAppStoreIndex as g, APP_STORE_LIMITS as h, appPasteUrl as i, addedAppPermissions as l, planAppUpdate as m, APP_FETCH_LIMITS as n, boundedAppFetch as o, checkAppBeforeRun as p, AppFetchError as r, isAppFetchUrl as s, APP_FETCH_HOSTS as t, appRevocationFor as u, readAppStoreSteps as v, seedSigner as x, repeatedJsonKey as y };
601
601
 
602
- //# sourceMappingURL=appFetch-D56GsYuq.js.map
602
+ //# sourceMappingURL=appFetch-CW9fJPHh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"appFetch-D56GsYuq.js","names":[],"sources":["../../../core/src/signer.ts","../../../core/src/appStore.ts","../../../core/src/appUpdates.ts","../../../browser/src/engine/appFetch.ts"],"sourcesContent":["import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { sign } from \"./identity\";\n\n/*\n * A signer (WISP 06 § Terms): an Ed25519 key that signs without the caller holding its seed. The device signing key\n * is non-extractable where WebCrypto offers Ed25519, so the app has no bytes to sign with; where it does not, the key\n * is a stored seed. Both are this one interface, and so is a chat's participation seed when a session is given one.\n *\n * Signing is asynchronous because WebCrypto is. The public key is known at once: a session puts it in its offer\n * before it signs anything.\n */\nexport interface Signer {\n /** The Ed25519 public key, 32 bytes. */\n readonly publicKey: Uint8Array;\n /** The 64-byte signature of `bytes`. */\n sign(bytes: Uint8Array): Promise<Uint8Array>;\n}\n\n/** A seed held by the app, as every key of a profile is today. */\nexport function seedSigner(seed: Uint8Array): Signer {\n if (seed.length !== 32) throw new Error(\"Seed must be exactly 32 bytes\");\n const publicKey = ed25519.getPublicKey(seed);\n return { publicKey, sign: async (bytes) => sign(bytes, seed) };\n}\n\n/**\n * A WebCrypto Ed25519 private key, non-extractable or not, with its raw public key. The app never sees the private\n * bytes: `crypto.subtle` signs.\n */\nexport function webCryptoSigner(privateKey: CryptoKey, publicKey: Uint8Array): Signer {\n if (publicKey.length !== 32) throw new Error(\"An Ed25519 public key is 32 bytes\");\n return {\n publicKey,\n sign: async (bytes) => new Uint8Array(await crypto.subtle.sign({ name: \"Ed25519\" }, privateKey, new Uint8Array(bytes))),\n };\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, toZ32 } from \"./bytes\";\nimport { canonicalJsonBytes, readCanonicalJson, type JsonValue } from \"./canonicalJson\";\nimport { findAppForbiddenKey, isAppUrl } from \"./appBundle\";\nimport {\n APP_PREFIXES, isAppHash, isAppKey, isAppLine, isAppRef, readAppRevocationShape, readAppSignature, signAppObject, verifyAppRevocation, verifyAppSignature,\n type AppRevocationsChecked, type AppSignature, type SignedAppRevocation,\n} from \"./appStatements\";\nimport type { Signer } from \"./signer\";\n\n/*\n * A store index (WISP 1200 · Stores): `ghostly-store.json`, canonical JSON, signed by the store key under\n * `ghostly-store/1` in `ghostly-store.sig` beside it (the same statement as a bundle's). It lists apps by reference and\n * digest, the versions it removed, and publishers' revocations copied verbatim. Times are Unix seconds.\n *\n * A store lists and ranks; it never changes what installs: the bundle a listing points at is checked on its own, and\n * its icon and description come from the bundle. `listing.json` in a store's repository is one entry of `apps`.\n */\n\nexport const APP_STORE_LIMITS = {\n /** The index's bytes, uncompressed. */\n indexBytes: 16 * 1024 * 1024,\n /** How far ahead `expires` may be. */\n expiresAheadS: 90 * 24 * 60 * 60,\n name: 40,\n description: 2000,\n title: 40,\n tagline: 80,\n /** `category`, `developer`, `submitter`. */\n label: 40,\n reason: 200,\n urls: 4,\n apps: 4096,\n removed: 4096,\n revoked: 4096,\n} as const;\n\nexport const APP_STORE_KINDS = [\"curated\", \"indexed\"] as const;\nexport type AppStoreKind = typeof APP_STORE_KINDS[number];\n\nexport interface AppListing {\n ref: string;\n sequence: number;\n digest: string;\n urls: string[];\n title: string;\n tagline: string;\n category?: string;\n developer?: string;\n submitter?: string;\n repo?: string;\n support?: string;\n}\nexport interface AppRemoval { ref: string; digest: string; reason: string; at: number }\nexport interface AppStoreIndex {\n ghostlyStore: 1;\n key: string;\n name: string;\n description?: string;\n kind: AppStoreKind;\n sequence: number;\n expires: number;\n apps: AppListing[];\n removed: AppRemoval[];\n revoked: SignedAppRevocation[];\n}\n\nexport type AppStoreRefusal =\n | \"too-large\" | \"not-json\" | \"not-canonical\" | \"unsupported-format\" | \"unknown-key\" | \"missing-key\" | \"bad-field\"\n | \"duplicate-app\" | \"bad-signature-statement\" | \"signature-key\" | \"bad-signature\" | \"store-key\" | \"expires-too-far\"\n | \"bad-revocation\";\n\nconst isObject = (v: unknown): v is Record<string, JsonValue> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst isText = (v: unknown, max: number): v is string => typeof v === \"string\" && [...v].length <= max && !/[^\\P{Cc}\\n]/u.test(v);\nconst isCount = (v: unknown, min: number): v is number => typeof v === \"number\" && Number.isSafeInteger(v) && v >= min;\n\ntype Check = { ok: true } | { ok: false; reason: AppStoreRefusal; detail?: string };\nconst fine: Check = { ok: true };\n\n/**\n * How a check treats a key it does not know. A reader (`readAppStore`, the client) ignores it, so a later format can\n * add an optional key without a client refusing the whole signed index; the signature still covers the bytes as they\n * are, unknown keys included. A writer (`signAppStore`, the CLI, a store's check of a `listing.json` through\n * `readAppListing`) passes `strict` and refuses it, so a misspelt key is caught before anything is signed. Required\n * keys, their types and their bounds hold in both, and `APP_FORBIDDEN_KEYS` are refused in both, at any level.\n */\nexport interface AppFormatOptions { strict?: boolean }\n\nfunction keysOf(value: Record<string, unknown>, required: readonly string[], optional: readonly string[], options: AppFormatOptions = {}): Check {\n // `__proto__` and its kin are refused in both modes, at any level (`findAppForbiddenKey`): a reader keeps what it ignores.\n const forbidden = findAppForbiddenKey(value);\n if (forbidden !== undefined) return { ok: false, reason: \"unknown-key\", detail: forbidden };\n for (const k of Object.keys(value)) {\n if (options.strict && !required.includes(k) && !optional.includes(k)) return { ok: false, reason: \"unknown-key\", detail: k };\n }\n for (const k of required) if (!(k in value)) return { ok: false, reason: \"missing-key\", detail: k };\n return fine;\n}\n\nconst LISTING_REQUIRED = [\"ref\", \"sequence\", \"digest\", \"urls\", \"title\", \"tagline\"] as const;\nconst LISTING_OPTIONAL = [\"category\", \"developer\", \"submitter\", \"repo\", \"support\"] as const;\n\n/** Checks one entry of `apps`, which is also the whole of a `listing.json`. An unknown key is ignored unless `strict`. */\nexport function checkAppListing(value: unknown, options: AppFormatOptions = {}): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A listing is not an object\" };\n const keys = keysOf(value, LISTING_REQUIRED, LISTING_OPTIONAL, options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: `apps: ${field}` });\n if (!isAppRef(value.ref)) return bad(\"ref\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isAppHash(value.digest)) return bad(\"digest\");\n const urls = value.urls;\n if (!Array.isArray(urls) || urls.length < 1 || urls.length > APP_STORE_LIMITS.urls || !urls.every(isAppUrl)) return bad(\"urls\");\n if (!isAppLine(value.title, APP_STORE_LIMITS.title, 1)) return bad(\"title\");\n if (!isAppLine(value.tagline, APP_STORE_LIMITS.tagline, 1)) return bad(\"tagline\");\n for (const k of [\"category\", \"developer\", \"submitter\"] as const) if (value[k] !== undefined && !isAppLine(value[k], APP_STORE_LIMITS.label, 1)) return bad(k);\n for (const k of [\"repo\", \"support\"] as const) if (value[k] !== undefined && !isAppUrl(value[k])) return bad(k);\n return fine;\n}\n\n/**\n * The first object key `text` writes twice in one object, as JSON.parse reads it (`\"title\"` is `title`), or null.\n * `text` is JSON that JSON.parse already took: one pass, each string read to its closing quote.\n */\nexport function repeatedJsonKey(text: string): string | null {\n /** Each open object's keys so far; null for an array. */\n const open: (Set<string> | null)[] = [];\n let keyNext = false;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (c === \"\\\"\") {\n let end = i + 1;\n while (text[end] !== \"\\\"\") end += text[end] === \"\\\\\" ? 2 : 1;\n const keys = open[open.length - 1];\n if (keys && keyNext) {\n const key = JSON.parse(text.slice(i, end + 1)) as string;\n if (keys.has(key)) return key;\n keys.add(key);\n keyNext = false;\n }\n i = end;\n } else if (c === \"{\") { open.push(new Set()); keyNext = true; }\n else if (c === \"[\") open.push(null);\n else if (c === \"}\" || c === \"]\") open.pop();\n else if (c === \",\") keyNext = open[open.length - 1] !== null;\n }\n return null;\n}\n\n/**\n * Reads a `listing.json`: JSON holding exactly one listing (written by hand in release 1.2, so not required canonical).\n * A store reads it, as a writer: strict by default, so a misspelt key is refused before the owner signs the index (the\n * client never reads a `listing.json`, only the signed index). `{ strict: false }` reads it as a client reads an index\n * entry, ignoring a later key.\n */\nexport function readAppListing(text: string, options: AppFormatOptions = { strict: true }): { ok: true; listing: AppListing } | { ok: false; reason: AppStoreRefusal; detail?: string } {\n let value: unknown;\n try { value = JSON.parse(text); } catch (error) { return { ok: false, reason: \"not-json\", detail: String(error) }; }\n // JSON.parse keeps a key's last value, where a person reading the file sees the first: strict, both are refused.\n const twice = options.strict ? repeatedJsonKey(text) : null;\n if (twice !== null) return { ok: false, reason: \"not-json\", detail: `${JSON.stringify(twice)} is written twice` };\n const checked = checkAppListing(value, options);\n return checked.ok ? { ok: true, listing: value as AppListing } : checked;\n}\n\nfunction checkRemoval(value: unknown, options: AppFormatOptions): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A removal is not an object\" };\n const keys = keysOf(value, [\"ref\", \"digest\", \"reason\", \"at\"], [], options);\n if (!keys.ok) return keys;\n if (!isAppRef(value.ref) || !isAppHash(value.digest) || !isAppLine(value.reason, APP_STORE_LIMITS.reason, 1) || !isCount(value.at, 0)) {\n return { ok: false, reason: \"bad-field\", detail: \"removed: not {ref, digest, reason, at}\" };\n }\n return fine;\n}\n\nconst STORE_REQUIRED = [\"ghostlyStore\", \"key\", \"name\", \"kind\", \"sequence\", \"expires\", \"apps\", \"removed\", \"revoked\"] as const;\n\n/** Runs a check written in steps to its end, in one go. */\nfunction inOneRun<T>(steps: Generator<void, T>): T {\n for (;;) {\n const step = steps.next();\n if (step.done) return step.value;\n }\n}\n\n/**\n * Checks an index's fields and bounds, and every revocation it carries (one that does not verify refuses the index:\n * the store copied it, so a broken one is the store's fault). The signature and `expires` are `readAppStore`'s. An\n * unknown key of the index, a listing or a removal is ignored unless `strict`; a revocation is its publisher's signed\n * statement and keeps its exact keys. With `checked`, a revocation it holds is not checked again.\n */\nexport function checkAppStoreIndex(value: unknown, options: AppFormatOptions = {}, checked?: AppRevocationsChecked): Check {\n const fields = inOneRun(checkAppStoreFieldsSteps(value, options));\n return fields.ok ? inOneRun(checkAppStoreRevocationsSteps(value as unknown as AppStoreIndex, checked)) : fields;\n}\n\n/**\n * The first half of `checkAppStoreIndex`: the fields and bounds, and the shape of every revocation, with no signature\n * checked. A step after each listing, removal and revocation (see `readAppStoreSteps`).\n */\nfunction* checkAppStoreFieldsSteps(value: unknown, options: AppFormatOptions = {}): Generator<void, Check> {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"The index is not an object\" };\n if (value.ghostlyStore !== undefined && value.ghostlyStore !== 1) return { ok: false, reason: \"unsupported-format\", detail: \"ghostlyStore is not 1\" };\n const keys = keysOf(value, STORE_REQUIRED, [\"description\"], options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: field });\n if (!isAppKey(value.key)) return bad(\"key\");\n if (!isAppLine(value.name, APP_STORE_LIMITS.name, 1)) return bad(\"name\");\n if (value.description !== undefined && !isText(value.description, APP_STORE_LIMITS.description)) return bad(\"description\");\n if (!(APP_STORE_KINDS as readonly unknown[]).includes(value.kind)) return bad(\"kind\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isCount(value.expires, 0)) return bad(\"expires\");\n const { apps, removed, revoked } = value;\n if (!Array.isArray(apps) || apps.length > APP_STORE_LIMITS.apps) return bad(\"apps\");\n const refs = new Set<string>();\n for (const listing of apps) {\n const checked = checkAppListing(listing, options);\n if (!checked.ok) return checked;\n const ref = (listing as { ref: string }).ref;\n if (refs.has(ref)) return { ok: false, reason: \"duplicate-app\", detail: ref };\n refs.add(ref);\n yield;\n }\n if (!Array.isArray(removed) || removed.length > APP_STORE_LIMITS.removed) return bad(\"removed\");\n for (const entry of removed) { const checked = checkRemoval(entry, options); if (!checked.ok) return checked; yield; }\n if (!Array.isArray(revoked) || revoked.length > APP_STORE_LIMITS.revoked) return bad(\"revoked\");\n for (const entry of revoked) {\n const read = readAppRevocationShape(entry);\n if (!read.ok) return { ok: false, reason: \"bad-revocation\", detail: read.detail ?? read.reason };\n yield;\n }\n return fine;\n}\n\n/** The second half: the signature of each revocation of an index whose fields hold, one step each. */\nfunction* checkAppStoreRevocationsSteps(index: AppStoreIndex, checked?: AppRevocationsChecked): Generator<void, Check> {\n for (const revocation of index.revoked) {\n const verified = verifyAppRevocation(revocation, checked);\n if (!verified.ok) return { ok: false, reason: \"bad-revocation\", detail: verified.reason };\n yield;\n }\n return fine;\n}\n\nexport interface AppStoreReading {\n index: AppStoreIndex;\n /** SHA-256 of the index's bytes, base64url: what the update rule compares at one `sequence`. */\n digest: string;\n /** Past `expires`: it still installs, and the Apps page says when the store was last updated. */\n expired: boolean;\n}\n\nexport type AppStoreRead = { ok: true; store: AppStoreReading } | { ok: false; reason: AppStoreRefusal; detail?: string };\n\n/**\n * Reads `ghostly-store.json` with its `ghostly-store.sig`, in this order: size, JSON, canonical bytes, fields and the\n * shape of each revocation, the signature statement, the key the reader holds for this store (when it holds one), the\n * signature, the signature of each revocation, then `expires` against `now` (seconds): more than 90 days ahead is\n * refused, past is `expired`. The index's own signature comes before its revocations': an index nobody signed costs\n * its reader one signature check, whatever it carries. A key it does not know is ignored (a later store's optional\n * field) and stays in the bytes the signature covers. With `checked`, a revocation it holds is not checked again.\n */\nexport function readAppStore(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): AppStoreRead {\n return inOneRun(readAppStoreSteps(indexBytes, sigBytes, now, heldKey, checked));\n}\n\n/**\n * `readAppStore` in steps, for a reader that shares its thread (a page): it stops after each listing, removal and\n * revocation, and after each revocation's signature check, so the caller can let the thread go between two `next()`\n * and an index of 4096 revocations never holds it for seconds. With `checked`, a revocation it holds is not checked again.\n */\nexport function* readAppStoreSteps(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): Generator<void, AppStoreRead> {\n if (indexBytes.length > APP_STORE_LIMITS.indexBytes) return { ok: false, reason: \"too-large\" };\n const read = readCanonicalJson(indexBytes);\n if (!read.ok) return read;\n yield;\n const fields = yield* checkAppStoreFieldsSteps(read.value);\n if (!fields.ok) return fields;\n const index = read.value as unknown as AppStoreIndex;\n const statement = readAppSignature(sigBytes);\n if (!statement.ok) return statement;\n if (heldKey !== undefined && index.key !== heldKey) return { ok: false, reason: \"store-key\", detail: \"Another key than the store's\" };\n const signed = verifyAppSignature(APP_PREFIXES.store, indexBytes, statement.signature, index.key);\n if (!signed.ok) return signed;\n yield;\n const revocations = yield* checkAppStoreRevocationsSteps(index, checked);\n if (!revocations.ok) return revocations;\n if (index.expires > now + APP_STORE_LIMITS.expiresAheadS) return { ok: false, reason: \"expires-too-far\" };\n return { ok: true, store: { index, digest: toBase64Url(sha256(indexBytes)), expired: index.expires < now } };\n}\n\n/**\n * Signs an index with the store key: its canonical bytes and the `ghostly-store.sig` bytes. Throws on a bad index, and\n * on a key this format does not define: a writer is strict, so a misspelt key is never signed. With `revocations`, a\n * revocation it holds is not checked again.\n */\nexport async function signAppStore(index: AppStoreIndex, signer: Signer, revocations?: AppRevocationsChecked): Promise<{ indexBytes: Uint8Array; sigBytes: Uint8Array; signature: AppSignature }> {\n if (index.key !== toZ32(signer.publicKey)) throw new Error(\"A store index is signed by its own key\");\n const checked = checkAppStoreIndex(JSON.parse(JSON.stringify(index)), { strict: true }, revocations);\n if (!checked.ok) throw new Error(`Not a valid store index (${checked.reason}${checked.detail ? `: ${checked.detail}` : \"\"})`);\n const { bytes, signature } = await signAppObject(APP_PREFIXES.store, index, signer);\n return { indexBytes: bytes, sigBytes: canonicalJsonBytes(signature), signature };\n}\n","import { appRefPublisher, type SignedAppRevocation } from \"./appStatements\";\nimport type { AppRemoval, AppStoreKind } from \"./appStore\";\n\n/*\n * The client's rules for updates, rollback, removals and revocations (WISP 1200 · Updates and rollback, Takedowns), as\n * pure functions over what the client holds. A client keeps, per installed app, the reference (publisher key and\n * name), the highest `sequence` it has seen and the digest of that version; per store, its key, `sequence` and the\n * digest of its index. Where a version came from never matters: the bytes are checked, not the messenger.\n */\n\n/** A version of an app, as the client holds it or a checked bundle shows it. */\nexport interface AppVersion { ref: string; sequence: number; digest: string }\n\n/**\n * What a valid package means next to the installed one:\n * - `update`: the same app with a higher `sequence`, from anywhere;\n * - `same`: the version installed;\n * - `rollback`: a lower `sequence`, never installed over a higher one;\n * - `equivocation`: the same `sequence` with another digest; the client keeps what it runs, refuses the other and marks\n * the app (\"Two different versions 7 exist\");\n * - `other-app`: another reference (another publisher key or another name), never an update of this one.\n */\nexport type AppUpdateDecision = \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-app\";\n\nexport function appUpdateDecision(installed: AppVersion, candidate: AppVersion): AppUpdateDecision {\n if (installed.ref !== candidate.ref) return \"other-app\";\n if (candidate.sequence > installed.sequence) return \"update\";\n if (candidate.sequence < installed.sequence) return \"rollback\";\n return candidate.digest === installed.digest ? \"same\" : \"equivocation\";\n}\n\n/** The permissions an update adds: when there is any, the update waits for the person, who sees only these. */\nexport function addedAppPermissions(granted: readonly string[], requested: readonly string[]): string[] {\n return requested.filter((p) => !granted.includes(p));\n}\n\n/**\n * What to do with a newer package: install it (the permissions it keeps or drops apply by themselves) or ask about the\n * permissions it adds. Anything but `update` from `appUpdateDecision` is not installed.\n */\nexport type AppUpdatePlan =\n | { action: \"install\" }\n | { action: \"ask\"; added: string[] }\n | { action: \"refuse\"; decision: Exclude<AppUpdateDecision, \"update\"> };\n\nexport function planAppUpdate(installed: AppVersion & { permissions: readonly string[] }, candidate: AppVersion & { permissions: readonly string[] }): AppUpdatePlan {\n const decision = appUpdateDecision(installed, candidate);\n if (decision !== \"update\") return { action: \"refuse\", decision };\n const added = addedAppPermissions(installed.permissions, candidate.permissions);\n return added.length ? { action: \"ask\", added } : { action: \"install\" };\n}\n\n/**\n * The revocation that stops a version, or null: one signed by the app's own publisher (a reader verified it) that names\n * its digest, or reaches its `sequence` with `upTo`.\n */\nexport function appRevocationFor(version: AppVersion, revocations: readonly SignedAppRevocation[]): SignedAppRevocation | null {\n const publisher = appRefPublisher(version.ref);\n for (const r of revocations) {\n const s = r.statement;\n if (s.app !== version.ref || r.signature.key !== publisher) continue;\n if (\"digests\" in s ? s.digests.includes(version.digest) : version.sequence <= s.upTo) return r;\n }\n return null;\n}\n\n/** A store the person added, as the run check needs it. */\nexport interface AppStoreView { key: string; name: string; kind: AppStoreKind; removed: readonly AppRemoval[]; revoked: readonly SignedAppRevocation[] }\n\n/**\n * The check before Install is enabled, at every update check and before a run:\n * - `revoked`: its publisher revoked it; it stops, with no \"Run anyway\";\n * - `removed`: a store the person added removed this digest; it stops and the person decides (Remove, Keep it stopped,\n * or, behind Details, Run anyway);\n * - `ok`.\n * Revocations come from the app's sources and from every store's `revoked`; a store the person did not add has no say.\n */\nexport type AppRunCheck =\n | { status: \"ok\" }\n | { status: \"revoked\"; revocation: SignedAppRevocation }\n | { status: \"removed\"; by: { store: string; name: string; reason: string; at: number }[] };\n\nexport function checkAppBeforeRun(version: AppVersion, stores: readonly AppStoreView[], revocations: readonly SignedAppRevocation[] = []): AppRunCheck {\n for (const list of [revocations, ...stores.map((s) => s.revoked)]) {\n const revocation = appRevocationFor(version, indexed(list, (r) => r.statement.app).get(version.ref) ?? []);\n if (revocation) return { status: \"revoked\", revocation };\n }\n const by = stores.flatMap((s) => (indexed(s.removed, (r) => `${r.ref} ${r.digest}`).get(`${version.ref} ${version.digest}`) ?? [])\n .map((r) => ({ store: s.key, name: s.name, reason: r.reason, at: r.at })));\n return by.length ? { status: \"removed\", by } : { status: \"ok\" };\n}\n\n/*\n * A list's entries by key, in the list's order, made once per list: a store's `revoked` and `removed` reach 4096 entries\n * each (`APP_STORE_LIMITS`), and an app's every storage call, frame and read lane answer is checked against them. The\n * lists are never changed in place (a new index is a new list); one whose length changed is read again all the same.\n */\nconst indexes = new WeakMap<readonly object[], { length: number; byKey: Map<string, unknown[]> }>();\n\nfunction indexed<T extends object>(list: readonly T[], key: (entry: T) => string): Map<string, T[]> {\n const held = indexes.get(list);\n if (held && held.length === list.length) return held.byKey as Map<string, T[]>;\n const byKey = new Map<string, T[]>();\n for (const entry of list) {\n const k = key(entry);\n const same = byKey.get(k);\n if (same) same.push(entry);\n else byKey.set(k, [entry]);\n }\n indexes.set(list, { length: list.length, byKey });\n return byKey;\n}\n\n/** A store index as the client holds it. */\nexport interface AppStoreVersion { key: string; sequence: number; digest: string }\n\n/**\n * What a newly read index means next to the one held: `new` (none held), `update`, `same`, `rollback` (a lower\n * `sequence`, refused), `equivocation` (the same `sequence`, other bytes: refused, the held one kept) or `other-key`\n * (another store: a store is its key).\n */\nexport type AppStoreDecision = \"new\" | \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-key\";\n\nexport function appStoreDecision(held: AppStoreVersion | null, read: AppStoreVersion): AppStoreDecision {\n if (!held) return \"new\";\n if (held.key !== read.key) return \"other-key\";\n if (read.sequence > held.sequence) return \"update\";\n if (read.sequence < held.sequence) return \"rollback\";\n return read.digest === held.digest ? \"same\" : \"equivocation\";\n}\n","import { isAppUrl } from \"@ghostly/core\";\n\n/*\n * Where mini-apps and stores are read from (WISP 1200 § Stores, § Apps sent in a chat): in phase 1 only two hosts,\n * `raw.githubusercontent.com` and `cdn.jsdelivr.net` pinned to a full commit, both readable from a page (CORS `*`).\n * HTTPS only, no user or password, no port, no redirect (one would walk out of the list), no cookies, no referrer, and a\n * cap on the bytes read while the body streams in. Every read of the apps feature goes through `boundedAppFetch`.\n */\n\n/** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */\nexport const APP_FETCH_HOSTS = [\"raw.githubusercontent.com\", \"cdn.jsdelivr.net\"] as const;\n\nexport const APP_FETCH_LIMITS = {\n /**\n * A store index as read (WISP 1200 § Stores, Privacy): 4 MiB in phase 1, under the format's 16 MiB. Counted on the body\n * as it arrives, after the browser undid any compression, since a page never sees the compressed size.\n */\n storeIndexBytes: 4 * 1024 * 1024,\n /** A store's signature statement, `ghostly-store.sig` (canonical, at most 1 KiB). */\n sigBytes: 1024,\n /** `ghostly-revoke.json`: at most 4096 signed revocations. */\n revocationsBytes: 16 * 1024 * 1024,\n /** How long the host has to answer (the response's headers). */\n timeoutMs: 30_000,\n /** How long the body may go without a byte: a read still arriving is never cut by the clock alone. */\n idleMs: 30_000,\n /** A whole read at most: the 16 MiB cap at about 224 kbit/s. */\n totalMs: 10 * 60_000,\n} as const;\n\n/** A URL this client may read an app, a store or a revocation list from. */\nexport function isAppFetchUrl(value: unknown): value is string {\n if (!isAppUrl(value)) return false;\n const url = new URL(value);\n return url.port === \"\" && (APP_FETCH_HOSTS as readonly string[]).includes(url.hostname.toLowerCase());\n}\n\n/** `slow`: the host did not answer in time, went silent, or the read ran past its whole budget. */\nexport type AppFetchErrorCode = \"host\" | \"offline\" | \"status\" | \"too-large\" | \"network\" | \"slow\";\n\nexport class AppFetchError extends Error {\n constructor(readonly code: AppFetchErrorCode, message: string, readonly status?: number) {\n // Its code first, as every error of the apps calls (`<code>: words`).\n super(`${code}: ${message}`);\n this.name = \"AppFetchError\";\n }\n}\n\n/**\n * Reads a URL of the list: its bytes, at most `maxBytes`. With `peek`, the first `maxBytes` bytes and no more, the rest\n * left unread (a bundle's manifest, to see whether it is newer before reading all of it). `signal` stops a read whose\n * bytes nobody will use any more (`network`). `revalidate`: a file every update check reads again (a store's index and\n * its sig, `ghostly-revoke.json`), kept by the browser and asked again with its ETag every time, so an unchanged one is\n * an empty 304 and never a copy the host was not asked about. Anything else is not kept by the browser (a bundle is\n * kept in file storage, a peek is a range).\n */\nexport type AppFetcher = (url: string, options: { maxBytes: number; peek?: boolean; revalidate?: boolean; signal?: AbortSignal }) => Promise<Uint8Array>;\n\nexport function boundedAppFetch(options: { fetcher?: typeof fetch; online?: () => boolean; timeoutMs?: number; idleMs?: number; totalMs?: number } = {}): AppFetcher {\n return async (url, { maxBytes, peek = false, revalidate = false, signal: stopped }) => {\n if (!isAppFetchUrl(url)) throw new AppFetchError(\"host\", \"Apps are read only from raw.githubusercontent.com, or from cdn.jsdelivr.net at a commit, over HTTPS\");\n if (options.online && !options.online()) throw new AppFetchError(\"offline\", \"Offline\");\n if (stopped?.aborted) throw new AppFetchError(\"network\", \"The read was stopped\");\n const fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);\n // One signal for the request and its body: the host has `timeoutMs` to answer, then the body `idleMs` between two\n // bytes, the whole read `totalMs`. A read still arriving goes on; one cut by the clock is `slow`, not `network`.\n const controller = new AbortController();\n const cut = () => { controller.abort(new DOMException(\"The read took too long\", \"TimeoutError\")); };\n const stop = () => { controller.abort(new DOMException(\"The read was stopped\", \"AbortError\")); };\n stopped?.addEventListener(\"abort\", stop);\n const total = setTimeout(cut, options.totalMs ?? APP_FETCH_LIMITS.totalMs);\n let idle = setTimeout(cut, options.timeoutMs ?? APP_FETCH_LIMITS.timeoutMs);\n const heard = () => { clearTimeout(idle); idle = setTimeout(cut, options.idleMs ?? APP_FETCH_LIMITS.idleMs); };\n const failure = (error: unknown) => stopped?.aborted ? new AppFetchError(\"network\", \"The read was stopped\")\n : controller.signal.aborted ? new AppFetchError(\"slow\", \"That took too long on this connection\")\n : new AppFetchError(\"network\", error instanceof Error ? error.message : String(error));\n const { signal } = controller;\n let response: Response;\n try {\n response = await fetcher(url, {\n signal,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: revalidate && !peek ? \"no-cache\" : \"no-store\", redirect: \"error\",\n ...(peek && { headers: { range: `bytes=0-${maxBytes - 1}` } }),\n });\n } catch (error) {\n clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop);\n throw failure(error);\n }\n heard();\n const parts: Uint8Array[] = [];\n let length = 0;\n try {\n // A redirect a fetcher followed after all (one that ignores `redirect`) still lands only on a host of the list.\n if (response.url && response.url !== url && !isAppFetchUrl(response.url)) throw new AppFetchError(\"host\", \"The host sent the request elsewhere\");\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"status\", `The host answered ${response.status}`, response.status);\n }\n if (!peek && Number(response.headers.get(\"content-length\")) > maxBytes) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"too-large\", \"Too large\");\n }\n const reader = response.body?.getReader();\n if (reader) {\n // A body the signal does not reach (a fetcher of its own) is let go all the same: its pending read ends.\n const letGo = () => { reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", letGo);\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw failure(signal.reason);\n if (done) break;\n heard();\n if (length + value.length > maxBytes) {\n if (!peek) throw new AppFetchError(\"too-large\", \"Too large\");\n parts.push(value.subarray(0, maxBytes - length));\n length = maxBytes;\n break;\n }\n parts.push(value);\n length += value.length;\n }\n } catch (error) {\n if (error instanceof AppFetchError) throw error;\n throw failure(error);\n } finally {\n signal.removeEventListener(\"abort\", letGo);\n await reader.cancel().catch(() => {});\n }\n }\n } finally { clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop); }\n const bytes = new Uint8Array(length);\n let at = 0;\n for (const part of parts) { bytes.set(part, at); at += part.length; }\n return bytes;\n };\n}\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * The URL a pasted address reads `file` from (WISP 1200 § Paste a URL), or null when it is not one this client reads:\n * - `https://github.com/<owner>/<repo>`, or `/tree/<ref>`: `raw.githubusercontent.com/<owner>/<repo>/<ref or HEAD>/<file>`,\n * with no request to `github.com` or `api.github.com`;\n * - a file as GitHub shows it, `https://github.com/<owner>/<repo>/blob/<ref>/<path>` (or `/raw/`), naming a `.ghostlyapp`\n * or `.json` file: `raw.githubusercontent.com/<owner>/<repo>/<ref>/<path>`, again with no request to `github.com`;\n * - a URL of the list that names a file (`….ghostlyapp`, `….json`): itself;\n * - a URL of the list that names a folder: `<file>` in it.\n */\nexport function appPasteUrl(input: string, file: \"app.ghostlyapp\" | \"ghostly-store.json\"): string | null {\n let url: URL;\n try { url = new URL(input.trim()); } catch { return null; }\n if (url.protocol !== \"https:\" || url.username || url.password || url.port) return null;\n const host = url.hostname.toLowerCase();\n if (host === \"github.com\" || host === \"www.github.com\") {\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n const owner = parts[0]!, repo = parts[1]!.replace(/\\.git$/, \"\");\n if (!NAME.test(owner) || !NAME.test(repo)) return null;\n let ref = \"HEAD\";\n if (parts.length > 2) {\n const rest = parts.slice(3);\n if (!rest.length || !rest.every((p) => NAME.test(p) && p !== \".\" && p !== \"..\")) return null;\n if (parts[2] === \"blob\" || parts[2] === \"raw\") {\n // `<ref>/<path>`: raw.githubusercontent.com takes the two joined the same way github.com does.\n if (rest.length < 2 || !/\\.(ghostlyapp|json)$/.test(rest[rest.length - 1]!)) return null;\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${rest.join(\"/\")}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n if (parts[2] !== \"tree\") return null;\n ref = rest.join(\"/\");\n }\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n const last = url.pathname.split(\"/\").pop() ?? \"\";\n const named = /\\.(ghostlyapp|json)$/.test(last) ? url.href : new URL(`${url.pathname.replace(/\\/?$/, \"/\")}${file}`, url).href;\n return isAppFetchUrl(named) ? named : null;\n}\n\n/** A page of github.com (any scheme): a link `appPasteUrl` could not read is still GitHub, and is answered as such. */\nexport function isGitHubPage(input: string): boolean {\n try {\n const host = new URL(input.trim()).hostname.toLowerCase();\n return host === \"github.com\" || host === \"www.github.com\";\n } catch { return false; }\n}\n\n/** A file beside another (`ghostly-store.sig` beside the index, `ghostly-revoke.json` beside a bundle). */\nexport function besideUrl(url: string, name: string): string {\n const target = new URL(url);\n target.search = \"\";\n target.hash = \"\";\n return new URL(name, target).href;\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,WAAW,MAA0B;CACnD,IAAI,KAAK,WAAW,IAAI,MAAM,I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,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,MAAM,OAAO,IAAI,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,SAAS,YAAY;EACxD,OAAO,SAAS,gBAAgB,SAAS;CAC3C,QAAQ;EAAE,OAAO;CAAO;AAC1B;;AAGA,SAAgB,UAAU,KAAa,MAAsB;CAC3D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,OAAO,SAAS;CAChB,OAAO,OAAO;CACd,OAAO,IAAI,IAAI,MAAM,MAAM,CAAC,CAAC;AAC/B"}
1
+ {"version":3,"file":"appFetch-CW9fJPHh.js","names":[],"sources":["../../../core/src/signer.ts","../../../core/src/appStore.ts","../../../core/src/appUpdates.ts","../../../browser/src/engine/appFetch.ts"],"sourcesContent":["import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { sign } from \"./identity\";\n\n/*\n * A signer (WISP 06 § Terms): an Ed25519 key that signs without the caller holding its seed. The device signing key\n * is non-extractable where WebCrypto offers Ed25519, so the app has no bytes to sign with; where it does not, the key\n * is a stored seed. Both are this one interface, and so is a chat's participation seed when a session is given one.\n *\n * Signing is asynchronous because WebCrypto is. The public key is known at once: a session puts it in its offer\n * before it signs anything.\n */\nexport interface Signer {\n /** The Ed25519 public key, 32 bytes. */\n readonly publicKey: Uint8Array;\n /** The 64-byte signature of `bytes`. */\n sign(bytes: Uint8Array): Promise<Uint8Array>;\n}\n\n/** A seed held by the app, as every key of a profile is today. */\nexport function seedSigner(seed: Uint8Array): Signer {\n if (seed.length !== 32) throw new Error(\"Seed must be exactly 32 bytes\");\n const publicKey = ed25519.getPublicKey(seed);\n return { publicKey, sign: async (bytes) => sign(bytes, seed) };\n}\n\n/**\n * A WebCrypto Ed25519 private key, non-extractable or not, with its raw public key. The app never sees the private\n * bytes: `crypto.subtle` signs.\n */\nexport function webCryptoSigner(privateKey: CryptoKey, publicKey: Uint8Array): Signer {\n if (publicKey.length !== 32) throw new Error(\"An Ed25519 public key is 32 bytes\");\n return {\n publicKey,\n sign: async (bytes) => new Uint8Array(await crypto.subtle.sign({ name: \"Ed25519\" }, privateKey, new Uint8Array(bytes))),\n };\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, toZ32 } from \"./bytes\";\nimport { canonicalJsonBytes, readCanonicalJson, type JsonValue } from \"./canonicalJson\";\nimport { findAppForbiddenKey, isAppUrl } from \"./appBundle\";\nimport {\n APP_PREFIXES, isAppHash, isAppKey, isAppLine, isAppRef, readAppRevocationShape, readAppSignature, signAppObject, verifyAppRevocation, verifyAppSignature,\n type AppRevocationsChecked, type AppSignature, type SignedAppRevocation,\n} from \"./appStatements\";\nimport type { Signer } from \"./signer\";\n\n/*\n * A store index (WISP 1200 · Stores): `ghostly-store.json`, canonical JSON, signed by the store key under\n * `ghostly-store/1` in `ghostly-store.sig` beside it (the same statement as a bundle's). It lists apps by reference and\n * digest, the versions it removed, and publishers' revocations copied verbatim. Times are Unix seconds.\n *\n * A store lists and ranks; it never changes what installs: the bundle a listing points at is checked on its own, and\n * its icon and description come from the bundle. `listing.json` in a store's repository is one entry of `apps`.\n */\n\nexport const APP_STORE_LIMITS = {\n /** The index's bytes, uncompressed. */\n indexBytes: 16 * 1024 * 1024,\n /** How far ahead `expires` may be. */\n expiresAheadS: 90 * 24 * 60 * 60,\n name: 40,\n description: 2000,\n title: 40,\n tagline: 80,\n /** `category`, `developer`, `submitter`. */\n label: 40,\n reason: 200,\n urls: 4,\n apps: 4096,\n removed: 4096,\n revoked: 4096,\n} as const;\n\nexport const APP_STORE_KINDS = [\"curated\", \"indexed\"] as const;\nexport type AppStoreKind = typeof APP_STORE_KINDS[number];\n\nexport interface AppListing {\n ref: string;\n sequence: number;\n digest: string;\n urls: string[];\n title: string;\n tagline: string;\n category?: string;\n developer?: string;\n submitter?: string;\n repo?: string;\n support?: string;\n}\nexport interface AppRemoval { ref: string; digest: string; reason: string; at: number }\nexport interface AppStoreIndex {\n ghostlyStore: 1;\n key: string;\n name: string;\n description?: string;\n kind: AppStoreKind;\n sequence: number;\n expires: number;\n apps: AppListing[];\n removed: AppRemoval[];\n revoked: SignedAppRevocation[];\n}\n\nexport type AppStoreRefusal =\n | \"too-large\" | \"not-json\" | \"not-canonical\" | \"unsupported-format\" | \"unknown-key\" | \"missing-key\" | \"bad-field\"\n | \"duplicate-app\" | \"bad-signature-statement\" | \"signature-key\" | \"bad-signature\" | \"store-key\" | \"expires-too-far\"\n | \"bad-revocation\";\n\nconst isObject = (v: unknown): v is Record<string, JsonValue> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst isText = (v: unknown, max: number): v is string => typeof v === \"string\" && [...v].length <= max && !/[^\\P{Cc}\\n]/u.test(v);\nconst isCount = (v: unknown, min: number): v is number => typeof v === \"number\" && Number.isSafeInteger(v) && v >= min;\n\ntype Check = { ok: true } | { ok: false; reason: AppStoreRefusal; detail?: string };\nconst fine: Check = { ok: true };\n\n/**\n * How a check treats a key it does not know. A reader (`readAppStore`, the client) ignores it, so a later format can\n * add an optional key without a client refusing the whole signed index; the signature still covers the bytes as they\n * are, unknown keys included. A writer (`signAppStore`, the CLI, a store's check of a `listing.json` through\n * `readAppListing`) passes `strict` and refuses it, so a misspelt key is caught before anything is signed. Required\n * keys, their types and their bounds hold in both, and `APP_FORBIDDEN_KEYS` are refused in both, at any level.\n */\nexport interface AppFormatOptions { strict?: boolean }\n\nfunction keysOf(value: Record<string, unknown>, required: readonly string[], optional: readonly string[], options: AppFormatOptions = {}): Check {\n // `__proto__` and its kin are refused in both modes, at any level (`findAppForbiddenKey`): a reader keeps what it ignores.\n const forbidden = findAppForbiddenKey(value);\n if (forbidden !== undefined) return { ok: false, reason: \"unknown-key\", detail: forbidden };\n for (const k of Object.keys(value)) {\n if (options.strict && !required.includes(k) && !optional.includes(k)) return { ok: false, reason: \"unknown-key\", detail: k };\n }\n for (const k of required) if (!(k in value)) return { ok: false, reason: \"missing-key\", detail: k };\n return fine;\n}\n\nconst LISTING_REQUIRED = [\"ref\", \"sequence\", \"digest\", \"urls\", \"title\", \"tagline\"] as const;\nconst LISTING_OPTIONAL = [\"category\", \"developer\", \"submitter\", \"repo\", \"support\"] as const;\n\n/** Checks one entry of `apps`, which is also the whole of a `listing.json`. An unknown key is ignored unless `strict`. */\nexport function checkAppListing(value: unknown, options: AppFormatOptions = {}): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A listing is not an object\" };\n const keys = keysOf(value, LISTING_REQUIRED, LISTING_OPTIONAL, options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: `apps: ${field}` });\n if (!isAppRef(value.ref)) return bad(\"ref\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isAppHash(value.digest)) return bad(\"digest\");\n const urls = value.urls;\n if (!Array.isArray(urls) || urls.length < 1 || urls.length > APP_STORE_LIMITS.urls || !urls.every(isAppUrl)) return bad(\"urls\");\n if (!isAppLine(value.title, APP_STORE_LIMITS.title, 1)) return bad(\"title\");\n if (!isAppLine(value.tagline, APP_STORE_LIMITS.tagline, 1)) return bad(\"tagline\");\n for (const k of [\"category\", \"developer\", \"submitter\"] as const) if (value[k] !== undefined && !isAppLine(value[k], APP_STORE_LIMITS.label, 1)) return bad(k);\n for (const k of [\"repo\", \"support\"] as const) if (value[k] !== undefined && !isAppUrl(value[k])) return bad(k);\n return fine;\n}\n\n/**\n * The first object key `text` writes twice in one object, as JSON.parse reads it (`\"title\"` is `title`), or null.\n * `text` is JSON that JSON.parse already took: one pass, each string read to its closing quote.\n */\nexport function repeatedJsonKey(text: string): string | null {\n /** Each open object's keys so far; null for an array. */\n const open: (Set<string> | null)[] = [];\n let keyNext = false;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (c === \"\\\"\") {\n let end = i + 1;\n while (text[end] !== \"\\\"\") end += text[end] === \"\\\\\" ? 2 : 1;\n const keys = open[open.length - 1];\n if (keys && keyNext) {\n const key = JSON.parse(text.slice(i, end + 1)) as string;\n if (keys.has(key)) return key;\n keys.add(key);\n keyNext = false;\n }\n i = end;\n } else if (c === \"{\") { open.push(new Set()); keyNext = true; }\n else if (c === \"[\") open.push(null);\n else if (c === \"}\" || c === \"]\") open.pop();\n else if (c === \",\") keyNext = open[open.length - 1] !== null;\n }\n return null;\n}\n\n/**\n * Reads a `listing.json`: JSON holding exactly one listing (written by hand in release 1.2, so not required canonical).\n * A store reads it, as a writer: strict by default, so a misspelt key is refused before the owner signs the index (the\n * client never reads a `listing.json`, only the signed index). `{ strict: false }` reads it as a client reads an index\n * entry, ignoring a later key.\n */\nexport function readAppListing(text: string, options: AppFormatOptions = { strict: true }): { ok: true; listing: AppListing } | { ok: false; reason: AppStoreRefusal; detail?: string } {\n let value: unknown;\n try { value = JSON.parse(text); } catch (error) { return { ok: false, reason: \"not-json\", detail: String(error) }; }\n // JSON.parse keeps a key's last value, where a person reading the file sees the first: strict, both are refused.\n const twice = options.strict ? repeatedJsonKey(text) : null;\n if (twice !== null) return { ok: false, reason: \"not-json\", detail: `${JSON.stringify(twice)} is written twice` };\n const checked = checkAppListing(value, options);\n return checked.ok ? { ok: true, listing: value as AppListing } : checked;\n}\n\nfunction checkRemoval(value: unknown, options: AppFormatOptions): Check {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"A removal is not an object\" };\n const keys = keysOf(value, [\"ref\", \"digest\", \"reason\", \"at\"], [], options);\n if (!keys.ok) return keys;\n if (!isAppRef(value.ref) || !isAppHash(value.digest) || !isAppLine(value.reason, APP_STORE_LIMITS.reason, 1) || !isCount(value.at, 0)) {\n return { ok: false, reason: \"bad-field\", detail: \"removed: not {ref, digest, reason, at}\" };\n }\n return fine;\n}\n\nconst STORE_REQUIRED = [\"ghostlyStore\", \"key\", \"name\", \"kind\", \"sequence\", \"expires\", \"apps\", \"removed\", \"revoked\"] as const;\n\n/** Runs a check written in steps to its end, in one go. */\nfunction inOneRun<T>(steps: Generator<void, T>): T {\n for (;;) {\n const step = steps.next();\n if (step.done) return step.value;\n }\n}\n\n/**\n * Checks an index's fields and bounds, and every revocation it carries (one that does not verify refuses the index:\n * the store copied it, so a broken one is the store's fault). The signature and `expires` are `readAppStore`'s. An\n * unknown key of the index, a listing or a removal is ignored unless `strict`; a revocation is its publisher's signed\n * statement and keeps its exact keys. With `checked`, a revocation it holds is not checked again.\n */\nexport function checkAppStoreIndex(value: unknown, options: AppFormatOptions = {}, checked?: AppRevocationsChecked): Check {\n const fields = inOneRun(checkAppStoreFieldsSteps(value, options));\n return fields.ok ? inOneRun(checkAppStoreRevocationsSteps(value as unknown as AppStoreIndex, checked)) : fields;\n}\n\n/**\n * The first half of `checkAppStoreIndex`: the fields and bounds, and the shape of every revocation, with no signature\n * checked. A step after each listing, removal and revocation (see `readAppStoreSteps`).\n */\nfunction* checkAppStoreFieldsSteps(value: unknown, options: AppFormatOptions = {}): Generator<void, Check> {\n if (!isObject(value)) return { ok: false, reason: \"bad-field\", detail: \"The index is not an object\" };\n if (value.ghostlyStore !== undefined && value.ghostlyStore !== 1) return { ok: false, reason: \"unsupported-format\", detail: \"ghostlyStore is not 1\" };\n const keys = keysOf(value, STORE_REQUIRED, [\"description\"], options);\n if (!keys.ok) return keys;\n const bad = (field: string): Check => ({ ok: false, reason: \"bad-field\", detail: field });\n if (!isAppKey(value.key)) return bad(\"key\");\n if (!isAppLine(value.name, APP_STORE_LIMITS.name, 1)) return bad(\"name\");\n if (value.description !== undefined && !isText(value.description, APP_STORE_LIMITS.description)) return bad(\"description\");\n if (!(APP_STORE_KINDS as readonly unknown[]).includes(value.kind)) return bad(\"kind\");\n if (!isCount(value.sequence, 1)) return bad(\"sequence\");\n if (!isCount(value.expires, 0)) return bad(\"expires\");\n const { apps, removed, revoked } = value;\n if (!Array.isArray(apps) || apps.length > APP_STORE_LIMITS.apps) return bad(\"apps\");\n const refs = new Set<string>();\n for (const listing of apps) {\n const checked = checkAppListing(listing, options);\n if (!checked.ok) return checked;\n const ref = (listing as { ref: string }).ref;\n if (refs.has(ref)) return { ok: false, reason: \"duplicate-app\", detail: ref };\n refs.add(ref);\n yield;\n }\n if (!Array.isArray(removed) || removed.length > APP_STORE_LIMITS.removed) return bad(\"removed\");\n for (const entry of removed) { const checked = checkRemoval(entry, options); if (!checked.ok) return checked; yield; }\n if (!Array.isArray(revoked) || revoked.length > APP_STORE_LIMITS.revoked) return bad(\"revoked\");\n for (const entry of revoked) {\n const read = readAppRevocationShape(entry);\n if (!read.ok) return { ok: false, reason: \"bad-revocation\", detail: read.detail ?? read.reason };\n yield;\n }\n return fine;\n}\n\n/** The second half: the signature of each revocation of an index whose fields hold, one step each. */\nfunction* checkAppStoreRevocationsSteps(index: AppStoreIndex, checked?: AppRevocationsChecked): Generator<void, Check> {\n for (const revocation of index.revoked) {\n const verified = verifyAppRevocation(revocation, checked);\n if (!verified.ok) return { ok: false, reason: \"bad-revocation\", detail: verified.reason };\n yield;\n }\n return fine;\n}\n\nexport interface AppStoreReading {\n index: AppStoreIndex;\n /** SHA-256 of the index's bytes, base64url: what the update rule compares at one `sequence`. */\n digest: string;\n /** Past `expires`: it still installs, and the Apps page says when the store was last updated. */\n expired: boolean;\n}\n\nexport type AppStoreRead = { ok: true; store: AppStoreReading } | { ok: false; reason: AppStoreRefusal; detail?: string };\n\n/**\n * Reads `ghostly-store.json` with its `ghostly-store.sig`, in this order: size, JSON, canonical bytes, fields and the\n * shape of each revocation, the signature statement, the key the reader holds for this store (when it holds one), the\n * signature, the signature of each revocation, then `expires` against `now` (seconds): more than 90 days ahead is\n * refused, past is `expired`. The index's own signature comes before its revocations': an index nobody signed costs\n * its reader one signature check, whatever it carries. A key it does not know is ignored (a later store's optional\n * field) and stays in the bytes the signature covers. With `checked`, a revocation it holds is not checked again.\n */\nexport function readAppStore(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): AppStoreRead {\n return inOneRun(readAppStoreSteps(indexBytes, sigBytes, now, heldKey, checked));\n}\n\n/**\n * `readAppStore` in steps, for a reader that shares its thread (a page): it stops after each listing, removal and\n * revocation, and after each revocation's signature check, so the caller can let the thread go between two `next()`\n * and an index of 4096 revocations never holds it for seconds. With `checked`, a revocation it holds is not checked again.\n */\nexport function* readAppStoreSteps(indexBytes: Uint8Array, sigBytes: Uint8Array, now: number, heldKey?: string, checked?: AppRevocationsChecked): Generator<void, AppStoreRead> {\n if (indexBytes.length > APP_STORE_LIMITS.indexBytes) return { ok: false, reason: \"too-large\" };\n const read = readCanonicalJson(indexBytes);\n if (!read.ok) return read;\n yield;\n const fields = yield* checkAppStoreFieldsSteps(read.value);\n if (!fields.ok) return fields;\n const index = read.value as unknown as AppStoreIndex;\n const statement = readAppSignature(sigBytes);\n if (!statement.ok) return statement;\n if (heldKey !== undefined && index.key !== heldKey) return { ok: false, reason: \"store-key\", detail: \"Another key than the store's\" };\n const signed = verifyAppSignature(APP_PREFIXES.store, indexBytes, statement.signature, index.key);\n if (!signed.ok) return signed;\n yield;\n const revocations = yield* checkAppStoreRevocationsSteps(index, checked);\n if (!revocations.ok) return revocations;\n if (index.expires > now + APP_STORE_LIMITS.expiresAheadS) return { ok: false, reason: \"expires-too-far\" };\n return { ok: true, store: { index, digest: toBase64Url(sha256(indexBytes)), expired: index.expires < now } };\n}\n\n/**\n * Signs an index with the store key: its canonical bytes and the `ghostly-store.sig` bytes. Throws on a bad index, and\n * on a key this format does not define: a writer is strict, so a misspelt key is never signed. With `revocations`, a\n * revocation it holds is not checked again.\n */\nexport async function signAppStore(index: AppStoreIndex, signer: Signer, revocations?: AppRevocationsChecked): Promise<{ indexBytes: Uint8Array; sigBytes: Uint8Array; signature: AppSignature }> {\n if (index.key !== toZ32(signer.publicKey)) throw new Error(\"A store index is signed by its own key\");\n const checked = checkAppStoreIndex(JSON.parse(JSON.stringify(index)), { strict: true }, revocations);\n if (!checked.ok) throw new Error(`Not a valid store index (${checked.reason}${checked.detail ? `: ${checked.detail}` : \"\"})`);\n const { bytes, signature } = await signAppObject(APP_PREFIXES.store, index, signer);\n return { indexBytes: bytes, sigBytes: canonicalJsonBytes(signature), signature };\n}\n","import { appRefPublisher, type SignedAppRevocation } from \"./appStatements\";\nimport type { AppRemoval, AppStoreKind } from \"./appStore\";\n\n/*\n * The client's rules for updates, rollback, removals and revocations (WISP 1200 · Updates and rollback, Takedowns), as\n * pure functions over what the client holds. A client keeps, per installed app, the reference (publisher key and\n * name), the highest `sequence` it has seen and the digest of that version; per store, its key, `sequence` and the\n * digest of its index. Where a version came from never matters: the bytes are checked, not the messenger.\n */\n\n/** A version of an app, as the client holds it or a checked bundle shows it. */\nexport interface AppVersion { ref: string; sequence: number; digest: string }\n\n/**\n * What a valid package means next to the installed one:\n * - `update`: the same app with a higher `sequence`, from anywhere;\n * - `same`: the version installed;\n * - `rollback`: a lower `sequence`, never installed over a higher one;\n * - `equivocation`: the same `sequence` with another digest; the client keeps what it runs, refuses the other and marks\n * the app (\"Two different versions 7 exist\");\n * - `other-app`: another reference (another publisher key or another name), never an update of this one.\n */\nexport type AppUpdateDecision = \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-app\";\n\nexport function appUpdateDecision(installed: AppVersion, candidate: AppVersion): AppUpdateDecision {\n if (installed.ref !== candidate.ref) return \"other-app\";\n if (candidate.sequence > installed.sequence) return \"update\";\n if (candidate.sequence < installed.sequence) return \"rollback\";\n return candidate.digest === installed.digest ? \"same\" : \"equivocation\";\n}\n\n/** The permissions an update adds: when there is any, the update waits for the person, who sees only these. */\nexport function addedAppPermissions(granted: readonly string[], requested: readonly string[]): string[] {\n return requested.filter((p) => !granted.includes(p));\n}\n\n/**\n * What to do with a newer package: install it (the permissions it keeps or drops apply by themselves) or ask about the\n * permissions it adds. Anything but `update` from `appUpdateDecision` is not installed.\n */\nexport type AppUpdatePlan =\n | { action: \"install\" }\n | { action: \"ask\"; added: string[] }\n | { action: \"refuse\"; decision: Exclude<AppUpdateDecision, \"update\"> };\n\nexport function planAppUpdate(installed: AppVersion & { permissions: readonly string[] }, candidate: AppVersion & { permissions: readonly string[] }): AppUpdatePlan {\n const decision = appUpdateDecision(installed, candidate);\n if (decision !== \"update\") return { action: \"refuse\", decision };\n const added = addedAppPermissions(installed.permissions, candidate.permissions);\n return added.length ? { action: \"ask\", added } : { action: \"install\" };\n}\n\n/**\n * The revocation that stops a version, or null: one signed by the app's own publisher (a reader verified it) that names\n * its digest, or reaches its `sequence` with `upTo`.\n */\nexport function appRevocationFor(version: AppVersion, revocations: readonly SignedAppRevocation[]): SignedAppRevocation | null {\n const publisher = appRefPublisher(version.ref);\n for (const r of revocations) {\n const s = r.statement;\n if (s.app !== version.ref || r.signature.key !== publisher) continue;\n if (\"digests\" in s ? s.digests.includes(version.digest) : version.sequence <= s.upTo) return r;\n }\n return null;\n}\n\n/** A store the person added, as the run check needs it. */\nexport interface AppStoreView { key: string; name: string; kind: AppStoreKind; removed: readonly AppRemoval[]; revoked: readonly SignedAppRevocation[] }\n\n/**\n * The check before Install is enabled, at every update check and before a run:\n * - `revoked`: its publisher revoked it; it stops, with no \"Run anyway\";\n * - `removed`: a store the person added removed this digest; it stops and the person decides (Remove, Keep it stopped,\n * or, behind Details, Run anyway);\n * - `ok`.\n * Revocations come from the app's sources and from every store's `revoked`; a store the person did not add has no say.\n */\nexport type AppRunCheck =\n | { status: \"ok\" }\n | { status: \"revoked\"; revocation: SignedAppRevocation }\n | { status: \"removed\"; by: { store: string; name: string; reason: string; at: number }[] };\n\nexport function checkAppBeforeRun(version: AppVersion, stores: readonly AppStoreView[], revocations: readonly SignedAppRevocation[] = []): AppRunCheck {\n for (const list of [revocations, ...stores.map((s) => s.revoked)]) {\n const revocation = appRevocationFor(version, indexed(list, (r) => r.statement.app).get(version.ref) ?? []);\n if (revocation) return { status: \"revoked\", revocation };\n }\n const by = stores.flatMap((s) => (indexed(s.removed, (r) => `${r.ref} ${r.digest}`).get(`${version.ref} ${version.digest}`) ?? [])\n .map((r) => ({ store: s.key, name: s.name, reason: r.reason, at: r.at })));\n return by.length ? { status: \"removed\", by } : { status: \"ok\" };\n}\n\n/*\n * A list's entries by key, in the list's order, made once per list: a store's `revoked` and `removed` reach 4096 entries\n * each (`APP_STORE_LIMITS`), and an app's every storage call, frame and read lane answer is checked against them. The\n * lists are never changed in place (a new index is a new list); one whose length changed is read again all the same.\n */\nconst indexes = new WeakMap<readonly object[], { length: number; byKey: Map<string, unknown[]> }>();\n\nfunction indexed<T extends object>(list: readonly T[], key: (entry: T) => string): Map<string, T[]> {\n const held = indexes.get(list);\n if (held && held.length === list.length) return held.byKey as Map<string, T[]>;\n const byKey = new Map<string, T[]>();\n for (const entry of list) {\n const k = key(entry);\n const same = byKey.get(k);\n if (same) same.push(entry);\n else byKey.set(k, [entry]);\n }\n indexes.set(list, { length: list.length, byKey });\n return byKey;\n}\n\n/** A store index as the client holds it. */\nexport interface AppStoreVersion { key: string; sequence: number; digest: string }\n\n/**\n * What a newly read index means next to the one held: `new` (none held), `update`, `same`, `rollback` (a lower\n * `sequence`, refused), `equivocation` (the same `sequence`, other bytes: refused, the held one kept) or `other-key`\n * (another store: a store is its key).\n */\nexport type AppStoreDecision = \"new\" | \"update\" | \"same\" | \"rollback\" | \"equivocation\" | \"other-key\";\n\nexport function appStoreDecision(held: AppStoreVersion | null, read: AppStoreVersion): AppStoreDecision {\n if (!held) return \"new\";\n if (held.key !== read.key) return \"other-key\";\n if (read.sequence > held.sequence) return \"update\";\n if (read.sequence < held.sequence) return \"rollback\";\n return read.digest === held.digest ? \"same\" : \"equivocation\";\n}\n","import { isAppUrl } from \"@ghostly/core\";\n\n/*\n * Where mini-apps and stores are read from (WISP 1200 § Stores, § Apps sent in a chat): in phase 1 only two hosts,\n * `raw.githubusercontent.com` and `cdn.jsdelivr.net` pinned to a full commit, both readable from a page (CORS `*`).\n * HTTPS only, no user or password, no port, no redirect (one would walk out of the list), no cookies, no referrer, and a\n * cap on the bytes read while the body streams in. Every read of the apps feature goes through `boundedAppFetch`.\n */\n\n/** The hosts phase 1 reads from. A jsDelivr URL must also name a 40-character commit (`isAppUrl`). */\nexport const APP_FETCH_HOSTS = [\"raw.githubusercontent.com\", \"cdn.jsdelivr.net\"] as const;\n\nexport const APP_FETCH_LIMITS = {\n /**\n * A store index as read (WISP 1200 § Stores, Privacy): 4 MiB in phase 1, under the format's 16 MiB. Counted on the body\n * as it arrives, after the browser undid any compression, since a page never sees the compressed size.\n */\n storeIndexBytes: 4 * 1024 * 1024,\n /** A store's signature statement, `ghostly-store.sig` (canonical, at most 1 KiB). */\n sigBytes: 1024,\n /** `ghostly-revoke.json`: at most 4096 signed revocations. */\n revocationsBytes: 16 * 1024 * 1024,\n /** How long the host has to answer (the response's headers). */\n timeoutMs: 30_000,\n /** How long the body may go without a byte: a read still arriving is never cut by the clock alone. */\n idleMs: 30_000,\n /** A whole read at most: the 16 MiB cap at about 224 kbit/s. */\n totalMs: 10 * 60_000,\n} as const;\n\n/** A URL this client may read an app, a store or a revocation list from. */\nexport function isAppFetchUrl(value: unknown): value is string {\n if (!isAppUrl(value)) return false;\n const url = new URL(value);\n return url.port === \"\" && (APP_FETCH_HOSTS as readonly string[]).includes(url.hostname.toLowerCase());\n}\n\n/** `slow`: the host did not answer in time, went silent, or the read ran past its whole budget. */\nexport type AppFetchErrorCode = \"host\" | \"offline\" | \"status\" | \"too-large\" | \"network\" | \"slow\";\n\nexport class AppFetchError extends Error {\n constructor(readonly code: AppFetchErrorCode, message: string, readonly status?: number) {\n // Its code first, as every error of the apps calls (`<code>: words`).\n super(`${code}: ${message}`);\n this.name = \"AppFetchError\";\n }\n}\n\n/**\n * Reads a URL of the list: its bytes, at most `maxBytes`. With `peek`, the first `maxBytes` bytes and no more, the rest\n * left unread (a bundle's manifest, to see whether it is newer before reading all of it). `signal` stops a read whose\n * bytes nobody will use any more (`network`). `revalidate`: a file every update check reads again (a store's index and\n * its sig, `ghostly-revoke.json`), kept by the browser and asked again with its ETag every time, so an unchanged one is\n * an empty 304 and never a copy the host was not asked about. Anything else is not kept by the browser (a bundle is\n * kept in file storage, a peek is a range).\n */\nexport type AppFetcher = (url: string, options: { maxBytes: number; peek?: boolean; revalidate?: boolean; signal?: AbortSignal }) => Promise<Uint8Array>;\n\nexport function boundedAppFetch(options: { fetcher?: typeof fetch; online?: () => boolean; timeoutMs?: number; idleMs?: number; totalMs?: number } = {}): AppFetcher {\n return async (url, { maxBytes, peek = false, revalidate = false, signal: stopped }) => {\n if (!isAppFetchUrl(url)) throw new AppFetchError(\"host\", \"Apps are read only from raw.githubusercontent.com, or from cdn.jsdelivr.net at a commit, over HTTPS\");\n if (options.online && !options.online()) throw new AppFetchError(\"offline\", \"Offline\");\n if (stopped?.aborted) throw new AppFetchError(\"network\", \"The read was stopped\");\n const fetcher = options.fetcher ?? globalThis.fetch.bind(globalThis);\n // One signal for the request and its body: the host has `timeoutMs` to answer, then the body `idleMs` between two\n // bytes, the whole read `totalMs`. A read still arriving goes on; one cut by the clock is `slow`, not `network`.\n const controller = new AbortController();\n const cut = () => { controller.abort(new DOMException(\"The read took too long\", \"TimeoutError\")); };\n const stop = () => { controller.abort(new DOMException(\"The read was stopped\", \"AbortError\")); };\n stopped?.addEventListener(\"abort\", stop);\n const total = setTimeout(cut, options.totalMs ?? APP_FETCH_LIMITS.totalMs);\n let idle = setTimeout(cut, options.timeoutMs ?? APP_FETCH_LIMITS.timeoutMs);\n const heard = () => { clearTimeout(idle); idle = setTimeout(cut, options.idleMs ?? APP_FETCH_LIMITS.idleMs); };\n const failure = (error: unknown) => stopped?.aborted ? new AppFetchError(\"network\", \"The read was stopped\")\n : controller.signal.aborted ? new AppFetchError(\"slow\", \"That took too long on this connection\")\n : new AppFetchError(\"network\", error instanceof Error ? error.message : String(error));\n const { signal } = controller;\n let response: Response;\n try {\n response = await fetcher(url, {\n signal,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: revalidate && !peek ? \"no-cache\" : \"no-store\", redirect: \"error\",\n ...(peek && { headers: { range: `bytes=0-${maxBytes - 1}` } }),\n });\n } catch (error) {\n clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop);\n throw failure(error);\n }\n heard();\n const parts: Uint8Array[] = [];\n let length = 0;\n try {\n // A redirect a fetcher followed after all (one that ignores `redirect`) still lands only on a host of the list.\n if (response.url && response.url !== url && !isAppFetchUrl(response.url)) throw new AppFetchError(\"host\", \"The host sent the request elsewhere\");\n if (!response.ok) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"status\", `The host answered ${response.status}`, response.status);\n }\n if (!peek && Number(response.headers.get(\"content-length\")) > maxBytes) {\n await response.body?.cancel().catch(() => {});\n throw new AppFetchError(\"too-large\", \"Too large\");\n }\n const reader = response.body?.getReader();\n if (reader) {\n // A body the signal does not reach (a fetcher of its own) is let go all the same: its pending read ends.\n const letGo = () => { reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", letGo);\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw failure(signal.reason);\n if (done) break;\n heard();\n if (length + value.length > maxBytes) {\n if (!peek) throw new AppFetchError(\"too-large\", \"Too large\");\n parts.push(value.subarray(0, maxBytes - length));\n length = maxBytes;\n break;\n }\n parts.push(value);\n length += value.length;\n }\n } catch (error) {\n if (error instanceof AppFetchError) throw error;\n throw failure(error);\n } finally {\n signal.removeEventListener(\"abort\", letGo);\n await reader.cancel().catch(() => {});\n }\n }\n } finally { clearTimeout(total); clearTimeout(idle); stopped?.removeEventListener(\"abort\", stop); }\n const bytes = new Uint8Array(length);\n let at = 0;\n for (const part of parts) { bytes.set(part, at); at += part.length; }\n return bytes;\n };\n}\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\n/**\n * The URL a pasted address reads `file` from (WISP 1200 § Paste a URL), or null when it is not one this client reads:\n * - `https://github.com/<owner>/<repo>`, or `/tree/<ref>`: `raw.githubusercontent.com/<owner>/<repo>/<ref or HEAD>/<file>`,\n * with no request to `github.com` or `api.github.com`;\n * - a file as GitHub shows it, `https://github.com/<owner>/<repo>/blob/<ref>/<path>` (or `/raw/`), naming a `.ghostlyapp`\n * or `.json` file: `raw.githubusercontent.com/<owner>/<repo>/<ref>/<path>`, again with no request to `github.com`;\n * - a URL of the list that names a file (`….ghostlyapp`, `….json`): itself;\n * - a URL of the list that names a folder: `<file>` in it.\n */\nexport function appPasteUrl(input: string, file: \"app.ghostlyapp\" | \"ghostly-store.json\"): string | null {\n let url: URL;\n try { url = new URL(input.trim()); } catch { return null; }\n if (url.protocol !== \"https:\" || url.username || url.password || url.port) return null;\n const host = url.hostname.toLowerCase();\n if (host === \"github.com\" || host === \"www.github.com\") {\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 2) return null;\n const owner = parts[0]!, repo = parts[1]!.replace(/\\.git$/, \"\");\n if (!NAME.test(owner) || !NAME.test(repo)) return null;\n let ref = \"HEAD\";\n if (parts.length > 2) {\n const rest = parts.slice(3);\n if (!rest.length || !rest.every((p) => NAME.test(p) && p !== \".\" && p !== \"..\")) return null;\n if (parts[2] === \"blob\" || parts[2] === \"raw\") {\n // `<ref>/<path>`: raw.githubusercontent.com takes the two joined the same way github.com does.\n if (rest.length < 2 || !/\\.(ghostlyapp|json)$/.test(rest[rest.length - 1]!)) return null;\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${rest.join(\"/\")}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n if (parts[2] !== \"tree\") return null;\n ref = rest.join(\"/\");\n }\n const raw = `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${file}`;\n return isAppFetchUrl(raw) ? raw : null;\n }\n const last = url.pathname.split(\"/\").pop() ?? \"\";\n const named = /\\.(ghostlyapp|json)$/.test(last) ? url.href : new URL(`${url.pathname.replace(/\\/?$/, \"/\")}${file}`, url).href;\n return isAppFetchUrl(named) ? named : null;\n}\n\n/** A page of github.com (any scheme): a link `appPasteUrl` could not read is still GitHub, and is answered as such. */\nexport function isGitHubPage(input: string): boolean {\n try {\n const host = new URL(input.trim()).hostname.toLowerCase();\n return host === \"github.com\" || host === \"www.github.com\";\n } catch { return false; }\n}\n\n/** A file beside another (`ghostly-store.sig` beside the index, `ghostly-revoke.json` beside a bundle). */\nexport function besideUrl(url: string, name: string): string {\n const target = new URL(url);\n target.search = \"\";\n target.hash = \"\";\n return new URL(name, target).href;\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,WAAW,MAA0B;CACnD,IAAI,KAAK,WAAW,IAAI,MAAM,IAAI,MAAM,+BAA+B;CAEvE,OAAO;EAAE,WADS,QAAQ,aAAa,IAC9B;EAAW,MAAM,OAAO,UAAU,KAAK,OAAO,IAAI;CAAE;AAC/D;;;;;AAMA,SAAgB,gBAAgB,YAAuB,WAA+B;CACpF,IAAI,UAAU,WAAW,IAAI,MAAM,IAAI,MAAM,mCAAmC;CAChF,OAAO;EACL;EACA,MAAM,OAAO,UAAU,IAAI,WAAW,MAAM,OAAO,OAAO,KAAK,EAAE,MAAM,UAAU,GAAG,YAAY,IAAI,WAAW,KAAK,CAAC,CAAC;CACxH;AACF;;AChBA,IAAa,mBAAmB;;CAE9B,YAAY;;CAEZ,eAAe;CACf,MAAM;CACN,aAAa;CACb,OAAO;CACP,SAAS;;CAET,OAAO;CACP,QAAQ;CACR,MAAM;CACN,MAAM;CACN,SAAS;CACT,SAAS;AACX;AAEA,IAAa,kBAAkB,CAAC,WAAW,SAAS;AAmCpD,IAAM,YAAY,MAA+C,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,CAAC;AACxH,IAAM,UAAU,GAAY,QAA6B,OAAO,MAAM,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,OAAO,CAAC,eAAe,KAAK,CAAC;AAChI,IAAM,WAAW,GAAY,QAA6B,OAAO,MAAM,YAAY,OAAO,cAAc,CAAC,KAAK,KAAK;AAGnH,IAAM,OAAc,EAAE,IAAI,KAAK;AAW/B,SAAS,OAAO,OAAgC,UAA6B,UAA6B,UAA4B,CAAC,GAAU;CAE/I,MAAM,YAAY,oBAAoB,KAAK;CAC3C,IAAI,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O,IAAI,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC9C,MAAM,QAAQ,uBAAuB,KAAK,IAAI,IAAI,IAAI,OAAO,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,QAAQ,GAAG,IAAI,QAAQ,GAAG,CAAC,CAAC;CACzH,OAAO,cAAc,KAAK,IAAI,QAAQ;AACxC;;AAGA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,MAAM,OAAO,IAAI,IAAI,MAAM,KAAK,CAAC,CAAC,CAAC,SAAS,YAAY;EACxD,OAAO,SAAS,gBAAgB,SAAS;CAC3C,QAAQ;EAAE,OAAO;CAAO;AAC1B;;AAGA,SAAgB,UAAU,KAAa,MAAsB;CAC3D,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,OAAO,SAAS;CAChB,OAAO,OAAO;CACd,OAAO,IAAI,IAAI,MAAM,MAAM,CAAC,CAAC;AAC/B"}
@@ -1 +1 @@
1
- export { s as initApp, c as publishApp, l as revokeApp, u as signStore, d as verifyApp } from "./apps-XnZ8VEuj.js";
1
+ export { s as initApp, c as publishApp, l as revokeApp, u as signStore, d as verifyApp } from "./apps-CL8TXHhu.js";
@@ -1,10 +1,10 @@
1
- import { Aa as appRef, Da as APP_PREFIXES, Fa as isAppLine, Ha as signAppObject, Ma as checkAppRevokeStatement, Na as isAppHash, Oa as APP_STATEMENT_LIMITS, Sa as isAppUrl, Ua as signAppRevocation, Va as setAppSignatureFastPath, Xa as canonicalJsonBytes, Ya as canonicalJson, ba as checkAppManifest, ka as appFingerprint, ma as APP_BUNDLE_LIMITS, wa as readAppBundle, ya as assembleAppBundle, za as readAppRevocations } from "./groupMeta-DTQAJG50.js";
2
- import { _ as readAppStore, b as signAppStore, d as appStoreDecision, g as checkAppStoreIndex, s as isAppFetchUrl, t as APP_FETCH_HOSTS, u as appRevocationFor, x as seedSigner, y as repeatedJsonKey } from "./appFetch-D56GsYuq.js";
1
+ import { Aa as appFingerprint, Ba as readAppRevocations, Ca as isAppUrl, Ha as setAppSignatureFastPath, Ia as isAppLine, Na as checkAppRevokeStatement, Oa as APP_PREFIXES, Pa as isAppHash, Ta as readAppBundle, Ua as signAppObject, Wa as signAppRevocation, Xa as canonicalJson, Za as canonicalJsonBytes, ba as assembleAppBundle, ha as APP_BUNDLE_LIMITS, ja as appRef, ka as APP_STATEMENT_LIMITS, xa as checkAppManifest } from "./groupMeta-DxuJzko_.js";
2
+ import { _ as readAppStore, b as signAppStore, d as appStoreDecision, g as checkAppStoreIndex, s as isAppFetchUrl, t as APP_FETCH_HOSTS, u as appRevocationFor, x as seedSigner, y as repeatedJsonKey } from "./appFetch-CW9fJPHh.js";
3
3
  import { i as fromBase64Url, l as toBase64Url, u as toZ32 } from "./bytes-C1DNGY18.js";
4
4
  import { i as localFileError, t as CliError } from "./errors-DDLFO4Gf.js";
5
- import { V as jsonOut } from "./apiKit-CVaEzKWQ.js";
6
- import { t as guardText } from "./secretGuard-B4-LlMjv.js";
7
- import { S as userPath } from "./profiles-BFSGqDFC.js";
5
+ import { V as jsonOut } from "./apiKit-BlsNk-Cx.js";
6
+ import { t as guardText } from "./secretGuard-BrATm_gl.js";
7
+ import { S as userPath } from "./profiles-BOYGlmu2.js";
8
8
  import { closeSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
9
9
  import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
10
10
  import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, verify } from "node:crypto";
@@ -1015,4 +1015,4 @@ async function signStore(indexArg, keyArg, outArg, now = Math.floor(Date.now() /
1015
1015
  }
1016
1016
  export { STORE_SIG_FILE as a, publishApp as c, verifyApp as d, writeWhole as f, STORE_INDEX_FILE as i, revokeApp as l, APP_REVOKE_FILE as n, checkedBundle as o, nativePublicKey as p, APP_SOURCE as r, initApp as s, APP_BUNDLE_FILE as t, signStore as u };
1017
1017
 
1018
- //# sourceMappingURL=apps-XnZ8VEuj.js.map
1018
+ //# sourceMappingURL=apps-CL8TXHhu.js.map