@ghostlytools/cli 1.13.1 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +6 -4
  2. package/dist/assets/api-DV52o7A8.js +3 -0
  3. package/dist/assets/{api-Dnq86JAA.js → api-O57SNJcb.js} +375 -77
  4. package/dist/assets/api-O57SNJcb.js.map +1 -0
  5. package/dist/assets/{apiKit-nLK4jeTq.js → apiKit-CPTFJHA7.js} +39 -7
  6. package/dist/assets/{apiKit-nLK4jeTq.js.map → apiKit-CPTFJHA7.js.map} +1 -1
  7. package/dist/assets/{appFetch-wqBWi3Ry.js → appFetch-Ca9DNQQ2.js} +2 -2
  8. package/dist/assets/{appFetch-wqBWi3Ry.js.map → appFetch-Ca9DNQQ2.js.map} +1 -1
  9. package/dist/assets/{apps-DBVhKpfe.js → apps-gXpGFPiv.js} +11 -9
  10. package/dist/assets/apps-gXpGFPiv.js.map +1 -0
  11. package/dist/assets/{apps-nLtyhC2f.js → apps-uZTu5FlR.js} +1 -1
  12. package/dist/assets/{arkade-DryM-q5n.js → arkade-B6UNf5HI.js} +2 -2
  13. package/dist/assets/{arkade-DryM-q5n.js.map → arkade-B6UNf5HI.js.map} +1 -1
  14. package/dist/assets/{backup-Bczllmzf.js → backup-CxH3auHB.js} +8 -6
  15. package/dist/assets/backup-CxH3auHB.js.map +1 -0
  16. package/dist/assets/{backup-D6s0LQdg.js → backup-Di2U6QVH.js} +1 -1
  17. package/dist/assets/{bitcoind-DML_-Xbv.js → bitcoind-BpZn3bRN.js} +2 -2
  18. package/dist/assets/{bitcoind-DML_-Xbv.js.map → bitcoind-BpZn3bRN.js.map} +1 -1
  19. package/dist/assets/{buttons-B3C3vdhH.js → buttons-D4udKEvT.js} +4 -4
  20. package/dist/assets/{buttons-B3C3vdhH.js.map → buttons-D4udKEvT.js.map} +1 -1
  21. package/dist/assets/buttons-YTYEqvGC.js +1 -0
  22. package/dist/assets/{client-B7jRrSnb.js → client-DGx7E8b3.js} +2 -2
  23. package/dist/assets/{client-B7jRrSnb.js.map → client-DGx7E8b3.js.map} +1 -1
  24. package/dist/assets/{engineErrors--9hfgKlK.js → engineErrors-wWlLy54D.js} +11 -3
  25. package/dist/assets/engineErrors-wWlLy54D.js.map +1 -0
  26. package/dist/assets/{fixedHosts-H3i6o9Iy.js → fixedHosts-CODN2pTL.js} +3 -3
  27. package/dist/assets/{fixedHosts-H3i6o9Iy.js.map → fixedHosts-CODN2pTL.js.map} +1 -1
  28. package/dist/assets/{groupMeta--fxSh792.js → groupMeta-CeZpqVVC.js} +105 -36
  29. package/dist/assets/groupMeta-CeZpqVVC.js.map +1 -0
  30. package/dist/assets/{host-CGzVFfMz.js → host-CRA7h5A2.js} +113 -40
  31. package/dist/assets/host-CRA7h5A2.js.map +1 -0
  32. package/dist/assets/{hyperdhtRelay-Ce-gWsRY.js → hyperdhtRelay-B34Zhz4P.js} +2 -2
  33. package/dist/assets/{hyperdhtRelay-Ce-gWsRY.js.map → hyperdhtRelay-B34Zhz4P.js.map} +1 -1
  34. package/dist/assets/{hyperdhtRelay-B4_wdCtx.js → hyperdhtRelay-DDwU5b4P.js} +2 -2
  35. package/dist/assets/{hyperdhtRelay-B4_wdCtx.js.map → hyperdhtRelay-DDwU5b4P.js.map} +1 -1
  36. package/dist/assets/{identityProofs-Cksc_K7_.js → identityProofs-B8zCp5_0.js} +140 -27
  37. package/dist/assets/identityProofs-B8zCp5_0.js.map +1 -0
  38. package/dist/assets/{irohWeb-Dp1i8v6n.js → irohWeb-mnOi2Jp7.js} +10832 -4832
  39. package/dist/assets/irohWeb-mnOi2Jp7.js.map +1 -0
  40. package/dist/assets/{linkPreview-DdMf-YAc.js → linkPreview-5kHmKUTN.js} +20 -8
  41. package/dist/assets/linkPreview-5kHmKUTN.js.map +1 -0
  42. package/dist/assets/{main-C8J53SwH.js → main-Chc871HV.js} +72 -39
  43. package/dist/assets/main-Chc871HV.js.map +1 -0
  44. package/dist/assets/{mainline-DY95WbuK.js → mainline-CDUXtV-I.js} +2 -2
  45. package/dist/assets/{mainline-DY95WbuK.js.map → mainline-CDUXtV-I.js.map} +1 -1
  46. package/dist/assets/{networkReason-Be-hMghr.js → networkReason-DYlPZS5M.js} +2 -2
  47. package/dist/assets/{networkReason-Be-hMghr.js.map → networkReason-DYlPZS5M.js.map} +1 -1
  48. package/dist/assets/{ownDid-oa-T2vmZ.js → ownDid-BOuSlDv-.js} +4 -4
  49. package/dist/assets/{ownDid-oa-T2vmZ.js.map → ownDid-BOuSlDv-.js.map} +1 -1
  50. package/dist/assets/{ownStatus-Bc08eNJY.js → ownStatus-CLA1VPkL.js} +3 -3
  51. package/dist/assets/{ownStatus-Bc08eNJY.js.map → ownStatus-CLA1VPkL.js.map} +1 -1
  52. package/dist/assets/{pairedTransports-Dppn8lUN.js → pairedTransports-DAzupLYo.js} +21 -15
  53. package/dist/assets/pairedTransports-DAzupLYo.js.map +1 -0
  54. package/dist/assets/{paymentIntent-DySU3Ajm.js → paymentIntent-Cr3uZa_0.js} +2 -2
  55. package/dist/assets/{paymentIntent-DySU3Ajm.js.map → paymentIntent-Cr3uZa_0.js.map} +1 -1
  56. package/dist/assets/{profiles-B2uy04ph.js → profiles-BH1bH9aE.js} +2 -2
  57. package/dist/assets/{profiles-B2uy04ph.js.map → profiles-BH1bH9aE.js.map} +1 -1
  58. package/dist/assets/{registry-bLIfG619.js → registry-DAq16T-V.js} +1 -1
  59. package/dist/assets/{registry-DbTLLs3y.js → registry-DP_-RA-v.js} +5 -5
  60. package/dist/assets/{registry-DbTLLs3y.js.map → registry-DP_-RA-v.js.map} +1 -1
  61. package/dist/assets/{relay-CHWg5hpZ.js → relay-gJTOYQJZ.js} +93 -7
  62. package/dist/assets/relay-gJTOYQJZ.js.map +1 -0
  63. package/dist/assets/{resolve-DNX-eecG.js → resolve-B1eQ4dVQ.js} +3 -3
  64. package/dist/assets/{resolve-DNX-eecG.js.map → resolve-B1eQ4dVQ.js.map} +1 -1
  65. package/dist/assets/{server-DWJ4RzJn.js → server-Bd2ofxc1.js} +717 -6389
  66. package/dist/assets/server-Bd2ofxc1.js.map +1 -0
  67. package/dist/assets/{sshForges-BnvwmNj-.js → sshForges-As7dbGXM.js} +2 -2
  68. package/dist/assets/{sshForges-BnvwmNj-.js.map → sshForges-As7dbGXM.js.map} +1 -1
  69. package/dist/assets/{translate-CHj_PdLg.js → translate-DnuQMfj0.js} +10 -4
  70. package/dist/assets/translate-DnuQMfj0.js.map +1 -0
  71. package/dist/assets/{usdt-CBJ4Q5Ji.js → usdt-DLmtf8F9.js} +4 -4
  72. package/dist/assets/{usdt-CBJ4Q5Ji.js.map → usdt-DLmtf8F9.js.map} +1 -1
  73. package/dist/assets/{waitNotice-Cvz5CiKR.js → waitNotice-BHuMofaH.js} +2 -2
  74. package/dist/assets/{waitNotice-Cvz5CiKR.js.map → waitNotice-BHuMofaH.js.map} +1 -1
  75. package/dist/ghostly.mjs +1 -1
  76. package/npm-shrinkwrap.json +2 -2
  77. package/package.json +1 -1
  78. package/dist/assets/api-DF36rBJK.js +0 -3
  79. package/dist/assets/api-Dnq86JAA.js.map +0 -1
  80. package/dist/assets/apps-DBVhKpfe.js.map +0 -1
  81. package/dist/assets/backup-Bczllmzf.js.map +0 -1
  82. package/dist/assets/buttons-DaY5FYlV.js +0 -1
  83. package/dist/assets/engineErrors--9hfgKlK.js.map +0 -1
  84. package/dist/assets/groupMeta--fxSh792.js.map +0 -1
  85. package/dist/assets/host-CGzVFfMz.js.map +0 -1
  86. package/dist/assets/identityProofs-Cksc_K7_.js.map +0 -1
  87. package/dist/assets/irohWeb-Dp1i8v6n.js.map +0 -1
  88. package/dist/assets/linkPreview-DdMf-YAc.js.map +0 -1
  89. package/dist/assets/main-C8J53SwH.js.map +0 -1
  90. package/dist/assets/pairedTransports-Dppn8lUN.js.map +0 -1
  91. package/dist/assets/relay-CHWg5hpZ.js.map +0 -1
  92. package/dist/assets/server-DWJ4RzJn.js.map +0 -1
  93. package/dist/assets/translate-CHj_PdLg.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client-B7jRrSnb.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * The call's own clock, in ms: monotonic, so the device's clock set back or ahead mid-call (a phone or a VM fixing its\n * time) moves the time of day, not the audio. On `Date.now()`, a clock set back held the next frame for as long as the\n * jump, and one set ahead read as that long without a packet from the contact.\n */\nexport const monotonic = (): number => performance.now();\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */\n private owed = false;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = monotonic, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n if (this.owed) {\n this.owed = false;\n chunk = chunk.subarray(1);\n }\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n // The queue ends on a whole sample here, so an odd number lost ends on half of one.\n if (lost % 2) this.owed = true;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n // Half a sample queued: its other half is the program's next byte.\n if (this.length % 2) this.owed = true;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n /**\n * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is\n * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much\n * was dropped, in milliseconds.\n */\n newWriter(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n // A flush that cut the last program's half sample owes nothing to the next program: it starts on a whole sample.\n this.owed = false;\n return ms;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n","import { readFileSync } from \"node:fs\";\nimport { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\nimport { lockPath } from \"./profiles\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/**\n * The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody\n * holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,\n * which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether\n * a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.\n */\nexport function notTheDaemon(address: DaemonAddress, held = profileHeld(address.dir)): CliError {\n if (!held) {\n return new CliError(\"refused\", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, { reason: \"not-the-daemon\", socket: address.socket });\n }\n return new CliError(\"refused\", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\n/** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */\nfunction profileHeld(dir: string): boolean {\n try {\n const pid = Number(readFileSync(lockPath(dir), \"utf8\").trim());\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */\nconst unanswered = new WeakSet<CliError>();\n\n/**\n * A call the daemon read and never answered, because it stopped (a restart, a crash): what was asked may be done, so\n * it is no plain failure a bot tries again (a send went twice). A daemon that stops answers its waits first (`serve`);\n * this is for the calls it could not.\n */\nfunction stoppedUnanswered(method: string): CliError {\n const error = new CliError(\"timeout\", `The daemon stopped before it answered ${method}, which may be done: check (\\`ghostly chat history\\` for a message) before you try again`, { method, reason: \"daemon-stopped\" });\n unanswered.add(error);\n return error;\n}\n\n/**\n * A call whose connection ended before the daemon read it, or before it proved itself: nothing was done. `leaving`: this\n * client ended it (a deadline, Ctrl-C), so it is no daemon that stopped under the call.\n */\nfunction wentAway(leaving: boolean): CliError {\n const error = new CliError(\"unavailable\", \"The daemon went away\");\n if (!leaving) unanswered.add(error);\n return error;\n}\n\n/**\n * Whether a call failed because its connection ended unanswered (the daemon stopped, restarted or crashed under it),\n * not because the daemon answered it with an error. A read that did can be asked again: it changed nothing. So may one\n * refused because the daemon's secret was gone when its greeting or its hello's answer came: a daemon that stops removes\n * it first, and the greeting it wrote just before is read after. Nothing but the hello was written to it, and a listener\n * that never proves itself is refused again on the new connection.\n */\nexport function endedUnanswered(error: unknown): boolean {\n return error instanceof CliError && unanswered.has(error);\n}\n\n/**\n * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are\n * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.\n */\nexport function endedUnsent(error: unknown): boolean {\n return endedUnanswered(error) && (error as CliError).details?.reason !== \"daemon-stopped\";\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n /** `written`: the call is on the socket, so the daemon may have acted on it. */\n private readonly pending = new Map<number, { method: string; written: boolean; resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n /** This client closed the connection: what was still unanswered is its own doing, not a daemon that stopped. */\n private leaving = false;\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(!secret); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse(!secret);\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? wentAway(this.leaving);\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(waiting.written && !this.refusal && !this.leaving ? stoppedUnanswered(waiting.method) : why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */\n private refuse(secretGone = false): void {\n this.refusal = notTheDaemon(this.address);\n if (secretGone) unanswered.add(this.refusal);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? wentAway(this.leaving));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n method, written: false,\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => {\n if (!this.pending.has(id) || this.socket.destroyed) return;\n this.socket.write(line);\n settle.written = true;\n },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.leaving = true;\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.leaving = true;\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });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E,aAAa,gBAAyC,CAAC,GAAiC;CACjK,MAAM,OAAO,QAAQ;CAErB,IAAI,CAAC,UAAU,IAAI,GAAG,OAAO,QAAQ,QAAQ,IAAI;CACjD,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,QAAQ,IAAI;EAC3B,MAAM,QAAQ,iBAAiB;GAAE,OAAO,QAAQ;GAAG,QAAQ,IAAI;EAAG,GAAG,SAAS;EAC9E,OAAO,KAAK,iBAAiB;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI,aAAa,QAAQ,SAAS,UAAU,CAAC;EAAG,CAAC;EAC7G,OAAO,KAAK,eAAe;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI;EAAG,CAAC;CACpE,CAAC;AACH"}
1
+ {"version":3,"file":"client-DGx7E8b3.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts","../../src/client.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * The call's own clock, in ms: monotonic, so the device's clock set back or ahead mid-call (a phone or a VM fixing its\n * time) moves the time of day, not the audio. On `Date.now()`, a clock set back held the next frame for as long as the\n * jump, and one set ahead read as that long without a packet from the contact.\n */\nexport const monotonic = (): number => performance.now();\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n /** Half a sample was dropped (a flush, a full queue): the program's next byte is its other half, dropped too. */\n private owed = false;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = monotonic, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n if (this.owed) {\n this.owed = false;\n chunk = chunk.subarray(1);\n }\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n // The queue ends on a whole sample here, so an odd number lost ends on half of one.\n if (lost % 2) this.owed = true;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n // Half a sample queued: its other half is the program's next byte.\n if (this.length % 2) this.owed = true;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n /**\n * Another program writes from now on (it replaced the last one on the call's socket): what the last one left is\n * dropped, half a sample included, so the new one starts on a whole sample and is heard at once. Returns how much\n * was dropped, in milliseconds.\n */\n newWriter(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n // A flush that cut the last program's half sample owes nothing to the next program: it starts on a whole sample.\n this.owed = false;\n return ms;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n","import { readFileSync } from \"node:fs\";\nimport { connect, type Socket } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport { CliError, type ErrorCode } from \"./errors\";\nimport type { GhostlyEvent } from \"./events\";\nimport { daemonOfThisRelease, HELLO, newNonce, provesDaemon, provesGreeting, readDaemonSecret } from \"./daemonProof\";\nimport { ownSocket } from \"./privateFolder\";\nimport { lockPath } from \"./profiles\";\n\n/** The id of the hello on every connection: a string, so it is never one of the calls' numbers. */\nconst HELLO_ID = \"hello\";\n\n/**\n * How long a client waits for the daemon's greeting before it asks who holds the profile: a daemon greets as it\n * accepts the connection, and one of an older release (before the greeting) never does. A daemon of this release\n * holding the profile (`daemonOfThisRelease`) is busy and is waited for, under each call's own deadline; anything\n * else is refused then. It used to refuse every late greeting, after 10 s: a daemon busy that long on one task (an\n * outbox backlog, 14 to 29 s) had every command and `listen` refused as an older release's, to be restarted.\n */\nexport const GREETING_MS = 2_000;\n\n/** The longest request line the daemon reads (WISP 1100 § Framing): it cuts the connection on a longer one. */\nexport const MAX_LINE = 16 * 1024 * 1024;\n\n/** What a client needs of a profile to reach its daemon: the socket, and the folder the daemon's secret is in. */\nexport interface DaemonAddress { socket: string; dir: string }\n\n/**\n * The refusal of a listener that did not prove it is the profile's daemon (`isNotTheDaemon` tells it apart). With nobody\n * holding the profile it is no daemon of any release, and no restart moves it: the answer pointed at `daemon restart`,\n * which answered the same, and a start said a daemon ran. What listens there has to stop, or its file go. `held`: whether\n * a process holds the profile, as the caller knows it (`lockOwner`); read here as a greeting's proof reads it otherwise.\n */\nexport function notTheDaemon(address: DaemonAddress, held = profileHeld(address.dir)): CliError {\n if (!held) {\n return new CliError(\"refused\", `Something that is not this profile's daemon listens on ${address.socket}, and no ghostly process holds the profile: nothing was sent to it. Stop the program that listens there, or remove that file, then start the daemon with ghostly daemon --detach`, { reason: \"not-the-daemon\", socket: address.socket });\n }\n return new CliError(\"refused\", `What answers on ${address.socket} did not prove it is this profile's daemon, so nothing was sent to it. A daemon of an older release cannot: \\`ghostly daemon restart\\` starts this one's`, { reason: \"not-the-daemon\" });\n}\n\n/** Whether a live process of this user's is in the profile's lock (`daemonProof.ts` reads it the same way). */\nfunction profileHeld(dir: string): boolean {\n try {\n const pid = Number(readFileSync(lockPath(dir), \"utf8\").trim());\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/** The failures of calls whose connection ended unanswered (`endedUnanswered`), not answers the daemon gave. */\nconst unanswered = new WeakSet<CliError>();\n\n/**\n * A call the daemon read and never answered, because it stopped (a restart, a crash): what was asked may be done, so\n * it is no plain failure a bot tries again (a send went twice). A daemon that stops answers its waits first (`serve`);\n * this is for the calls it could not.\n */\nfunction stoppedUnanswered(method: string): CliError {\n const error = new CliError(\"timeout\", `The daemon stopped before it answered ${method}, which may be done: check (\\`ghostly chat history\\` for a message) before you try again`, { method, reason: \"daemon-stopped\" });\n unanswered.add(error);\n return error;\n}\n\n/**\n * A call whose connection ended before the daemon read it, or before it proved itself: nothing was done. `leaving`: this\n * client ended it (a deadline, Ctrl-C), so it is no daemon that stopped under the call.\n */\nfunction wentAway(leaving: boolean): CliError {\n const error = new CliError(\"unavailable\", \"The daemon went away\");\n if (!leaving) unanswered.add(error);\n return error;\n}\n\n/**\n * Whether a call failed because its connection ended unanswered (the daemon stopped, restarted or crashed under it),\n * not because the daemon answered it with an error. A read that did can be asked again: it changed nothing. So may one\n * refused because the daemon's secret was gone when its greeting or its hello's answer came: a daemon that stops removes\n * it first, and the greeting it wrote just before is read after. Nothing but the hello was written to it, and a listener\n * that never proves itself is refused again on the new connection.\n */\nexport function endedUnanswered(error: unknown): boolean {\n return error instanceof CliError && unanswered.has(error);\n}\n\n/**\n * Whether a call ended unanswered before it was written (`endedUnanswered`, and not a call the daemon read: those are\n * `daemon-stopped`): nothing reached the daemon, so the call may go to the daemon that runs next, whatever it does.\n */\nexport function endedUnsent(error: unknown): boolean {\n return endedUnanswered(error) && (error as CliError).details?.reason !== \"daemon-stopped\";\n}\n\nexport function isNotTheDaemon(error: unknown): boolean {\n return error instanceof CliError && error.code === \"refused\" && error.details?.reason === \"not-the-daemon\";\n}\n\n/**\n * A connection to a profile's daemon over its socket (WISP 1100 § Local control API). `null` from `connectDaemon`\n * means no daemon answers there: a one-shot command runs the profile itself.\n *\n * The client writes nothing on it until the daemon's greeting, its first line, proves the other end read the\n * profile's daemon secret and holds the profile's lock (`provesGreeting`): a listener that cannot prove it has read\n * nothing from this client, so it cannot impersonate it either (`daemonProof.ts`). Then the first line written is a\n * `daemon.hello`, and no call is written until its answer proves the same over the client's own nonce. Until then\n * every call waits, under its own deadline, and a listener that does not prove both gets every call refused\n * (`refused`, `isNotTheDaemon`). Nothing it writes before that is read either.\n */\nexport class DaemonClient {\n private nextId = 1;\n /** `written`: the call is on the socket, so the daemon may have acted on it. */\n private readonly pending = new Map<number, { method: string; written: boolean; resolve: (value: unknown) => void; reject: (error: Error) => void }>();\n /** This client closed the connection: what was still unanswered is its own doing, not a daemon that stopped. */\n private leaving = false;\n private eventListener: ((event: GhostlyEvent) => void) | null = null;\n private closedListener: (() => void) | null = null;\n /** While paused: the events of the chunk already read, given to the listener on resume. */\n private held: GhostlyEvent[] | null = null;\n private greeted = false;\n private verified = false;\n private refusal: CliError | null = null;\n private readonly ready: Promise<void>;\n private settle!: { resolve: () => void; reject: (error: CliError) => void };\n\n constructor(private readonly socket: Socket, private readonly address: DaemonAddress, greetingMs = GREETING_MS) {\n this.ready = new Promise<void>((resolve, reject) => { this.settle = { resolve, reject }; });\n this.ready.catch(() => {});\n const nonce = newNonce();\n // Nothing is written until the greeting either way: a busy daemon only keeps the calls waiting.\n const waitedTooLong = setTimeout(() => { if (!this.greeted && !this.refusal && !daemonOfThisRelease(this.address.dir)) this.refuse(); }, greetingMs);\n waitedTooLong.unref?.();\n const lines = createInterface({ input: socket, crlfDelay: Infinity });\n // readline passes on its input's errors: a daemon that went away with this client's lines unread (ECONNRESET) ended\n // the command on an unhandled 'error' instead of the close below (unavailable).\n lines.on(\"error\", () => {});\n lines.on(\"line\", (line) => {\n let message: { id?: number | string; result?: unknown; error?: { code: ErrorCode; message: string; details?: Record<string, unknown> }; event?: GhostlyEvent };\n // A first line that is not even JSON is no greeting: refused as one that does not prove itself.\n try { message = JSON.parse(line); } catch { if (!this.greeted && !this.refusal) this.refuse(); return; }\n if (this.refusal) return;\n if (!this.greeted) {\n clearTimeout(waitedTooLong);\n // The secret is read once a listener spoke: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!secret || !provesGreeting(secret, this.address.dir, message)) { this.refuse(!secret); return; }\n this.greeted = true;\n // A client closed before the greeting came (a start's readiness probe) has nothing to say.\n if (socket.writableEnded || socket.destroyed) return;\n socket.write(JSON.stringify({ id: HELLO_ID, method: HELLO, params: { nonce } }) + \"\\n\");\n return;\n }\n if (!this.verified) {\n if (message?.id !== HELLO_ID) return;\n // The secret is read once a listener answered: the daemon wrote it before it listened.\n const secret = readDaemonSecret(this.address.dir);\n if (!message.error && secret && provesDaemon(secret, nonce, message.result)) { this.verified = true; this.settle.resolve(); return; }\n this.refuse(!secret);\n return;\n }\n if (message.event) { if (this.held) this.held.push(message.event); else this.eventListener?.(message.event); return; }\n const waiting = typeof message.id === \"number\" ? this.pending.get(message.id) : undefined;\n if (!waiting) return;\n this.pending.delete(message.id as number);\n if (message.error) waiting.reject(new CliError(message.error.code, message.error.message, message.error.details));\n else waiting.resolve(message.result);\n });\n socket.on(\"close\", () => {\n clearTimeout(waitedTooLong);\n const why = this.refusal ?? wentAway(this.leaving);\n if (!this.verified) this.settle.reject(why);\n for (const waiting of this.pending.values()) waiting.reject(waiting.written && !this.refusal && !this.leaving ? stoppedUnanswered(waiting.method) : why);\n this.pending.clear();\n this.closedListener?.();\n });\n socket.on(\"error\", () => {});\n }\n\n /** `secretGone`: the daemon's secret was not there to check against, as when it stops (`endedUnanswered`). */\n private refuse(secretGone = false): void {\n this.refusal = notTheDaemon(this.address);\n if (secretGone) unanswered.add(this.refusal);\n this.settle.reject(this.refusal);\n this.socket.destroy();\n }\n\n /**\n * `timeoutMs`: give up (code `timeout`, exit 4) when the daemon has not answered by then; without it the call waits\n * for as long as the connection holds. A call that timed out closes the connection: its answer, if one ever comes,\n * is of no use, and the process leaves once nothing else keeps it (not every caller reaches `exit`).\n *\n * A call whose line is longer than `MAX_LINE` is refused here, never written: the daemon cut the connection on it,\n * and the command answered \"The daemon went away\" (`unavailable`, read as try later) while the daemon ran on.\n */\n call(method: string, params: unknown = {}, { timeoutMs }: { timeoutMs?: number } = {}): Promise<unknown> {\n if (this.socket.destroyed) return Promise.reject(this.refusal ?? wentAway(this.leaving));\n const id = this.nextId++;\n const line = JSON.stringify({ id, method, params }) + \"\\n\";\n const bytes = Buffer.byteLength(line);\n if (bytes > MAX_LINE) return Promise.reject(new CliError(\"bad_request\", `${method} came to ${(bytes / 1024 / 1024).toFixed(1)} MiB as JSON, more than a daemon reads in one request (16 MiB): nothing was sent (a long text goes as a file: ghostly file send <chat|group> <path>)`));\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (!this.pending.delete(id)) return;\n reject(new CliError(\"timeout\", `The daemon did not answer ${method} in ${timeoutMs / 1000} s: \\`ghostly daemon restart\\` starts a fresh one`, { method }));\n this.destroy();\n }, timeoutMs);\n timer.unref?.();\n }\n const settle = {\n method, written: false,\n resolve: (value: unknown) => { if (timer) clearTimeout(timer); resolve(value); },\n reject: (error: Error) => { if (timer) clearTimeout(timer); reject(error); },\n };\n this.pending.set(id, settle);\n // Written once the daemon proved itself, in the order the calls were made; a refusal ends each instead.\n this.ready.then(\n () => {\n if (!this.pending.has(id) || this.socket.destroyed) return;\n this.socket.write(line);\n settle.written = true;\n },\n (error: CliError) => { if (this.pending.delete(id)) settle.reject(error); },\n );\n });\n }\n\n /** Events after `since` (replayed from the journal), then every new one, until the connection closes. */\n async subscribe(since: number | undefined, listener: (event: GhostlyEvent) => void, onClosed?: () => void): Promise<{ lastSeq: number }> {\n this.eventListener = listener;\n this.closedListener = onClosed ?? null;\n return this.call(\"events.subscribe\", since === undefined ? {} : { since }) as Promise<{ lastSeq: number }>;\n }\n\n /**\n * Stops reading: what the daemon sends waits in the connection (and past its bound the daemon ends it), and no\n * event reaches the listener until `resume`.\n */\n pause(): void {\n if (this.held) return;\n this.held = [];\n this.socket.pause();\n }\n\n /** Gives the listener the events held, then reads again; a listener that pauses again keeps the rest held. */\n resume(): void {\n const held = this.held;\n if (!held) return;\n this.held = null;\n for (let i = 0; i < held.length; i++) {\n this.eventListener?.(held[i]);\n if (this.held) { (this.held as GhostlyEvent[]).unshift(...held.slice(i + 1)); return; }\n }\n this.socket.resume();\n }\n\n close(): void {\n this.leaving = true;\n this.socket.end();\n }\n\n /** Closes at once: what the daemon still sends is not read. */\n destroy(): void {\n this.leaving = true;\n this.socket.destroy();\n }\n}\n\n/**\n * `timeoutMs` bounds the connect only; `greetingMs`, the wait for the daemon's greeting (above). The client it gives\n * has written nothing yet; whether the listener is the daemon is known at the first call.\n */\nexport function connectDaemon(address: DaemonAddress, timeoutMs = 2_000, { greetingMs = GREETING_MS }: { greetingMs?: number } = {}): Promise<DaemonClient | null> {\n const path = address.socket;\n // Someone else's socket (or a link) where the daemon's should be is no daemon of this profile's.\n if (!ownSocket(path)) return Promise.resolve(null);\n return new Promise((resolve) => {\n const socket = connect(path);\n const timer = setTimeout(() => { socket.destroy(); resolve(null); }, timeoutMs);\n socket.once(\"connect\", () => { clearTimeout(timer); resolve(new DaemonClient(socket, address, greetingMs)); });\n socket.once(\"error\", () => { clearTimeout(timer); resolve(null); });\n });\n}\n"],"mappings":";;;;;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OAAQ,GAAI;AAExG,SAAgB,WAAW,OAAmC;CAC5D,OAAO,WAAW,SAAS,KAAiB;AAC9C;;AAGA,IAAa,eAAe;;;;;;AAa5B,IAAa,kBAA0B,YAAY,IAAI;;;;;AAMvD,IAAa,gBAAb,MAA2B;CAaJ;CAAiC;CAZtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAAiB;CACjB,WAAmB;;CAEnB,OAAe;CACf;CACA;CACA;;CAEA,UAAU;CAEV,YAAY,MAAyB,MAAqC,WAAW,QAAQ,cAAc;EAAtF,KAAA,OAAA;EAAiC,KAAA,MAAA;EACpD,KAAK,QAAQ,WAAW,IAAI;EAE5B,KAAK,MAAM,KAAK,MAAO,OAAO,QAAS,GAAI,IAAI;EAC/C,KAAK,UAAU,OAAO,MAAM,KAAK,KAAK;CACxC;;CAGA,KAAK,OAAuB;EAC1B,IAAI,CAAC,MAAM,QAAQ,OAAO;EAC1B,KAAK,W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,KAAK,OAAO;EACZ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;GACpC,KAAK,gBAAgB,KAAK,EAAE;GAC5B,IAAI,KAAK,MAAM;IAAE,KAAM,KAAwB,QAAQ,GAAG,KAAK,MAAM,IAAI,CAAC,CAAC;IAAG;GAAQ;EACxF;EACA,KAAK,OAAO,OAAO;CACrB;CAEA,QAAc;EACZ,KAAK,UAAU;EACf,KAAK,OAAO,IAAI;CAClB;;CAGA,UAAgB;EACd,KAAK,UAAU;EACf,KAAK,OAAO,QAAQ;CACtB;AACF;;;;;AAMA,SAAgB,cAAc,SAAwB,YAAY,KAAO,EAAE,aAAa,gBAAyC,CAAC,GAAiC;CACjK,MAAM,OAAO,QAAQ;CAErB,IAAI,CAAC,UAAU,IAAI,GAAG,OAAO,QAAQ,QAAQ,IAAI;CACjD,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAS,QAAQ,IAAI;EAC3B,MAAM,QAAQ,iBAAiB;GAAE,OAAO,QAAQ;GAAG,QAAQ,IAAI;EAAG,GAAG,SAAS;EAC9E,OAAO,KAAK,iBAAiB;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI,aAAa,QAAQ,SAAS,UAAU,CAAC;EAAG,CAAC;EAC7G,OAAO,KAAK,eAAe;GAAE,aAAa,KAAK;GAAG,QAAQ,IAAI;EAAG,CAAC;CACpE,CAAC;AACH"}
@@ -31,6 +31,7 @@ var ENGINE_ERRORS = {
31
31
  ecashBeingReceived: "This ecash is already being received",
32
32
  ecashFeeTakesAll: "The mint keeps all {amount} sats of this ecash as its fee to take it in: nothing was redeemed, and its sender can still take it back",
33
33
  ecashOtherUnit: "This ecash is in {unit}: only sat ecash can be redeemed here",
34
+ ecashUnnamedUnit: "This ecash is in another unit: only sat ecash can be redeemed here",
34
35
  reviewedEcashSpent: "The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.",
35
36
  reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.",
36
37
  mintFailedQuote: "{host} could not take this payment right now, and no sats left your wallet: try again later. The mint said: {reason}",
@@ -106,12 +107,19 @@ function engineText(code, values = {}) {
106
107
  return ENGINE_ERRORS[code].replace(/\{(\w+)\}/g, (_, name) => name in values ? String(values[name]) : `{${name}}`);
107
108
  }
108
109
  var engineError = (code, values) => new EngineError(code, values);
110
+ /** A unit as the app names it: a unit's shape (`frames.ts` `isUnit`, in any case), never a token sender's other text. */
111
+ var NAMED_UNIT = "[A-Za-z0-9]{1,12}";
112
+ /**
113
+ * Why ecash of `unit` is not redeemed here. The unit is named only when it looks like one: a token's unit is whatever
114
+ * its sender wrote, and the line is the app's own (a contact's payment's refusal row, the CLI's answer).
115
+ */
116
+ var ecashUnitError = (unit) => new RegExp(`^${NAMED_UNIT}$`).test(unit) ? engineError("ecashOtherUnit", { unit }) : engineError("ecashUnnamedUnit");
109
117
  /** What each kind of value looks like in a text: never a space in a host, a network by its name, an amount as digits. */
110
118
  var VALUE = {
111
119
  host: "(\\S+)",
112
120
  domain: "(\\S+)",
113
121
  chain: "(\\S+)",
114
- unit: "(\\S+)",
122
+ unit: `(${NAMED_UNIT})`,
115
123
  network: "(Mainnet|Testnet)",
116
124
  amount: "(\\d[\\d.,\\u00a0\\u202f' ]*?)",
117
125
  fee: "(\\d[\\d.,\\u00a0\\u202f' ]*?)",
@@ -145,6 +153,6 @@ function parseEngineError(text) {
145
153
  }
146
154
  return null;
147
155
  }
148
- export { parseEngineError as i, engineError as n, engineText as r, EngineError as t };
156
+ export { parseEngineError as a, engineText as i, ecashUnitError as n, engineError as r, EngineError as t };
149
157
 
150
- //# sourceMappingURL=engineErrors--9hfgKlK.js.map
158
+ //# sourceMappingURL=engineErrors-wWlLy54D.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engineErrors-wWlLy54D.js","names":[],"sources":["../../../core/src/engineErrors.ts"],"sourcesContent":["/**\n * The engine's known errors: a stable code each, and its English text with the values in it. The engine throws\n * `engineError(code, values)`; the text is the one it always wrote, so the CLI and every log keep printing the same.\n * The app's pages get only the text (it crosses the engine's RPC and is kept on payments and operations as a string),\n * and `parseEngineError` finds the code and the values back in it, to say it in the app's language. A text that is\n * none of these (a mint's own words, a provider's) stays as it is.\n *\n * `{name}` in a template is a value: a host or domain (no spaces), a network (\"Mainnet\" or \"Testnet\"), a chain's name,\n * an ecash unit (\"usd\"), an amount (digits, with the separators of whatever locale wrote it), or a server's own `{reason}`\n * (one line, last in its text).\n */\nexport const ENGINE_ERRORS = {\n // Reaching a mint, a server, the network.\n mintUnreachable: \"Could not reach {host}. Check the address: it should be a Cashu mint.\",\n lnurlUnreachable: \"Could not reach {host}. It may be down, or not allow web apps to read it (CORS).\",\n hostUnreachable: \"Could not reach {host}\",\n networkUnreachable: \"Could not reach the network\",\n hostTimedOut: \"{host} did not answer in time\",\n networkTimedOut: \"The network did not answer in time\",\n // Cashu mints.\n testMintOnMainnet: \"This is a test mint, and its sats are worth nothing: add it to a Testnet Cashu wallet\",\n realMintOnTestnet: \"This mint holds real sats: add it to a Mainnet Cashu wallet\",\n mintHoldsSats: \"Move your sats out of this mint before removing it\",\n lastMint: \"This is the last mint of your {network} Cashu wallet: remove the wallet to remove it\",\n invalidMintUrl: \"That is not a valid mint URL\",\n mintNotHttps: \"Mints must use https\",\n notEnoughSats: \"Not enough sats in your wallet\",\n notEnoughForFee: \"Not enough sats in your wallet: {amount} sats leave room for the fee\",\n mintsNoAnyAmount: \"None of your mints can pay an invoice with no amount\",\n noSharedMint: \"You share no mint with this contact\",\n ecashAlreadySpent: \"This ecash was already spent somewhere else\",\n ecashBeingReceived: \"This ecash is already being received\",\n ecashFeeTakesAll: \"The mint keeps all {amount} sats of this ecash as its fee to take it in: nothing was redeemed, and its sender can still take it back\",\n ecashOtherUnit: \"This ecash is in {unit}: only sat ecash can be redeemed here\",\n // A token's unit is its sender's free text: one that does not look like a unit is not named (`ecashUnitError`).\n ecashUnnamedUnit: \"This ecash is in another unit: only sat ecash can be redeemed here\",\n reviewedEcashSpent: \"The ecash for this payment was already spent somewhere else. Nothing was sent, and your balance now shows what the mint still holds.\",\n reviewedSatsGone: \"The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.\",\n // A mint that failed (a server error, a closed connection), not refused: nothing happened, and it may work later.\n mintFailedQuote: \"{host} could not take this payment right now, and no sats left your wallet: try again later. The mint said: {reason}\",\n mintFailedFaucet: \"{host} could not give test coins right now: try again later. The mint said: {reason}\",\n mintFailedInvoice: \"{host} could not create an invoice right now: try again later. The mint said: {reason}\",\n // Lightning.\n lightningFeeTooHigh: \"The Lightning fee ({fee} sats) is too high\",\n lightningRefused: \"The mint refused this Lightning payment, and no sats left your wallet: it is safe to try again. The mint said: {reason}\",\n invoiceExpired: \"That invoice has expired\",\n lnurlExactly: \"{domain} asks for exactly {amount} sats\",\n lnurlRange: \"{domain} takes between {min} and {max} sats\",\n // A reviewed payment, from its review to its outcome (paymentAdapters/coordinator.ts, persistence.ts, node.ts).\n feeAboveLimit: \"The fee exceeds your limit\",\n cashuFeeAboveLimit: \"Cashu fee exceeds your limit\",\n invalidMaxFee: \"Invalid maximum fee\",\n methodUnavailable: \"This payment method is unavailable\",\n unknownPaymentIntent: \"Unknown payment intent\",\n paymentExpired: \"Payment request expired or has an invalid expiry\",\n requestHasPayment: \"This request already has a payment. Reconcile it before trying again.\",\n requestPaymentInFlight: \"This request already has a payment; reconcile it instead\",\n requestNotAwaiting: \"This request is no longer awaiting payment. Check its status before spending.\",\n reconnectBeforeApprove: \"Reconnect the data link before approving. Your review was saved.\",\n cannotSubmitAgain: \"This payment cannot be submitted again. Reconcile its existing transaction.\",\n alreadySubmitted: \"This payment was already submitted or could not be saved\",\n sentAfterReview: \"A payment from this wallet was sent after this review was made. Create a new review\",\n cannotCancelSubmitted: \"A submitted payment cannot be cancelled; reconcile it instead\",\n outcomeUnknown: \"Outcome unknown. Check the existing payment; do not send another.\",\n notYetConfirmed: \"Not yet confirmed. No second payment was sent.\",\n couldNotVerify: \"Could not verify this payment yet. No second payment was sent.\",\n paymentTakenBack: \"This payment was taken back. The sats are in your wallet.\",\n parkedSigned: \"Needs your decision: this payment was signed before this copy of your profile took over. It is never sent again from here. Check it before you pay again.\",\n // Paying in a chat.\n contactAway: \"Your contact is offline. Nothing was sent: pay once the chat is live.\",\n contactNoWallet: \"Your contact has no wallet yet: they need one to pay or be paid\",\n contactNoPayments: \"Your contact has payments off in this chat, or needs an updated Ghostly\",\n // Real money and test coins.\n realMoneyUnconfirmed: \"This pays with real money: confirm it with Send real money first. Nothing was sent.\",\n mainnetPaymentOnTestnet: \"This is a Mainnet payment (real money): a Testnet wallet never pays it. Use a Mainnet wallet.\",\n testnetPaymentOnMainnet: \"This is a Testnet payment (test coins): a Mainnet wallet never pays it. Use a Testnet wallet.\",\n // USDT.\n usdtRpcUnavailable: \"USDT RPC unavailable\",\n usdtNotEnoughTokens: \"Insufficient token balance\",\n usdtNotEnoughGas: \"Insufficient ETH for gas\",\n usdtGasAboveLimit: \"Estimated maximum gas exceeds your limit\",\n usdtNeedsSepoliaGas: \"This needs a little Sepolia ETH for gas first\",\n // Fedimint.\n fedimintNotInvite: \"That is not a Fedimint invite code: it starts with fed1\",\n fedimintAlreadyJoined: \"You already joined this federation\",\n fedimintConnecting: \"Wait for the federation to connect\",\n fedimintNotEnough: \"Not enough in this federation\",\n fedimintRedeemUnheard: \"Could not hear from the federation about these notes: if they don't show in your balance soon, paste them again\",\n fedimintRealOnTestnet: \"This federation holds real bitcoin: it belongs in a Mainnet Fedimint wallet\",\n fedimintTestOnMainnet: \"This federation is on {chain}, a test network: it belongs in a Testnet Fedimint wallet\",\n walletAway: \"{wallet} can't be used here. Use it on {device}.\",\n walletAwayUnnamed: \"{wallet} can't be used here: its home is another device.\",\n // Web apps shared with a contact.\n serviceShareFull: \"A contact can reach at most {max} of your apps: take one back from them before sharing another\",\n // One profile on several devices (WISP 06).\n groupTurnUnconfirmed: \"Can't check which device is active, so the group was not changed. Try again in a moment.\",\n // Group calls through the group's node (WISP 602).\n groupNoCall: \"This group has no calls: its admin has not set a call server\",\n groupCallNotMember: \"You are not in this group, so you can't join its call\",\n groupCallRefused: \"{host} did not let you into the group's call. Try again in a minute.\",\n groupCallBusy: \"{host} is busy. Try the call again in a minute.\",\n groupCallFailed: \"{host} could not start the group's call. Try again later.\",\n} as const;\n\nexport type EngineErrorCode = keyof typeof ENGINE_ERRORS;\nexport type EngineErrorValues = Record<string, string | number>;\n\n/**\n * An error the engine knows: `engineCode` travels with it inside the engine, the text everywhere. Not `code`: the\n * CLI reads a `code` as its own exit code, and Node's errors carry one of theirs.\n */\nexport class EngineError extends Error {\n constructor(readonly engineCode: EngineErrorCode, readonly values: EngineErrorValues = {}) {\n super(engineText(engineCode, values));\n }\n}\n\n/** The English text of `code` with its values in it, exactly as the engine writes it. */\nexport function engineText(code: EngineErrorCode, values: EngineErrorValues = {}): string {\n return ENGINE_ERRORS[code].replace(/\\{(\\w+)\\}/g, (_, name: string) => (name in values ? String(values[name]) : `{${name}}`));\n}\n\nexport const engineError = (code: EngineErrorCode, values?: EngineErrorValues): EngineError => new EngineError(code, values);\n\n/** A unit as the app names it: a unit's shape (`frames.ts` `isUnit`, in any case), never a token sender's other text. */\nconst NAMED_UNIT = \"[A-Za-z0-9]{1,12}\";\n\n/**\n * Why ecash of `unit` is not redeemed here. The unit is named only when it looks like one: a token's unit is whatever\n * its sender wrote, and the line is the app's own (a contact's payment's refusal row, the CLI's answer).\n */\nexport const ecashUnitError = (unit: string): EngineError =>\n new RegExp(`^${NAMED_UNIT}$`).test(unit) ? engineError(\"ecashOtherUnit\", { unit }) : engineError(\"ecashUnnamedUnit\");\n\n/** What each kind of value looks like in a text: never a space in a host, a network by its name, an amount as digits. */\nconst VALUE: Record<string, string> = {\n host: \"(\\\\S+)\", domain: \"(\\\\S+)\", chain: \"(\\\\S+)\", unit: `(${NAMED_UNIT})`, network: \"(Mainnet|Testnet)\",\n amount: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\", fee: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\", min: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\", max: \"(\\\\d[\\\\d.,\\\\u00a0\\\\u202f' ]*?)\",\n};\nconst escape = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst PATTERNS = (Object.keys(ENGINE_ERRORS) as EngineErrorCode[]).map((code) => {\n const names: string[] = [];\n const source = ENGINE_ERRORS[code].split(/(\\{\\w+\\})/).map((part) => {\n const value = /^\\{(\\w+)\\}$/.exec(part);\n if (!value) return escape(part);\n names.push(value[1]);\n return VALUE[value[1]] ?? \"(.+?)\";\n }).join(\"\");\n return { code, names, pattern: new RegExp(`^${source}$`) };\n});\n\n/** The code and values of a text the engine wrote, or null for any other text (it is then shown as it is). */\nexport function parseEngineError(text: string): { code: EngineErrorCode; values: Record<string, string> } | null {\n const trimmed = text.trim();\n for (const { code, names, pattern } of PATTERNS) {\n const match = pattern.exec(trimmed);\n if (match) return { code, values: Object.fromEntries(names.map((name, i) => [name, match[i + 1]])) };\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;AAWA,IAAa,gBAAgB;CAE3B,iBAAiB;CACjB,kBAAkB;CAClB,iBAAiB;CACjB,oBAAoB;CACpB,cAAc;CACd,iBAAiB;CAEjB,mBAAmB;CACnB,mBAAmB;CACnB,eAAe;CACf,UAAU;CACV,gBAAgB;CAChB,cAAc;CACd,eAAe;CACf,iBAAiB;CACjB,kBAAkB;CAClB,cAAc;CACd,mBAAmB;CACnB,oBAAoB;CACpB,kBAAkB;CAClB,gBAAgB;CAEhB,kBAAkB;CAClB,oBAAoB;CACpB,kBAAkB;CAElB,iBAAiB;CACjB,kBAAkB;CAClB,mBAAmB;CAEnB,qBAAqB;CACrB,kBAAkB;CAClB,gBAAgB;CAChB,cAAc;CACd,YAAY;CAEZ,eAAe;CACf,oBAAoB;CACpB,eAAe;CAC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O;CAAU,MAAM,IAAI,WAAW;CAAI,SAAS;CACrF,QAAQ;CAAkC,KAAK;CAAkC,KAAK;CAAkC,KAAK;AAC/H;AACA,IAAM,UAAU,SAAiB,KAAK,QAAQ,uBAAuB,MAAM;AAC3E,IAAM,WAAY,OAAO,KAAK,aAAa,CAAC,CAAuB,KAAK,SAAS;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,SAAS,cAAc,KAAK,CAAC,MAAM,WAAW,CAAC,CAAC,KAAK,SAAS;EAClE,MAAM,QAAQ,cAAc,KAAK,IAAI;EACrC,IAAI,CAAC,OAAO,OAAO,OAAO,IAAI;EAC9B,MAAM,KAAK,MAAM,EAAE;EACnB,OAAO,MAAM,MAAM,OAAO;CAC5B,CAAC,CAAC,CAAC,KAAK,EAAE;CACV,OAAO;EAAE;EAAM;EAAO,SAAS,IAAI,OAAO,IAAI,OAAO,EAAE;CAAE;AAC3D,CAAC;;AAGD,SAAgB,iBAAiB,MAAgF;CAC/G,MAAM,UAAU,KAAK,KAAK;CAC1B,KAAK,MAAM,EAAE,MAAM,OAAO,aAAa,UAAU;EAC/C,MAAM,QAAQ,QAAQ,KAAK,OAAO;EAClC,IAAI,OAAO,OAAO;GAAE;GAAM,QAAQ,OAAO,YAAY,MAAM,KAAK,MAAM,MAAM,CAAC,MAAM,MAAM,IAAI,EAAE,CAAC,CAAC;EAAE;CACrG;CACA,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
- import { m as pkarrRelays, n as plcDirectory, o as DOH_RESOLVERS } from "./resolve-DNX-eecG.js";
2
- import { a as PUBKY_RELAYS, t as SSH_FORGE_HOST, u as oidcProviders } from "./sshForges-BnvwmNj-.js";
1
+ import { m as pkarrRelays, n as plcDirectory, o as DOH_RESOLVERS } from "./resolve-B1eQ4dVQ.js";
2
+ import { a as PUBKY_RELAYS, t as SSH_FORGE_HOST, u as oidcProviders } from "./sshForges-As7dbGXM.js";
3
3
  // ../browser/src/proofs/fixedHosts.ts
4
4
  /**
5
5
  * The hosts a contact's proof may be checked on while "Hide my IP from contacts" is on: the ones this app names
@@ -19,4 +19,4 @@ function fixedIdentityHosts() {
19
19
  }
20
20
  export { fixedIdentityHosts };
21
21
 
22
- //# sourceMappingURL=fixedHosts-H3i6o9Iy.js.map
22
+ //# sourceMappingURL=fixedHosts-CODN2pTL.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fixedHosts-H3i6o9Iy.js","names":[],"sources":["../../../browser/src/proofs/fixedHosts.ts"],"sourcesContent":["import { plcDirectory } from \"./atproto/resolve\";\nimport { DOH_RESOLVERS } from \"./domain\";\nimport { oidcProviders } from \"./oidc/providers\";\nimport { pkarrRelays } from \"./pkarrRelays\";\nimport { PUBKY_RELAYS } from \"./pubkyRelays\";\nimport { SSH_FORGE_HOST } from \"./sshForges\";\n\n/**\n * The hosts a contact's proof may be checked on while \"Hide my IP from contacts\" is on: the ones this app names\n * (DNS-over-HTTPS resolvers, the PLC directory, Pubky's Pkarr relays and the profile's own, the OpenID providers' keys,\n * the forges' APIs), never one the contact's evidence names (a did:web or a domain's own web server, an AT Protocol\n * server, a Pubky homeserver), which would see this device's IP address.\n */\nexport function fixedIdentityHosts(): ReadonlySet<string> {\n const urls = [...DOH_RESOLVERS.map(r => r.url), plcDirectory(), ...PUBKY_RELAYS, ...pkarrRelays(), ...oidcProviders().map(p => p.jwksUri)];\n return new Set([...urls.map(u => new URL(u).host), ...Object.values(SSH_FORGE_HOST)]);\n}\n"],"mappings":";;;;;;;;;AAaA,SAAgB,qBAA0C;CACxD,MAAM,OAAO;EAAC,GAAG,cAAc,KAAI,MAAK,EAAE,GAAG;EAAG,aAAa;EAAG,GAAG;EAAc,GAAG,YAAY;EAAG,GAAG,cAAc,CAAC,CAAC,KAAI,MAAK,EAAE,OAAO;CAAC;CACzI,uBAAO,IAAI,IAAI,CAAC,GAAG,KAAK,KAAI,MAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,GAAG,OAAO,OAAO,cAAc,CAAC,CAAC;AACtF"}
1
+ {"version":3,"file":"fixedHosts-CODN2pTL.js","names":[],"sources":["../../../browser/src/proofs/fixedHosts.ts"],"sourcesContent":["import { plcDirectory } from \"./atproto/resolve\";\nimport { DOH_RESOLVERS } from \"./domain\";\nimport { oidcProviders } from \"./oidc/providers\";\nimport { pkarrRelays } from \"./pkarrRelays\";\nimport { PUBKY_RELAYS } from \"./pubkyRelays\";\nimport { SSH_FORGE_HOST } from \"./sshForges\";\n\n/**\n * The hosts a contact's proof may be checked on while \"Hide my IP from contacts\" is on: the ones this app names\n * (DNS-over-HTTPS resolvers, the PLC directory, Pubky's Pkarr relays and the profile's own, the OpenID providers' keys,\n * the forges' APIs), never one the contact's evidence names (a did:web or a domain's own web server, an AT Protocol\n * server, a Pubky homeserver), which would see this device's IP address.\n */\nexport function fixedIdentityHosts(): ReadonlySet<string> {\n const urls = [...DOH_RESOLVERS.map(r => r.url), plcDirectory(), ...PUBKY_RELAYS, ...pkarrRelays(), ...oidcProviders().map(p => p.jwksUri)];\n return new Set([...urls.map(u => new URL(u).host), ...Object.values(SSH_FORGE_HOST)]);\n}\n"],"mappings":";;;;;;;;;AAaA,SAAgB,qBAA0C;CACxD,MAAM,OAAO;EAAC,GAAG,cAAc,KAAI,MAAK,EAAE,GAAG;EAAG,aAAa;EAAG,GAAG;EAAc,GAAG,YAAY;EAAG,GAAG,cAAc,CAAC,CAAC,KAAI,MAAK,EAAE,OAAO;CAAC;CACzI,uBAAO,IAAI,IAAI,CAAC,GAAG,KAAK,KAAI,MAAK,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG,GAAG,OAAO,OAAO,cAAc,CAAC,CAAC;AACtF"}
@@ -1,11 +1,11 @@
1
1
  import { a as fromZ32, c as toBase64, d as utf8Decode, f as utf8Encode, i as fromBase64Url, l as toBase64Url, n as concatBytes, o as isZ32Key, r as fromBase64, s as randomBytes, t as bytesEqual, u as toZ32 } from "./bytes-C1DNGY18.js";
2
2
  import { a as stripHidden, i as sanitizeNick, n as hasVisible, o as trimEndOf, r as sanitizeDisplayText, s as unwrapPasted } from "./text-li76pThX.js";
3
- import { i as parseLinkPreview, o as sanitizeAvatar } from "./linkPreview-DdMf-YAc.js";
4
- import { C as generateEncryptionKey, S as encrypt, T as tryDecrypt, a as checkedDescriptors, c as irohRelayUrl, f as relayedTransports, i as automaticTransport, l as rankTransports, m as HOLD_CAPABILITY, n as RELAY_WITH_SECRETS, p as transportOrder, r as TRANSPORTS, t as RELAY_URL, u as relayUrl, w as sealedLength } from "./pairedTransports-Dppn8lUN.js";
3
+ import { a as parseLinkPreview, s as sanitizeAvatar } from "./linkPreview-5kHmKUTN.js";
4
+ import { C as encrypt, E as tryDecrypt, T as sealedLength, a as checkedDescriptors, c as irohRelayUrl, f as relayedTransports, i as automaticTransport, l as rankTransports, m as HOLD_CAPABILITY, n as RELAY_WITH_SECRETS, p as transportOrder, r as TRANSPORTS, t as RELAY_URL, u as relayUrl, w as generateEncryptionKey } from "./pairedTransports-DAzupLYo.js";
5
5
  import { S as verify, _ as identityFromSeed, a as createRelayPayload, g as createIdentity, i as RELAY_PAYLOAD_MAX_BYTES, l as parseRelayPayload, n as PKARR_FUTURE_SKEW_MS, o as measureRecords, s as newerPacket, t as MAX_DNS_PACKET_BYTES, v as identityFromSeedB64, x as sign, y as publicKeyFromZ32 } from "./pkarr-BQo4PcCg.js";
6
- import { a as RelaysFailedError, d as traceLink, h as publishedNowhere, m as isDiscoveryBudgetError, p as budgetRetryMs } from "./relay-CHWg5hpZ.js";
7
- import { a as IDENTITY_PROOF_CAPABILITY, t as IDENTITY_FRAME_WINDOW_MS } from "./identityProofs-Cksc_K7_.js";
8
- import { n as engineError } from "./engineErrors--9hfgKlK.js";
6
+ import { a as RelaysFailedError, d as traceLink, h as publishedNowhere, m as isDiscoveryBudgetError, p as budgetRetryMs } from "./relay-gJTOYQJZ.js";
7
+ import { a as IDENTITY_PROOF_CAPABILITY, t as IDENTITY_FRAME_WINDOW_MS } from "./identityProofs-B8zCp5_0.js";
8
+ import { r as engineError } from "./engineErrors-wWlLy54D.js";
9
9
  import b4a from "b4a";
10
10
  import { ed25519, x25519 } from "@noble/curves/ed25519.js";
11
11
  import { sha256 } from "@noble/hashes/sha2.js";
@@ -501,6 +501,42 @@ function readCanonicalJson(bytes) {
501
501
  value
502
502
  };
503
503
  }
504
+ /**
505
+ * The entries of bytes that must be a canonical JSON list, each as its own bytes, one at a time: a scan that builds no
506
+ * value and goes no further than the entry it yields, so a caller reads (and may refuse) each before the next is
507
+ * found. It ends with null at the closing `]`; `not-list` past `maxEntries` entries, at an entry over `maxEntryBytes`,
508
+ * or when the bytes are not within `[` and `]`; `not-json` when brackets or quotes do not close. A canonical list is
509
+ * `[`, its entries' canonical texts joined by `,`, then `]`, so the bytes are canonical exactly when the scan ends with
510
+ * null and each entry read alone with `readCanonicalJson` is.
511
+ */
512
+ function* canonicalJsonListEntries(bytes, maxEntries, maxEntryBytes) {
513
+ const end = bytes.length - 1;
514
+ if (end < 1 || bytes[0] !== 91 || bytes[end] !== 93) return "not-list";
515
+ if (end === 1) return null;
516
+ let depth = 0;
517
+ let inString = false;
518
+ let start = 1;
519
+ let count = 0;
520
+ for (let i = 1; i <= end; i++) {
521
+ const b = bytes[i];
522
+ if (i === end || b === 44 && depth === 0 && !inString) {
523
+ if (i === end && (depth !== 0 || inString)) return "not-json";
524
+ if (count === maxEntries || i - start > maxEntryBytes) return "not-list";
525
+ count++;
526
+ yield bytes.subarray(start, i);
527
+ start = i + 1;
528
+ continue;
529
+ }
530
+ if (i - start >= maxEntryBytes) return "not-list";
531
+ if (inString) {
532
+ if (b === 92) i++;
533
+ else if (b === 34) inString = false;
534
+ } else if (b === 34) inString = true;
535
+ else if (b === 91 || b === 123) depth++;
536
+ else if ((b === 93 || b === 125) && --depth < 0) return "not-json";
537
+ }
538
+ return start === end + 1 ? null : "not-json";
539
+ }
504
540
  // ../core/src/image.ts
505
541
  var IMAGE_LIMITS = {
506
542
  /** Pixels on either side: the most a JPEG can say, well past what anyone sends as a picture. */
@@ -680,7 +716,12 @@ var APP_STATEMENT_LIMITS = {
680
716
  /** A revocation's reason, in characters. */
681
717
  reason: 200,
682
718
  /** Revocations in one `ghostly-revoke.json`. */
683
- revocations: 4096
719
+ revocations: 4096,
720
+ /**
721
+ * One signed revocation's canonical bytes: twice the largest a valid one can be (64 digests, a 32-character name and
722
+ * a 200-character reason of 4-byte characters: about 4.1 KB), so a reader refuses a larger entry before parsing it.
723
+ */
724
+ revocationBytes: 8192
684
725
  };
685
726
  /** A z-base32 Ed25519 public key: 52 characters that decode to 32 bytes and encode back to the same text. */
686
727
  function isAppKey(value) {
@@ -962,24 +1003,39 @@ function verifyAppRevocation(revocation, checked) {
962
1003
  * file, as a store index's `revoked` does. With `checked`, a revocation it holds is not checked again.
963
1004
  */
964
1005
  function readAppRevocations(bytes, checked) {
965
- const read = readCanonicalJson(bytes);
966
- if (!read.ok) return read;
967
- if (!Array.isArray(read.value) || read.value.length > APP_STATEMENT_LIMITS.revocations) return {
968
- ok: false,
969
- reason: "bad-revocation",
970
- detail: "Not a list of at most 4096 revocations"
971
- };
972
1006
  const revocations = [];
973
- for (const entry of read.value) {
974
- const one = readAppRevocation(entry, checked);
1007
+ const entries = appRevocationsFileEntries(bytes);
1008
+ let next = entries.next();
1009
+ for (; !next.done; next = entries.next()) {
1010
+ const read = readCanonicalJson(next.value);
1011
+ if (!read.ok) return read;
1012
+ const one = readAppRevocation(read.value, checked);
975
1013
  if (!one.ok) return one;
976
1014
  revocations.push(one.revocation);
977
1015
  }
978
- return {
1016
+ return next.value ?? {
979
1017
  ok: true,
980
1018
  revocations
981
1019
  };
982
1020
  }
1021
+ /**
1022
+ * The entries of a `ghostly-revoke.json`, each as its own bytes, one at a time and with nothing parsed: a file past
1023
+ * 4096 entries, or with one larger than any revocation can be, is refused there, however large it is. It ends with null
1024
+ * when the list closed. Each entry read alone (`readCanonicalJson`, then `readAppRevocation`) refuses exactly the files
1025
+ * reading the file whole refuses.
1026
+ */
1027
+ function* appRevocationsFileEntries(bytes) {
1028
+ const end = yield* canonicalJsonListEntries(bytes, APP_STATEMENT_LIMITS.revocations, APP_STATEMENT_LIMITS.revocationBytes);
1029
+ if (end === "not-list") return {
1030
+ ok: false,
1031
+ reason: "bad-revocation",
1032
+ detail: "Not a list of at most 4096 revocations"
1033
+ };
1034
+ return end && {
1035
+ ok: false,
1036
+ reason: end
1037
+ };
1038
+ }
983
1039
  // ../core/src/appBundle.ts
984
1040
  var APP_BUNDLE_MAGIC = "GHOSTLYAPP1";
985
1041
  var MAGIC = utf8Encode(APP_BUNDLE_MAGIC);
@@ -4177,9 +4233,9 @@ var LinkSession = class {
4177
4233
  if (publish) this.publish().catch(() => {});
4178
4234
  if (read) this.pollNow();
4179
4235
  }
4180
- /** This side's packet goes out now, unless one already did. */
4236
+ /** This side's packet goes out now, unless one already did (in this run, once it left DHT only: `presenceDue`). */
4181
4237
  ensureAdvertised() {
4182
- if (!this.running || this.lastPublishedAt > 0 || this.publishing) return;
4238
+ if (!this.running || this.lastPublishedAt > 0 && !this.presenceDueOut || this.publishing) return;
4183
4239
  this.publish().catch(() => {});
4184
4240
  }
4185
4241
  /** This side's packet goes out again as it is: another writer of its key (a second device on a device code) may have replaced it. */
@@ -9616,7 +9672,7 @@ var TransportSwitch = class {
9616
9672
  remoteReplaces = false;
9617
9673
  /** This side chose while no session was open: the next one begins with it as a choice. */
9618
9674
  apart = false;
9619
- policiesRead = new RateWindow(10, POLICY_RECEIVE_WINDOW_MS);
9675
+ policiesRead = new RateWindow(30, POLICY_RECEIVE_WINDOW_MS);
9620
9676
  /** The session on which the contact's policy, the one read already, was said again and read for free (`handle`). */
9621
9677
  repeatRead = "";
9622
9678
  policyHeld = null;
@@ -13582,6 +13638,19 @@ function storeFailure(error) {
13582
13638
  const message = (error instanceof Error ? error.message : String(error)).trim();
13583
13639
  return `Could not store the file: ${error?.name === "QuotaExceededError" && !message.startsWith("QuotaExceededError") ? `QuotaExceededError${message ? `: ${message}` : ""}` : message}`;
13584
13640
  }
13641
+ /**
13642
+ * The room this device tells a contact (`pf-room`, a `no-room` refusal): its free space rounded down to a power of two or
13643
+ * one and a half of one. The exact bytes would be the same from every profile on the device, and move with whatever it
13644
+ * stores, so a contact could tell one device from another, or watch it, by asking. Never more than the room itself.
13645
+ */
13646
+ function coarseRoom(room) {
13647
+ if (!Number.isSafeInteger(room)) return null;
13648
+ if (room <= 0) return 0;
13649
+ let step = 2 ** Math.floor(Math.log2(room));
13650
+ while (step > room) step /= 2;
13651
+ while (step * 2 <= room) step *= 2;
13652
+ return room >= step * 1.5 ? step * 1.5 : step;
13653
+ }
13585
13654
  /** What a refusal means to the sender's person. */
13586
13655
  function refusalText(why, room) {
13587
13656
  switch (why) {
@@ -13835,9 +13904,19 @@ var ChatFiles = class {
13835
13904
  }
13836
13905
  async sayRoom() {
13837
13906
  const room = await this.host.room?.().catch(() => null);
13838
- if (typeof room === "number" && Number.isSafeInteger(room)) this.send({
13907
+ const max = typeof room === "number" ? coarseRoom(room) : null;
13908
+ if (max !== null) this.send({
13839
13909
  t: "pf-room",
13840
- max: room
13910
+ max
13911
+ });
13912
+ }
13913
+ refuseOffer(id, decision) {
13914
+ const room = decision.room !== void 0 ? coarseRoom(decision.room) : null;
13915
+ this.send({
13916
+ t: "pf-refuse",
13917
+ id,
13918
+ why: decision.refuse,
13919
+ ...room !== null && { room }
13841
13920
  });
13842
13921
  }
13843
13922
  /** A new file to send: offered now if a session is open, or on the next one. */
@@ -14261,12 +14340,7 @@ var ChatFiles = class {
14261
14340
  }
14262
14341
  if (this.entries.has(key("in", id))) return;
14263
14342
  if (typeof decision === "object") {
14264
- this.send({
14265
- t: "pf-refuse",
14266
- id,
14267
- why: decision.refuse,
14268
- ...decision.room !== void 0 && { room: decision.room }
14269
- });
14343
+ this.refuseOffer(id, decision);
14270
14344
  return;
14271
14345
  }
14272
14346
  const entry = {
@@ -14320,12 +14394,7 @@ var ChatFiles = class {
14320
14394
  decision = { refuse: "invalid" };
14321
14395
  }
14322
14396
  if (typeof decision === "object") {
14323
- this.send({
14324
- t: "pf-refuse",
14325
- id: record.id,
14326
- why: decision.refuse,
14327
- ...decision.room !== void 0 && { room: decision.room }
14328
- });
14397
+ this.refuseOffer(record.id, decision);
14329
14398
  return false;
14330
14399
  }
14331
14400
  if (decision === "ask") {
@@ -17485,11 +17554,11 @@ var GhostLink = class {
17485
17554
  if (this.myPubKeyZ32 > this.options.params.peerPubKeyZ32) this.session.presenceDue();
17486
17555
  this.session.start();
17487
17556
  }
17488
- await this.dht.setMode(mode);
17489
17557
  if (mode === "dht") {
17490
17558
  await this.session.stop(false);
17491
17559
  await Promise.allSettled([...this.endpoints.keys()].map((t) => this.releaseEndpoint(t)));
17492
17560
  }
17561
+ await this.dht.setMode(mode);
17493
17562
  this.streamBlockChanged();
17494
17563
  this.emitDeliveryState();
17495
17564
  }
@@ -21959,6 +22028,6 @@ function groupMetaChange(before, after, first) {
21959
22028
  if (a.pic !== b.pic) change.picture = b.pic ?? null;
21960
22029
  return "name" in change || "picture" in change ? change : null;
21961
22030
  }
21962
- export { beaconKeys as $, canonicalJson as $a, MAX_SHARED_APPS as $i, reactionEmoji as $n, sortRoster as $r, vapidKeysMatch as $t, GROUP_WANT_FRAME as A, sha256Paced as Aa, GhostlyHttpError as Ai, baseMime as An, statusCardText as Ar, TypingSender as At, GROUP_SIGNAL_FRAME as B, isAppRef as Ba, QUICK_REDIAL_MS as Bi, REMOVED_TEXT as Bn, GROUP_MEMBER_CAP as Br, WAKE_CALL_INTERVAL_MS as Bt, MESSAGE_PACED as C, assembleAppBundle as Ca, DAEMON_WATCH_PEER_IDLE_MS as Ci, dhtFileId as Cn, cardEditNumber as Cr, liveStatus as Ct, pairedMessageFrame as D, pacer as Da, RELAY_POLL_INTERVALS as Di, PLAYABLE_AUDIO as Dn, readStatusCard as Dr, TYPING_KINDS as Dt, pairedMessageFits as E, isAppUrl as Ea, PRESENCE_WINDOW as Ei, sanitizeMime as En, checkStatusCard as Er, TYPING_FRAME as Et, readGroupFileMeta as F, appRefPublisher as Fa, LIMITS as Fi, voiceLevel as Fn, heardTime as Fr, mayPin as Ft, readGroupSignal as G, setAppSignatureFastPath as Ga, callSignalHeardAt as Gi, forwardedAgain as Gn, commitHash as Gr, WakeLimiter as Gt, SIGNAL_HOLD_MS as H, readAppRevocationShape as Ha, answersOffer as Hi, dhtEditId as Hn, MEMBER_KEY as Hr, WAKE_ONLINE_BATCH_MS as Ht, readGroupHave as I, checkAppRevokeStatement as Ia, decodeControl as Ii, parseVideoMeta as In, receivedTimestamp as Ir, nextPinNumber as It, mayBeHub as J, verifyAppRevocation as Ja, parseCallSignal as Ji, GROUP_REACTION_FRAME as Jn, parseGroupCommit as Jr, parseWakeFrame as Jt, MESH_HUBS as K, signAppObject as Ka, contactRtcConfig as Ki, readForwarded as Kn, commitUntaggedHash as Kr, deviceWakeRequest as Kt, readGroupWant as L, isAppHash as La, encodeControl as Li, EDIT_BUFFER_MS as Ln, shownTime as Lr, pinIsNewer as Lt, fetchesByItself as M, APP_STATEMENT_LIMITS as Ma, formatLocalTarget as Mi, fileMessageText as Mn, MESSAGE_CLOCK_SKEW_MS as Mr, typingActivity as Mt, groupFileFallback as N, appFingerprint as Na, parseLocalTarget as Ni, parseVoiceMeta as Nn, arrivalKey as Nr, GROUP_PIN_FRAME as Nt, GROUP_FILE_LIMITS as O, readAppBundle as Oa, WATCH_PEER_MS as Oi, VOICE_LIMITS as On, sameButtonText as Or, TYPING_REFRESH_MS as Ot, isGroupMessageId as P, appRef as Pa, webLocalFetch as Pi, voiceDownloadName as Pn, claimedTime as Pr, PIN_LIMITS as Pt, COMMUNITY_TOPOLOGY as Q, readImageMeta as Qa, LEGACY_SERVICES as Qi, queueReaction as Qn, signCommit as Qr, checkPushEndpoint as Qt, readGroupWantNo as R, isAppKey as Ra, BURST_RING_MS as Ri, EDIT_RATE_WINDOW_MS as Rn, GROUP_ADMIN_OFF_ERROR as Rr, pinNumberHolds as Rt, LIVENESS_PING_MS as S, appViewOf as Sa, AWAITING_PEER_MS as Si, DHT_FILE_CAPABILITY as Sn, buttonLabelClash as Sr, STATUS_IDLE_AFTER_MS as St, pairedEditFits as T, findAppForbiddenKey as Ta, EXPECT_PEER_MS as Ti, sanitizeFileName as Tn, cardUrl as Tr, sanitizeStatusText as Tt, SIGNAL_REPLY_MS as U, readAppRevocations as Ua, buildSdpFromSignal as Ui, validEditNumber as Un, OWN_FRAME_LIMIT as Ur, WAKE_ONLINE_DELAY_MS as Ut, SIGNAL_FRESH_MS as V, readAppRevocation as Va, RTC_CONFIG as Vi, RateWindow as Vn, MAX_GROUP_CHAIN as Vr, WAKE_INTERVAL_MS as Vt, groupSignalFrame as W, readAppSignature as Wa, callRtcConfig as Wi, validRemovalNumber as Wn, SAID_AGAIN as Wr, WAKE_ONLINE_INTERVAL_MS as Wt, meshRendezvous as X, exifOrientation as Xa, emptyLinkRecords as Xi, ReactionWindow as Xn, rosterAdmin as Xr, wakeFrame as Xt, meshHubs as Y, verifyAppSignature as Ya, signalHasVideo as Yi, REACTION_LIMITS as Yn, rememberAlone as Yr, relayRequest as Yt, pickMeshHubs as Z, parseImageMeta as Za, HTTP_SERVICE_PROTO as Zi, nextReactionNumber as Zn, rosterHas as Zr, wakeRequest as Zt, signGroupMeta as _, seenEntry as _a, RATCHET_CAPABILITY as _i, ACTIVE_DHT_POLL_MS as _n, deviceKeyZ32 as _o, RUN_RESULTS as _r, FileUplink as _t, groupMetaChange as a, contactDay as aa, confirmationTag as ai, APPS_CAPABILITY as an, createChatInvite as ao, groupReplyAuthor as ar, lobbyRecords as at, GhostLink as b, APP_ICON_PATH as ba, ratchetSessionOf as bi, DHT_PACKET_BUDGET as bn, newDeviceSetSecret as bo, appCardId as br, transferStalled as bt, groupMetaTag as c, knockSlotOf as ca, encryptText as ci, STATUS_CARD_CAPABILITY as cn, inviteLink as co, replySnippet as cr, newerHead as ct, keepPastGroupMeta as d, makeStampPaced as da, newEpochSecret as di, DHT_TEXT_CAPABILITY as dn, pastedAgain as do, BUTTON_STYLES as dr, readBeacon as dt, serviceIdFromName as ea, verifyChain as ei, APP_RANGE_LIMITS as en, canonicalJsonBytes as eo, reactionIsNewer as er, beaconRecords as et, nextGroupMetaRevision as f, mergeContactKnocks as fa, openPair as fi, capsDescriptors as fn, DEVICES_CAPABILITY as fo, CRON_LINE as fr, readBeaconHead as ft, parseGroupMetaTag as g, requestRecords as ga, sha256Hex as gi, validExternalKey as gn, deviceEchoNonce as go, ROUTINE_STATES as gr, FILE_LIMITS as gt, parseGroupMetaFrame as h, readLinkRecord as ha, sealSecret as hi, emptyProofLedger as hn, deviceEchoFrame as ho, PR_STATES as hr, ChatFiles as ht, groupMetaBody as i, contactAskerHolds as ia, confirmationMatches as ii, isAppVersion as in, OwnInviteError as io, REPLY_LIMITS as ir, lobbyKeys as it, GROUP_WANT_NO_FRAME as j, APP_PREFIXES as ja, VIEWER_PERMISSIONS_POLICY as ji, downsamplePeaks as jn, withoutAppLink as jr, sanitizeTypingStatus as jt, GROUP_HAVE_FRAME as k, readAppBundleAsync as ka, presenceSeenAt as ki, VOICE_METER as kn, statusCardBytes as kr, TypingReceiver as kt, groupMetaToHand as l, knockSlotRecords as la, epochKeys as li, UPGRADE_CAPABILITY as ln, inviteOwnership as lo, wireReply as lr, pickHubs as lt, parseGroupMetaBody as m, readKnockSlot as ma, sealPair as mi, PeerProofs as mn, HANDOFF_CAPABILITY as mo, PR_CHECKS as mr, shouldBeHub as mt, groupCallSfu as n, REQUEST_LIFETIME_MS as na, verifyCommitSignature as ni, APP_DATA_MAX_BYTES as nn, INVITE_HRP as no, validReactionNumber as nr, freshHubs as nt, groupMetaNewer as o, knockHolds as oa, decryptText as oi, BUTTONS_CAPABILITY as on, decodeInviteCode as oo, pairedReplyAuthor as or, mergeBeacon as ot, openGroupMeta as p, openRequest as pa, openSecret as pi, dialDescriptors as pn, ENROLL_CAPABILITY as po, ITEM_STATES as pr, readLobby as pt, NO_HUB_POLICY as q, signAppRevocation as qa, extractParamsFromSdp as qi, COMMUNITY_REACTION_FRAME as qn, expectedRoster as qr, newWakeToken as qt, groupDisplayName as r, contactAskerFrame as ra, GROUP_PROFILE as ri, chatAppId as rn, INVITE_MAX_LENGTH as ro, wireReaction as rr, hubRank as rt, groupMetaPicture as s, knockSlotIdentity as sa, edgeParams as si, EDIT_CAPABILITY as sn, encodeInviteCode as so, readReply as sr, mergeLobby as st, encodeGroupMetaBody as t, ContactRequestError as ta, verifyCommit as ti, isServeId as tn, readCanonicalJson as to, readReaction as tr, doorHubs as tt, groupName as u, linkRecords as ua, groupCallKey as ui, CapsExchange as un, ownInviteRefusal as uo, BUTTON_ID as ur, rankHubs as ut, verifyGroupMetaSignature as v, APP_BUNDLE_LIMITS as va, RatchetBox as vi, DHT_FILE_TOO_LARGE as vn, deviceLinkPairing as vo, STATUS_CARD_LIMITS as vr, sentWhole as vt, PAIRED_FRAME_TOO_LARGE as w, checkAppManifest as wa, DHT_POLL_INTERVALS as wi, formatFileSize as wn, cardLine as wr, personStatus as wt, INVITE_TAKEN as x, appDigest as xa, DirectPathWatch as xi, peekDhtMailbox as xn, appCardUrl as xr, STATUS_AVAILABILITIES as xt, wrapGroupMeta as y, APP_BUNDLE_MAGIC as ya, emptyRatchetState as yi, DHT_MESSAGE_TTL as yn, devicePingFrame as yo, TASK_STATUSES as yr, transferEnded as yt, CarriedTransport as z, isAppLine as za, CALL_SIGNAL_MAX_AGE_MS as zi, MAX_REMOVAL_NUMBER as zn, GROUP_ID as zr, readPin as zt };
22031
+ export { beaconKeys as $, readImageMeta as $a, MAX_SHARED_APPS as $i, reactionEmoji as $n, sortRoster as $r, vapidKeysMatch as $t, GROUP_WANT_FRAME as A, sha256Paced as Aa, GhostlyHttpError as Ai, baseMime as An, statusCardText as Ar, TypingSender as At, GROUP_SIGNAL_FRAME as B, isAppLine as Ba, QUICK_REDIAL_MS as Bi, REMOVED_TEXT as Bn, GROUP_MEMBER_CAP as Br, WAKE_CALL_INTERVAL_MS as Bt, MESSAGE_PACED as C, assembleAppBundle as Ca, DAEMON_WATCH_PEER_IDLE_MS as Ci, dhtFileId as Cn, cardEditNumber as Cr, liveStatus as Ct, pairedMessageFrame as D, pacer as Da, RELAY_POLL_INTERVALS as Di, PLAYABLE_AUDIO as Dn, readStatusCard as Dr, TYPING_KINDS as Dt, pairedMessageFits as E, isAppUrl as Ea, PRESENCE_WINDOW as Ei, sanitizeMime as En, checkStatusCard as Er, TYPING_FRAME as Et, readGroupFileMeta as F, appRefPublisher as Fa, LIMITS as Fi, voiceLevel as Fn, heardTime as Fr, mayPin as Ft, readGroupSignal as G, readAppSignature as Ga, callSignalHeardAt as Gi, forwardedAgain as Gn, commitHash as Gr, WakeLimiter as Gt, SIGNAL_HOLD_MS as H, readAppRevocation as Ha, answersOffer as Hi, dhtEditId as Hn, MEMBER_KEY as Hr, WAKE_ONLINE_BATCH_MS as Ht, readGroupHave as I, appRevocationsFileEntries as Ia, decodeControl as Ii, parseVideoMeta as In, receivedTimestamp as Ir, nextPinNumber as It, mayBeHub as J, signAppRevocation as Ja, parseCallSignal as Ji, GROUP_REACTION_FRAME as Jn, parseGroupCommit as Jr, parseWakeFrame as Jt, MESH_HUBS as K, setAppSignatureFastPath as Ka, contactRtcConfig as Ki, readForwarded as Kn, commitUntaggedHash as Kr, deviceWakeRequest as Kt, readGroupWant as L, checkAppRevokeStatement as La, encodeControl as Li, EDIT_BUFFER_MS as Ln, shownTime as Lr, pinIsNewer as Lt, fetchesByItself as M, APP_STATEMENT_LIMITS as Ma, formatLocalTarget as Mi, fileMessageText as Mn, MESSAGE_CLOCK_SKEW_MS as Mr, typingActivity as Mt, groupFileFallback as N, appFingerprint as Na, parseLocalTarget as Ni, parseVoiceMeta as Nn, arrivalKey as Nr, GROUP_PIN_FRAME as Nt, GROUP_FILE_LIMITS as O, readAppBundle as Oa, WATCH_PEER_MS as Oi, VOICE_LIMITS as On, sameButtonText as Or, TYPING_REFRESH_MS as Ot, isGroupMessageId as P, appRef as Pa, webLocalFetch as Pi, voiceDownloadName as Pn, claimedTime as Pr, PIN_LIMITS as Pt, COMMUNITY_TOPOLOGY as Q, parseImageMeta as Qa, LEGACY_SERVICES as Qi, queueReaction as Qn, signCommit as Qr, checkPushEndpoint as Qt, readGroupWantNo as R, isAppHash as Ra, BURST_RING_MS as Ri, EDIT_RATE_WINDOW_MS as Rn, GROUP_ADMIN_OFF_ERROR as Rr, pinNumberHolds as Rt, LIVENESS_PING_MS as S, appViewOf as Sa, AWAITING_PEER_MS as Si, DHT_FILE_CAPABILITY as Sn, buttonLabelClash as Sr, STATUS_IDLE_AFTER_MS as St, pairedEditFits as T, findAppForbiddenKey as Ta, EXPECT_PEER_MS as Ti, sanitizeFileName as Tn, cardUrl as Tr, sanitizeStatusText as Tt, SIGNAL_REPLY_MS as U, readAppRevocationShape as Ua, buildSdpFromSignal as Ui, validEditNumber as Un, OWN_FRAME_LIMIT as Ur, WAKE_ONLINE_DELAY_MS as Ut, SIGNAL_FRESH_MS as V, isAppRef as Va, RTC_CONFIG as Vi, RateWindow as Vn, MAX_GROUP_CHAIN as Vr, WAKE_INTERVAL_MS as Vt, groupSignalFrame as W, readAppRevocations as Wa, callRtcConfig as Wi, validRemovalNumber as Wn, SAID_AGAIN as Wr, WAKE_ONLINE_INTERVAL_MS as Wt, meshRendezvous as X, verifyAppSignature as Xa, emptyLinkRecords as Xi, ReactionWindow as Xn, rosterAdmin as Xr, wakeFrame as Xt, meshHubs as Y, verifyAppRevocation as Ya, signalHasVideo as Yi, REACTION_LIMITS as Yn, rememberAlone as Yr, relayRequest as Yt, pickMeshHubs as Z, exifOrientation as Za, HTTP_SERVICE_PROTO as Zi, nextReactionNumber as Zn, rosterHas as Zr, wakeRequest as Zt, signGroupMeta as _, seenEntry as _a, RATCHET_CAPABILITY as _i, ACTIVE_DHT_POLL_MS as _n, deviceEchoNonce as _o, RUN_RESULTS as _r, FileUplink as _t, groupMetaChange as a, contactDay as aa, confirmationTag as ai, APPS_CAPABILITY as an, OwnInviteError as ao, groupReplyAuthor as ar, lobbyRecords as at, GhostLink as b, APP_ICON_PATH as ba, ratchetSessionOf as bi, DHT_PACKET_BUDGET as bn, devicePingFrame as bo, appCardId as br, transferStalled as bt, groupMetaTag as c, knockSlotOf as ca, encryptText as ci, STATUS_CARD_CAPABILITY as cn, encodeInviteCode as co, replySnippet as cr, newerHead as ct, keepPastGroupMeta as d, makeStampPaced as da, newEpochSecret as di, DHT_TEXT_CAPABILITY as dn, ownInviteRefusal as do, BUTTON_STYLES as dr, readBeacon as dt, serviceIdFromName as ea, verifyChain as ei, APP_RANGE_LIMITS as en, canonicalJson as eo, reactionIsNewer as er, beaconRecords as et, nextGroupMetaRevision as f, mergeContactKnocks as fa, openPair as fi, capsDescriptors as fn, pastedAgain as fo, CRON_LINE as fr, readBeaconHead as ft, parseGroupMetaTag as g, requestRecords as ga, sha256Hex as gi, validExternalKey as gn, deviceEchoFrame as go, ROUTINE_STATES as gr, FILE_LIMITS as gt, parseGroupMetaFrame as h, readLinkRecord as ha, sealSecret as hi, emptyProofLedger as hn, HANDOFF_CAPABILITY as ho, PR_STATES as hr, ChatFiles as ht, groupMetaBody as i, contactAskerHolds as ia, confirmationMatches as ii, isAppVersion as in, INVITE_MAX_LENGTH as io, REPLY_LIMITS as ir, lobbyKeys as it, GROUP_WANT_NO_FRAME as j, APP_PREFIXES as ja, VIEWER_PERMISSIONS_POLICY as ji, downsamplePeaks as jn, withoutAppLink as jr, sanitizeTypingStatus as jt, GROUP_HAVE_FRAME as k, readAppBundleAsync as ka, presenceSeenAt as ki, VOICE_METER as kn, statusCardBytes as kr, TypingReceiver as kt, groupMetaToHand as l, knockSlotRecords as la, epochKeys as li, UPGRADE_CAPABILITY as ln, inviteLink as lo, wireReply as lr, pickHubs as lt, parseGroupMetaBody as m, readKnockSlot as ma, sealPair as mi, PeerProofs as mn, ENROLL_CAPABILITY as mo, PR_CHECKS as mr, shouldBeHub as mt, groupCallSfu as n, REQUEST_LIFETIME_MS as na, verifyCommitSignature as ni, APP_DATA_MAX_BYTES as nn, readCanonicalJson as no, validReactionNumber as nr, freshHubs as nt, groupMetaNewer as o, knockHolds as oa, decryptText as oi, BUTTONS_CAPABILITY as on, createChatInvite as oo, pairedReplyAuthor as or, mergeBeacon as ot, openGroupMeta as p, openRequest as pa, openSecret as pi, dialDescriptors as pn, DEVICES_CAPABILITY as po, ITEM_STATES as pr, readLobby as pt, NO_HUB_POLICY as q, signAppObject as qa, extractParamsFromSdp as qi, COMMUNITY_REACTION_FRAME as qn, expectedRoster as qr, newWakeToken as qt, groupDisplayName as r, contactAskerFrame as ra, GROUP_PROFILE as ri, chatAppId as rn, INVITE_HRP as ro, wireReaction as rr, hubRank as rt, groupMetaPicture as s, knockSlotIdentity as sa, edgeParams as si, EDIT_CAPABILITY as sn, decodeInviteCode as so, readReply as sr, mergeLobby as st, encodeGroupMetaBody as t, ContactRequestError as ta, verifyCommit as ti, isServeId as tn, canonicalJsonBytes as to, readReaction as tr, doorHubs as tt, groupName as u, linkRecords as ua, groupCallKey as ui, CapsExchange as un, inviteOwnership as uo, BUTTON_ID as ur, rankHubs as ut, verifyGroupMetaSignature as v, APP_BUNDLE_LIMITS as va, RatchetBox as vi, DHT_FILE_TOO_LARGE as vn, deviceKeyZ32 as vo, STATUS_CARD_LIMITS as vr, sentWhole as vt, PAIRED_FRAME_TOO_LARGE as w, checkAppManifest as wa, DHT_POLL_INTERVALS as wi, formatFileSize as wn, cardLine as wr, personStatus as wt, INVITE_TAKEN as x, appDigest as xa, DirectPathWatch as xi, peekDhtMailbox as xn, newDeviceSetSecret as xo, appCardUrl as xr, STATUS_AVAILABILITIES as xt, wrapGroupMeta as y, APP_BUNDLE_MAGIC as ya, emptyRatchetState as yi, DHT_MESSAGE_TTL as yn, deviceLinkPairing as yo, TASK_STATUSES as yr, transferEnded as yt, CarriedTransport as z, isAppKey as za, CALL_SIGNAL_MAX_AGE_MS as zi, MAX_REMOVAL_NUMBER as zn, GROUP_ID as zr, readPin as zt };
21963
22032
 
21964
- //# sourceMappingURL=groupMeta--fxSh792.js.map
22033
+ //# sourceMappingURL=groupMeta-CeZpqVVC.js.map