@ghostlytools/cli 1.13.0 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +7 -6
  2. package/dist/assets/{api-CVtg7MpI.js → api-DF36rBJK.js} +2 -2
  3. package/dist/assets/{api-CjOaoG-v.js → api-Dnq86JAA.js} +135 -37
  4. package/dist/assets/api-Dnq86JAA.js.map +1 -0
  5. package/dist/assets/{apiKit-BAGvlQtm.js → apiKit-nLK4jeTq.js} +3 -3
  6. package/dist/assets/{apiKit-BAGvlQtm.js.map → apiKit-nLK4jeTq.js.map} +1 -1
  7. package/dist/assets/{appFetch-BwJd-kNq.js → appFetch-wqBWi3Ry.js} +2 -2
  8. package/dist/assets/{appFetch-BwJd-kNq.js.map → appFetch-wqBWi3Ry.js.map} +1 -1
  9. package/dist/assets/{apps-Cuk45sz5.js → apps-DBVhKpfe.js} +10 -10
  10. package/dist/assets/apps-DBVhKpfe.js.map +1 -0
  11. package/dist/assets/{apps-DjY095Af.js → apps-nLtyhC2f.js} +1 -1
  12. package/dist/assets/{backup-DekVCDWv.js → backup-Bczllmzf.js} +4 -4
  13. package/dist/assets/{backup-DekVCDWv.js.map → backup-Bczllmzf.js.map} +1 -1
  14. package/dist/assets/{backup-B56sQqoQ.js → backup-D6s0LQdg.js} +1 -1
  15. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
  16. package/dist/assets/{bitcoind-B2bbVSzh.js → bitcoind-DML_-Xbv.js} +2 -2
  17. package/dist/assets/{bitcoind-B2bbVSzh.js.map → bitcoind-DML_-Xbv.js.map} +1 -1
  18. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
  19. package/dist/assets/{buttons-BGxzOtrq.js → buttons-B3C3vdhH.js} +8 -8
  20. package/dist/assets/buttons-B3C3vdhH.js.map +1 -0
  21. package/dist/assets/buttons-DaY5FYlV.js +1 -0
  22. package/dist/assets/{client-DcQAfc3h.js → client-B7jRrSnb.js} +3 -3
  23. package/dist/assets/{client-DcQAfc3h.js.map → client-B7jRrSnb.js.map} +1 -1
  24. package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
  25. package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
  26. package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
  27. package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
  28. package/dist/assets/{fixedHosts-C3hBliM9.js → fixedHosts-H3i6o9Iy.js} +2 -2
  29. package/dist/assets/{fixedHosts-C3hBliM9.js.map → fixedHosts-H3i6o9Iy.js.map} +1 -1
  30. package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
  31. package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
  32. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  33. package/dist/assets/{groupMeta-goASqzOt.js → groupMeta--fxSh792.js} +72 -4
  34. package/dist/assets/groupMeta--fxSh792.js.map +1 -0
  35. package/dist/assets/{host-C2WRKj3g.js → host-CGzVFfMz.js} +169 -36
  36. package/dist/assets/host-CGzVFfMz.js.map +1 -0
  37. package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-B4_wdCtx.js} +2 -2
  38. package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-B4_wdCtx.js.map} +1 -1
  39. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-Ce-gWsRY.js} +2 -2
  40. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-Ce-gWsRY.js.map} +1 -1
  41. package/dist/assets/{irohWeb-NfthOL98.js → irohWeb-Dp1i8v6n.js} +12 -11
  42. package/dist/assets/irohWeb-Dp1i8v6n.js.map +1 -0
  43. package/dist/assets/{main-Dh7fePd8.js → main-C8J53SwH.js} +67 -62
  44. package/dist/assets/main-C8J53SwH.js.map +1 -0
  45. package/dist/assets/{ownDid-BErplN7N.js → ownDid-oa-T2vmZ.js} +8 -4
  46. package/dist/assets/ownDid-oa-T2vmZ.js.map +1 -0
  47. package/dist/assets/{ownStatus-ClrFjd7h.js → ownStatus-Bc08eNJY.js} +6 -6
  48. package/dist/assets/{ownStatus-ClrFjd7h.js.map → ownStatus-Bc08eNJY.js.map} +1 -1
  49. package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-Dppn8lUN.js} +3 -3
  50. package/dist/assets/pairedTransports-Dppn8lUN.js.map +1 -0
  51. package/dist/assets/{profiles-B8xO8-oj.js → profiles-B2uy04ph.js} +3 -3
  52. package/dist/assets/{profiles-B8xO8-oj.js.map → profiles-B2uy04ph.js.map} +1 -1
  53. package/dist/assets/{registry-CU8PevhI.js → registry-DbTLLs3y.js} +9 -5
  54. package/dist/assets/registry-DbTLLs3y.js.map +1 -0
  55. package/dist/assets/{registry--Rg2YvOH.js → registry-bLIfG619.js} +1 -1
  56. package/dist/assets/{resolve-B1upovPM.js → resolve-DNX-eecG.js} +9 -4
  57. package/dist/assets/resolve-DNX-eecG.js.map +1 -0
  58. package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
  59. package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
  60. package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
  61. package/dist/assets/{server-Dgxx_DaN.js → server-DWJ4RzJn.js} +536 -209
  62. package/dist/assets/server-DWJ4RzJn.js.map +1 -0
  63. package/dist/assets/{translate-BcbSWkuq.js → translate-CHj_PdLg.js} +13 -8
  64. package/dist/assets/translate-CHj_PdLg.js.map +1 -0
  65. package/dist/assets/{waitNotice-ylU3XwjO.js → waitNotice-Cvz5CiKR.js} +57 -3
  66. package/dist/assets/waitNotice-Cvz5CiKR.js.map +1 -0
  67. package/dist/ghostly.mjs +1 -1
  68. package/npm-shrinkwrap.json +2 -2
  69. package/package.json +1 -1
  70. package/dist/assets/api-CjOaoG-v.js.map +0 -1
  71. package/dist/assets/apps-Cuk45sz5.js.map +0 -1
  72. package/dist/assets/buttons-BGxzOtrq.js.map +0 -1
  73. package/dist/assets/buttons-CsN2WJOf.js +0 -1
  74. package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
  75. package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
  76. package/dist/assets/groupMeta-goASqzOt.js.map +0 -1
  77. package/dist/assets/host-C2WRKj3g.js.map +0 -1
  78. package/dist/assets/irohWeb-NfthOL98.js.map +0 -1
  79. package/dist/assets/main-Dh7fePd8.js.map +0 -1
  80. package/dist/assets/ownDid-BErplN7N.js.map +0 -1
  81. package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
  82. package/dist/assets/registry-CU8PevhI.js.map +0 -1
  83. package/dist/assets/resolve-B1upovPM.js.map +0 -1
  84. package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
  85. package/dist/assets/server-Dgxx_DaN.js.map +0 -1
  86. package/dist/assets/translate-BcbSWkuq.js.map +0 -1
  87. package/dist/assets/waitNotice-ylU3XwjO.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"groupMeta--fxSh792.js","names":["SEMVER","isObject","u32","NONCE_LENGTH","label","MAX_NAME_LENGTH","CANDIDATE_TYPES","compareBytes","header","NONCE_LENGTH","info","SIG","HASH","ID","isObject","ID","BASE64URL","ID","ID","hex","key","SIG","SIG","DIGEST","B64"],"sources":["../../../core/src/deviceLink.ts","../../../core/src/invite.ts","../../../core/src/canonicalJson.ts","../../../core/src/image.ts","../../../core/src/appStatements.ts","../../../core/src/appBundle.ts","../../../core/src/contactRecords.ts","../../../core/src/services.ts","../../../core/src/records.ts","../../../core/src/callSignal.ts","../../../core/src/signal.ts","../../../core/src/frames.ts","../../../core/src/http.ts","../../../core/src/link.ts","../../../core/src/directPath.ts","../../../core/src/datalink.ts","../../../core/src/ratchet.ts","../../../core/src/groupCrypto.ts","../../../core/src/groupCommits.ts","../../../core/src/messageTime.ts","../../../core/src/statusCards.ts","../../../core/src/replies.ts","../../../core/src/reactions.ts","../../../core/src/forwards.ts","../../../core/src/pairedEdits.ts","../../../core/src/video.ts","../../../core/src/voice.ts","../../../core/src/files.ts","../../../core/src/dhtFiles.ts","../../../core/src/dhtDelivery.ts","../../../core/src/pairedFiles.ts","../../../core/src/transportSwitch.ts","../../../core/src/pubkyRing.ts","../../../core/src/peerProofs.ts","../../../core/src/capsRecord.ts","../../../core/src/pairedSignal.ts","../../../core/src/pairedSession.ts","../../../core/src/pairedHttp.ts","../../../core/src/pairedCapabilities.ts","../../../core/src/pairedApps.ts","../../../core/src/pairedAppRanges.ts","../../../core/src/webPush.ts","../../../core/src/pairedWake.ts","../../../core/src/pins.ts","../../../core/src/pairedTyping.ts","../../../core/src/pairedStatus.ts","../../../core/src/chatFiles.ts","../../../core/src/pairedCalls.ts","../../../core/src/communityRendezvous.ts","../../../core/src/groupHubs.ts","../../../core/src/groupSignals.ts","../../../core/src/groupFiles.ts","../../../core/src/pairingProgress.ts","../../../core/src/ghostlink.ts","../../../core/src/groupMeta.ts"],"sourcesContent":["import { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesEqual, concatBytes, fromBase64Url, randomBytes, toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { identityFromSeed, verify } from \"./identity\";\nimport type { LinkParams } from \"./invite\";\nimport type { PairingCredentials } from \"./pairedSession\";\nimport type { Signer } from \"./signer\";\n\n/*\n * Device links (WISP 06 § Terms): the channel between two of a person's devices. It is an ordinary paired session\n * whose keys nobody exchanged: both ends derive them from the device-set secret `D` and the two device signing keys.\n * So any two enrolled devices have a link without ever having met, and a device that does not hold the current `D`\n * has none: under another `D` every key below is another key.\n *\n * - `linkSecret = HKDF-SHA256(ikm = D, salt = \"ghostly-devices/1\", info = \"link\" || lowerKey || higherKey, 32)`;\n * - each side's rendezvous seed: `HKDF-SHA256(linkSecret, salt, info = \"rv\" || ownSigningKey, 32)`;\n * - the key that seals the link's records: `HKDF-SHA256(linkSecret, salt, info = \"enc\", 32)`.\n *\n * The WISP names no salt for the last two; the device set's own (`ghostly-devices/1`) is used, and the vectors in\n * `packages/core/test/vectors/device-links.json` pin it. \"Lower\" and \"higher\" compare the two 32-byte keys as bytes.\n *\n * Each side's participation key is its device signing key, pinned from the turn record: a holder of `D` can compute\n * both rendezvous seeds and so disturb the rendezvous, and cannot pass the session's authentication without a device\n * signing key. Nothing here touches the network.\n */\n\nconst SALT = utf8Encode(\"ghostly-devices/1\");\n\n/**\n * A new device-set secret `D`: 32 random bytes (WISP 06 § Terms). The first `D` of a profile is not random, it comes\n * from the DID key's seed (`firstDeviceSetSecret`); every later one, made when a device is removed, is.\n */\nexport const newDeviceSetSecret = (): Uint8Array => randomBytes(32);\n\n/** -1, 0 or 1: two keys compared as bytes. */\nfunction compareKeys(a: Uint8Array, b: Uint8Array): number {\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;\n return 0;\n}\n\nfunction checkKeys(d: Uint8Array, a: Uint8Array, b: Uint8Array): void {\n if (d.length !== 32) throw new Error(\"The device-set secret is 32 bytes\");\n if (a.length !== 32 || b.length !== 32) throw new Error(\"A device signing key is 32 bytes\");\n if (bytesEqual(a, b)) throw new Error(\"A device has no link with itself\");\n}\n\n/** The secret of the link between two devices of the set that holds `D`. The same whichever key is given first. */\nexport function deviceLinkSecret(d: Uint8Array, keyA: Uint8Array, keyB: Uint8Array): Uint8Array {\n checkKeys(d, keyA, keyB);\n const [lower, higher] = compareKeys(keyA, keyB) < 0 ? [keyA, keyB] : [keyB, keyA];\n return hkdf(sha256, d, SALT, concatBytes(utf8Encode(\"link\"), lower, higher), 32);\n}\n\n/** One side's rendezvous seed on a link: the identity its packets of that link are published under. */\nexport function deviceLinkRendezvousSeed(linkSecret: Uint8Array, signingKey: Uint8Array): Uint8Array {\n return hkdf(sha256, linkSecret, SALT, concatBytes(utf8Encode(\"rv\"), signingKey), 32);\n}\n\n/** The key that seals the link's discovery records. */\nexport function deviceLinkSealKey(linkSecret: Uint8Array): Uint8Array {\n return hkdf(sha256, linkSecret, SALT, utf8Encode(\"enc\"), 32);\n}\n\n/**\n * The link from the device with `ownKey` to the one with `peerKey`, as a paired link's parameters: this side's\n * rendezvous seed, the other side's rendezvous key, and the shared sealing key.\n */\nexport function deviceLinkParams(d: Uint8Array, ownKey: Uint8Array, peerKey: Uint8Array): LinkParams {\n const secret = deviceLinkSecret(d, ownKey, peerKey);\n return {\n seedB64: toBase64Url(deviceLinkRendezvousSeed(secret, ownKey)),\n peerPubKeyZ32: identityFromSeed(deviceLinkRendezvousSeed(secret, peerKey)).pubKeyZ32,\n encKeyB64: toBase64Url(deviceLinkSealKey(secret)),\n profile: \"paired-chat/1\",\n };\n}\n\n/** A device signing key as a session names a participation key (z-base-32). */\nexport const deviceKeyZ32 = (signingKey: Uint8Array): string => toZ32(signingKey);\n\n/*\n * A device link's transports in its own packet (`_tr`, as a group's link has them): which layer-1 transports the app\n * runs and how to dial its native ones. The packet is published under a key derived from `D`, so any holder of `D`\n * could write a `_tr` there: endpoints of its own, or \"no WebRTC\", and stall the link. So on a device link the value\n * is signed with the device signing key, over the two rendezvous keys and the value, and a reader takes only one\n * signed by the key it pinned.\n */\nconst SIGNATURE = /^[A-Za-z0-9_-]{86}$/;\nconst transportsMessage = (from: string, to: string, t: unknown, d: unknown) =>\n utf8Encode(JSON.stringify([\"ghostly-device-transports\", 1, from, to, t, d ?? null]));\n\n/** A `_tr` value signed by this device: `{\"t\":…,\"d\":…,\"s\":\"<signature>\"}`. `from`/`to`: the link's two rendezvous keys, this side's first. */\nexport async function signDeviceTransports(value: string, signer: Signer, from: string, to: string): Promise<string> {\n const parsed = JSON.parse(value) as { t?: unknown; d?: unknown };\n const signature = await signer.sign(transportsMessage(from, to, parsed.t, parsed.d));\n return JSON.stringify({ t: parsed.t, d: parsed.d, s: toBase64Url(signature) });\n}\n\n/** The unsigned `_tr` value of one signed by `signingKey`, or null for anything else (unsigned, another key, another link). */\nexport function verifyDeviceTransports(value: string, from: string, to: string, signingKey: Uint8Array): string | null {\n try {\n if (value.length > 1_200) return null;\n const parsed = JSON.parse(value) as { t?: unknown; d?: unknown; s?: unknown };\n if (!parsed || typeof parsed !== \"object\" || typeof parsed.s !== \"string\" || !SIGNATURE.test(parsed.s)) return null;\n if (!verify(fromBase64Url(parsed.s), transportsMessage(from, to, parsed.t, parsed.d), signingKey)) return null;\n return JSON.stringify({ t: parsed.t, d: parsed.d });\n } catch { return null; }\n}\n\n/**\n * The `_tr` value of a signed one, unchecked, or null for anything that is not one: for an enrollment's inviter only,\n * which has no key to check it against until a joiner authenticated (`GhostLink`, trust on first use). Where to dial,\n * and nothing more: the session there still authenticates.\n */\nexport function unsignedDeviceTransports(value: string): string | null {\n try {\n if (value.length > 1_200) return null;\n const parsed = JSON.parse(value) as { t?: unknown; d?: unknown; s?: unknown };\n if (!parsed || typeof parsed !== \"object\" || typeof parsed.s !== \"string\" || !SIGNATURE.test(parsed.s)) return null;\n return JSON.stringify({ t: parsed.t, d: parsed.d });\n } catch { return null; }\n}\n\n/** What a paired link needs to be a device link: its derived parameters and its pinned, signer-backed pairing. */\nexport interface DeviceLinkPairing {\n params: LinkParams;\n pairing: { credentials: PairingCredentials; pinPeer: (key: string) => Promise<void>; trustOnFirstUse: false };\n}\n\n/**\n * The link from this device (its signer) to the device with `peerKey`, ready for a `GhostLink`. The other device's\n * signing key is pinned before anything is said, as the turn record names it: there is nothing to trust on first\n * use, and no other key is ever saved in its place. Signals in the link's packets must be signed by that key too.\n */\nexport function deviceLinkPairing(d: Uint8Array, signer: Signer, peerKey: Uint8Array): DeviceLinkPairing {\n const peer = deviceKeyZ32(peerKey);\n return {\n params: deviceLinkParams(d, signer.publicKey, peerKey),\n pairing: {\n credentials: { seedB64: \"\", signer, peerKey: peer, expectedPeerKey: peer, verifiedPeerKey: peer, requireSignedSignals: true },\n pinPeer: async (key) => { if (key !== peer) throw new Error(\"Not the device this link belongs to\"); },\n trustOnFirstUse: false,\n },\n };\n}\n\n/*\n * Frames. Everything two devices say to each other travels on a device link only, under a capability that only\n * device links offer (WISP 06 § Removing a device, § Frames, § Adding a device). A frame's `t` says which:\n *\n * | `t` starts with | Capability | Part of the WISP |\n * |-----------------|--------------|------------------------------------|\n * | `device-` | `devices/1` | the link itself (ping and echo) |\n * | `set-` | `devices/1` | removing a device |\n * | `handoff-` | `handoff/1` | the handoff |\n * | `enroll-` | `enroll/1` | adding a device |\n *\n * A frame is handed on only when both ends announced its capability on the open session, so a chat (which offers\n * none of them) drops every one. The frames carry no message id, as other session frames that older apps drop.\n * This part offers `devices/1` and defines `device-ping` and `device-echo`; the others are the later parts'.\n */\nexport const DEVICES_CAPABILITY = \"devices/1\";\nexport const HANDOFF_CAPABILITY = \"handoff/1\";\nexport const ENROLL_CAPABILITY = \"enroll/1\";\nexport type DeviceCapability = typeof DEVICES_CAPABILITY | typeof HANDOFF_CAPABILITY | typeof ENROLL_CAPABILITY;\nexport const DEVICE_CAPABILITIES: readonly DeviceCapability[] = [DEVICES_CAPABILITY, HANDOFF_CAPABILITY, ENROLL_CAPABILITY];\n\nconst FRAME_PREFIXES: readonly [string, DeviceCapability][] = [\n [\"device-\", DEVICES_CAPABILITY], [\"set-\", DEVICES_CAPABILITY], [\"handoff-\", HANDOFF_CAPABILITY], [\"enroll-\", ENROLL_CAPABILITY],\n];\n\n/** The capability a frame of this type travels under, or null when it is no device frame. */\nexport function deviceFrameCapability(type: unknown): DeviceCapability | null {\n if (typeof type !== \"string\") return null;\n return FRAME_PREFIXES.find(([prefix]) => type.startsWith(prefix) && type.length > prefix.length)?.[1] ?? null;\n}\n\n/** A frame between two devices: `t` names it, the rest is its body. */\nexport interface DeviceFrame {\n t: string;\n [field: string]: unknown;\n}\n\nexport const DEVICE_PING_FRAME = \"device-ping\";\nexport const DEVICE_ECHO_FRAME = \"device-echo\";\nconst PING_NONCE = /^[A-Za-z0-9_-]{22}$/;\n\n/** `{\"t\":\"device-ping\",\"n\":\"<16 random bytes, base64url>\"}`: asks the other device to say the nonce back. */\nexport function devicePingFrame(nonce: Uint8Array = randomBytes(16)): DeviceFrame & { n: string } {\n if (nonce.length !== 16) throw new Error(\"A ping's nonce is 16 bytes\");\n return { t: DEVICE_PING_FRAME, n: toBase64Url(nonce) };\n}\n\n/** The echo of a ping, or null when the frame is not a well-formed ping. */\nexport function deviceEchoFrame(ping: DeviceFrame): (DeviceFrame & { n: string }) | null {\n if (ping.t !== DEVICE_PING_FRAME || typeof ping.n !== \"string\" || !PING_NONCE.test(ping.n)) return null;\n return { t: DEVICE_ECHO_FRAME, n: ping.n };\n}\n\n/** The nonce an echo says back, or null when the frame is not a well-formed echo. */\nexport function deviceEchoNonce(frame: DeviceFrame): string | null {\n return frame.t === DEVICE_ECHO_FRAME && typeof frame.n === \"string\" && PING_NONCE.test(frame.n) ? frame.n : null;\n}\n","import { bech32, bech32m } from \"@scure/base\";\nimport { generateEncryptionKey } from \"./crypto\";\nimport { createIdentity, identityFromSeedB64 } from \"./identity\";\nimport { fromBase64Url, fromZ32, isZ32Key, toBase64Url, toZ32 } from \"./bytes\";\nimport { trimEndOf, unwrapPasted } from \"./text\";\n\n/**\n * A link between two peers: my identity, the peer's public key and the shared\n * secretbox key. The slash forms are the invite formats of Ghostly 0.4\n * (`<seed>/<peer public key>/<encryption key>`) and of pre-0.5 builds\n * (`pair1/…`, `pair2d/…`); a current app reads them and makes only `ghostly1…`\n * codes (WISP 801).\n */\nexport interface LinkParams {\n profile?: \"paired-chat/1\";\n deliveryMode?: \"stream\" | \"dht\";\n seedB64: string;\n peerPubKeyZ32: string;\n encKeyB64: string;\n /**\n * The inviter's participation public key, carried by a `ghostly1` code: the\n * joiner pins the inviter from it before either path answers.\n */\n peerParticipationKeyZ32?: string;\n /**\n * The inviter's own participation seed, on the inviter's side only (the one\n * whose public key its invite carries). Never part of a code.\n */\n participationSeedB64?: string;\n}\n\n/** The human-readable part of every invite code: codes read `ghostly1…`. */\nexport const INVITE_HRP = \"ghostly\";\n/** The format version this build makes; the first data symbol (`p`). */\nexport const INVITE_VERSION = 1;\n/**\n * The version of a code that adds a device to a profile (WISP 06 § Adding a device, `deviceInvite.ts`): no chat. The\n * chat reader refuses it as `device`; an app from before WISP 06 refuses it as a newer version.\n */\nexport const DEVICE_INVITE_VERSION = 2;\n/** Decoders refuse anything longer before computing a checksum (WISP 801 lifts bech32's 90). */\nexport const INVITE_MAX_LENGTH = 1023;\n/** The canonical link host (Q11): the code travels in the fragment, never sent to a server. */\nexport const INVITE_LINK_ORIGIN = \"https://ghostly.tools\";\nconst V1_BYTES = 128;\n\n/**\n * Why a code was refused, each with the one message the UI shows for it. `device`: a code that adds a device to a\n * profile (WISP 06), which no chat can be made from.\n */\nexport type InviteRefusal = \"typo\" | \"update\" | \"not-ghostly\" | \"damaged\" | \"device\";\n\n/** What reading a pasted or scanned invite gives: the chat's parameters, or why not. */\nexport type InviteReading =\n | { ok: true; params: LinkParams; format: \"ghostly1\" | \"pair1\" | \"pair2d\" | \"legacy\" }\n | { ok: false; reason: InviteRefusal; detail?: string };\n\n/** The `ghostly1…` code of a new chat. `params` must carry the inviter's participation key. */\nexport function encodeGhostlyInvite(params: LinkParams): string {\n if (!params.peerParticipationKeyZ32) throw new Error(\"A ghostly1 invite needs the inviter's participation key\");\n const payload = new Uint8Array(V1_BYTES);\n const fields = [fromBase64Url(params.seedB64), fromZ32(params.peerPubKeyZ32), fromBase64Url(params.encKeyB64), fromZ32(params.peerParticipationKeyZ32)];\n fields.forEach((field, index) => {\n if (field.length !== 32) throw new Error(\"Every field of a ghostly1 invite is 32 bytes\");\n payload.set(field, index * 32);\n });\n return bech32m.encode(INVITE_HRP, [INVITE_VERSION, ...bech32m.toWords(payload)], false);\n}\n\n/**\n * The code for these parameters: `ghostly1…` when they carry the inviter's\n * participation key (every invite a current app makes), else the slash form\n * they were read from, so a stored older code round-trips.\n */\nexport function encodeInviteCode(params: LinkParams): string {\n if (params.peerParticipationKeyZ32) return encodeGhostlyInvite(params);\n return `${params.profile ? (params.deliveryMode === \"dht\" ? \"pair2d/\" : \"pair1/\") : \"\"}${params.seedB64}/${params.peerPubKeyZ32}/${params.encKeyB64}`;\n}\n\n/** `https://ghostly.tools/#ghostly1…`: the form an invite is shared in. */\nexport function inviteLink(code: string, origin = INVITE_LINK_ORIGIN): string {\n return `${trimEndOf(origin, \"/\")}/#${code}`;\n}\n\n/** What goes in a QR code: upper case, so the code fits the alphanumeric mode. Older codes stay as they are. */\nexport function inviteQrText(code: string): string {\n return /^ghostly1/i.test(code) ? code.toUpperCase() : code;\n}\n\n/**\n * The QR segments of an invite's link, in capitals: `HTTPS://GHOSTLY.TOOLS/`\n * and the code in alphanumeric mode, the `#` between them in byte mode (QR\n * version 9 at level M). An encoder that takes a list of strings picks each\n * one's mode; one string with the `#` in it would be all bytes. Older codes\n * stay one segment, as they are.\n */\nexport function inviteQrSegments(code: string, origin = INVITE_LINK_ORIGIN): string[] {\n if (!/^ghostly1/i.test(code)) return [code];\n return [`${trimEndOf(origin, \"/\")}/`.toUpperCase(), \"#\", code.toUpperCase()];\n}\n\n/** The code inside whatever was pasted or scanned: after the last `#`, without a leading `chat/`. */\nfunction inviteBody(input: string): string {\n return input.trim().replace(/^.*#/, \"\").replace(/^\\/?chat\\//, \"\");\n}\n\nfunction readGhostly(code: string): InviteReading {\n if (code.length > INVITE_MAX_LENGTH) return { ok: false, reason: \"not-ghostly\", detail: \"Longer than 1,023 characters\" };\n const decoded = bech32m.decodeUnsafe(code, INVITE_MAX_LENGTH);\n if (!decoded) {\n // A valid bech32 (not bech32m) checksum is another kind of string, not a typo.\n if (bech32.decodeUnsafe(code, INVITE_MAX_LENGTH)) return { ok: false, reason: \"not-ghostly\", detail: \"bech32, not bech32m\" };\n return { ok: false, reason: \"typo\" };\n }\n if (decoded.prefix !== INVITE_HRP) return { ok: false, reason: \"typo\" };\n const [version, ...words] = decoded.words;\n if (version === undefined || version === 0) return { ok: false, reason: \"not-ghostly\", detail: \"Version 0 is reserved\" };\n // Newer than every version this reader knows (a chat's 1, a device's 2): a newer Ghostly made it.\n if (version > DEVICE_INVITE_VERSION) return { ok: false, reason: \"update\", detail: `Version ${version}` };\n if (version === DEVICE_INVITE_VERSION) return { ok: false, reason: \"device\" };\n const payload = bech32m.fromWordsUnsafe(words);\n if (!payload) return { ok: false, reason: \"damaged\", detail: \"Padding\" };\n if (payload.length !== V1_BYTES) return { ok: false, reason: \"damaged\", detail: `${payload.length} bytes, not ${V1_BYTES}` };\n const field = (index: number) => payload.slice(index * 32, index * 32 + 32);\n return {\n ok: true,\n format: \"ghostly1\",\n params: {\n profile: \"paired-chat/1\",\n seedB64: toBase64Url(field(0)),\n peerPubKeyZ32: toZ32(field(1)),\n encKeyB64: toBase64Url(field(2)),\n peerParticipationKeyZ32: toZ32(field(3)),\n },\n };\n}\n\nconst B64_KEY = /^[A-Za-z0-9_-]{43}$/;\n\nfunction readSlashForm(code: string): InviteReading {\n const dht = code.startsWith(\"pair2d/\");\n const profile = (dht || code.startsWith(\"pair1/\")) ? \"paired-chat/1\" as const : undefined;\n const parts = (profile ? code.slice(dht ? 7 : 6) : code).split(\"/\");\n if (parts.length !== 3) {\n // A string of another kind (`npub1…`, `lnbc1…`, a word): not a Ghostly invite. A known prefix that lost a part: damaged.\n return profile ? { ok: false, reason: \"damaged\", detail: \"Three fields expected\" } : { ok: false, reason: \"not-ghostly\" };\n }\n const [seedB64, peerPubKeyZ32, encKeyB64] = parts;\n const bad = !B64_KEY.test(seedB64) ? \"The seed\" : !isZ32Key(peerPubKeyZ32) ? \"The contact's key\" : !B64_KEY.test(encKeyB64) ? \"The shared key\" : null;\n if (bad) return { ok: false, reason: \"damaged\", detail: `${bad} is malformed` };\n return {\n ok: true,\n format: profile ? (dht ? \"pair2d\" : \"pair1\") : \"legacy\",\n params: { seedB64, peerPubKeyZ32, encKeyB64, ...(profile ? { profile, ...(dht ? { deliveryMode: \"dht\" as const } : {}) } : {}) },\n };\n}\n\n/**\n * Reads an invite by the rules of WISP 801: a `ghostly1…` code in any case, bare\n * or in a link (`https://ghostly.tools/#…`, `app.ghostly.tools/#…`), or one of\n * the older slash forms. A refused code is never retried as another format.\n */\nexport function readInviteCode(input: string): InviteReading {\n const reading = readInviteForm(input);\n if (reading.ok) return reading;\n // Copied with the words around it (\"Here: <…#ghostly1…>.\", \"« ghostly1… »\", \"…?\"): read once more as the token in\n // it (`unwrapPasted`), taken when it reads. A refusal of that token is said over \"not an invite\" when the paste\n // as a whole was not one: a code with a typo in a sentence is a code with a typo.\n return pastedAgain(input, reading, readInviteForm);\n}\n\n/** `reading` of `input`, or the reading of the token in it (`unwrapPasted`) when that reads or says more. */\nexport function pastedAgain<T extends { ok: true } | { ok: false; reason: string }>(input: string, reading: T, read: (input: string) => T): T {\n const bare = unwrapPasted(input);\n if (bare === input.trim() || !bare) return reading;\n const again = read(bare);\n if (again.ok || (!reading.ok && reading.reason === \"not-ghostly\")) return again;\n return reading;\n}\n\nfunction readInviteForm(input: string): InviteReading {\n const code = inviteBody(input);\n if (!code) return { ok: false, reason: \"not-ghostly\" };\n if (/^ghostly1/i.test(code)) return readGhostly(code.toLowerCase());\n return readSlashForm(code);\n}\n\n/** The parameters of an invite, or null when it is refused (`readInviteCode` says why). */\nexport function decodeInviteCode(input: string): LinkParams | null {\n const reading = readInviteCode(input);\n return reading.ok ? reading.params : null;\n}\n\n/** Creates both ends of a link: keep `mine`, hand `invite` to the peer. */\nexport function createLink(): { mine: LinkParams; invite: LinkParams } {\n const a = createIdentity();\n const b = createIdentity();\n const encKeyB64 = toBase64Url(generateEncryptionKey());\n return {\n mine: { seedB64: a.seedB64, peerPubKeyZ32: b.pubKeyZ32, encKeyB64 },\n invite: { seedB64: b.seedB64, peerPubKeyZ32: a.pubKeyZ32, encKeyB64 },\n };\n}\n\n/**\n * A new chat, the way a current app makes one: `mine` keeps this side's\n * participation seed, `invite` carries its public key, and `inviteCode` is the\n * `ghostly1…` code to hand over.\n */\nexport function createChatInvite(): { mine: LinkParams; invite: LinkParams; inviteCode: string } {\n const { mine, invite } = createLink();\n const participation = createIdentity();\n const pairedMine: LinkParams = { ...mine, profile: \"paired-chat/1\", participationSeedB64: participation.seedB64 };\n const pairedInvite: LinkParams = { ...invite, profile: \"paired-chat/1\", peerParticipationKeyZ32: participation.pubKeyZ32 };\n return { mine: pairedMine, invite: pairedInvite, inviteCode: encodeGhostlyInvite(pairedInvite) };\n}\n\n/** A chat this side already has, as `inviteOwnership` reads it: its own seed and the contact's link key. */\nexport interface KnownLink {\n seedB64: string;\n peerPubKeyZ32: string;\n}\n\n/**\n * Whose invite a code is, among the chats a profile already has: `own` when this profile made it (the\n * invite's seed derives the contact key one of its chats waits for, which holds for every format, since\n * an inviter keeps the contact's public key), `joined` when this profile already joined by it (the\n * invite's seed is a chat's own), `new` otherwise. Another profile's chats are never passed, so its\n * invites read as new: two profiles on one app may chat with each other.\n */\nexport type InviteOwnership<T extends KnownLink> = { kind: \"own\" | \"joined\"; link: T } | { kind: \"new\" };\n\nexport function inviteOwnership<T extends KnownLink>(invite: Pick<LinkParams, \"seedB64\">, links: Iterable<T>): InviteOwnership<T> {\n const known = [...links];\n const joined = known.find((link) => link.seedB64 === invite.seedB64);\n if (joined) return { kind: \"joined\", link: joined };\n const inviteKey = identityFromSeedB64(invite.seedB64).pubKeyZ32;\n const own = known.find((link) => link.peerPubKeyZ32 === inviteKey);\n return own ? { kind: \"own\", link: own } : { kind: \"new\" };\n}\n\nconst OWN_INVITE_PREFIX = \"own-invite\";\n\n/**\n * A join refused because the invite is this profile's own (WISP 801 Q9). The message carries the reason\n * and the chat that owns the invite, so a client on the other side of an RPC (which gets the message and\n * nothing else) reads them back with `ownInviteRefusal`.\n */\nexport class OwnInviteError extends Error {\n readonly reason = OWN_INVITE_PREFIX;\n constructor(readonly linkId: string | null) {\n super(`${OWN_INVITE_PREFIX}${linkId ? ` ${linkId}` : \"\"}: This is your own invite. Share it with a contact; they join with it.`);\n this.name = \"OwnInviteError\";\n }\n}\n\n/** The refusal an error (or an error's message, as an RPC hands it over) carries, or null when it is another error. */\nexport function ownInviteRefusal(error: unknown): { linkId: string | null } | null {\n if (error instanceof OwnInviteError) return { linkId: error.linkId };\n const message = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\";\n const match = message.match(/^own-invite(?: (\\S+))?: /);\n return match ? { linkId: match[1] ?? null } : null;\n}\n","import { bytesEqual, utf8Decode, utf8Encode } from \"./bytes\";\n\n/*\n * JSON in its canonical form (RFC 8785, JCS), as WISP 1200 signs and reads it: object keys sorted by their UTF-16 code\n * units, no whitespace, strings and numbers written as ECMAScript's JSON.stringify writes them. A reader never trusts\n * that bytes are canonical: it parses them and writes the value again, and refuses the bytes when the two differ. That\n * one comparison refuses a duplicated key, a key out of order, whitespace, a byte order mark, `1.0` or `1e2`, an\n * escape written another way and an integer past 2^53, so two parsers can never read different values from one text.\n */\n\n/** A value JSON can hold. */\nexport type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };\n\n/** True when `s` holds a lone UTF-16 surrogate, which I-JSON (and so JCS) does not allow. */\nfunction hasLoneSurrogate(s: string): boolean {\n for (let i = 0; i < s.length; i++) {\n const c = s.charCodeAt(i);\n if (c >= 0xd800 && c <= 0xdbff) {\n const next = s.charCodeAt(i + 1);\n if (next >= 0xdc00 && next <= 0xdfff) { i++; continue; }\n return true;\n }\n if (c >= 0xdc00 && c <= 0xdfff) return true;\n }\n return false;\n}\n\nfunction write(value: unknown, depth: number): string {\n if (depth > 64) throw new Error(\"JSON nested deeper than 64 levels\");\n if (value === null) return \"null\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new Error(\"JSON numbers must be finite\");\n return JSON.stringify(value);\n }\n if (typeof value === \"string\") {\n if (hasLoneSurrogate(value)) throw new Error(\"A JSON string holds a lone surrogate\");\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `[${value.map((v) => write(v, depth + 1)).join(\",\")}]`;\n if (typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n // A member whose value is undefined is left out, as JSON.stringify leaves it out.\n const keys = Object.keys(value).filter((k) => record[k] !== undefined).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${keys.map((k) => {\n if (hasLoneSurrogate(k)) throw new Error(\"A JSON key holds a lone surrogate\");\n return `${JSON.stringify(k)}:${write(record[k], depth + 1)}`;\n }).join(\",\")}}`;\n }\n throw new Error(`Not a JSON value: ${typeof value}`);\n}\n\n/** The canonical text of a JSON value. Throws on a value JSON cannot hold (a non-finite number, a lone surrogate). */\nexport function canonicalJson(value: unknown): string {\n return write(value, 0);\n}\n\n/** The canonical UTF-8 bytes of a JSON value. */\nexport function canonicalJsonBytes(value: unknown): Uint8Array {\n return utf8Encode(canonicalJson(value));\n}\n\nexport type CanonicalJsonRefusal = \"not-json\" | \"not-canonical\";\nexport type CanonicalJsonReading = { ok: true; value: JsonValue } | { ok: false; reason: CanonicalJsonRefusal; detail?: string };\n\n/**\n * Reads bytes that must be the canonical form of a JSON value: `not-json` when they are not UTF-8 JSON, `not-canonical`\n * when writing the value again gives other bytes.\n */\nexport function readCanonicalJson(bytes: Uint8Array): CanonicalJsonReading {\n let value: JsonValue;\n try {\n value = JSON.parse(utf8Decode(bytes)) as JsonValue;\n } catch (error) {\n return { ok: false, reason: \"not-json\", detail: error instanceof Error ? error.message : String(error) };\n }\n let again: Uint8Array;\n try {\n again = canonicalJsonBytes(value);\n } catch (error) {\n return { ok: false, reason: \"not-canonical\", detail: error instanceof Error ? error.message : String(error) };\n }\n if (!bytesEqual(again, bytes)) return { ok: false, reason: \"not-canonical\" };\n return { ok: true, value };\n}\n","/**\n * Pictures. A picture is an ordinary file (files/2, files/3 or a held item) whose announcement may also carry an\n * `image` description: its size in pixels as it is shown, so the receiver lays out its box before a byte of it has\n * arrived and the chat does not move when it loads. A peer that does not know `image` ignores it and shows the\n * picture as before; a bad description only means no box.\n *\n * The sender reads the size from the file's first bytes (`imageSize`): no decoding, the same on every platform.\n */\nexport interface ImageMeta {\n /** Pixels, as it is shown (EXIF orientation applied). */\n width: number;\n height: number;\n}\n\nexport const IMAGE_LIMITS = {\n /** Pixels on either side: the most a JPEG can say, well past what anyone sends as a picture. */\n maxEdge: 65_535,\n /** How much of a file is read for its size: past a JPEG's EXIF, thumbnails and colour profile. */\n headBytes: 256 * 1024,\n /**\n * The most pixels a picture drawn in a chat may have: a 50-megapixel phone photo (8160 × 6120), about 200 MB once\n * decoded. A few kilobytes can say far more (a PNG of 23000 × 23000 is 64 KB and 2 GB decoded): past this a picture\n * is kept and saved, not drawn.\n */\n previewPixels: 50_000_000,\n /** The longest side a picture drawn in a chat may have: a wide panorama. */\n previewEdge: 16_384,\n} as const;\n\n/**\n * Whether a picture of this size, read from its own bytes (never from what its sender said), may be drawn: undefined\n * (its bytes do not say) may not either, as what draws it would find its size only by decoding it.\n */\nexport function previewable(size: ImageMeta | undefined): boolean {\n return !!size && size.width <= IMAGE_LIMITS.previewEdge && size.height <= IMAGE_LIMITS.previewEdge\n && size.width * size.height <= IMAGE_LIMITS.previewPixels;\n}\n\n/** Whether a file is a picture, by its type. */\nexport function isImageMime(mime: string): boolean {\n return mime.split(\";\")[0]!.trim().toLowerCase().startsWith(\"image/\");\n}\n\nconst edge = (n: unknown): n is number => typeof n === \"number\" && Number.isSafeInteger(n) && n > 0 && n <= IMAGE_LIMITS.maxEdge;\n\n/** A peer's `image` description, or undefined when it is not one. It never refuses the file. */\nexport function parseImageMeta(value: unknown, mime?: string): ImageMeta | undefined {\n if (mime !== undefined && !isImageMime(mime)) return undefined;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const { width, height } = value as { width?: unknown; height?: unknown };\n return edge(width) && edge(height) ? { width, height } : undefined;\n}\n\nconst u16be = (b: Uint8Array, at: number) => (b[at]! << 8) | b[at + 1]!;\nconst u16le = (b: Uint8Array, at: number) => b[at]! | (b[at + 1]! << 8);\nconst u24le = (b: Uint8Array, at: number) => b[at]! | (b[at + 1]! << 8) | (b[at + 2]! << 16);\nconst u32be = (b: Uint8Array, at: number) => ((b[at]! << 24) >>> 0) + (b[at + 1]! << 16) + (b[at + 2]! << 8) + b[at + 3]!;\nconst ascii = (b: Uint8Array, at: number, text: string) => [...text].every((c, i) => b[at + i] === c.charCodeAt(0));\n\nconst sized = (width: number, height: number): ImageMeta | undefined => (edge(width) && edge(height) ? { width, height } : undefined);\n\n/** SOFn markers: every frame type but DHT (C4), JPG (C8) and DAC (CC). */\nconst JPEG_FRAME = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);\n\n/** The EXIF orientation in an APP1 segment's TIFF block (1 when it says none). */\nexport function exifOrientation(b: Uint8Array, tiff: number, end: number): number {\n if (tiff + 8 > end) return 1;\n const little = ascii(b, tiff, \"II\");\n if (!little && !ascii(b, tiff, \"MM\")) return 1;\n const u16 = (at: number) => (little ? u16le(b, at) : u16be(b, at));\n const u32 = (at: number) => (little ? (u16le(b, at) + u16le(b, at + 2) * 65536) : u32be(b, at));\n if (u16(tiff + 2) !== 42) return 1;\n const ifd = tiff + u32(tiff + 4);\n if (ifd + 2 > end) return 1;\n const count = u16(ifd);\n for (let i = 0; i < count; i++) {\n const entry = ifd + 2 + i * 12;\n if (entry + 12 > end) return 1;\n // Orientation, a SHORT: its value sits in the first two bytes of the value field.\n if (u16(entry) === 0x0112) { const value = u16(entry + 8); return value >= 1 && value <= 8 ? value : 1; }\n }\n return 1;\n}\n\nfunction jpegSize(b: Uint8Array): ImageMeta | undefined {\n let at = 2, orientation = 1;\n while (at + 4 <= b.length) {\n if (b[at] !== 0xff) return undefined;\n const marker = b[at + 1]!;\n // Fill bytes, then markers that stand alone.\n if (marker === 0xff) { at++; continue; }\n if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { at += 2; continue; }\n // The image data or its end, and still no frame header.\n if (marker === 0xd9 || marker === 0xda) return undefined;\n const length = u16be(b, at + 2);\n if (length < 2) return undefined;\n const end = Math.min(b.length, at + 2 + length);\n if (marker === 0xe1 && ascii(b, at + 4, \"Exif\\0\\0\")) orientation = exifOrientation(b, at + 10, end);\n if (JPEG_FRAME.has(marker)) {\n if (at + 9 > b.length) return undefined;\n const height = u16be(b, at + 5), width = u16be(b, at + 7);\n // 5 to 8 turn it a quarter: shown, it is as wide as it is stored tall.\n return orientation >= 5 ? sized(height, width) : sized(width, height);\n }\n at += 2 + length;\n }\n return undefined;\n}\n\nfunction webpSize(b: Uint8Array): ImageMeta | undefined {\n if (b.length < 30) return undefined;\n if (ascii(b, 12, \"VP8 \")) {\n // A key frame: its start code, then 14-bit sizes (the top two bits are scaling).\n if (b[23] !== 0x9d || b[24] !== 0x01 || b[25] !== 0x2a) return undefined;\n return sized(u16le(b, 26) & 0x3fff, u16le(b, 28) & 0x3fff);\n }\n if (ascii(b, 12, \"VP8L\")) {\n if (b[20] !== 0x2f) return undefined;\n const bits = b[21]! | (b[22]! << 8) | (b[23]! << 16) | (b[24]! << 24);\n return sized((bits & 0x3fff) + 1, ((bits >>> 14) & 0x3fff) + 1);\n }\n if (ascii(b, 12, \"VP8X\")) return sized(u24le(b, 24) + 1, u24le(b, 27) + 1);\n return undefined;\n}\n\n/**\n * A GIF's size as it is decoded: its logical screen, or as far as its first frame reaches past it (a browser decodes\n * the first frame whole, at its own size, however small the screen says it is). Undefined when its first frame is not\n * in these bytes: what it would be drawn at is not known.\n */\nfunction gifSize(b: Uint8Array): ImageMeta | undefined {\n if (b.length < 13) return undefined;\n const screenWidth = u16le(b, 6), screenHeight = u16le(b, 8);\n // The global colour table, when there is one: 3 bytes a colour, 2 to 256 colours.\n let at = 13 + (b[10]! & 0x80 ? 3 * (2 << (b[10]! & 7)) : 0);\n while (at < b.length) {\n const block = b[at]!;\n if (block === 0x2c) {\n if (at + 9 > b.length) return undefined;\n const left = u16le(b, at + 1), top = u16le(b, at + 3), width = u16le(b, at + 5), height = u16le(b, at + 7);\n return sized(Math.max(screenWidth, left + width), Math.max(screenHeight, top + height));\n }\n // No frame at all: nothing past the screen is drawn.\n if (block === 0x3b) return sized(screenWidth, screenHeight);\n if (block !== 0x21 || at + 2 > b.length) return undefined;\n // An extension: its label, then sub-blocks (a length byte, then that many bytes) up to an empty one.\n at += 2;\n while (at < b.length && b[at] !== 0) at += 1 + b[at]!;\n at++;\n }\n return undefined;\n}\n\n/**\n * A picture's size as it is shown, read from its first bytes (PNG, JPEG, GIF, WebP), or undefined when they do not\n * say. Only the header is read: a JPEG whose frame header, or a GIF whose first frame, sits past\n * `IMAGE_LIMITS.headBytes` goes without.\n */\nexport function imageSize(head: Uint8Array): ImageMeta | undefined {\n const b = head;\n try {\n if (b.length >= 24 && b[0] === 0x89 && ascii(b, 1, \"PNG\\r\\n\\x1a\\n\") && ascii(b, 12, \"IHDR\")) return sized(u32be(b, 16), u32be(b, 20));\n if (b.length >= 10 && (ascii(b, 0, \"GIF87a\") || ascii(b, 0, \"GIF89a\"))) return gifSize(b);\n if (b.length >= 4 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return jpegSize(b);\n if (b.length >= 16 && ascii(b, 0, \"RIFF\") && ascii(b, 8, \"WEBP\")) return webpSize(b);\n } catch { /* not a picture this reads */ }\n return undefined;\n}\n\n/**\n * The description a picture is sent with, read from the start of the file, or undefined when it is not a picture\n * or its first bytes do not say (it then goes without one).\n */\nexport async function readImageMeta(source: Blob, mime: string): Promise<ImageMeta | undefined> {\n if (!isImageMime(mime)) return undefined;\n try {\n return imageSize(new Uint8Array(await source.slice(0, IMAGE_LIMITS.headBytes).arrayBuffer()));\n } catch {\n return undefined;\n }\n}\n","import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { fromBase64Url, fromZ32, toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { canonicalJsonBytes, readCanonicalJson, type CanonicalJsonRefusal, type JsonValue } from \"./canonicalJson\";\nimport type { Signer } from \"./signer\";\nimport { hasVisible, stripHidden } from \"./text\";\n\n/*\n * Signed statements of WISP 1200 (Apps · Signatures): every signed object is signed the same way, Ed25519 over the\n * bytes `<prefix>`, a zero byte, then the SHA-256 of the object's canonical JSON (RFC 8785). The prefix says what the\n * object is, so no signature can be replayed as another kind. The signature travels as a statement of its own,\n * `{\"alg\":\"ed25519\",\"key\":\"<z-base32>\",\"sig\":\"<base64url>\"}`, itself canonical.\n *\n * A revocation (`ghostly-revoke/1`) is the publisher's: it names digests of its app, or every version up to a\n * `sequence`, and travels as `{\"statement\": {...}, \"signature\": {...}}` in `ghostly-revoke.json` and, verbatim, in a\n * store index's `revoked`.\n */\n\n/** The prefixes of phase 1. The others of the WISP (reports, reviews, licences, rotation, publisher proofs) come later. */\nexport const APP_PREFIXES = {\n app: \"ghostly-app/1\",\n store: \"ghostly-store/1\",\n revoke: \"ghostly-revoke/1\",\n} as const;\nexport type AppPrefix = typeof APP_PREFIXES[keyof typeof APP_PREFIXES];\n\nexport const APP_STATEMENT_LIMITS = {\n /** A signature statement's canonical bytes: 52 + 86 characters of values and the keys around them. */\n signatureBytes: 1024,\n /** Digests named by one revocation. */\n revokeDigests: 64,\n /** A revocation's reason, in characters. */\n reason: 200,\n /** Revocations in one `ghostly-revoke.json`. */\n revocations: 4096,\n} as const;\n\n/** A z-base32 Ed25519 public key: 52 characters that decode to 32 bytes and encode back to the same text. */\nexport function isAppKey(value: unknown): value is string {\n if (typeof value !== \"string\" || !/^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/.test(value)) return false;\n const bytes = fromZ32(value);\n return bytes.length === 32 && toZ32(bytes) === value;\n}\n\n/** A SHA-256 in base64url without padding: 43 characters that decode to 32 bytes and encode back to the same text. */\nexport function isAppHash(value: unknown): value is string {\n if (typeof value !== \"string\" || !/^[A-Za-z0-9_-]{43}$/.test(value)) return false;\n return toBase64Url(fromBase64Url(value)) === value;\n}\n\n/** An app reference, `<publisher key>/<name>`. */\nexport const APP_NAME = /^[a-z][a-z0-9-]{0,31}$/;\nexport function isAppRef(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n const slash = value.indexOf(\"/\");\n return slash === 52 && isAppKey(value.slice(0, 52)) && APP_NAME.test(value.slice(53));\n}\nexport function appRef(publisher: string, name: string): string {\n return `${publisher}/${name}`;\n}\n/** The publisher key of a reference. */\nexport function appRefPublisher(ref: string): string {\n return ref.slice(0, 52);\n}\n\n/**\n * The publisher fingerprint people see: the first 16 z-base32 characters of the key (80 bits), in four groups.\n */\nexport function appFingerprint(key: string): string {\n return (key.slice(0, 16).match(/.{1,4}/g) ?? []).join(\" \");\n}\n\n/** The bytes a signature covers: the prefix, a zero byte, then the SHA-256 of the object's canonical bytes. */\nexport function appSignedBytes(prefix: AppPrefix, canonical: Uint8Array): Uint8Array {\n const p = utf8Encode(prefix);\n const out = new Uint8Array(p.length + 1 + 32);\n out.set(p, 0);\n out.set(sha256(canonical), p.length + 1);\n return out;\n}\n\nexport interface AppSignature { alg: \"ed25519\"; key: string; sig: string }\n\n/** Signs an object under a prefix: its canonical bytes and the signature statement. */\nexport async function signAppObject(prefix: AppPrefix, value: unknown, signer: Signer): Promise<{ bytes: Uint8Array; signature: AppSignature }> {\n const bytes = canonicalJsonBytes(value);\n const sig = await signer.sign(appSignedBytes(prefix, bytes));\n return { bytes, signature: { alg: \"ed25519\", key: toZ32(signer.publicKey), sig: toBase64Url(sig) } };\n}\n\n/**\n * A faster Ed25519 check a host may give (the CLI gives node:crypto's): RFC 8032's verification without the cofactor,\n * which compares the signature's R with the encoding of the [S]B - [k]A it computes, as OpenSSL's does. It is asked only\n * when the key is the canonical encoding of a point not of small order and S is below the group order, and only its yes\n * counts: R is then the canonical encoding of that point, so the strict check below says yes too. Its no, or a throw,\n * leaves the answer to the strict check, so what verifies is exactly what verifies without it.\n */\nexport type AppSignatureFastPath = (signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array) => boolean;\n\nlet fastPath: AppSignatureFastPath | null = null;\n\n/** Gives (or, with `null`, takes back) the faster check of every app signature this process verifies. */\nexport function setAppSignatureFastPath(check: AppSignatureFastPath | null): void {\n fastPath = check;\n}\n\n/** The group order L, little-endian: an S at or above it is refused by the strict check. */\nconst GROUP_ORDER = Uint8Array.from([\n 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10,\n]);\n/** Whether each key seen lately is a canonical encoding of a point not of small order: a list repeats its publishers. */\nconst keysFit = new Map<string, boolean>();\n\nfunction fastPathTakes(signature: Uint8Array, publicKey: Uint8Array): boolean {\n if (signature.length !== 64 || publicKey.length !== 32) return false;\n let below = false;\n for (let i = 31; i >= 0; i--) {\n if (signature[32 + i] !== GROUP_ORDER[i]) { below = signature[32 + i] < GROUP_ORDER[i]; break; }\n }\n if (!below) return false;\n const id = toBase64Url(publicKey);\n let fit = keysFit.get(id);\n if (fit === undefined) {\n try { fit = !ed25519.Point.fromBytes(publicKey, false).isSmallOrder(); } catch { fit = false; }\n if (keysFit.size >= 256) keysFit.clear();\n keysFit.set(id, fit);\n }\n return fit;\n}\n\n/**\n * Ed25519 verification as RFC 8032 writes it (`zip215: false`): canonical encodings of the point and the scalar only,\n * so every parser (this one, a Rust one with `verify_strict`) accepts exactly the same signatures.\n */\nfunction strictVerify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n if (fastPath && fastPathTakes(signature, publicKey)) {\n try { if (fastPath(signature, message, publicKey)) return true; } catch { /* the strict check answers */ }\n }\n try {\n return ed25519.verify(signature, message, publicKey, { zip215: false });\n } catch {\n return false;\n }\n}\n\nexport type AppSignatureRefusal = \"bad-signature-statement\" | \"signature-key\" | \"bad-signature\";\n\nconst exactKeys = (value: unknown, keys: readonly string[], optional: readonly string[] = []): value is Record<string, JsonValue> => {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const have = Object.keys(value);\n return keys.every((k) => have.includes(k)) && have.every((k) => keys.includes(k) || optional.includes(k));\n};\n\n/** Checks the shape of a signature statement: exactly `alg`, `key` and `sig`, a 64-byte signature. */\nexport function isAppSignature(value: unknown): value is AppSignature {\n if (!exactKeys(value, [\"alg\", \"key\", \"sig\"])) return false;\n if (value.alg !== \"ed25519\" || !isAppKey(value.key)) return false;\n return typeof value.sig === \"string\" && /^[A-Za-z0-9_-]{86}$/.test(value.sig) && toBase64Url(fromBase64Url(value.sig)) === value.sig;\n}\n\n/** Reads a signature statement from its bytes, which must be canonical. */\nexport function readAppSignature(bytes: Uint8Array): { ok: true; signature: AppSignature } | { ok: false; reason: \"bad-signature-statement\"; detail?: string } {\n if (bytes.length > APP_STATEMENT_LIMITS.signatureBytes) return { ok: false, reason: \"bad-signature-statement\", detail: \"Too large\" };\n const read = readCanonicalJson(bytes);\n if (!read.ok) return { ok: false, reason: \"bad-signature-statement\", detail: read.reason };\n if (!isAppSignature(read.value)) return { ok: false, reason: \"bad-signature-statement\", detail: \"Not {alg, key, sig}\" };\n return { ok: true, signature: read.value };\n}\n\n/**\n * Verifies a signature over an object's canonical bytes under a prefix, made by `key`: `signature-key` when the\n * statement names another key, `bad-signature` when it does not verify.\n */\nexport function verifyAppSignature(prefix: AppPrefix, canonical: Uint8Array, signature: AppSignature, key: string): { ok: true } | { ok: false; reason: AppSignatureRefusal } {\n if (!isAppSignature(signature)) return { ok: false, reason: \"bad-signature-statement\" };\n if (signature.key !== key) return { ok: false, reason: \"signature-key\" };\n return strictVerify(fromBase64Url(signature.sig), appSignedBytes(prefix, canonical), fromZ32(key)) ? { ok: true } : { ok: false, reason: \"bad-signature\" };\n}\n\n/** Verifies a signed object given as bytes: they must be canonical, then the signature as above. */\nexport function verifyAppStatementBytes(prefix: AppPrefix, bytes: Uint8Array, signature: AppSignature, key: string): { ok: true; value: JsonValue } | { ok: false; reason: CanonicalJsonRefusal | AppSignatureRefusal } {\n const read = readCanonicalJson(bytes);\n if (!read.ok) return read;\n const checked = verifyAppSignature(prefix, bytes, signature, key);\n return checked.ok ? { ok: true, value: read.value } : checked;\n}\n\n// ---------- revocations ----------\n\n/** A publisher's revocation: the listed digests of its app, or every version up to `upTo` (inclusive). */\nexport type AppRevokeStatement =\n | { ghostlyRevoke: 1; app: string; digests: string[]; reason?: string }\n | { ghostlyRevoke: 1; app: string; upTo: number; reason?: string };\nexport interface SignedAppRevocation { statement: AppRevokeStatement; signature: AppSignature }\n\nexport type AppRevocationRefusal = \"bad-revocation\" | AppSignatureRefusal;\n\nconst isSequence = (v: unknown): v is number => typeof v === \"number\" && Number.isSafeInteger(v) && v >= 1;\n\n/**\n * One line of an app's text, from `min` to `max` code points: a title, a tagline, a store's name, a removal's or a\n * revocation's reason. It is shown alone (a heading, a window title), so it holds no control character and none of\n * what `stripHidden` takes from a nickname (invisible and direction-changing characters, line and paragraph\n * separators), and when it is not empty it shows something (`hasVisible`). The joiners an emoji or a script needs stay.\n */\nexport const isAppLine = (v: unknown, max: number, min = 0): v is string => {\n if (typeof v !== \"string\") return false;\n const length = [...v].length;\n return length >= min && length <= max && stripHidden(v) === v && (v === \"\" || hasVisible(v));\n};\n\n/** Checks a revocation statement's shape; the reason it is refused, or null. */\nexport function checkAppRevokeStatement(value: unknown): string | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return \"Not an object\";\n const v = value as Record<string, unknown>;\n const byDigests = \"digests\" in v;\n if (!exactKeys(v, [\"ghostlyRevoke\", \"app\", byDigests ? \"digests\" : \"upTo\"], [\"reason\"])) return \"Keys are not ghostlyRevoke, app, and exactly one of digests and upTo (reason optional)\";\n if (v.ghostlyRevoke !== 1) return \"ghostlyRevoke is not 1\";\n if (!isAppRef(v.app)) return \"app is not a reference\";\n if (byDigests) {\n const d = v.digests;\n if (!Array.isArray(d) || d.length < 1 || d.length > APP_STATEMENT_LIMITS.revokeDigests) return \"digests is not 1 to 64 digests\";\n if (!d.every(isAppHash) || new Set(d).size !== d.length) return \"digests holds a bad or repeated digest\";\n } else if (!isSequence(v.upTo)) return \"upTo is not a sequence\";\n if (v.reason !== undefined && !isAppLine(v.reason, APP_STATEMENT_LIMITS.reason)) return \"reason is not one line of 200 characters\";\n return null;\n}\n\n/** Signs a revocation with the publisher's key. */\nexport async function signAppRevocation(statement: AppRevokeStatement, signer: Signer): Promise<SignedAppRevocation> {\n const problem = checkAppRevokeStatement(statement);\n if (problem) throw new Error(`Not a revocation: ${problem}`);\n if (toZ32(signer.publicKey) !== appRefPublisher(statement.app)) throw new Error(\"A revocation is signed by its app's publisher\");\n const { signature } = await signAppObject(APP_PREFIXES.revoke, statement, signer);\n return { statement, signature };\n}\n\n/**\n * The revocations a reader has already checked, by `appRevocationId`: a store index copies its `revoked` again in every\n * version, so a reader that holds this checks each revocation's signature once. The reader bounds what it holds.\n */\nexport interface AppRevocationsChecked { has(id: string): boolean; add(id: string): void }\n\n/** What a checked revocation is kept by: the SHA-256 of its canonical bytes (statement and signature), base64url. */\nexport function appRevocationId(revocation: SignedAppRevocation): string {\n return toBase64Url(sha256(canonicalJsonBytes(revocation as unknown as JsonValue)));\n}\n\ntype AppRevocationRead = { ok: true; revocation: SignedAppRevocation } | { ok: false; reason: AppRevocationRefusal; detail?: string };\n\n/**\n * Reads one signed revocation (a parsed value, from `ghostly-revoke.json` or a store index's `revoked`): its shape, then\n * the signature under `ghostly-revoke/1` by the publisher its `app` names. One that `checked` holds verified before, so\n * its signature is not checked again; one that verifies now is added to it.\n */\nexport function readAppRevocation(value: unknown, checked?: AppRevocationsChecked): AppRevocationRead {\n const read = readAppRevocationShape(value);\n if (!read.ok) return read;\n const verified = verifyAppRevocation(read.revocation, checked);\n return verified.ok ? read : verified;\n}\n\n/** The first half of `readAppRevocation`: the shape of a signed revocation, with no signature checked. */\nexport function readAppRevocationShape(value: unknown): AppRevocationRead {\n if (!exactKeys(value, [\"statement\", \"signature\"])) return { ok: false, reason: \"bad-revocation\", detail: \"Keys are not statement and signature\" };\n const problem = checkAppRevokeStatement(value.statement);\n if (problem) return { ok: false, reason: \"bad-revocation\", detail: problem };\n if (!isAppSignature(value.signature)) return { ok: false, reason: \"bad-signature-statement\" };\n return { ok: true, revocation: { statement: value.statement as unknown as AppRevokeStatement, signature: value.signature } };\n}\n\n/** The second half: the signature of a revocation of the right shape, unless `checked` holds it. */\nexport function verifyAppRevocation(revocation: SignedAppRevocation, checked?: AppRevocationsChecked): { ok: true } | { ok: false; reason: AppSignatureRefusal } {\n const id = checked && appRevocationId(revocation);\n if (id !== undefined && checked!.has(id)) return { ok: true };\n const verified = verifyAppSignature(APP_PREFIXES.revoke, canonicalJsonBytes(revocation.statement as unknown as JsonValue), revocation.signature, appRefPublisher(revocation.statement.app));\n if (verified.ok && id !== undefined) checked!.add(id);\n return verified;\n}\n\n/**\n * Reads `ghostly-revoke.json`: canonical bytes holding a list of signed revocations. One that does not verify refuses the\n * file, as a store index's `revoked` does. With `checked`, a revocation it holds is not checked again.\n */\nexport function readAppRevocations(bytes: Uint8Array, checked?: AppRevocationsChecked): { ok: true; revocations: SignedAppRevocation[] } | { ok: false; reason: CanonicalJsonRefusal | AppRevocationRefusal; detail?: string } {\n const read = readCanonicalJson(bytes);\n if (!read.ok) return read;\n if (!Array.isArray(read.value) || read.value.length > APP_STATEMENT_LIMITS.revocations) return { ok: false, reason: \"bad-revocation\", detail: \"Not a list of at most 4096 revocations\" };\n const revocations: SignedAppRevocation[] = [];\n for (const entry of read.value) {\n const one = readAppRevocation(entry, checked);\n if (!one.ok) return one;\n revocations.push(one.revocation);\n }\n return { ok: true, revocations };\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { canonicalJsonBytes, readCanonicalJson, type JsonValue } from \"./canonicalJson\";\nimport { imageSize } from \"./image\";\nimport {\n APP_NAME, APP_PREFIXES, isAppHash, isAppKey, isAppLine, readAppSignature, signAppObject, verifyAppSignature, type AppSignature,\n} from \"./appStatements\";\nimport type { Signer } from \"./signer\";\n\n/*\n * The app bundle (WISP 1200 · The package): one `.ghostlyapp` file is one version of one app.\n *\n * \"GHOSTLYAPP1\" | u32 manifest length | manifest | u32 statement length | signature statement | file bytes...\n *\n * Lengths are 32-bit big-endian. The manifest is canonical JSON (RFC 8785); the statement is the publisher's\n * `ghostly-app/1` signature over it; the files follow in the order of the manifest's `files`, delimited by their sizes,\n * and nothing follows the last one. The digest, SHA-256 of the manifest's bytes, names every byte of the version.\n *\n * `readAppBundle` is the whole client check, in a fixed order so that every parser refuses a broken bundle with the same\n * reason: size, magic, the two lengths, the manifest (JSON, canonical, every field and bound), the statement, the\n * bundle's length against the files' sizes, the signature, every file's hash, then the icon. A client runs it before it\n * stores a bundle and again before it runs one.\n */\n\nexport const APP_BUNDLE_MAGIC = \"GHOSTLYAPP1\";\nconst MAGIC = utf8Encode(APP_BUNDLE_MAGIC);\n\nexport const APP_BUNDLE_LIMITS = {\n /** The whole bundle, phase 1. */\n bundleBytes: 16 * 1024 * 1024,\n files: 64,\n manifestBytes: 64 * 1024,\n /** A path, in bytes (paths are ASCII). */\n pathBytes: 128,\n iconBytes: 256 * 1024,\n /** The icon's width and height, in pixels: a client decodes it whole to draw it, whatever its bytes. */\n iconEdge: 1024,\n screenshots: 8,\n /** Lengths in Unicode code points. */\n title: 40,\n tagline: 80,\n description: 2000,\n releaseNotes: 500,\n version: 64,\n license: 128,\n /** An https URL, in characters. */\n url: 512,\n sources: 8,\n} as const;\n\nexport const APP_ICON_PATH = \"icon.png\";\nexport const APP_SCREENSHOTS_DIR = \"screenshots/\";\nconst SCREENSHOT_TYPES = /\\.(png|jpg|webp)$/;\n\n/**\n * The permissions an app may ask (WISP 1200 · Permissions). `internet`: the app reaches HTTPS and WSS servers of its\n * choosing (the client runs it in its network runner); without it, an app has no network. `files`: the app reads files\n * and folders the person picks, linked by the client rather than copied (WISP 1200 · Linked files).\n */\nexport const APP_PERMISSIONS = [\"chat\", \"files\", \"internet\", \"name\"] as const;\nexport type AppPermission = typeof APP_PERMISSIONS[number];\n/**\n * The clients a writer may name in `runtime.clients` (WISP 1200 · Manifest). A reader also accepts a client name it does\n * not know (`APP_CLIENT_NAME`), since `runtime` is advisory and a later client (Android, say) must not make every older\n * reader refuse the bundle.\n */\nexport const APP_CLIENTS = [\"web\", \"desktop\", \"extension\"] as const;\n/** A client name a reader accepts in `runtime.clients`, a later client's included. */\nexport const APP_CLIENT_NAME = /^[a-z][a-z0-9-]{0,31}$/;\n/**\n * Where an app shows (WISP 1200 · Manifest, `view`). `chat`, the default when the manifest has none: inside a 1:1 chat\n * only, beside it on a wide screen. `full`: full screen, alone or from a chat, never beside one.\n */\nexport const APP_VIEWS = [\"chat\", \"full\"] as const;\nexport type AppViewMode = typeof APP_VIEWS[number];\n/** The view of a manifest: `chat` when it names none. */\nexport const appViewOf = (manifest: { view?: AppViewMode }): AppViewMode => manifest.view ?? \"chat\";\nexport type AppClient = typeof APP_CLIENTS[number];\n\nexport interface AppFileEntry { path: string; size: number; sha256: string }\nexport interface AppManifest {\n ghostlyApp: 1;\n publisher: string;\n name: string;\n version: string;\n sequence: number;\n kind: \"mini-app\";\n title: string;\n tagline: string;\n description?: string;\n entry: string;\n permissions: AppPermission[];\n /** Absent: `chat` (`appViewOf`). */\n view?: AppViewMode;\n /** Advisory: a writer names only `APP_CLIENTS`; a reader may hold a later client's name. */\n runtime: { host: string; clients: string[] };\n license: string;\n sources?: string[];\n proofs?: never[];\n homepage?: string;\n support?: string;\n releaseNotes?: string;\n files: AppFileEntry[];\n}\n\nconst REQUIRED = [\"ghostlyApp\", \"publisher\", \"name\", \"version\", \"sequence\", \"kind\", \"title\", \"tagline\", \"entry\", \"permissions\", \"runtime\", \"license\", \"files\"] as const;\nconst OPTIONAL = [\"description\", \"view\", \"sources\", \"proofs\", \"homepage\", \"support\", \"releaseNotes\"] as const;\n/**\n * Reserved for phase 2 and refused in phase 1, by a reader too: an app that names a price or a recovery key asks for\n * something this client cannot honour, so it is not one to ignore.\n */\nconst RESERVED = [\"price\", \"recovery\"] as const;\n/**\n * How `checkAppManifest` treats a key it does not know. A reader (`readAppBundle`, the client) ignores it, at the top of\n * the manifest and in `runtime`, so a later publisher can add an optional key without every older client refusing the\n * app; the publisher's signature and the digest still cover the manifest's bytes as they are. A writer\n * (`buildAppBundle`, the CLI) passes `strict` and refuses it, so a misspelt key is caught before anything is signed.\n * Required keys, their types and bounds, `price` and `recovery`, and a file's exact `{path, size, sha256}` (which lay\n * out the bundle's bytes) hold in both.\n */\nexport interface AppManifestOptions { strict?: boolean }\n/**\n * Keys refused in every mode and at any level, wherever a reader ignores unknown keys: kept and passed on, they would\n * name an object's prototype the moment anything spreads or assigns a manifest or a listing.\n */\nexport const APP_FORBIDDEN_KEYS: readonly string[] = [\"__proto__\", \"constructor\", \"prototype\"];\n\n/**\n * The path of an `APP_FORBIDDEN_KEYS` key anywhere in a parsed JSON value (`later.0.__proto__`), the values of ignored\n * keys included, or undefined: WISP 1200 refuses them at any level. `JSON.parse` makes `__proto__` an own key, so\n * `Object.keys` sees it. A stack, not recursion: a `listing.json` is read with `JSON.parse` alone, at any depth.\n */\nexport function findAppForbiddenKey(value: unknown): string | undefined {\n const stack: [unknown, string][] = [[value, \"\"]];\n for (let next = stack.pop(); next; next = stack.pop()) {\n const [v, path] = next;\n if (typeof v !== \"object\" || v === null) continue;\n for (const key of Object.keys(v)) {\n const at = path ? `${path}.${key}` : key;\n if (APP_FORBIDDEN_KEYS.includes(key)) return at;\n stack.push([(v as Record<string, unknown>)[key], at]);\n }\n }\n return undefined;\n}\n/** At most this many clients in `runtime.clients`. */\nconst MAX_CLIENTS = 16;\n\nexport type AppBundleRefusal =\n | \"too-large\" | \"magic\" | \"truncated\" | \"trailing-bytes\" | \"manifest-too-large\"\n | \"not-json\" | \"not-canonical\" | \"unsupported-format\" | \"unknown-key\" | \"reserved-key\" | \"missing-key\" | \"bad-field\"\n | \"proofs-unsupported\" | \"too-many-files\" | \"bad-path\" | \"path-collision\" | \"files-unsorted\" | \"bad-entry\"\n | \"too-many-screenshots\" | \"bad-icon\"\n | \"bad-signature-statement\" | \"signature-key\" | \"bad-signature\" | \"file-hash\";\n\nexport type AppManifestCheck = { ok: true; manifest: AppManifest } | { ok: false; reason: AppBundleRefusal; detail?: string };\n\nconst SEMVER = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\nconst HOST = /^>=(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(\\.(0|[1-9]\\d*))?$/;\nconst SEGMENT = /^[A-Za-z0-9._-]+$/;\n\nconst codePoints = (s: string) => [...s].length;\n/** Text of several lines: no control character but the line feed. */\nconst isText = (v: unknown, max: number): v is string => typeof v === \"string\" && codePoints(v) <= max && !/[^\\P{Cc}\\n]/u.test(v);\nconst isSafeCount = (v: unknown, min: number): v is number => typeof v === \"number\" && Number.isSafeInteger(v) && v >= min;\nconst isObject = (v: unknown): v is Record<string, JsonValue> => typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/**\n * An https URL as WISP 1200 takes one anywhere: at most 512 characters, no user or password, and on jsDelivr only\n * `https://cdn.jsdelivr.net/gh/<owner>/<repo>@<40-hex commit>/...`, since a branch, a tag, a range or `latest` is\n * served from a copy that moves.\n */\nexport function isAppUrl(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > APP_BUNDLE_LIMITS.url || !value.startsWith(\"https://\")) return false;\n let url: URL;\n try { url = new URL(value); } catch { return false; }\n if (url.protocol !== \"https:\" || url.username || url.password || !url.hostname) return false;\n // A fully qualified `cdn.jsdelivr.net.` is the same host: drop the trailing dots before the jsDelivr test.\n const host = url.hostname.toLowerCase().replace(/\\.+$/, \"\");\n if (host === \"jsdelivr.net\" || host.endsWith(\".jsdelivr.net\")) {\n return host === \"cdn.jsdelivr.net\" && /^\\/gh\\/[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+@[0-9a-f]{40}\\/./.test(url.pathname);\n }\n return true;\n}\n\n/**\n * An SPDX license expression, read lightly: identifiers (`MIT`, `GPL-3.0-or-later`, `LicenseRef-x`, `Apache-2.0+`)\n * joined by `AND` and `OR`, `WITH` an exception, and parentheses; or `proprietary`.\n */\nexport function isAppLicense(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length < 1 || value.length > APP_BUNDLE_LIMITS.license) return false;\n const tokens = value.match(/\\(|\\)|[^\\s()]+/g);\n if (!tokens || tokens.join(\"\").length !== value.replace(/\\s/g, \"\").length) return false;\n let i = 0;\n const id = () => { const t = tokens[i]; if (t && /^[A-Za-z0-9][A-Za-z0-9.-]*\\+?$/.test(t) && ![\"AND\", \"OR\", \"WITH\"].includes(t)) { i++; return true; } return false; };\n const term = (depth: number): boolean => {\n if (tokens[i] === \"(\") { i++; if (depth > 8 || !expr(depth + 1) || tokens[i] !== \")\") return false; i++; return true; }\n if (!id()) return false;\n if (tokens[i] === \"WITH\") { i++; return id(); }\n return true;\n };\n const expr = (depth: number): boolean => {\n if (!term(depth)) return false;\n while (tokens[i] === \"AND\" || tokens[i] === \"OR\") { i++; if (!term(depth)) return false; }\n return true;\n };\n return expr(0) && i === tokens.length;\n}\n\n/** A path of a bundle: relative, `/`-separated, `[A-Za-z0-9._-]` per segment, no `.` or `..`, at most 128 bytes. */\nexport function isAppPath(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length < 1 || value.length > APP_BUNDLE_LIMITS.pathBytes) return false;\n return value.split(\"/\").every((s) => SEGMENT.test(s) && s !== \".\" && s !== \"..\");\n}\n\nconst bad = (field: string, detail = `${field} is not valid`): AppManifestCheck => ({ ok: false, reason: \"bad-field\", detail });\n\n/**\n * Checks a parsed manifest against every rule and bound of WISP 1200 that the manifest alone decides. An unknown key is\n * ignored unless `strict` (`AppManifestOptions`).\n */\nexport function checkAppManifest(value: unknown, options: AppManifestOptions = {}): AppManifestCheck {\n if (!isObject(value)) return bad(\"manifest\", \"The manifest is not an object\");\n if (value.ghostlyApp !== undefined && value.ghostlyApp !== 1) return { ok: false, reason: \"unsupported-format\", detail: \"ghostlyApp is not 1\" };\n const forbidden = findAppForbiddenKey(value);\n if (forbidden !== undefined) return { ok: false, reason: \"unknown-key\", detail: forbidden };\n for (const key of Object.keys(value)) {\n if ((RESERVED as readonly string[]).includes(key)) return { ok: false, reason: \"reserved-key\", detail: key };\n if (options.strict && !(REQUIRED as readonly string[]).includes(key) && !(OPTIONAL as readonly string[]).includes(key)) return { ok: false, reason: \"unknown-key\", detail: key };\n }\n for (const key of REQUIRED) if (!(key in value)) return { ok: false, reason: \"missing-key\", detail: key };\n const m = value;\n if (!isAppKey(m.publisher)) return bad(\"publisher\");\n if (typeof m.name !== \"string\" || !APP_NAME.test(m.name)) return bad(\"name\");\n if (typeof m.version !== \"string\" || m.version.length > APP_BUNDLE_LIMITS.version || !SEMVER.test(m.version)) return bad(\"version\");\n if (!isSafeCount(m.sequence, 1)) return bad(\"sequence\");\n if (m.kind !== \"mini-app\") return bad(\"kind\");\n if (!isAppLine(m.title, APP_BUNDLE_LIMITS.title, 1)) return bad(\"title\");\n if (!isAppLine(m.tagline, APP_BUNDLE_LIMITS.tagline, 1)) return bad(\"tagline\");\n if (m.description !== undefined && !isText(m.description, APP_BUNDLE_LIMITS.description)) return bad(\"description\");\n if (m.releaseNotes !== undefined && !isAppLine(m.releaseNotes, APP_BUNDLE_LIMITS.releaseNotes)) return bad(\"releaseNotes\");\n const permissions = m.permissions;\n if (!Array.isArray(permissions) || new Set(permissions).size !== permissions.length\n || !permissions.every((p) => (APP_PERMISSIONS as readonly unknown[]).includes(p))) return bad(\"permissions\");\n if (m.view !== undefined && !(APP_VIEWS as readonly unknown[]).includes(m.view)) return bad(\"view\", `view is \"chat\" or \"full\"`);\n const runtime = m.runtime;\n if (!isObject(runtime)) return bad(\"runtime\");\n for (const key of Object.keys(runtime)) {\n if (key === \"host\" || key === \"clients\") continue;\n if (options.strict) return { ok: false, reason: \"unknown-key\", detail: `runtime.${key}` };\n }\n if (typeof runtime.host !== \"string\" || !HOST.test(runtime.host)) return bad(\"runtime\");\n // Advisory (WISP 1200 · Manifest): a writer names only the clients it knows, a reader accepts a later client's name.\n const clients = runtime.clients;\n if (!Array.isArray(clients) || clients.length < 1 || clients.length > MAX_CLIENTS || new Set(clients).size !== clients.length\n || !clients.every((c) => options.strict ? (APP_CLIENTS as readonly unknown[]).includes(c) : typeof c === \"string\" && APP_CLIENT_NAME.test(c))) return bad(\"runtime\");\n if (!isAppLicense(m.license)) return bad(\"license\");\n if (m.sources !== undefined && (!Array.isArray(m.sources) || m.sources.length > APP_BUNDLE_LIMITS.sources || !m.sources.every(isAppUrl))) return bad(\"sources\");\n if (m.homepage !== undefined && !isAppUrl(m.homepage)) return bad(\"homepage\");\n if (m.support !== undefined && !isAppUrl(m.support)) return bad(\"support\");\n if (m.proofs !== undefined) {\n if (!Array.isArray(m.proofs)) return bad(\"proofs\");\n if (m.proofs.length > 0) return { ok: false, reason: \"proofs-unsupported\", detail: \"Publisher proofs come after phase 1\" };\n }\n\n const files = m.files;\n if (!Array.isArray(files)) return bad(\"files\");\n if (files.length > APP_BUNDLE_LIMITS.files) return { ok: false, reason: \"too-many-files\", detail: `${files.length} files` };\n const lower = new Set<string>();\n let previous = \"\";\n let screenshots = 0;\n for (const f of files) {\n if (!isObject(f) || Object.keys(f).length !== 3 || !isAppPath(f.path) || !isSafeCount(f.size, 0) || !isAppHash(f.sha256)) {\n return isObject(f) && typeof f.path === \"string\" && !isAppPath(f.path) ? { ok: false, reason: \"bad-path\", detail: f.path } : bad(\"files\", \"A file is not {path, size, sha256}\");\n }\n if (lower.has(f.path.toLowerCase())) return { ok: false, reason: \"path-collision\", detail: f.path };\n lower.add(f.path.toLowerCase());\n if (f.path <= previous) return { ok: false, reason: \"files-unsorted\", detail: f.path };\n previous = f.path;\n if (f.size > APP_BUNDLE_LIMITS.bundleBytes) return bad(\"files\", `${f.path} is larger than a bundle`);\n if (f.path.startsWith(APP_SCREENSHOTS_DIR)) {\n if (!SCREENSHOT_TYPES.test(f.path)) return { ok: false, reason: \"bad-path\", detail: `${f.path}: a screenshot is .png, .jpg or .webp` };\n if (++screenshots > APP_BUNDLE_LIMITS.screenshots) return { ok: false, reason: \"too-many-screenshots\" };\n }\n if (f.path === APP_ICON_PATH && f.size > APP_BUNDLE_LIMITS.iconBytes) return { ok: false, reason: \"bad-icon\", detail: \"icon.png is larger than 256 KiB\" };\n }\n const entry = m.entry;\n if (typeof entry !== \"string\" || !entry.endsWith(\".html\") || !files.some((f) => isObject(f) && f.path === entry)) {\n return { ok: false, reason: \"bad-entry\", detail: \"The entry is not an .html file of the bundle\" };\n }\n return { ok: true, manifest: m as unknown as AppManifest };\n}\n\n/** The digest of a version: SHA-256 of its canonical manifest bytes, base64url. */\nexport function appDigest(manifestBytes: Uint8Array): string {\n return toBase64Url(sha256(manifestBytes));\n}\n\nexport interface AppBundle {\n manifest: AppManifest;\n /** The manifest's canonical bytes, as in the bundle. */\n manifestBytes: Uint8Array;\n digest: string;\n signature: AppSignature;\n /** Every file's bytes, by path, in the manifest's order (views into the bundle's bytes). */\n files: Map<string, Uint8Array>;\n}\nexport type AppBundleReading = { ok: true; bundle: AppBundle } | { ok: false; reason: AppBundleRefusal; detail?: string };\n\nconst u32 = (b: Uint8Array, at: number) => ((b[at]! << 24) >>> 0) + (b[at + 1]! << 16) + (b[at + 2]! << 8) + b[at + 3]!;\n\n/**\n * Lets the thread go for one turn: what waits (input, drawing, timers, port messages, IndexedDB answers) runs, then the\n * caller goes on. A message to itself, queued behind the page's other tasks. Never `scheduler.yield()`: in Chromium its\n * continuation outranks every normal task, so a paced read of 4096 revocations held the page's timers, its apps' broker\n * ports and IndexedDB for the whole 1.8 s. Never `setTimeout(0)` but as the last resort: from the fifth nested timer on\n * the browser waits at least 4 ms (HTML's clamp), which made that read take 60% longer than the work, and a hidden tab\n * runs timers once a second.\n */\nexport function yieldThread(): Promise<void> {\n if (typeof MessageChannel === \"function\") {\n return new Promise((resolve) => {\n const channel = new MessageChannel();\n channel.port1.onmessage = () => {\n channel.port1.close();\n resolve();\n };\n channel.port2.postMessage(null);\n });\n }\n return new Promise((resolve) => setTimeout(resolve, 0));\n}\n\n/**\n * A pause for a loop of short steps: `await pause()` after each step lets the thread go once `sliceMs` of work has\n * run since the last time, and answers at once otherwise.\n */\nexport function pacer(sliceMs: number): () => Promise<void> | undefined {\n let since = performance.now();\n return () => {\n if (performance.now() - since < sliceMs) return undefined;\n return yieldThread().then(() => {\n since = performance.now();\n });\n };\n}\n\n/** `sha256Paced` hashes up to this much at once: under a millisecond of the thread. */\nconst HASH_AT_ONCE = 64 * 1024;\n/** Without `crypto.subtle`, `sha256Paced` hashes this much (a few ms), then lets the thread go. */\nconst HASH_SLICE = 256 * 1024;\n/** `readAppBundleAsync` hashes files for this long at most before it lets the thread go, however small each file. */\nconst HASH_SLICE_MS = 5;\n\n/**\n * SHA-256 of bytes that may be a whole bundle, for a client whose engine shares its page's thread: `sha256` in\n * JavaScript takes about 12 ms per MiB on a desktop CPU, so 16 MiB in one run is a page that draws nothing and takes no\n * input for 200 ms. With `crypto.subtle` the bytes are hashed off the thread; without it (a page not served over\n * HTTPS), a slice at a time with a pause between slices. The bytes must not change until it answers.\n */\nexport async function sha256Paced(bytes: Uint8Array): Promise<Uint8Array> {\n if (bytes.length <= HASH_AT_ONCE) return sha256(bytes);\n const subtle = globalThis.crypto?.subtle as SubtleCrypto | undefined;\n const away = subtle ? await subtle.digest(\"SHA-256\", bytes as BufferSource).catch(() => null) : null;\n if (away) return new Uint8Array(away);\n const hash = sha256.create();\n for (let at = 0; at < bytes.length; at += HASH_SLICE) {\n if (at) await yieldThread();\n hash.update(bytes.subarray(at, at + HASH_SLICE));\n }\n return hash.digest();\n}\n\n/** A bundle read up to its files: everything `readAppBundle` checks before a file's hash, and where the files start. */\ninterface AppBundleHead { manifest: AppManifest; manifestBytes: Uint8Array; signature: AppSignature; filesAt: number }\n\nfunction readAppBundleHead(bytes: Uint8Array): { ok: true; head: AppBundleHead } | { ok: false; reason: AppBundleRefusal; detail?: string } {\n if (bytes.length > APP_BUNDLE_LIMITS.bundleBytes) return { ok: false, reason: \"too-large\" };\n const head = bytes.subarray(0, MAGIC.length);\n if (!head.every((b, i) => b === MAGIC[i])) return { ok: false, reason: \"magic\" };\n if (head.length < MAGIC.length) return { ok: false, reason: \"truncated\" };\n let at = MAGIC.length;\n if (bytes.length < at + 4) return { ok: false, reason: \"truncated\" };\n const manifestLength = u32(bytes, at); at += 4;\n if (manifestLength > APP_BUNDLE_LIMITS.manifestBytes) return { ok: false, reason: \"manifest-too-large\" };\n if (bytes.length < at + manifestLength + 4) return { ok: false, reason: \"truncated\" };\n const manifestBytes = bytes.subarray(at, at + manifestLength); at += manifestLength;\n const statementLength = u32(bytes, at); at += 4;\n if (bytes.length < at + statementLength) return { ok: false, reason: \"truncated\" };\n const statementBytes = bytes.subarray(at, at + statementLength); at += statementLength;\n\n const read = readCanonicalJson(manifestBytes);\n if (!read.ok) return read;\n const checked = checkAppManifest(read.value);\n if (!checked.ok) return checked;\n const manifest = checked.manifest;\n\n const statement = readAppSignature(statementBytes);\n if (!statement.ok) return statement;\n\n const total = manifest.files.reduce((sum, f) => sum + f.size, 0);\n const rest = bytes.length - at;\n if (total > rest) return { ok: false, reason: \"truncated\" };\n if (total < rest) return { ok: false, reason: \"trailing-bytes\", detail: `${rest - total} bytes past the last file` };\n\n const signed = verifyAppSignature(APP_PREFIXES.app, manifestBytes, statement.signature, manifest.publisher);\n if (!signed.ok) return signed;\n return { ok: true, head: { manifest, manifestBytes, signature: statement.signature, filesAt: at } };\n}\n\n/** The last check, once every file's hash held: the icon. */\nfunction closeAppBundle({ manifest, manifestBytes, signature }: AppBundleHead, files: Map<string, Uint8Array>): AppBundleReading {\n const icon = files.get(APP_ICON_PATH);\n if (icon) {\n const size = imageSize(icon);\n if (!size || icon[0] !== 0x89 || size.width !== size.height) return { ok: false, reason: \"bad-icon\", detail: \"icon.png is not a square PNG\" };\n if (size.width > APP_BUNDLE_LIMITS.iconEdge) return { ok: false, reason: \"bad-icon\", detail: \"icon.png is larger than 1024 × 1024 pixels\" };\n }\n return { ok: true, bundle: { manifest, manifestBytes, digest: appDigest(manifestBytes), signature, files } };\n}\n\n/** Reads and checks a bundle (the order of the checks is part of the format: see above). */\nexport function readAppBundle(bytes: Uint8Array): AppBundleReading {\n const read = readAppBundleHead(bytes);\n if (!read.ok) return read;\n const files = new Map<string, Uint8Array>();\n let at = read.head.filesAt;\n for (const f of read.head.manifest.files) {\n const content = bytes.subarray(at, at + f.size); at += f.size;\n if (toBase64Url(sha256(content)) !== f.sha256) return { ok: false, reason: \"file-hash\", detail: f.path };\n files.set(f.path, content);\n }\n return closeAppBundle(read.head, files);\n}\n\n/**\n * `readAppBundle` for a client whose engine shares its page's thread: the same checks in the same order, with the same\n * refusals, and each file hashed by `sha256Paced`, one after the other, with the thread let go between files every\n * `HASH_SLICE_MS` (64 files of 64 KiB, each hashed at once, held it for 50 ms). The bytes must not change until it\n * answers.\n */\nexport async function readAppBundleAsync(bytes: Uint8Array): Promise<AppBundleReading> {\n const read = readAppBundleHead(bytes);\n if (!read.ok) return read;\n const files = new Map<string, Uint8Array>();\n const pause = pacer(HASH_SLICE_MS);\n let at = read.head.filesAt;\n for (const f of read.head.manifest.files) {\n const content = bytes.subarray(at, at + f.size); at += f.size;\n if (toBase64Url(await sha256Paced(content)) !== f.sha256) return { ok: false, reason: \"file-hash\", detail: f.path };\n files.set(f.path, content);\n await pause();\n }\n return closeAppBundle(read.head, files);\n}\n\n/** Puts a bundle's parts together, checking nothing: for builders, and for tests that need a broken bundle. */\nexport function assembleAppBundle(manifestBytes: Uint8Array, statementBytes: Uint8Array, files: Uint8Array[]): Uint8Array {\n const total = MAGIC.length + 8 + manifestBytes.length + statementBytes.length + files.reduce((s, f) => s + f.length, 0);\n const out = new Uint8Array(total);\n const view = new DataView(out.buffer);\n let at = 0;\n out.set(MAGIC, at); at += MAGIC.length;\n view.setUint32(at, manifestBytes.length); at += 4;\n out.set(manifestBytes, at); at += manifestBytes.length;\n view.setUint32(at, statementBytes.length); at += 4;\n out.set(statementBytes, at); at += statementBytes.length;\n for (const f of files) { out.set(f, at); at += f.length; }\n return out;\n}\n\n/** What a publisher writes: every manifest field but `publisher` and `files`, which the bundle's contents decide. */\nexport type AppManifestDraft = Omit<AppManifest, \"publisher\" | \"files\" | \"ghostlyApp\"> & { ghostlyApp?: 1 };\n\n/**\n * Builds and signs a bundle: lists the files (sorted, with sizes and hashes), signs the canonical manifest with the\n * publisher's key under `ghostly-app/1`, and reads the result back, so it throws rather than return a bundle a client\n * would refuse.\n */\nexport async function buildAppBundle(draft: AppManifestDraft, files: { path: string; bytes: Uint8Array }[], signer: Signer): Promise<{ bytes: Uint8Array; digest: string; manifest: AppManifest }> {\n const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n const manifest = {\n ...draft,\n ghostlyApp: 1,\n publisher: toZ32(signer.publicKey),\n files: sorted.map((f) => ({ path: f.path, size: f.bytes.length, sha256: toBase64Url(sha256(f.bytes)) })),\n } as AppManifest;\n const checked = checkAppManifest(JSON.parse(JSON.stringify(manifest)), { strict: true });\n if (!checked.ok) throw new Error(`Not a valid manifest (${checked.reason}${checked.detail ? `: ${checked.detail}` : \"\"})`);\n const { bytes: manifestBytes, signature } = await signAppObject(APP_PREFIXES.app, manifest, signer);\n const bytes = assembleAppBundle(manifestBytes, canonicalJsonBytes(signature), sorted.map((f) => f.bytes));\n const read = readAppBundle(bytes);\n if (!read.ok) throw new Error(`Not a valid bundle (${read.reason}${read.detail ? `: ${read.detail}` : \"\"})`);\n return { bytes, digest: read.bundle.digest, manifest: read.bundle.manifest };\n}\n","import { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { ed25519, x25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { pacer } from \"./appBundle\";\nimport { concatBytes, fromBase64Url, randomBytes, toBase64Url, utf8Decode, utf8Encode } from \"./bytes\";\nimport { identityFromSeed, identityFromSeedB64, publicKeyFromZ32, type Identity } from \"./identity\";\nimport { readInviteCode } from \"./invite\";\nimport { measureRecords, type GhostRecord } from \"./pkarr\";\nimport { hasVisible, stripHidden } from \"./text\";\n\n/*\n * The three records of a contact link (WISP 8xx § Records): the owner's link record under the link key, the four knock\n * slots every holder of the link writes, and a request under the requester's own asker key, sealed to the link key.\n * Pure functions: who publishes, reads and when is the engine's.\n */\n\nexport const LINK_RECORD_LABEL = \"_cl\";\nexport const KNOCK_SLOT_LABEL = \"_knock\";\nexport const REQUEST_LABEL = \"_req\";\n/** Every record of a contact link carries this TTL: readers never read it. */\nexport const CONTACT_RECORD_TTL = 300;\nexport const KNOCK_SLOTS = 4;\nexport const MAX_SLOT_KNOCKS = 6;\nexport const MAX_SEEN = 32;\nexport const STAMP_BITS_DEFAULT = 18;\nexport const STAMP_BITS_MIN = 16;\nexport const STAMP_BITS_MAX = 24;\nexport const REQUEST_NAME_UNITS = 48;\nexport const REQUEST_TEXT_BYTES = 200;\nexport const REQUEST_LIFETIME_MS = 7 * 24 * 60 * 60_000;\n/** How far ahead of the owner's clock a request may be dated: two devices' clocks are often minutes apart. */\nexport const REQUEST_CLOCK_SKEW_MS = 10 * 60_000;\n/** A request's packet, as a WISP 403 envelope's: 8 bytes under the DHT's 1,000. */\nexport const REQUEST_PACKET_BYTES = 992;\nconst DAY_MS = 86_400_000;\nconst NONCE_LENGTH = 24;\nconst TAG_LENGTH = 16;\nconst Z32_KEY = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\nconst SEEN_ENTRY = /^[A-Za-z0-9_-]{12}$/;\n\nexport type LinkState = \"open\" | \"busy\" | \"off\";\n/** What the owner says under the link key: everyone with the link may read it. */\nexport interface LinkRecord {\n state: LinkState;\n bits: number;\n /** The `seen` entries of the requests taken, newest first. */\n seen: string[];\n}\n\n/** One knock: an asker key, the UTC day its stamp was made for, and the stamp. */\nexport interface ContactKnock {\n key: string;\n day: number;\n stamp: number;\n}\n\n/** What a request says. `invite` is the requester's own `ghostly1p…` code: accepting is joining it. */\nexport interface ContactRequest {\n invite: string;\n name: string;\n text: string;\n issued: number;\n expires: number;\n}\n\n/** Why a request cannot be sent as it is: the person changes something and tries again. */\nexport type ContactRequestProblem = \"name\" | \"text\" | \"invite\" | \"dates\" | \"too-long\";\n\nexport class ContactRequestError extends Error {\n constructor(readonly problem: ContactRequestProblem) {\n super(`The request cannot be sent: ${problem}`);\n this.name = \"ContactRequestError\";\n }\n}\n\nconst label = (text: string) => utf8Encode(text);\n\nfunction derive(linkKeyZ32: string, info: string): Uint8Array {\n return hkdf(sha256, publicKeyFromZ32(linkKeyZ32), label(\"ghostly-contact/1\"), label(info), 32);\n}\n\n/** The UTC day number of a time: a stamp is made for one. */\nexport function contactDay(ms: number): number {\n return Math.floor(ms / DAY_MS);\n}\n\n// --- The link record ------------------------------------------------------------------------------------------------\n\n/** The `seen` entry of an asker key on a link: the first 9 bytes of a hash, so the record names nobody. */\nexport function seenEntry(linkKeyZ32: string, askerZ32: string): string {\n return toBase64Url(sha256(concatBytes(label(\"ghostly-contact/1 seen\"), publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32))).slice(0, 9));\n}\n\nexport function linkRecords(record: LinkRecord): GhostRecord[] {\n if (!Number.isInteger(record.bits) || record.bits < STAMP_BITS_MIN || record.bits > STAMP_BITS_MAX) throw new Error(\"A link asks for 16 to 24 bits\");\n return [{ label: LINK_RECORD_LABEL, value: JSON.stringify([1, record.state, record.bits, record.seen.slice(0, MAX_SEEN)]), ttl: CONTACT_RECORD_TTL }];\n}\n\n/** The link record, or null for anything that is not one. Elements after the fourth are a later revision's: ignored. */\nexport function readLinkRecord(records: GhostRecord[]): LinkRecord | null {\n const value = records.find(r => r.label === LINK_RECORD_LABEL)?.value;\n if (!value || value.length > 900) return null;\n try {\n const parsed: unknown = JSON.parse(value);\n if (!Array.isArray(parsed) || parsed[0] !== 1) return null;\n const [, state, bits, seen] = parsed as unknown[];\n if (state !== \"open\" && state !== \"busy\" && state !== \"off\") return null;\n if (!Number.isInteger(bits) || (bits as number) < STAMP_BITS_MIN || (bits as number) > STAMP_BITS_MAX) return null;\n if (!Array.isArray(seen) || seen.length > MAX_SEEN || !seen.every(e => typeof e === \"string\" && SEEN_ENTRY.test(e))) return null;\n return { state, bits: bits as number, seen: seen as string[] };\n } catch { return null; }\n}\n\n// --- The stamp ------------------------------------------------------------------------------------------------------\n\nfunction stampPrefix(linkKeyZ32: string, askerZ32: string, day: number): Uint8Array {\n const tail = new Uint8Array(4);\n new DataView(tail.buffer).setUint32(0, day);\n return concatBytes(label(\"ghostly-contact/1 stamp\"), publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32), tail);\n}\n\nfunction leadingZeroBits(hash: Uint8Array): number {\n let bits = 0;\n for (const byte of hash) {\n if (byte === 0) { bits += 8; continue; }\n return bits + Math.clz32(byte) - 24;\n }\n return bits;\n}\n\nfunction stampBytes(stamp: number): Uint8Array {\n const bytes = new Uint8Array(4);\n new DataView(bytes.buffer).setUint32(0, stamp);\n return bytes;\n}\n\n/** Whether `stamp` has at least `bits` zero bits for this link, asker key and day. */\nexport function stampHolds(linkKeyZ32: string, askerZ32: string, day: number, stamp: number, bits: number): boolean {\n if (!Number.isInteger(stamp) || stamp < 0 || stamp > 0xffffffff || !Number.isInteger(day) || day < 0 || day > 0xffffffff) return false;\n return leadingZeroBits(sha256(concatBytes(stampPrefix(linkKeyZ32, askerZ32, day), stampBytes(stamp)))) >= bits;\n}\n\n/** The first stamp with `bits` zero bits: about 2^bits hashes, once per day and link. */\nexport function makeStamp(linkKeyZ32: string, askerZ32: string, day: number, bits: number): number {\n const base = sha256.create().update(stampPrefix(linkKeyZ32, askerZ32, day));\n for (let stamp = 0; stamp <= 0xffffffff; stamp++) {\n if (leadingZeroBits(base.clone().update(stampBytes(stamp)).digest()) >= bits) return stamp;\n }\n throw new Error(\"No stamp\");\n}\n\n/** `makeStampPaced` hashes for this long at most before it lets the thread go. */\nconst STAMP_SLICE_MS = 8;\n/** It looks at the clock once every this many hashes: a fraction of a millisecond. */\nconst STAMP_HASHES_AT_ONCE = 1024;\n\n/**\n * `makeStamp` on a thread with other work, as the engine's is the page's on the web and Desktop: 2^24 hashes take from\n * seconds to minutes, so it hashes in slices and lets the thread go between them. The same stamp, a little later.\n */\nexport async function makeStampPaced(linkKeyZ32: string, askerZ32: string, day: number, bits: number): Promise<number> {\n const base = sha256.create().update(stampPrefix(linkKeyZ32, askerZ32, day));\n const pause = pacer(STAMP_SLICE_MS);\n for (let stamp = 0; stamp <= 0xffffffff; stamp++) {\n if (leadingZeroBits(base.clone().update(stampBytes(stamp)).digest()) >= bits) return stamp;\n if (stamp % STAMP_HASHES_AT_ONCE === STAMP_HASHES_AT_ONCE - 1) await pause();\n }\n throw new Error(\"No stamp\");\n}\n\n/** The owner's check of a knock: a stamp for today or yesterday by its clock, with the bits its link asks for now. */\nexport function knockHolds(linkKeyZ32: string, knock: ContactKnock, bits: number, now: number): boolean {\n const today = contactDay(now);\n return (knock.day === today || knock.day === today - 1) && stampHolds(linkKeyZ32, knock.key, knock.day, knock.stamp, bits);\n}\n\n// --- The knock slots ------------------------------------------------------------------------------------------------\n\n/** Slot `index`'s Pkarr identity: every holder of the link derives it. */\nexport function knockSlotIdentity(linkKeyZ32: string, index: number): Identity {\n if (!Number.isInteger(index) || index < 0 || index >= KNOCK_SLOTS) throw new Error(\"A link has four knock slots\");\n return identityFromSeed(derive(linkKeyZ32, `knock seed ${index}`));\n}\n\n/** The slot an asker key knocks in. */\nexport function knockSlotOf(linkKeyZ32: string, askerZ32: string): number {\n return sha256(concatBytes(publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32)))[0] % KNOCK_SLOTS;\n}\n\nexport function knockSlotRecords(linkKeyZ32: string, knocks: ContactKnock[]): GhostRecord[] {\n const nonce = randomBytes(NONCE_LENGTH);\n const body = label(JSON.stringify(knocks.slice(-MAX_SLOT_KNOCKS).map(k => [k.key, k.day, k.stamp])));\n const box = xchacha20poly1305(derive(linkKeyZ32, \"knock key\"), nonce, publicKeyFromZ32(linkKeyZ32)).encrypt(body);\n return [{ label: KNOCK_SLOT_LABEL, value: toBase64Url(concatBytes(nonce, box)), ttl: CONTACT_RECORD_TTL }];\n}\n\n/** The knocks of a slot that open with the link's key and are well formed; a malformed entry is skipped, not the slot. */\nexport function readKnockSlot(linkKeyZ32: string, records: GhostRecord[]): ContactKnock[] {\n const value = records.find(r => r.label === KNOCK_SLOT_LABEL)?.value;\n if (!value || value.length > 900) return [];\n try {\n const bytes = fromBase64Url(value);\n const body = xchacha20poly1305(derive(linkKeyZ32, \"knock key\"), bytes.slice(0, NONCE_LENGTH), publicKeyFromZ32(linkKeyZ32)).decrypt(bytes.slice(NONCE_LENGTH));\n const parsed: unknown = JSON.parse(utf8Decode(body));\n if (!Array.isArray(parsed)) return [];\n return parsed.slice(0, MAX_SLOT_KNOCKS).flatMap(entry => Array.isArray(entry) && typeof entry[0] === \"string\" && Z32_KEY.test(entry[0])\n && Number.isSafeInteger(entry[1]) && entry[1] >= 0 && Number.isInteger(entry[2]) && entry[2] >= 0 && entry[2] <= 0xffffffff\n ? [{ key: entry[0], day: entry[1] as number, stamp: entry[2] as number }] : []);\n } catch { return []; }\n}\n\n/** The knocks to write: others' made today or yesterday (at most five, the latest), and mine last. */\nexport function mergeContactKnocks(existing: ContactKnock[], mine: ContactKnock, now: number): ContactKnock[] {\n const today = contactDay(now);\n const fresh = existing.filter(k => k.key !== mine.key && k.day >= today - 1 && k.day <= today + 1);\n return [...fresh.slice(-(MAX_SLOT_KNOCKS - 1)), mine];\n}\n\n// --- The request ----------------------------------------------------------------------------------------------------\n\nfunction requestKey(linkKeyZ32: string, askerZ32: string, shared: Uint8Array): Uint8Array {\n return hkdf(sha256, shared, label(\"ghostly-contact/1 request\"), concatBytes(publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32)), 32);\n}\n\nconst REQUEST_AAD = label(\"ghostly-contact/1 request\");\n\n/** The value of a request's record for a plaintext of `length` bytes. */\nconst sealedValueLength = (length: number) => Math.ceil(((NONCE_LENGTH + length + TAG_LENGTH) * 4) / 3);\n\nlet plaintextBytes: number | undefined;\n/** The size every request's plaintext is padded to: the largest whose packet fits `REQUEST_PACKET_BYTES`. */\nexport function requestPlaintextBytes(): number {\n if (plaintextBytes !== undefined) return plaintextBytes;\n const anyKey = \"y\".repeat(52);\n let length = REQUEST_PACKET_BYTES;\n while (measureRecords(anyKey, [{ label: REQUEST_LABEL, value: \"A\".repeat(sealedValueLength(length)), ttl: CONTACT_RECORD_TTL }]) > REQUEST_PACKET_BYTES) length--;\n return (plaintextBytes = length);\n}\n\nfunction nameHolds(name: unknown): name is string {\n return typeof name === \"string\" && name.length <= REQUEST_NAME_UNITS && name === name.trim() && stripHidden(name) === name && hasVisible(name);\n}\n\nfunction textHolds(text: unknown): text is string {\n if (typeof text !== \"string\" || !text.trim()) return false;\n return utf8Encode(text).length <= REQUEST_TEXT_BYTES;\n}\n\nfunction inviteHolds(invite: unknown): invite is string {\n if (typeof invite !== \"string\") return false;\n const reading = readInviteCode(invite);\n return reading.ok && reading.format === \"ghostly1\" && invite === invite.trim().toLowerCase() && invite.startsWith(\"ghostly1p\");\n}\n\n/**\n * The request record the asker publishes under its own key. Throws `ContactRequestError` when the name, the text, the\n * invite or the dates break a bound, or when the whole does not fit the packet (\"Shorten the message\").\n */\nexport function requestRecords(askerSeedB64: string, linkKeyZ32: string, request: ContactRequest): GhostRecord[] {\n if (!nameHolds(request.name)) throw new ContactRequestError(\"name\");\n if (!textHolds(request.text)) throw new ContactRequestError(\"text\");\n if (!inviteHolds(request.invite)) throw new ContactRequestError(\"invite\");\n if (!Number.isSafeInteger(request.issued) || !Number.isSafeInteger(request.expires) || request.expires <= request.issued\n || request.expires - request.issued > REQUEST_LIFETIME_MS) throw new ContactRequestError(\"dates\");\n const asker = identityFromSeedB64(askerSeedB64);\n const json = label(JSON.stringify([1, request.invite, request.name, request.text, request.issued, request.expires]));\n const size = requestPlaintextBytes();\n if (json.length > size) throw new ContactRequestError(\"too-long\");\n // Spaces after the JSON value, so every request is the same size whatever it says.\n const plaintext = new Uint8Array(size).fill(0x20);\n plaintext.set(json);\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(asker.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(linkKeyZ32)));\n const nonce = randomBytes(NONCE_LENGTH);\n const box = xchacha20poly1305(requestKey(linkKeyZ32, asker.pubKeyZ32, shared), nonce, REQUEST_AAD).encrypt(plaintext);\n return [{ label: REQUEST_LABEL, value: toBase64Url(concatBytes(nonce, box)), ttl: CONTACT_RECORD_TTL }];\n}\n\n/**\n * The owner's reading of the request under `askerZ32`, with the link's seed. Null, whole, for a request that does not\n * open, does not hold, or has expired by `now`. That the packet is signed by the asker key is the resolver's check.\n */\nexport function openRequest(linkSeedB64: string, askerZ32: string, records: GhostRecord[], now: number): ContactRequest | null {\n const value = records.find(r => r.label === REQUEST_LABEL)?.value;\n if (!value || value.length > sealedValueLength(requestPlaintextBytes()) + 4) return null;\n try {\n const link = identityFromSeedB64(linkSeedB64);\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(link.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(askerZ32)));\n const bytes = fromBase64Url(value);\n const plaintext = xchacha20poly1305(requestKey(link.pubKeyZ32, askerZ32, shared), bytes.slice(0, NONCE_LENGTH), REQUEST_AAD).decrypt(bytes.slice(NONCE_LENGTH));\n const parsed: unknown = JSON.parse(utf8Decode(plaintext));\n if (!Array.isArray(parsed) || parsed[0] !== 1) return null;\n const [, invite, name, text, issued, expires] = parsed as unknown[];\n if (!inviteHolds(invite) || !nameHolds(name) || !textHolds(text)) return null;\n if (!Number.isSafeInteger(issued) || !Number.isSafeInteger(expires)) return null;\n const [from, until] = [issued as number, expires as number];\n // Dated ahead of the owner's clock by more than two clocks drift apart: it would wait past its seven days.\n if (until <= from || until - from > REQUEST_LIFETIME_MS || until <= now || from > now + REQUEST_CLOCK_SKEW_MS) return null;\n return { invite, name, text, issued: from, expires: until };\n } catch { return null; }\n}\n\n/**\n * The asker's proof (WISP 8xx § Accept): in the chat a request started, the requester's app says on the live session\n * that it holds the asker key the request came under. The invite a request carries is a bearer code, so whoever made\n * the chat the owner joined may be someone other than the asker; until this proof comes, the request's text shows as\n * not confirmed. Signed by *K* over the link key, *K*, and both sides' participation keys in that chat: the joiner's is\n * new with the join, so a proof is made in the chat and for it, never before.\n */\nexport const CONTACT_ASKER_FRAME = \"contact-asker\";\n\nexport interface ContactAskerFrame {\n t: typeof CONTACT_ASKER_FRAME;\n /** The link key and the asker key, z-base-32. */\n l: string;\n k: string;\n /** Ed25519 by *K*, base64url. */\n s: string;\n}\n\n/** Whose chat is whose: the inviter is the asker (it made the invite), the joiner the owner. */\nexport interface ContactAskerChat {\n inviter: string;\n joiner: string;\n}\n\nfunction askerProofBytes(linkKeyZ32: string, askerZ32: string, chat: ContactAskerChat): Uint8Array {\n return concatBytes(label(\"ghostly-contact/1 asker\"), publicKeyFromZ32(linkKeyZ32), publicKeyFromZ32(askerZ32), publicKeyFromZ32(chat.inviter), publicKeyFromZ32(chat.joiner));\n}\n\n/** The requester's proof for the chat its request started. */\nexport function contactAskerFrame(askerSeedB64: string, linkKeyZ32: string, chat: ContactAskerChat): ContactAskerFrame {\n const asker = identityFromSeedB64(askerSeedB64);\n return { t: CONTACT_ASKER_FRAME, l: linkKeyZ32, k: asker.pubKeyZ32, s: toBase64Url(ed25519.sign(askerProofBytes(linkKeyZ32, asker.pubKeyZ32, chat), asker.seed)) };\n}\n\n/**\n * Whether a proof heard in a chat is the one the owner waits for there: the link and asker keys of the request it\n * accepted, signed by that asker key for this chat's two participation keys. Anything else proves nothing.\n */\nexport function contactAskerHolds(frame: unknown, expected: { link: string; key: string }, chat: ContactAskerChat): boolean {\n const f = frame as Partial<ContactAskerFrame> | null;\n if (!f || typeof f !== \"object\" || f.t !== CONTACT_ASKER_FRAME || f.l !== expected.link || f.k !== expected.key) return false;\n if (typeof f.s !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(f.s)) return false;\n if (![chat.inviter, chat.joiner].every(key => Z32_KEY.test(key))) return false;\n try {\n return ed25519.verify(fromBase64Url(f.s), askerProofBytes(f.l, f.k, chat), publicKeyFromZ32(f.k));\n } catch { return false; }\n}\n","/**\n * Ephemeral services a peer offers while it is online. Chat, voice and video\n * are the services Ghostly always had; `http` exposes a local web application.\n * Unknown types are preserved so future services do not need a new protocol.\n */\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toZ32, utf8Encode } from \"./bytes\";\nimport { sanitizeDisplayText } from \"./text\";\n\nexport type BuiltinServiceType = \"chat\" | \"voice\" | \"video\" | \"http\";\n\nexport interface ServiceAd {\n /** Stable identifier, unique per peer. Remote peers address services by id only. */\n id: string;\n type: BuiltinServiceType | (string & {});\n name?: string;\n /** Wire protocol spoken over the data link, e.g. `ghostly-http/1`. */\n proto?: string;\n meta?: Record<string, string>;\n}\n\nexport const SERVICES_VERSION = 1;\nexport const HTTP_SERVICE_PROTO = \"ghostly-http/1\";\nexport const MAX_SERVICES = 16;\nconst MAX_NAME_LENGTH = 48;\nconst MAX_META_ENTRIES = 8;\nconst MAX_META_LENGTH = 64;\nconst SERVICE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;\n\n/** What a peer that predates `_svc` offers implicitly. */\nexport const LEGACY_SERVICES: ServiceAd[] = [\n { id: \"chat\", type: \"chat\" },\n { id: \"voice\", type: \"voice\" },\n { id: \"video\", type: \"video\" },\n];\n\n/**\n * How many of its web apps one contact may be granted: a chat not paired yet tells chat, voice and video first, and a\n * contact keeps only the first `MAX_SERVICES` of a list (`servicesFromWire`). A grant past it would read as shared here\n * and never reach the contact.\n */\nexport const MAX_SHARED_APPS = MAX_SERVICES - LEGACY_SERVICES.length;\n\nexport function isValidServiceId(id: string): boolean {\n return SERVICE_ID_PATTERN.test(id);\n}\n\nconst VIEWER_TAG_PATTERN = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{16}$/;\n\n/**\n * The label that makes the origin a contact's app opens in this side's own (WISP 04): derived from the key this\n * profile holds for the chat with that contact. Another profile on the device, a profile after \"Clear all data\", or\n * one made again after a delete has another chat key, so another origin, and never finds the storage, cookies or\n * session the app kept here. The contact already knows that key, so the label tells it nothing new.\n */\nexport function viewerTag(myPubKeyZ32: string): string {\n return toZ32(sha256(utf8Encode(`ghostly-viewer/1\\n${myPubKeyZ32}`)).subarray(0, 10));\n}\n\nexport function isViewerTag(tag: string): boolean {\n return VIEWER_TAG_PATTERN.test(tag);\n}\n\nexport function serviceIdFromName(name: string, taken: Iterable<string> = []): string {\n const used = new Set(taken);\n const base =\n name\n .toLowerCase()\n .normalize(\"NFKD\")\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 24) || \"service\";\n let id = base;\n for (let n = 2; used.has(id) || LEGACY_SERVICES.some((s) => s.id === id); n++) id = `${base}-${n}`;\n return id;\n}\n\ninterface WireService {\n i: string;\n t: string;\n n?: string;\n p?: string;\n m?: Record<string, string>;\n}\n\ninterface WireServices {\n v: number;\n s: (string | WireService)[];\n}\n\n/** Compact JSON; a service whose id equals its type and has no metadata is a bare string. */\nexport function servicesToWire(services: ServiceAd[]): WireServices {\n return {\n v: SERVICES_VERSION,\n s: services.map((s) => {\n if (s.id === s.type && !s.name && !s.proto && !s.meta) return s.id;\n const out: WireService = { i: s.id, t: s.type };\n if (s.name) out.n = s.name;\n if (s.proto) out.p = s.proto;\n if (s.meta && Object.keys(s.meta).length > 0) out.m = s.meta;\n return out;\n }),\n };\n}\n\nexport function encodeServices(services: ServiceAd[]): string {\n return JSON.stringify(servicesToWire(services));\n}\n\nfunction cleanString(value: unknown, max: number): string | undefined {\n // A service name is a button the user presses to run a contact's app, so it\n // must not be able to read as another service's.\n return typeof value === \"string\" ? sanitizeDisplayText(value, max) : undefined;\n}\n\n/** Parses an untrusted advertisement. Invalid entries are dropped, never thrown. */\nexport function decodeServices(json: string): ServiceAd[] | null {\n let wire: unknown;\n try {\n wire = JSON.parse(json);\n } catch {\n return null;\n }\n return servicesFromWire(wire);\n}\n\nexport function servicesFromWire(wire: unknown): ServiceAd[] | null {\n if (!wire || typeof wire !== \"object\") return null;\n const { v, s } = wire as Partial<WireServices>;\n if (typeof v !== \"number\" || v < 1 || !Array.isArray(s)) return null;\n\n const services: ServiceAd[] = [];\n const seen = new Set<string>();\n for (const entry of s.slice(0, MAX_SERVICES)) {\n let ad: ServiceAd | null = null;\n if (typeof entry === \"string\") {\n ad = { id: entry, type: entry };\n } else if (entry && typeof entry === \"object\") {\n const e = entry as Partial<WireService>;\n if (typeof e.i === \"string\" && typeof e.t === \"string\") {\n ad = { id: e.i, type: e.t };\n const name = cleanString(e.n, MAX_NAME_LENGTH);\n const proto = cleanString(e.p, MAX_META_LENGTH);\n if (name) ad.name = name;\n if (proto) ad.proto = proto;\n if (e.m && typeof e.m === \"object\") {\n const meta: Record<string, string> = {};\n for (const [k, val] of Object.entries(e.m).slice(0, MAX_META_ENTRIES)) {\n const key = cleanString(k, MAX_META_LENGTH);\n const value = cleanString(val, MAX_META_LENGTH);\n if (key && value) meta[key] = value;\n }\n if (Object.keys(meta).length > 0) ad.meta = meta;\n }\n }\n }\n if (!ad || !isValidServiceId(ad.id) || !SERVICE_ID_PATTERN.test(ad.type) || seen.has(ad.id)) continue;\n seen.add(ad.id);\n services.push(ad);\n }\n return services;\n}\n","import { encrypt, tryDecrypt } from \"./crypto\";\nimport { MAX_DNS_PACKET_BYTES, measureRecords, type GhostRecord, type SignedPacket } from \"./pkarr\";\nimport { decodeServices, encodeServices, type ServiceAd } from \"./services\";\nimport { sanitizeNick } from \"./text\";\n\n/**\n * TXT labels a peer publishes under its own key. Every value except `_ts` and\n * `_ack` is secretbox-encrypted with the link key.\n *\n * `_msgs`, `_ts`, `_ack`, `_nick` and `_call` are the original Ghost protocol.\n * `_svc` and `_rtc` are additive: clients that predate them ignore unknown\n * labels, so old and new peers keep chatting and calling each other.\n */\nexport const LABEL = {\n msgs: \"_msgs\",\n ts: \"_ts\",\n ack: \"_ack\",\n nick: \"_nick\",\n call: \"_call\",\n /** Service advertisement, see `services.ts`. */\n svc: \"_svc\",\n /** Signaling for the WebRTC data link, see `signal.ts`. */\n rtc: \"_rtc\",\n /**\n * A group link's layer-1 transports and how to dial its native ones (`encodePacketTransports` in `capsRecord.ts`):\n * published only by an app with no WebRTC and by a member answering one, so two apps that have WebRTC never send it.\n */\n tr: \"_tr\",\n} as const;\n\nexport const RECORD_TTL = 300;\n/** Same ceiling the Rust implementation applies to the encrypted message batch. */\nexport const MAX_MSGS_PAYLOAD_B64 = 800;\nconst MAX_SINGLE_MESSAGE_CHARS = 400;\n\nexport interface CompactMessage {\n t: number;\n m: string;\n}\n\nexport interface OutgoingLinkState {\n messages: CompactMessage[];\n ackTimestamp: number;\n nick?: string;\n callSignal?: string | null;\n rtcSignal?: string | null;\n /** `undefined` publishes no `_svc` at all, which is what a legacy peer looks like. */\n services?: ServiceAd[];\n /** A group link's `_tr` value, already encoded; absent publishes none. */\n transports?: string | null;\n}\n\nexport interface BuiltLinkRecords {\n records: GhostRecord[];\n /** How many of the newest messages made it into the packet. */\n keptMessages: number;\n /** False when the advertisement had to be left out to fit the packet. */\n servicesIncluded: boolean;\n}\n\nfunction record(label: string, value: string): GhostRecord {\n return { label, value, ttl: RECORD_TTL };\n}\n\n/**\n * The packet an inviter puts under the contact's key before they join, so that their first packet lands\n * as a newer one under a key the network already knows (seconds faster than a first packet under a\n * fresh key). It carries no message record, which every link session's own packet does, even empty:\n * that is how a reader tells it from a contact who is here (or was, and left without a word).\n */\nexport function emptyLinkRecords(): GhostRecord[] {\n return [record(LABEL.ts, \"0\")];\n}\n\n/** A packet nobody's link session published (see `emptyLinkRecords`): read as no packet at all. */\nexport function isEmptyLinkPacket(batch: ResolvedLink): boolean {\n return !batch.rawRecordNames.includes(LABEL.msgs);\n}\n\n/**\n * Builds the records for one publish. A Pkarr packet is at most 1000 bytes, so\n * space is handed out by priority: signaling first (it is what gets peers onto\n * WebRTC, where there is no such limit), then the service advertisement, then\n * as many of the newest messages as still fit.\n */\nexport function buildLinkRecords(\n pubKeyZ32: string,\n state: OutgoingLinkState,\n encKey: Uint8Array,\n): BuiltLinkRecords {\n const sorted = [...state.messages].sort((a, b) => a.t - b.t);\n const latestTs = sorted.length > 0 ? sorted[sorted.length - 1].t : 0;\n\n const fixed: GhostRecord[] = [record(LABEL.ts, String(latestTs))];\n if (state.ackTimestamp > 0) fixed.push(record(LABEL.ack, String(state.ackTimestamp)));\n if (state.nick) fixed.push(record(LABEL.nick, encrypt(state.nick, encKey)));\n if (state.callSignal) fixed.push(record(LABEL.call, encrypt(state.callSignal, encKey)));\n if (state.rtcSignal) fixed.push(record(LABEL.rtc, encrypt(state.rtcSignal, encKey)));\n const tr = state.transports ? record(LABEL.tr, encrypt(state.transports, encKey)) : null;\n\n const svc = state.services ? record(LABEL.svc, encrypt(encodeServices(state.services), encKey)) : null;\n\n const attempt = (withServices: boolean, withTransports = true): BuiltLinkRecords | null => {\n const head = withTransports && tr ? [...fixed, tr] : fixed;\n const base = withServices && svc ? [...head, svc] : head;\n const batch = [...sorted];\n for (;;) {\n let payload = encrypt(JSON.stringify(batch), encKey);\n if (batch.length === 1 && payload.length > MAX_MSGS_PAYLOAD_B64) {\n const truncated = { t: batch[0].t, m: [...batch[0].m].slice(0, MAX_SINGLE_MESSAGE_CHARS).join(\"\") };\n payload = encrypt(JSON.stringify([truncated]), encKey);\n }\n const records = [record(LABEL.msgs, payload), ...base];\n if (\n payload.length <= MAX_MSGS_PAYLOAD_B64 &&\n measureRecords(pubKeyZ32, records) <= MAX_DNS_PACKET_BYTES\n ) {\n return { records, keptMessages: batch.length, servicesIncluded: withServices && svc !== null };\n }\n if (batch.length === 0) return null;\n batch.shift();\n }\n };\n\n // The transports go before the advertisement, and are left out only when nothing else would fit.\n const built = attempt(true) ?? attempt(false) ?? attempt(false, false);\n if (!built) throw new Error(\"Link records do not fit in a Pkarr packet\");\n return built;\n}\n\nexport interface ResolvedMessage {\n text: string;\n timestamp: number;\n nick?: string;\n}\n\nexport interface ResolvedLink {\n messages: ResolvedMessage[];\n latestTimestamp: number;\n peerAck: number;\n nick?: string;\n callSignal: string | null;\n rtcSignal: string | null;\n /** `null` when the peer published no advertisement (legacy client or offline). */\n services: ServiceAd[] | null;\n /** A group link's `_tr` value as published (`parsePacketTransports`); `null` when there is none. */\n transports: string | null;\n rawRecordNames: string[];\n encryptedPayloadLength: number;\n /** Milliseconds since the UNIX epoch. */\n packetTimestamp: number;\n}\n\nexport function parseLinkRecords(packet: SignedPacket, encKey: Uint8Array): ResolvedLink {\n const resolved: ResolvedLink = {\n messages: [],\n latestTimestamp: 0,\n peerAck: 0,\n callSignal: null,\n rtcSignal: null,\n services: null,\n transports: null,\n rawRecordNames: [],\n encryptedPayloadLength: 0,\n packetTimestamp: Number(packet.timestampMicros / 1000n),\n };\n\n let msgsPayload = \"\";\n for (const { label, value } of packet.records) {\n resolved.rawRecordNames.push(label);\n switch (label) {\n case LABEL.msgs:\n resolved.encryptedPayloadLength = value.length;\n msgsPayload = value;\n break;\n case LABEL.ts:\n resolved.latestTimestamp = Number.parseInt(value, 10) || 0;\n break;\n case LABEL.ack:\n resolved.peerAck = Number.parseInt(value, 10) || 0;\n break;\n case LABEL.nick:\n // A nickname is shown beside every message and is copied onto each of\n // them, so it is cut and stripped before anything keeps it.\n resolved.nick = sanitizeNick(tryDecrypt(value, encKey));\n break;\n case LABEL.call:\n resolved.callSignal = tryDecrypt(value, encKey);\n break;\n case LABEL.rtc:\n resolved.rtcSignal = tryDecrypt(value, encKey);\n break;\n case LABEL.tr:\n resolved.transports = tryDecrypt(value, encKey);\n break;\n case LABEL.svc: {\n const json = tryDecrypt(value, encKey);\n if (json !== null) resolved.services = decodeServices(json);\n break;\n }\n default:\n break;\n }\n }\n\n if (msgsPayload) {\n const json = tryDecrypt(msgsPayload, encKey);\n if (json !== null) {\n try {\n const batch: unknown = JSON.parse(json);\n if (Array.isArray(batch)) {\n for (const entry of batch as Partial<CompactMessage>[]) {\n if (typeof entry?.t !== \"number\" || typeof entry?.m !== \"string\") continue;\n resolved.messages.push({ text: entry.m, timestamp: entry.t, nick: resolved.nick });\n }\n }\n } catch {\n // not a message batch\n }\n if (resolved.latestTimestamp === 0 && resolved.messages.length > 0) {\n resolved.latestTimestamp = Math.max(...resolved.messages.map((m) => m.timestamp));\n }\n }\n }\n\n return resolved;\n}\n","/**\n * Signaling for voice/video calls, carried in the `_call` record. A full SDP\n * does not fit in a Pkarr packet, so only the session-specific parameters\n * travel and each side rebuilds the SDP around them.\n */\nexport interface CallSignal {\n /**\n * offer, answer, hang-up, \"my picture changed\" while the call is up, or `r`: an offer that restarts ICE on the\n * call's own connection after its path was lost (WISP 601, \"Reconnecting\"). An app that does not know `r` drops it.\n */\n t: \"o\" | \"a\" | \"h\" | \"v\" | \"r\";\n /** The sender's clock when it made the signal: its order among that sender's signals. */\n ts: number;\n /** When this device heard a contact's signal, by its own clock. Never sent: the engine sets it (`heardCallSignal`). */\n at?: number;\n /**\n * On an answer: the `ts` of the offer it answers, so the caller takes it for that offer and no other, whatever the two\n * clocks say. Apps up to 1.0.2 send none and ignore it; they take an answer only when its `ts` is later than their\n * offer's, which a callee whose clock is behind by longer than it took to answer never met.\n */\n o?: number;\n u?: string;\n p?: string;\n f?: string;\n s?: string;\n m?: string[];\n c?: string[];\n ss?: number[];\n /** 1 while this peer is sending a picture, 0 while it is not. */\n v?: number;\n /** What the picture is: the camera or a screen. Only meaningful with `v: 1`. */\n k?: \"c\" | \"s\";\n /**\n * The payload types the sender's SDP gives Opus and VP8, when not 111 and 96 (the rebuilt SDP's own, and\n * Chromium's). WebKit offers H264 as 96 and VP8 as 106: rebuilt as `96 VP8`, the offerer read the answerer's\n * VP8 as H264 and never showed its picture.\n */\n ap?: number;\n vp?: number;\n /**\n * On a hang-up, why when it was not the person's choice: `u`, the call could not connect (no connection found a\n * candidate, or it did not connect in time). Older apps read it as a plain hang-up.\n */\n r?: \"u\";\n /**\n * On an offer or an answer: 1 when this side can restart ICE on the call's connection, so a call both sides said\n * it on reconnects after a network change instead of ending. Older apps leave it out, and ignore it.\n */\n x?: 1;\n /** On the answer to a restart offer (`r`): that offer's `ts`, so an answer to an older one is told apart. */\n re?: number;\n /**\n * On an offer or an answer: 0 when this side takes no picture and sends none (the headless CLI: a bot has no screen\n * to show one on). Its video section is rebuilt closed (`a=inactive`), so the other side sends nothing on it, a\n * camera turned on mid-call included. Older apps leave it out, and ignore it: they send a picture nobody reads.\n */\n vr?: 0;\n}\n\n/** What the rebuilt SDP gives Opus and VP8 unless the signal says otherwise. */\nconst DEFAULT_OPUS_PT = 111;\nconst DEFAULT_VP8_PT = 96;\n/** Dynamic RTP payload types: 96-127 (RFC 3551), and 35-63, which WebRTC engines use too. */\nconst dynamicPayloadType = (n: unknown): n is number => Number.isInteger(n) && (((n as number) >= 96 && (n as number) <= 127) || ((n as number) >= 35 && (n as number) <= 63));\n\nexport type CallState = \"idle\" | \"offering\" | \"incoming\" | \"answering\" | \"connecting\" | \"connected\" | \"ended\";\n\nexport type CallEventType =\n | \"call_started\"\n | \"call_received\"\n | \"call_connected\"\n | \"call_ended\"\n | \"call_missed\"\n /** Our call rang out (`RING_MS`) with nobody answering: the caller's line, as \"Missed call\" is the side it rang. */\n | \"call_unanswered\"\n /** We hung up our call while it still rang, before any answer. */\n | \"call_cancelled\"\n | \"call_rejected\"\n /** The call ended without ever connecting: no way to reach the contact was found, or none worked in time. */\n | \"call_failed\";\n\n/**\n * Where a call's media comes from: the browser's own WebRTC and capture, or a stand-in with the same shape.\n * Ghostly Desktop on Linux brings one: WebKitGTK has no WebRTC there, so GStreamer runs the call (WISP 601).\n */\nexport interface CallMedia {\n createPeerConnection(config: RTCConfiguration): RTCPeerConnection;\n getUserMedia(constraints: MediaStreamConstraints): Promise<MediaStream>;\n /** Left out where the screen cannot be shared. */\n getDisplayMedia?(options: DisplayMediaStreamOptions): Promise<MediaStream>;\n /**\n * Its connections restart ICE as a browser's do: `createOffer({ iceRestart: true })` on a connected one gives an\n * offer with new ICE credentials and candidates, and a remote offer with new credentials is answered on the same\n * connection (WISP 601, \"Reconnecting\"). The browser's own media does; a stand-in says so.\n */\n restartsIce?: boolean;\n /** Why the screen cannot be shared, where it cannot: the call window shows it on the share button, turned off. */\n screenUnavailable?: string;\n /**\n * Its connections keep to the configuration's relay policy (`iceTransportPolicy: \"relay\"`): they gather and use\n * only the TURN server's candidates, so a contact never learns this device's address. The browser's own media\n * does; a stand-in that does not say so is not used for a call while \"Hide my IP from contacts\" is on.\n */\n keepsToRelays?: boolean;\n /**\n * `getUserMedia` captures from the `deviceId` asked for, and `replaceTrack` on the audio sender switches the\n * microphone: the profile's devices and the call's device menu work as with the browser's own media.\n */\n choosesDevices?: boolean;\n}\n\nexport function compressSdp(sdp: string): string {\n return btoa(sdp);\n}\n\nexport function decompressSdp(compressed: string): string {\n return atob(compressed);\n}\n\n/**\n * The apps' STUN servers. No candidate pool: a call's connection is made when the call is placed and its offer follows\n * at once, so pre-gathered sessions save no time, and each one opens its own sockets, asks every STUN server and takes\n * its own TURN allocation (a TURN server's per-user quota then refuses the call's own).\n */\nexport const RTC_CONFIG: RTCConfiguration = {\n iceServers: [\n { urls: \"stun:stun.l.google.com:19302\" },\n { urls: \"stun:stun1.l.google.com:19302\" },\n { urls: \"stun:stun2.l.google.com:19302\" },\n { urls: \"stun:stun3.l.google.com:19302\" },\n { urls: \"stun:stun4.l.google.com:19302\" },\n ],\n};\n\n/** An ICE server as a profile's settings keep it: one or more URLs in `urls` (space or comma separated). */\nexport interface CallIceServer { urls: string | string[]; username?: string; credential?: string }\n\n/**\n * A call's WebRTC configuration: the apps' STUN servers, then the profile's own (Settings → Network → ICE\n * servers: a TURN relay, typically). A relay is what connects a call when no direct path works: a VPN that takes\n * every packet through its tunnel, or a NAT that maps each destination apart.\n *\n * `relayOnly` (\"Hide my IP from contacts\", WISP 100 § Relay only): the profile's TURN servers alone, no STUN server\n * (the apps' or the profile's), and the relay policy, so the connection gathers and uses relay candidates only. With\n * no usable TURN server it has no server at all, and finds no candidate: it fails, it never goes direct.\n */\nexport function callRtcConfig(extra: readonly CallIceServer[] = [], { relayOnly = false }: { relayOnly?: boolean } = {}): RTCConfiguration {\n const servers: RTCIceServer[] = [];\n for (const server of extra) {\n const urls = (Array.isArray(server.urls) ? server.urls : server.urls.split(/[\\s,]+/)).filter(Boolean)\n .filter((url) => !relayOnly || /^turns?:/i.test(url));\n if (!urls.length) continue;\n // A TURN server without its username and credential (a profile restored from a backup, which leaves the\n // credential out) is skipped: a browser refuses to make any connection with one in its list.\n if (urls.some((url) => /^turns?:/i.test(url)) && (!server.username?.trim() || !server.credential?.trim())) continue;\n servers.push({ urls, ...(server.username ? { username: server.username } : {}), ...(server.credential ? { credential: server.credential } : {}) });\n }\n if (relayOnly) return { ...RTC_CONFIG, iceServers: servers, iceTransportPolicy: \"relay\" };\n return { ...RTC_CONFIG, iceServers: [...(RTC_CONFIG.iceServers ?? []), ...servers] };\n}\n\n/**\n * The WebRTC configuration of a chat's data link or a group's edge, from the profile's settings: its ICE servers,\n * and \"Hide my IP from contacts\" (`relayOnly`), as a call's (`callRtcConfig`).\n */\nexport function contactRtcConfig(settings: { iceServers?: readonly CallIceServer[]; relayOnly?: boolean }): RTCConfiguration {\n return callRtcConfig(settings.iceServers ?? [], { relayOnly: settings.relayOnly === true });\n}\n\n/** Whether a connection keeps to relays (`iceTransportPolicy: \"relay\"`): what it sends a contact is then relay candidates only. */\nexport function keepsToRelays(pc: Pick<RTCPeerConnection, \"getConfiguration\"> | null | undefined): boolean {\n return pc?.getConfiguration?.().iceTransportPolicy === \"relay\";\n}\n\n/**\n * How many candidates a signal on the chat session carries (`paired-call`, WISP 601): the receiver takes eight.\n * A compatibility chat's `_call` record keeps to one host and one server reflexive candidate (a DHT packet's worth).\n */\nexport const PAIRED_CALL_CANDIDATES = 8;\n\n/**\n * The candidates a signal carries, from the `a=candidate:` values of an SDP, when it may carry up to `max`.\n *\n * A computer often has several interfaces (Wi-Fi, Ethernet, VM bridges, Tailscale, a VPN) and the one listed first is\n * not always one the contact can reach: on a Mac with a VPN as its default route it is the tunnel's address, which\n * nothing on that machine can answer. So the signal carries every usable path, in this order:\n *\n * 1. host candidates on local networks, IPv4 or an mDNS name (at most four);\n * 2. the first server reflexive candidate, and relay candidates (a TURN server, when the profile has one);\n * 3. IPv6 host candidates, global ones first (at most two);\n * 4. host candidates a browser marks as costly (`network-cost` 50 or more: a VPN, or an interface it does not know);\n * 5. whatever else fits.\n *\n * UDP only, loopback, link-local and unspecified addresses left out (loopback kept with `loopback`), the related\n * address dropped (it is informational, and an IPv6 one broke apps before 0.5).\n *\n * `relayOnly` (\"Hide my IP from contacts\"): relay candidates alone, whatever else the connection gathered. A relay\n * candidate's address is the TURN server's; its related address, dropped as every one is, would be this device's.\n */\nexport function pickCallCandidates(candidates: readonly string[], max = PAIRED_CALL_CANDIDATES, { loopback = false, relayOnly = false } = {}): string[] {\n const type = (c: string) => / typ (\\S+)/.exec(c)?.[1];\n const udp = candidates.map((c) => c.trim()).filter((c) => / udp /i.test(c) && (!relayOnly || type(c) === \"relay\"));\n const address = (c: string) => c.split(\" \")[4] ?? \"\";\n const cost = (c: string) => Number(/ network-cost (\\d+)/.exec(c)?.[1] ?? 0);\n const ipv6 = (c: string) => address(c).includes(\":\");\n const usable = (c: string) => {\n const a = address(c).toLowerCase();\n if (a === \"::\" || a === \"0.0.0.0\" || a.startsWith(\"169.254.\") || a.startsWith(\"fe80:\")) return false;\n return loopback || !(a === \"::1\" || a.startsWith(\"127.\"));\n };\n const hosts = udp.filter((c) => type(c) === \"host\" && usable(c));\n const costly = (c: string) => cost(c) >= 50;\n const groups = [\n hosts.filter((c) => !ipv6(c) && !costly(c)).slice(0, 4),\n udp.filter((c) => type(c) === \"srflx\").slice(0, 1),\n udp.filter((c) => type(c) === \"relay\").slice(0, 2),\n [...hosts.filter((c) => ipv6(c) && !/^f[cd]/i.test(address(c)) && !costly(c)), ...hosts.filter((c) => ipv6(c) && (/^f[cd]/i.test(address(c)) || costly(c)))].slice(0, 2),\n hosts.filter((c) => !ipv6(c) && costly(c)),\n hosts,\n ];\n const picked: string[] = [];\n for (const group of groups) for (const c of group) if (picked.length < max && !picked.includes(c)) picked.push(c);\n return picked.map((c) => c.replace(/ raddr \\S+ rport \\d+/, \"\"));\n}\n\n/**\n * The parameters of a call signal, from an SDP. `maxCandidates` above two (a signal on the chat session) carries\n * the candidates `pickCallCandidates` chooses; the default keeps a compatibility chat's one host and one server\n * reflexive candidate. `relayOnly` (\"Hide my IP from contacts\"): relay candidates only, in either; a compatibility\n * chat's two then go to the first two relay ones.\n */\nexport function extractParamsFromSdp(sdp: string, { maxCandidates = 2, loopback = false, relayOnly = false }: { maxCandidates?: number; loopback?: boolean; relayOnly?: boolean } = {}): Partial<CallSignal> {\n const lines = sdp.split(\"\\r\\n\");\n\n let ufrag = \"\";\n let pwd = \"\";\n let fingerprint = \"\";\n let setup = \"\";\n const media: string[] = [];\n const candidates: string[] = [];\n let audioSsrc: number | null = null;\n let videoSsrc: number | null = null;\n let opus: number | null = null;\n let vp8: number | null = null;\n let currentMedia = \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"a=ice-ufrag:\") && !ufrag) {\n ufrag = line.substring(\"a=ice-ufrag:\".length);\n }\n if (line.startsWith(\"a=ice-pwd:\") && !pwd) {\n pwd = line.substring(\"a=ice-pwd:\".length);\n }\n if (line.startsWith(\"a=fingerprint:sha-256 \") && !fingerprint) {\n fingerprint = line\n .substring(\"a=fingerprint:sha-256 \".length)\n .replace(/:/g, \"\");\n }\n if (line.startsWith(\"a=setup:\") && !setup) {\n setup = line.substring(\"a=setup:\".length);\n }\n if (line.startsWith(\"m=audio\")) {\n media.push(\"a\");\n currentMedia = \"a\";\n }\n if (line.startsWith(\"m=video\")) {\n media.push(\"v\");\n currentMedia = \"v\";\n }\n const rtpmap = line.match(/^a=rtpmap:(\\d+) (opus\\/48000|VP8\\/90000)/i);\n if (rtpmap) {\n const pt = Number(rtpmap[1]);\n if (currentMedia === \"a\" && opus === null && /^opus/i.test(rtpmap[2])) opus = pt;\n if (currentMedia === \"v\" && vp8 === null && /^VP8/i.test(rtpmap[2])) vp8 = pt;\n }\n // Component 1 alone: the rebuilt SDP says `a=rtcp-mux`, so a component 2 line (webrtc-rs, the Linux Desktop,\n // lists one of every candidate) is no path, and it would take another candidate's slot.\n if (line.startsWith(\"a=candidate:\") && line.split(\" \")[1] === \"1\") {\n candidates.push(line.substring(\"a=candidate:\".length));\n }\n if (line.startsWith(\"a=ssrc:\")) {\n const ssrcMatch = line.match(/^a=ssrc:(\\d+)/);\n if (ssrcMatch) {\n const ssrc = parseInt(ssrcMatch[1], 10);\n if (currentMedia === \"a\" && audioSsrc === null) {\n audioSsrc = ssrc;\n } else if (currentMedia === \"v\" && videoSsrc === null) {\n videoSsrc = ssrc;\n }\n }\n }\n }\n\n // `typ host` can end the line: browsers add `generation 0` after it, webrtc-rs (the Linux Desktop) does not.\n const srflxCandidates = candidates.filter(c => / typ srflx( |$)/.test(c));\n const hostCandidates = candidates.filter(c => / typ host( |$)/.test(c) && / udp /i.test(c));\n // Include 1 host candidate (for local connections) and 1 srflx (for remote)\n // Keep packet size under 1000 bytes DHT limit\n // The related address is informational and names an interface of the sender's (webrtc-rs gives its LAN address),\n // so it is left out, IPv4 too; an IPv6 one (`raddr ::`, WebKit's IPv6 srflx) also made apps before 0.5 refuse the\n // whole signal.\n const selectedCandidates = maxCandidates > 2 || relayOnly ? pickCallCandidates(candidates, maxCandidates, { loopback, relayOnly }) : [\n ...hostCandidates.slice(0, 1),\n ...srflxCandidates.slice(0, 1),\n ].map(c => c.replace(/ raddr \\S+ rport \\d+/, \"\"));\n \n const ssrcs: number[] = [];\n if (audioSsrc !== null) ssrcs.push(audioSsrc);\n if (videoSsrc !== null) ssrcs.push(videoSsrc);\n \n return {\n u: ufrag,\n p: pwd,\n f: fingerprint,\n s: setup,\n m: media,\n c: selectedCandidates,\n ss: ssrcs,\n // Only when they differ from what every rebuilt SDP assumes: signals between Chromium apps stay as they were.\n ...(opus !== null && opus !== DEFAULT_OPUS_PT && dynamicPayloadType(opus) ? { ap: opus } : {}),\n ...(vp8 !== null && vp8 !== DEFAULT_VP8_PT && dynamicPayloadType(vp8) ? { vp: vp8 } : {}),\n };\n}\n\n/** Offers, answers and hang-ups older (or further in the future) than this are ignored. */\nexport const CALL_SIGNAL_MAX_AGE_MS = 120_000;\n\n/**\n * A call that comes this soon after the contact's last missed one does not ring, when that one barely rang\n * (`BURST_RING_MS`): a bot looping call and hang-up does that (1,375 calls a minute), no person does. It is kept as a\n * missed call, and the wait starts over with it, so a burst rings once and a call placed after a pause rings again.\n * A person's call that rang a while, then was cancelled or rang out, holds nothing back: calling again at once (voice to\n * video, a slip of the finger) rings. The apps (`useWebRTC`) and the headless CLI's call manager both keep it.\n */\nexport const QUICK_REDIAL_MS = 2000;\n\n/** A missed call that rang shorter than this was not a person's (`QUICK_REDIAL_MS`). */\nexport const BURST_RING_MS = 1000;\n/**\n * A signal dated further ahead of this clock than this is not taken, however it was heard. A receiver acts on a signal\n * only when its `ts` is later than the last one it acted on: taken, a signal dated a day ahead would be that last one,\n * and every offer, answer and hang-up its sender made afterwards would be dropped as older, until the app started again.\n */\nexport const CALL_SIGNAL_FUTURE_MS = 10 * 60_000;\n\n/** RFC 8839: ice-char is ALPHA / DIGIT / \"+\" / \"/\"; ufrag is 4-256 of them, pwd 22-256. */\nconst ICE_UFRAG = /^[A-Za-z0-9+/]{4,256}$/;\nconst ICE_PWD = /^[A-Za-z0-9+/]{22,256}$/;\nconst ICE_FOUNDATION = /^[A-Za-z0-9+/]{1,32}$/;\nconst CANDIDATE_ADDRESS = /^[A-Za-z0-9.:-]{1,64}$/;\nconst IPV4 = /^(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}$/;\nconst MDNS_NAME = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\.local$/;\nconst CANDIDATE_TYPES = new Set([\"host\", \"srflx\", \"prflx\", \"relay\"]);\nconst EXTENSION_TOKEN = /^[A-Za-z0-9+/._-]{1,64}$/;\nconst DIGITS = /^\\d{1,10}$/;\nconst MAX_CANDIDATES = 8;\n\nfunction isIpv6(text: string): boolean {\n const halves = text.split(\"::\");\n if (halves.length > 2) return false;\n const groups = halves.flatMap((half) => (half ? half.split(\":\") : []));\n // An IPv4 tail (`::ffff:192.0.2.1`) counts as two groups.\n const v4 = groups.length > 0 && IPV4.test(groups[groups.length - 1]);\n if (v4) groups.pop();\n if (!groups.every((group) => /^[0-9a-fA-F]{1,4}$/.test(group))) return false;\n const count = groups.length + (v4 ? 2 : 0);\n return halves.length === 2 ? count < 8 : count === 8;\n}\n\n/**\n * Whether a contact's candidate address may go into this device's remote description: an IPv4 or IPv6 literal, or the\n * `<uuid>.local` name a browser gives its host candidate. Any other name would have this side's ICE agent look it up in\n * DNS, a request the contact chose, whatever the relay policy says.\n */\nexport function isCandidateAddress(address: string): boolean {\n return IPV4.test(address) || MDNS_NAME.test(address) || (address.includes(\":\") && isIpv6(address));\n}\n\nfunction uint(value: string, max: number): number | null {\n if (!DIGITS.test(value)) return null;\n const n = Number(value);\n return n <= max ? n : null;\n}\n\n/**\n * Parses the part of an `a=candidate:` line that the signal carries\n * (`foundation component transport priority address port typ type [raddr a rport p] [ext value]...`)\n * and serializes it again from the validated parts. Returns `undefined` for a\n * well-formed candidate that is not UDP or not on an address (`isCandidateAddress`), skipped, and `null` for anything\n * malformed.\n */\nfunction normalizeCandidate(candidate: unknown): string | null | undefined {\n if (typeof candidate !== \"string\" || candidate.length > 512) return null;\n const parts = candidate.split(\" \");\n if (parts.length < 8 || parts[6] !== \"typ\") return null;\n const [foundation, componentStr, transport, priorityStr, address, portStr, , type] = parts;\n const component = uint(componentStr, 256);\n const priority = uint(priorityStr, 0xffffffff);\n const port = uint(portStr, 65535);\n if (!ICE_FOUNDATION.test(foundation) || component === null || component < 1) return null;\n if (!/^[A-Za-z]{1,8}$/.test(transport) || priority === null || port === null) return null;\n if (!CANDIDATE_ADDRESS.test(address) || !CANDIDATE_TYPES.has(type)) return null;\n\n let raddr: string | null = null;\n let rport: number | null = null;\n const rest = parts.slice(8);\n if (rest.length % 2 !== 0) return null;\n for (let i = 0; i < rest.length; i += 2) {\n const [name, value] = [rest[i], rest[i + 1]];\n if (!EXTENSION_TOKEN.test(name)) return null;\n // raddr is an address, IPv6 too (`raddr ::`, as WebKit gives an IPv6 srflx): the address pattern, not the token one.\n if (name === \"raddr\") {\n if (!CANDIDATE_ADDRESS.test(value)) return null;\n raddr = value;\n } else if (name === \"rport\") {\n rport = uint(value, 65535);\n if (rport === null) return null;\n } else if (!EXTENSION_TOKEN.test(value)) return null;\n // Other extension attributes (generation, network-id, ufrag...) are dropped.\n }\n\n if (transport.toLowerCase() !== \"udp\") return undefined;\n if (!isCandidateAddress(address) || (raddr !== null && !isCandidateAddress(raddr))) return undefined;\n let line = `${foundation} ${component} udp ${priority} ${address} ${port} typ ${type}`;\n if (raddr !== null && rport !== null) line += ` raddr ${raddr} rport ${rport}`;\n return line;\n}\n\n/**\n * Validates an untrusted `_call` signal (from the Pkarr record or a `call`\n * frame). Every value that ends up in the rebuilt SDP is checked against an\n * anchored pattern and candidates are re-serialized from their parts, so a peer\n * cannot inject SDP lines. Signals outside {@link CALL_SIGNAL_MAX_AGE_MS} of\n * `now` are rejected so that a stale packet does not ring.\n */\nexport function parseCallSignal(json: string, now = Date.now()): CallSignal | null {\n let raw: Record<string, unknown>;\n try {\n raw = JSON.parse(json);\n } catch {\n return null;\n }\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n if (raw.t !== \"o\" && raw.t !== \"a\" && raw.t !== \"h\" && raw.t !== \"v\" && raw.t !== \"r\") return null;\n if (typeof raw.ts !== \"number\" || !Number.isFinite(raw.ts)) return null;\n if (raw.ts > now + CALL_SIGNAL_FUTURE_MS) return null;\n // How old it is, on this clock when the engine heard it come (`heardCallSignal`), by its own time otherwise.\n const heard = typeof raw.at === \"number\" && Number.isFinite(raw.at) ? { at: raw.at } : {};\n if (Math.abs(now - (heard.at ?? raw.ts)) > CALL_SIGNAL_MAX_AGE_MS) return null;\n if (raw.t === \"h\") return raw.r === \"u\" ? { t: \"h\", ts: raw.ts, r: \"u\", ...heard } : { t: \"h\", ts: raw.ts, ...heard };\n\n const picture = parsePicture(raw);\n if (picture === null) return null;\n // A media state carries no ICE: it only says whether a picture is on, and which.\n if (raw.t === \"v\") return { t: \"v\", ts: raw.ts, ...picture, ...heard };\n\n if (typeof raw.u !== \"string\" || !ICE_UFRAG.test(raw.u)) return null;\n if (typeof raw.p !== \"string\" || !ICE_PWD.test(raw.p)) return null;\n if (typeof raw.f !== \"string\" || !/^[0-9a-fA-F]{64}$/.test(raw.f)) return null;\n if (raw.s !== \"actpass\" && raw.s !== \"active\" && raw.s !== \"passive\") return null;\n\n let media: string[] | undefined;\n if (raw.m !== undefined) {\n if (!Array.isArray(raw.m) || raw.m.length < 1 || raw.m.length > 2) return null;\n if (!raw.m.every((m) => m === \"a\" || m === \"v\") || new Set(raw.m).size !== raw.m.length) return null;\n media = [...raw.m];\n }\n\n let ssrcs: number[] | undefined;\n if (raw.ss !== undefined) {\n if (!Array.isArray(raw.ss) || raw.ss.length > 2) return null;\n if (!raw.ss.every((n) => Number.isInteger(n) && n >= 0 && n <= 0xffffffff)) return null;\n ssrcs = [...raw.ss];\n }\n\n const candidates: string[] = [];\n if (raw.c !== undefined) {\n if (!Array.isArray(raw.c) || raw.c.length > MAX_CANDIDATES) return null;\n for (const c of raw.c) {\n const normalized = normalizeCandidate(c);\n if (normalized === null) return null;\n if (normalized !== undefined) candidates.push(normalized);\n }\n }\n\n const payloadTypes: Pick<CallSignal, \"ap\" | \"vp\"> = {};\n for (const key of [\"ap\", \"vp\"] as const) {\n const value = raw[key];\n if (value === undefined) continue;\n if (!dynamicPayloadType(value)) return null;\n payloadTypes[key] = value;\n }\n if (payloadTypes.ap !== undefined && payloadTypes.ap === payloadTypes.vp) return null;\n\n // Any other value of `x` says nothing. `re` only means something on an answer.\n const restart: Pick<CallSignal, \"x\" | \"re\"> = raw.x === 1 ? { x: 1 } : {};\n if (raw.re !== undefined) {\n if (raw.t !== \"a\" || typeof raw.re !== \"number\" || !Number.isFinite(raw.re)) return null;\n restart.re = raw.re;\n }\n\n // Any other value of `vr` says nothing: the video section stays open, as without it.\n const closed: Pick<CallSignal, \"vr\"> = raw.vr === 0 ? { vr: 0 } : {};\n\n // `o` names the offer an answer is for; on anything else it says nothing.\n if (raw.o !== undefined && (typeof raw.o !== \"number\" || !Number.isFinite(raw.o))) return null;\n const answers = raw.t === \"a\" && raw.o !== undefined ? { o: raw.o } : {};\n\n return { t: raw.t, ts: raw.ts, u: raw.u, p: raw.p, f: raw.f, s: raw.s, m: media, c: candidates, ss: ssrcs, ...picture, ...payloadTypes, ...restart, ...closed, ...answers, ...heard };\n}\n\n/**\n * A contact's signal as the engine hands it on: `at` says when this device heard it, by its own clock (absent: nothing\n * says, as for one found in a record). Whatever `at` the signal came with is dropped: it is never the sender's to say.\n *\n * A signal's `ts` is its sender's clock. It orders that sender's signals, and settles two calls made at once the same\n * way on both sides. It cannot say how long ago the signal was made, nor whether it came before or after something this\n * device did: two devices' clocks are often minutes apart. Held against this clock, a contact two minutes off never\n * rang here, and an answer from a contact whose clock was behind by longer than it took to answer was dropped as\n * \"from before the offer\", so the call never connected.\n */\nexport function heardCallSignal(json: string, at?: number): string {\n let raw: unknown;\n try { raw = JSON.parse(json); } catch { return json; }\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return json;\n const { at: _theirs, ...signal } = raw as Record<string, unknown>;\n return JSON.stringify(at === undefined ? signal : { ...signal, at });\n}\n\n/**\n * When a contact's signal came, to hold against something this device did (its own offer): on this clock when the\n * engine said (`at`), by the signal's own time otherwise, as before.\n */\nexport const callSignalHeardAt = (signal: Pick<CallSignal, \"ts\" | \"at\">): number => signal.at ?? signal.ts;\n\n/**\n * Whether a contact's answer is for the offer this side made at `offerTs` (its own clock). An answer that names its\n * offer (`o`) says so itself. One that names none (an app up to 1.0.2) is taken when it came after this side offered.\n */\nexport function answersOffer(answer: Pick<CallSignal, \"ts\" | \"at\" | \"o\">, offerTs: number): boolean {\n return answer.o !== undefined ? answer.o === offerTs : callSignalHeardAt(answer) > offerTs;\n}\n\n/** The `v`/`k` pair of any signal. Returns null for a malformed one, `{}` when it says nothing. */\nfunction parsePicture(raw: Record<string, unknown>): Pick<CallSignal, \"v\" | \"k\"> | null {\n const picture: Pick<CallSignal, \"v\" | \"k\"> = {};\n if (raw.v !== undefined) {\n if (raw.v !== 0 && raw.v !== 1) return null;\n picture.v = raw.v;\n }\n if (raw.k !== undefined) {\n if (raw.k !== \"c\" && raw.k !== \"s\") return null;\n picture.k = raw.k;\n }\n return picture;\n}\n\n/**\n * Whether the peer that sent this offer or answer is sending a picture.\n *\n * Since v2 every call negotiates a video section, on or off, so the media list\n * no longer answers this: `v` does. A v1 peer sends no `v`, and there the video\n * section only carries an SSRC when it is really sending on it.\n */\nexport function signalHasVideo(signal: CallSignal | null): boolean {\n if (!signal) return false;\n if (signal.v !== undefined) return signal.v === 1;\n return (signal.m?.includes(\"v\") ?? false) && (signal.ss?.length ?? 0) > 1;\n}\n\n/**\n * Rebuilds an SDP around a signal. Only pass signals returned by {@link parseCallSignal}.\n *\n * Offer and answer are built the same way: which of the two this is comes from\n * the signal itself, as `a=setup:`, not from the caller.\n */\nexport function buildSdpFromSignal(signal: CallSignal): string {\n const hexPairs = signal.f!.match(/.{2}/g)!;\n const fingerprint = `sha-256 ${hexPairs.join(\":\")}`;\n \n const mediaOrder = signal.m ?? [\"a\"];\n \n // One session for every description of one connection (its fingerprint names it): a restart offer and its answer\n // describe the session the call already has, a version later.\n const sessionId = parseInt(signal.f!.slice(0, 12), 16);\n const sessionVersion = signal.t === \"r\" || signal.re !== undefined ? Math.max(3, Math.floor(signal.ts)) : 2;\n const audioSsrc = signal.ss?.[0] ?? Math.floor(Math.random() * 0xFFFFFFFF);\n const videoSsrc = signal.ss?.[1] ?? Math.floor(Math.random() * 0xFFFFFFFF);\n const opus = signal.ap ?? DEFAULT_OPUS_PT;\n const vp8 = signal.vp ?? DEFAULT_VP8_PT;\n\n const lines: string[] = [\n \"v=0\",\n `o=- ${sessionId} ${sessionVersion} IN IP4 127.0.0.1`,\n \"s=-\",\n \"t=0 0\",\n ];\n\n const mids = mediaOrder.map((_, i) => String(i));\n lines.push(`a=group:BUNDLE ${mids.join(\" \")}`);\n lines.push(\"a=msid-semantic: WMS stream\");\n\n mediaOrder.forEach((mediaType, idx) => {\n const mid = String(idx);\n \n if (mediaType === \"a\") {\n lines.push(\n `m=audio 9 UDP/TLS/RTP/SAVPF ${opus}`,\n \"c=IN IP4 0.0.0.0\",\n \"a=rtcp:9 IN IP4 0.0.0.0\",\n );\n for (const c of signal.c ?? []) {\n lines.push(`a=candidate:${c}`);\n }\n lines.push(\n \"a=end-of-candidates\",\n `a=ice-ufrag:${signal.u}`,\n `a=ice-pwd:${signal.p}`,\n `a=fingerprint:${fingerprint}`,\n `a=setup:${signal.s}`,\n `a=mid:${mid}`,\n \"a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\",\n \"a=sendrecv\",\n \"a=msid:stream audio0\",\n \"a=rtcp-mux\",\n `a=rtpmap:${opus} opus/48000/2`,\n `a=fmtp:${opus} minptime=10;useinbandfec=1`,\n `a=ssrc:${audioSsrc} cname:pkarr`,\n `a=ssrc:${audioSsrc} msid:stream audio0`,\n );\n } else if (mediaType === \"v\") {\n lines.push(\n `m=video 9 UDP/TLS/RTP/SAVPF ${vp8}`,\n \"c=IN IP4 0.0.0.0\",\n \"a=rtcp:9 IN IP4 0.0.0.0\",\n );\n for (const c of signal.c ?? []) {\n lines.push(`a=candidate:${c}`);\n }\n lines.push(\n \"a=end-of-candidates\",\n `a=ice-ufrag:${signal.u}`,\n `a=ice-pwd:${signal.p}`,\n `a=fingerprint:${fingerprint}`,\n `a=setup:${signal.s}`,\n `a=mid:${mid}`,\n // No header extensions here: their ids differ between engines, and an\n // answer that maps an id differently from the real offer is rejected\n // by Chromium (\"Failed to set recv parameters\").\n // `vr: 0`: the sender takes no picture and sends none, so the section is closed and names no stream.\n ...(signal.vr === 0 ? [\"a=inactive\"] : [\"a=sendrecv\", \"a=msid:stream video0\"]),\n \"a=rtcp-mux\",\n \"a=rtcp-rsize\",\n `a=rtpmap:${vp8} VP8/90000`,\n `a=rtcp-fb:${vp8} ccm fir`,\n `a=rtcp-fb:${vp8} nack`,\n `a=rtcp-fb:${vp8} nack pli`,\n `a=rtcp-fb:${vp8} goog-remb`,\n ...(signal.vr === 0 ? [] : [`a=ssrc:${videoSsrc} cname:pkarr`, `a=ssrc:${videoSsrc} msid:stream video0`]),\n );\n }\n });\n\n return lines.join(\"\\r\\n\") + \"\\r\\n\";\n}\n\n/** Whether a description carries any candidate: one without cannot be reached, nor reach anyone. */\nexport function sdpHasCandidates(sdp: string | undefined | null): boolean {\n return /^a=candidate:/m.test(sdp ?? \"\");\n}\n\n/**\n * How long to keep collecting after the candidate we were waiting for showed up (a call's; a chat's data link sets its\n * own, the same). The host candidates are in before it, and a call's signal keeps the first reflexive one only\n * (`pickCallCandidates`): 400 ms held every call's offer, and its answer, back that long for nothing it carried.\n */\nconst ICE_SETTLE_MS = 150;\n\n/** IPv4 ranges that are not reachable from the internet: this network, private, shared (CGNAT), loopback, link-local, the documentation ones, benchmarking, multicast and up. */\nconst NOT_GLOBAL_IPV4: readonly [number, number][] = [\n [0x00000000, 8], [0x0a000000, 8], [0x64400000, 10], [0x7f000000, 8], [0xa9fe0000, 16], [0xac100000, 12],\n [0xc0000000, 24], [0xc0000200, 24], [0xc0a80000, 16], [0xc6120000, 15], [0xc6336400, 24], [0xcb007100, 24], [0xe0000000, 3],\n];\n\n/**\n * Whether an ICE candidate is a UDP host candidate on a globally routable IPv4 address. A device on such an address (no\n * NAT) is told that very address and port by a STUN server, and Chromium drops a reflexive candidate equal to a host\n * one: no `typ srflx` ever comes. It shows the host's address only when it does not hide it behind an mDNS name (once\n * the origin may use the camera or the microphone), which is also when it drops that reflexive candidate. The host\n * candidate then says what the reflexive one would have.\n */\nexport function isGlobalIpv4Host(candidate: string): boolean {\n if (!/ udp /i.test(candidate) || !/ typ host( |$)/.test(candidate)) return false;\n const text = candidate.split(\" \")[4] ?? \"\";\n if (!/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(text)) return false;\n const octets = text.split(\".\").map(Number);\n if (octets.some((octet) => octet > 255)) return false;\n const address = octets.reduce((n, octet) => n * 256 + octet, 0);\n return !NOT_GLOBAL_IPV4.some(([base, bits]) => Math.floor(address / 2 ** (32 - bits)) === Math.floor(base / 2 ** (32 - bits)));\n}\n\n/**\n * Resolves when the local description is good enough to publish. Waiting for\n * gathering to *complete* takes the full timeout whenever one STUN server or\n * address family does not answer, which made every call ring ~10 s late. The\n * signal only carries a host and a server reflexive candidate anyway (plus a\n * relay one when TURN is configured), so that is what is waited for. Without\n * TURN, a host candidate on a global IPv4 address counts as the reflexive one\n * (`isGlobalIpv4Host`): a device with no NAT gets none, and its offers waited\n * the whole timeout whenever gathering did not complete.\n */\nexport function waitForIceGathering(\n pc: RTCPeerConnection,\n timeoutMs = 10000,\n /**\n * Give up after this long when not a single candidate showed up. Host candidates come in a few milliseconds; a\n * connection with none by then has stalled (Chromium, rarely, under load) and will not find any later.\n */\n {\n stallMs,\n /**\n * The description was just set on a connection that gathered before (an ICE restart): \"complete\" may still be\n * the last round's, so it only counts once the description has a candidate of this round.\n */\n fresh = false,\n /** How long to keep collecting after the candidate waited for showed up (`ICE_SETTLE_MS` by default). */\n settleMs = ICE_SETTLE_MS,\n /**\n * Give up waiting for that candidate after this long once the connection has any candidate (a host one comes in\n * milliseconds): what was gathered by then goes. Unset: up to `timeoutMs`.\n */\n hostBoundMs,\n }: { stallMs?: number; fresh?: boolean; settleMs?: number; hostBoundMs?: number } = {},\n): Promise<void> {\n return new Promise((resolve) => {\n if (pc.iceGatheringState === \"complete\" && (!fresh || sdpHasCandidates(pc.localDescription?.sdp))) {\n resolve();\n return;\n }\n\n const usesTurn = (pc.getConfiguration().iceServers ?? []).some((server) =>\n [server.urls].flat().some((url) => url.startsWith(\"turn\")),\n );\n const wanted = usesTurn ? \" typ relay\" : \" typ srflx\";\n let settle: ReturnType<typeof setTimeout> | null = null;\n let found = false;\n\n const finish = () => {\n clearTimeout(timeout);\n if (stalled) clearTimeout(stalled);\n if (bounded) clearTimeout(bounded);\n if (settle) clearTimeout(settle);\n pc.removeEventListener(\"icegatheringstatechange\", onState);\n pc.removeEventListener(\"icecandidate\", onCandidate);\n resolve();\n };\n const timeout = setTimeout(finish, timeoutMs);\n const stalled = stallMs === undefined ? null : setTimeout(() => {\n if (!found && !sdpHasCandidates(pc.localDescription?.sdp)) finish();\n }, stallMs);\n const bounded = hostBoundMs === undefined ? null : setTimeout(() => {\n if (found || sdpHasCandidates(pc.localDescription?.sdp)) finish();\n }, hostBoundMs);\n\n const onState = () => {\n if (pc.iceGatheringState === \"complete\" && (!fresh || sdpHasCandidates(pc.localDescription?.sdp))) finish();\n };\n const onCandidate = (event: RTCPeerConnectionIceEvent) => {\n if (event.candidate) found = true;\n const line = event.candidate?.candidate;\n if (!settle && line && (line.includes(wanted) || (!usesTurn && isGlobalIpv4Host(line)))) settle = setTimeout(finish, settleMs);\n };\n\n pc.addEventListener(\"icegatheringstatechange\", onState);\n pc.addEventListener(\"icecandidate\", onCandidate);\n });\n}\n","/**\n * Signaling for the WebRTC data link, carried in the `_rtc` record. It follows\n * the convention `_call` established: only what is unique to the session\n * travels through Pkarr and the SDP is rebuilt locally. The DTLS fingerprint\n * arrives inside a packet that is signed by the peer's key and encrypted with\n * the link key, which is what binds the WebRTC connection to the peer identity.\n */\nimport { isCandidateAddress, isGlobalIpv4Host } from \"./callSignal\";\n\nexport interface RtcSignal {\n t: \"o\" | \"a\";\n ts: number;\n /** For answers: `ts` of the offer being answered. */\n o?: number;\n /** ICE ufrag */\n u: string;\n /** ICE pwd */\n p: string;\n /** DTLS SHA-256 fingerprint, hex without separators */\n f: string;\n /** DTLS setup role */\n s: string;\n /** Candidates as `<h|s|r>,<address>,<port>` (host, server reflexive, relay) */\n c: string[];\n}\n\nexport const DATA_CHANNEL_LABEL = \"ghostly/1\";\nexport const DATA_CHANNEL_ID = 0;\n/** An offer older than this is ignored. */\nexport const RTC_SIGNAL_MAX_AGE_MS = 120_000;\n/** A signal dated further ahead of this clock than this is not taken: its time would outrank every later one of its sender. */\nexport const RTC_SIGNAL_FUTURE_MS = 10 * 60_000;\n/**\n * How this device saw a signal come. `since`: when its read of the maker's record that did not have the signal began,\n * by this clock; only a read the network answered counts, never a copy kept from before. `after`: the time of the\n * maker's own packet that read found, by the maker's clock; null when that read found none of the maker's.\n */\nexport interface SignalSight { since: number; after: number | null; live?: boolean }\n/**\n * Whether an offer its maker dated `ts` is recent enough to answer.\n *\n * With a `sight`, two things place it in time without holding the maker's clock against this one. It was not in the\n * maker's record at `since`, so it reached the record after that; and it is not dated before the maker's packet that\n * was there (`after`, the same clock as `ts`), so it was not made before that packet either. An offer made earlier and\n * put in the record again later fails the second. Its time is then held between `since` and now, and only this clock\n * measures its age.\n *\n * When that read found nothing of the maker's (`after` null: a first contact), there is no packet to hold the offer\n * against, and a record that looked empty a moment ago is weaker ground: the offer's own time then has to be within\n * `RTC_SIGNAL_FUTURE_MS` of this clock too, which is as far as two clocks are taken to differ.\n *\n * Without a sight (the first read of a run found the offer) its own time is all there is to go by, and it may differ\n * from this clock by the age allowed, either way.\n */\nexport function offerIsFresh(ts: number, sight?: SignalSight, now = Date.now()): boolean {\n if (!sight) return Math.abs(now - ts) <= RTC_SIGNAL_MAX_AGE_MS;\n if (!sight.live && sight.after !== null && ts < sight.after) return false;\n if (!sight.live && sight.after === null && Math.abs(now - ts) > RTC_SIGNAL_FUTURE_MS) return false;\n return now - Math.max(sight.since, Math.min(ts, now)) <= RTC_SIGNAL_MAX_AGE_MS;\n}\nconst MAX_MESSAGE_SIZE = 262_144;\n\nconst CANDIDATE_TYPES = { host: \"h\", srflx: \"s\", relay: \"r\" } as const;\nconst CANDIDATE_LIMITS: Record<string, number> = { h: 2, s: 2, r: 1 };\nconst CANDIDATE_PRIORITY: Record<string, number> = { h: 2122260223, s: 1686052607, r: 41885439 };\nconst CANDIDATE_TYPE_NAME: Record<string, string> = { h: \"host\", s: \"srflx\", r: \"relay\" };\n\n/**\n * The signal carries two host candidates, and a computer often has more interfaces than that: Wi-Fi, Ethernet, VM\n * bridges, Tailscale, a VPN. The browser lists them in its own order, and the first two are not always ones the\n * contact can reach: on a Mac with two VM bridges they are the bridges (addresses that exist on that Mac only), and\n * the Wi-Fi and Ethernet addresses never left it, so a contact on the same network was reached only if the router\n * sends a packet for its own public address back in (2026-10-02). So host candidates go in this order of preference:\n * those a server reflexive candidate was gathered from (`raddr`: an interface with a way out, the network a contact\n * nearby shares), then the others, and in each case those the browser marks as costly last (`network-cost` 50 or\n * more: a VPN, or an interface it does not know), as a call's candidates do (`pickCallCandidates`). A host on a\n * global IPv4 address has a way out too: it gets no reflexive candidate (Chromium drops one equal to a host), and the\n * gathering wait ends on it (`isGlobalIpv4Host`). That wait ends 400 ms after the first reflexive candidate, so only\n * the interfaces whose STUN answer came by then are known to have a way out. With no reflexive candidate, or none\n * that says where it came from, the order is the browser's, as before.\n */\nfunction hostRank(parts: string[], reflexiveBases: ReadonlySet<string>): number {\n const cost = Number(parts[parts.indexOf(\"network-cost\") + 1]);\n const costly = parts.includes(\"network-cost\") && cost >= 50;\n const wayOut = reflexiveBases.has(parts[4]) || isGlobalIpv4Host(parts.join(\" \"));\n return (costly ? 2 : 0) + (wayOut ? 0 : 1);\n}\n\n/** `relayOnly` (\"Hide my IP from contacts\", the connection keeps to relays): relay candidates only, whatever else is in the SDP. */\nexport function extractRtcParams(sdp: string, { relayOnly = false }: { relayOnly?: boolean } = {}): Pick<RtcSignal, \"u\" | \"p\" | \"f\" | \"s\" | \"c\"> {\n let u = \"\";\n let p = \"\";\n let f = \"\";\n let s = \"\";\n /** UDP component-1 candidates of a type the signal carries, in the SDP's order. */\n const found: { type: string; parts: string[]; compact: string }[] = [];\n const reflexiveBases = new Set<string>();\n\n for (const line of sdp.split(/\\r?\\n/)) {\n if (line.startsWith(\"a=ice-ufrag:\") && !u) u = line.slice(\"a=ice-ufrag:\".length);\n else if (line.startsWith(\"a=ice-pwd:\") && !p) p = line.slice(\"a=ice-pwd:\".length);\n else if (line.toLowerCase().startsWith(\"a=fingerprint:sha-256 \") && !f) {\n f = line.slice(\"a=fingerprint:sha-256 \".length).replace(/:/g, \"\").toLowerCase();\n } else if (line.startsWith(\"a=setup:\") && !s) s = line.slice(\"a=setup:\".length);\n else if (line.startsWith(\"a=candidate:\")) {\n // foundation component transport priority address port typ <type> [raddr <address> rport <port>] ...\n const parts = line.slice(\"a=candidate:\".length).split(\" \");\n if (parts.length < 8 || parts[1] !== \"1\" || parts[2].toLowerCase() !== \"udp\") continue;\n const type = CANDIDATE_TYPES[parts[7] as keyof typeof CANDIDATE_TYPES];\n if (!type || (relayOnly && type !== \"r\")) continue;\n const compact = `${type},${parts[4]},${parts[5]}`;\n if (found.some((c) => c.compact === compact)) continue;\n found.push({ type, parts, compact });\n // A browser that hides local addresses says `raddr 0.0.0.0`: nothing to match then.\n const base = type === \"s\" && parts.includes(\"raddr\") ? parts[parts.indexOf(\"raddr\") + 1] : undefined;\n if (base && base !== \"0.0.0.0\" && base !== \"::\") reflexiveBases.add(base);\n }\n }\n // The host candidates the signal has room for, by preference; every type then goes out in the SDP's order.\n const hosts = found.filter((c) => c.type === \"h\");\n const preferred = new Set(hosts.map((c, at) => ({ c, at, rank: hostRank(c.parts, reflexiveBases) }))\n .sort((a, b) => a.rank - b.rank || a.at - b.at).slice(0, CANDIDATE_LIMITS.h).map(({ c }) => c));\n const candidates: string[] = [];\n const counts: Record<string, number> = { h: 0, s: 0, r: 0 };\n for (const c of found) {\n if (c.type === \"h\" ? !preferred.has(c) : counts[c.type] >= CANDIDATE_LIMITS[c.type]) continue;\n counts[c.type]++;\n candidates.push(c.compact);\n }\n return { u, p, f, s, c: candidates };\n}\n\nconst SAFE_TOKEN = /^[A-Za-z0-9+/=_-]{1,256}$/;\nconst SAFE_ADDRESS = /^[A-Za-z0-9.:-]{1,64}$/;\n\n/** Validates an untrusted signal; anything that could inject SDP lines is rejected. */\nexport function parseRtcSignal(json: string): RtcSignal | null {\n let raw: Partial<RtcSignal>;\n try {\n raw = JSON.parse(json);\n } catch {\n return null;\n }\n if (!raw || typeof raw !== \"object\") return null;\n if (raw.t !== \"o\" && raw.t !== \"a\") return null;\n if (typeof raw.ts !== \"number\" || !Number.isFinite(raw.ts)) return null;\n if (raw.o !== undefined && typeof raw.o !== \"number\") return null;\n if (typeof raw.u !== \"string\" || !SAFE_TOKEN.test(raw.u)) return null;\n if (typeof raw.p !== \"string\" || !SAFE_TOKEN.test(raw.p)) return null;\n if (typeof raw.f !== \"string\" || !/^[0-9a-fA-F]{64}$/.test(raw.f)) return null;\n if (raw.s !== \"actpass\" && raw.s !== \"active\" && raw.s !== \"passive\") return null;\n if (!Array.isArray(raw.c) || raw.c.length > 8) return null;\n for (const c of raw.c) {\n if (typeof c !== \"string\") return null;\n const [type, address, port] = c.split(\",\");\n if (!CANDIDATE_TYPE_NAME[type] || !SAFE_ADDRESS.test(address ?? \"\") || !/^\\d{1,5}$/.test(port ?? \"\")) {\n return null;\n }\n }\n // A candidate on a name other than a browser's mDNS one is skipped (`isCandidateAddress`).\n const c = raw.c.filter((candidate: string) => isCandidateAddress(candidate.split(\",\")[1]));\n return { t: raw.t, ts: raw.ts, o: raw.o, u: raw.u, p: raw.p, f: raw.f, s: raw.s, c };\n}\n\nexport function buildDataSdp(signal: RtcSignal): string {\n const fingerprint = signal.f.toUpperCase().match(/.{2}/g)!.join(\":\");\n const sessionId = Math.floor(Math.random() * 1e15);\n\n const lines = [\n \"v=0\",\n `o=- ${sessionId} 2 IN IP4 127.0.0.1`,\n \"s=-\",\n \"t=0 0\",\n \"a=group:BUNDLE 0\",\n \"a=msid-semantic: WMS\",\n \"m=application 9 UDP/DTLS/SCTP webrtc-datachannel\",\n \"c=IN IP4 0.0.0.0\",\n ];\n signal.c.forEach((c, index) => {\n const [type, address, port] = c.split(\",\");\n const priority = CANDIDATE_PRIORITY[type] - index;\n let line = `a=candidate:${index + 1} 1 udp ${priority} ${address} ${port} typ ${CANDIDATE_TYPE_NAME[type]}`;\n if (type !== \"h\") line += \" raddr 0.0.0.0 rport 0\";\n lines.push(line);\n });\n lines.push(\n \"a=end-of-candidates\",\n `a=ice-ufrag:${signal.u}`,\n `a=ice-pwd:${signal.p}`,\n `a=fingerprint:sha-256 ${fingerprint}`,\n `a=setup:${signal.s}`,\n \"a=mid:0\",\n \"a=sctp-port:5000\",\n `a=max-message-size:${MAX_MESSAGE_SIZE}`,\n );\n return lines.join(\"\\r\\n\") + \"\\r\\n\";\n}\n","import { utf8Encode } from \"./bytes\";\nimport { sanitizeNick } from \"./text\";\n\n/**\n * Framing on the `ghostly/1` DataChannel (ordered, reliable).\n *\n * - Text messages are control frames: compact JSON with a `t` discriminator,\n * the same shape Ghostly already uses for `_msgs` and `_call`.\n * - Binary messages are body chunks that belong to a stream opened by a\n * control frame: `<kind u8><stream id u32 BE><flags u8><payload>`.\n *\n * Everything here handles data from the remote peer and must never trust it.\n */\nexport const LIMITS = {\n /** Largest control frame accepted, headers included. */\n maxControlFrameBytes: 60 * 1024,\n /** Longest payment endpoint value (a Cashu token, an invoice) a payment frame may carry; a longer one is dropped. */\n maxPaymentEndpointChars: 32 * 1024,\n /** Largest DataChannel message sent. 16 KiB is safe across WebRTC stacks. */\n maxChunkMessageBytes: 16 * 1024,\n maxRequestBodyBytes: 8 * 1024 * 1024,\n maxResponseBodyBytes: 64 * 1024 * 1024,\n maxHeaderCount: 128,\n maxHeaderValueBytes: 16 * 1024,\n maxPathBytes: 8 * 1024,\n /** Requests a host serves at once for one peer. */\n maxConcurrentRequestsPerPeer: 32,\n /**\n * Request-body bytes a host holds for one peer at once, from a body's first chunk until its local fetch settles.\n * Past it a request is refused (`busy`). As much as a client's in-flight requests can carry, so only a peer that\n * ignores that limit reaches it.\n */\n maxHostBodyBytesPerPeer: 16 * 8 * 1024 * 1024,\n /** Requests a client keeps in flight; the rest wait in a queue. */\n maxClientInFlight: 16,\n /**\n * Requests, and their bodies' bytes, a client keeps waiting for a slot: past either, a request is refused at once\n * (`busy`), so whatever asks (a contact's app in a viewer) cannot make it hold unbounded memory.\n */\n maxClientWaiting: 64,\n maxClientWaitingBodyBytes: 64 * 1024 * 1024,\n /**\n * Response-body bytes a client holds for one response before whatever reads it took them. Past it, a response its\n * reader takes nothing of for `unreadStallMs` is reset: its reader stalled. Four times what a host keeps buffered on\n * the link (`sendHighWaterMark`), so a reader that keeps up never reaches it.\n */\n maxUnreadResponseBytes: 4 * 1024 * 1024,\n /**\n * How long a reader past `maxUnreadResponseBytes` may take nothing before its response is reset. One that keeps\n * reading, only slower than the link (a video playing as it arrives, a contact's app read through the web's services\n * worker), is not cut: it holds up to the response's own bound.\n */\n unreadStallMs: 2_000,\n /**\n * Response-body bytes a client holds for all its responses before their readers took them. Past it, a response over\n * `maxUnreadResponseBytes` is reset at once, its reader's pace aside: one slow reader keeps its whole response (as\n * much as `maxResponseBodyBytes`), but many cannot add up (a contact's app reading each answer a chunk at a time).\n */\n maxClientUnreadResponseBytes: 64 * 1024 * 1024,\n maxChatMessageBytes: 16 * 1024,\n maxFileBytes: 100 * 1024 * 1024,\n /** Files a peer may be sending us at once. */\n maxIncomingFilesPerPeer: 3,\n /** Received bytes kept for one peer, in flight included. Past it new files are refused. */\n maxStoredIncomingBytesPerPeer: 500 * 1024 * 1024,\n requestTimeoutMs: 60_000,\n bodyIdleTimeoutMs: 30_000,\n /**\n * What a request body must bring in each `bodyIdleTimeoutMs` (unless it ends) to count as moving: a peer that sends a\n * few bytes at a time is let go like one that stalls.\n */\n minRequestBodyBytesPerIdle: 16 * 1024,\n /** Stop writing to the channel above this many buffered bytes. */\n sendHighWaterMark: 1024 * 1024,\n sendLowWaterMark: 256 * 1024,\n} as const;\n\nexport const PROTOCOL_VERSION = 1;\n\nexport const CHUNK_KIND = { requestBody: 1, responseBody: 2, fileBody: 3 } as const;\nexport type ChunkKind = (typeof CHUNK_KIND)[keyof typeof CHUNK_KIND];\n\nexport const CHUNK_FLAG_END = 1;\nconst CHUNK_HEADER_BYTES = 6;\nexport const MAX_CHUNK_PAYLOAD_BYTES = LIMITS.maxChunkMessageBytes - CHUNK_HEADER_BYTES;\n\nexport type HeaderList = [string, string][];\n\n/** First frame in each direction once the channel opens. */\nexport interface HelloFrame {\n t: \"hello\";\n v: number;\n /** Authoritative service list, same wire shape as the `_svc` record. */\n svc: unknown;\n nick?: string;\n}\n\n/** Chat message. Used instead of `_msgs` while the data link is up. */\nexport interface ChatFrame {\n t: \"m\";\n ts: number;\n m: string;\n}\n\n/** A `_call` signal, sent here as well so a connected peer rings without waiting for its next poll. */\nexport interface CallFrame {\n t: \"call\";\n s: string;\n}\n\n/** Updated service list while connected. */\nexport interface ServicesFrame {\n t: \"svc\";\n svc: unknown;\n}\n\nexport interface HttpRequestFrame {\n t: \"req\";\n id: number;\n /** Service id. The host maps it to a target; the peer never names a URL. */\n s: string;\n m: string;\n /** Origin-form path with query, e.g. `/api/items?page=2` */\n p: string;\n h: HeaderList;\n /** True when request body chunks follow. */\n b: boolean;\n}\n\nexport interface HttpResponseFrame {\n t: \"res\";\n id: number;\n st: number;\n h: HeaderList;\n /** True when response body chunks follow. */\n b: boolean;\n}\n\n/** Announces a file; its bytes follow as `fileBody` chunks on stream `id`. */\nexport interface FileFrame {\n t: \"file\";\n id: number;\n /** File id chosen by the sender, unique within the link. */\n f: string;\n ts: number;\n n: string;\n /** Size in bytes. The transfer fails unless exactly this many arrive. */\n s: number;\n m: string;\n}\n\n/**\n * A way to get paid, in Paykit's terms: a Payment Endpoint Identifier\n * (`btc-lightning-bolt11`, `cashu`, …) and its payload (an invoice, the mints\n * accepted, …). See `payments.ts`.\n */\nexport type WireEndpoint = [identifier: string, payload: string];\n\n/** Payment Request: the sender asks to be paid. */\nexport interface PayRequestFrame {\n t: \"pay-req\";\n /** Request id, chosen by the payee. */\n id: string;\n ts: number;\n /** Decimal amount as text, and its asset (`sat`). */\n v: string;\n u: string;\n memo?: string;\n e: WireEndpoint[];\n /** The `pay-ask` this answers, if any. */\n a?: string;\n /**\n * `mainnet` (real money) or `testnet` (test coins): what pays it. Absent from apps before wallets had their own\n * network; the endpoints tell then (a test mint, a test chain).\n */\n n?: \"mainnet\" | \"testnet\";\n}\n\n/** A payer asking to pay: the payee answers with a `pay-req` whose `a` is this id. */\nexport interface PayAskFrame {\n t: \"pay-ask\";\n id: string;\n ts: number;\n v: string;\n u: string;\n m: \"arkade\" | \"usdt\" | \"bark\" | \"bitcoin\" | \"fedimint\" | \"spark\";\n memo?: string;\n /** The network the payer will pay from: the payee answers from its wallet of that network. */\n n?: \"mainnet\" | \"testnet\";\n}\n\n/** A payment that travels in band, such as an ecash token. */\nexport interface PayFrame {\n t: \"pay\";\n id: string;\n ts: number;\n /** The request this settles, if any. */\n rid?: string;\n v: string;\n u: string;\n memo?: string;\n /** The endpoint used and the payment itself. */\n e: WireEndpoint;\n}\n\n/** What became of a payment or a request: the payee's receipt, or a refusal. */\nexport interface PayResultFrame {\n t: \"pay-res\";\n /** Id of the `pay` or `pay-req` frame this answers. */\n id: string;\n ok: boolean;\n /** Amount credited, when it differs from what was sent (fees). */\n v?: string;\n err?: string;\n /** On the payee's own `pay-req`: closed for good, never to be paid (its wallet was removed). */\n c?: true;\n}\n\n/** Aborts a stream in either direction. */\nexport interface ResetFrame {\n t: \"rst\";\n id: number;\n /** Which stream: `q` a request I sent, `s` a response I am sending, `f` a file (either side). */\n d: \"q\" | \"s\" | \"f\";\n e: string;\n}\n\nexport interface PingFrame {\n t: \"ping\" | \"pong\";\n ts: number;\n}\n\nexport type ControlFrame =\n | PayAskFrame\n | HelloFrame\n | ChatFrame\n | CallFrame\n | ServicesFrame\n | HttpRequestFrame\n | HttpResponseFrame\n | FileFrame\n | PayRequestFrame\n | PayFrame\n | PayResultFrame\n | ResetFrame\n | PingFrame;\n\nexport interface ChunkFrame {\n kind: ChunkKind;\n id: number;\n end: boolean;\n payload: Uint8Array;\n}\n\nexport function encodeControl(frame: ControlFrame): string {\n const json = JSON.stringify(frame);\n if (utf8Encode(json).length > LIMITS.maxControlFrameBytes) throw new Error(\"Control frame too large\");\n return json;\n}\n\nfunction isHeaderList(value: unknown): value is HeaderList {\n if (!Array.isArray(value) || value.length > LIMITS.maxHeaderCount) return false;\n return value.every(\n (h) =>\n Array.isArray(h) &&\n h.length === 2 &&\n typeof h[0] === \"string\" &&\n typeof h[1] === \"string\" &&\n h[0].length <= 256 &&\n h[1].length <= LIMITS.maxHeaderValueBytes,\n );\n}\n\nfunction isStreamId(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 && value <= 0xffffffff;\n}\n\nfunction isPayId(value: unknown): value is string {\n return typeof value === \"string\" && /^[A-Za-z0-9_-]{8,64}$/.test(value);\n}\n\n/** Decimal text, as in Paykit's Payment Amount: no floats on the wire. */\nfunction isAmount(value: unknown): value is string {\n return typeof value === \"string\" && /^(0|[1-9]\\d{0,15})(\\.\\d{1,8})?$/.test(value);\n}\n\nfunction isUnit(value: unknown): value is string {\n return typeof value === \"string\" && /^[a-z0-9]{1,12}$/.test(value);\n}\n\nfunction isEndpoint(value: unknown): value is WireEndpoint {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === \"string\" &&\n value[0].length <= 64 &&\n /^[a-z0-9][a-z0-9-]*(?:\\/[1-9][0-9]*)?$/.test(value[0]) &&\n typeof value[1] === \"string\" &&\n value[1].length <= LIMITS.maxPaymentEndpointChars\n );\n}\n\n/** Returns null for anything malformed; callers drop the frame. */\nexport function decodeControl(text: string): ControlFrame | null {\n // A character is at least one byte: the cheap check first, then the real one.\n if (text.length > LIMITS.maxControlFrameBytes || utf8Encode(text).length > LIMITS.maxControlFrameBytes) return null;\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch {\n return null;\n }\n if (!raw || typeof raw !== \"object\") return null;\n const f = raw as Record<string, unknown>;\n\n switch (f.t) {\n case \"hello\":\n if (typeof f.v !== \"number\") return null;\n return { t: \"hello\", v: f.v, svc: f.svc, nick: sanitizeNick(f.nick) };\n case \"m\":\n if (typeof f.ts !== \"number\" || typeof f.m !== \"string\") return null;\n if (utf8Encode(f.m).length > LIMITS.maxChatMessageBytes) return null;\n return { t: \"m\", ts: f.ts, m: f.m };\n case \"call\":\n if (typeof f.s !== \"string\" || utf8Encode(f.s).length > LIMITS.maxChatMessageBytes) return null;\n return { t: \"call\", s: f.s };\n case \"svc\":\n return { t: \"svc\", svc: f.svc };\n case \"req\":\n if (!isStreamId(f.id) || typeof f.s !== \"string\" || typeof f.m !== \"string\") return null;\n if (typeof f.p !== \"string\" || f.p.length > LIMITS.maxPathBytes || !isHeaderList(f.h)) return null;\n return { t: \"req\", id: f.id, s: f.s, m: f.m, p: f.p, h: f.h, b: f.b === true };\n case \"res\":\n if (!isStreamId(f.id) || typeof f.st !== \"number\" || !Number.isInteger(f.st)) return null;\n if (f.st < 100 || f.st > 599 || !isHeaderList(f.h)) return null;\n return { t: \"res\", id: f.id, st: f.st, h: f.h, b: f.b === true };\n case \"file\":\n if (!isStreamId(f.id) || typeof f.f !== \"string\" || typeof f.ts !== \"number\") return null;\n if (typeof f.n !== \"string\" || typeof f.m !== \"string\") return null;\n if (typeof f.s !== \"number\" || !Number.isSafeInteger(f.s) || f.s < 0) return null;\n return { t: \"file\", id: f.id, f: f.f, ts: f.ts, n: f.n, s: f.s, m: f.m };\n case \"pay-req\":\n case \"pay\": {\n if (!isPayId(f.id) || typeof f.ts !== \"number\" || !isAmount(f.v) || !isUnit(f.u)) return null;\n const memo = typeof f.memo === \"string\" ? f.memo.slice(0, 140) : undefined;\n if (f.t === \"pay-req\") {\n if (!Array.isArray(f.e) || f.e.length === 0 || f.e.length > 8 || !f.e.every(isEndpoint)) return null;\n return { t: \"pay-req\", id: f.id, ts: f.ts, v: f.v, u: f.u, memo, e: f.e, a: isPayId(f.a) ? f.a : undefined, n: f.n === \"mainnet\" || f.n === \"testnet\" ? f.n : undefined };\n }\n if (!isEndpoint(f.e) || (f.rid !== undefined && !isPayId(f.rid))) return null;\n return { t: \"pay\", id: f.id, ts: f.ts, rid: f.rid, v: f.v, u: f.u, memo, e: f.e };\n }\n case \"pay-ask\": {\n if (!isPayId(f.id) || typeof f.ts !== \"number\" || !isAmount(f.v) || !isUnit(f.u)) return null;\n if (f.m !== \"arkade\" && f.m !== \"usdt\" && f.m !== \"bark\" && f.m !== \"bitcoin\" && f.m !== \"fedimint\" && f.m !== \"spark\") return null;\n return { t: \"pay-ask\", id: f.id, ts: f.ts, v: f.v, u: f.u, m: f.m, memo: typeof f.memo === \"string\" ? f.memo.slice(0, 140) : undefined, n: f.n === \"mainnet\" || f.n === \"testnet\" ? f.n : undefined };\n }\n case \"pay-res\":\n if (!isPayId(f.id) || typeof f.ok !== \"boolean\") return null;\n if (f.v !== undefined && !isAmount(f.v)) return null;\n return { t: \"pay-res\", id: f.id, ok: f.ok, v: f.v, err: typeof f.err === \"string\" ? f.err.slice(0, 200) : undefined, ...(f.c === true && !f.ok ? { c: true as const } : {}) };\n case \"rst\":\n if (!isStreamId(f.id) || (f.d !== \"q\" && f.d !== \"s\" && f.d !== \"f\")) return null;\n return { t: \"rst\", id: f.id, d: f.d, e: typeof f.e === \"string\" ? f.e.slice(0, 256) : \"\" };\n case \"ping\":\n case \"pong\":\n if (typeof f.ts !== \"number\") return null;\n return { t: f.t, ts: f.ts };\n default:\n return null;\n }\n}\n\nexport function encodeChunk(chunk: ChunkFrame): Uint8Array {\n if (chunk.payload.length > MAX_CHUNK_PAYLOAD_BYTES) throw new Error(\"Chunk payload too large\");\n const out = new Uint8Array(CHUNK_HEADER_BYTES + chunk.payload.length);\n const view = new DataView(out.buffer);\n view.setUint8(0, chunk.kind);\n view.setUint32(1, chunk.id);\n view.setUint8(5, chunk.end ? CHUNK_FLAG_END : 0);\n out.set(chunk.payload, CHUNK_HEADER_BYTES);\n return out;\n}\n\nexport function decodeChunk(data: Uint8Array): ChunkFrame | null {\n if (data.length < CHUNK_HEADER_BYTES || data.length > LIMITS.maxChunkMessageBytes) return null;\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const kind = view.getUint8(0);\n if (kind !== CHUNK_KIND.requestBody && kind !== CHUNK_KIND.responseBody && kind !== CHUNK_KIND.fileBody) return null;\n return {\n kind,\n id: view.getUint32(1),\n end: (view.getUint8(5) & CHUNK_FLAG_END) !== 0,\n payload: data.subarray(CHUNK_HEADER_BYTES),\n };\n}\n\n/**\n * The slice of RTCDataChannel the protocol needs. Tests use an in-memory pair,\n * platforms wrap a real channel with `wrapDataChannel`.\n */\nexport interface FrameChannel {\n send(data: string | Uint8Array): void;\n readonly bufferedAmount: number;\n /** Resolves once the send buffer has drained below the low water mark. */\n drained(): Promise<void>;\n /**\n * Bytes the channel queues before `send` throws (the native and iroh channels). Absent: it buffers freely, as a\n * WebRTC data channel does, and a sender only keeps under `LIMITS.sendHighWaterMark`.\n */\n readonly sendBudget?: number;\n /**\n * It carries binary messages as well as text (WISP 100 § Text and binary messages): a WebRTC data channel does.\n * Absent: text only, as the Iroh channels are, and nothing binary is offered or sent on it.\n */\n readonly binary?: boolean;\n /**\n * A frame the transport sends on this connection by itself as the app exits, should the page not be there to say it\n * (the Desktop's native channels: a logout ends the WebView's processes with the app); null takes it back. Absent:\n * whatever the page does not say on its way out is not said.\n */\n parting?(frame: string | null): void;\n close(): void;\n onMessage: ((data: string | Uint8Array) => void) | null;\n onClose: (() => void) | null;\n}\n\n/**\n * `ended`: its connection was torn down. The channel closes then as if the data channel had said so, and lets go of\n * the data channel's events: node-datachannel does not always report a channel of a closed connection closed, and its\n * native handle would hold whatever listens to it (the session, the link) for good.\n */\nexport function wrapDataChannel(dc: RTCDataChannel, ended?: AbortSignal): FrameChannel {\n dc.binaryType = \"arraybuffer\";\n dc.bufferedAmountLowThreshold = LIMITS.sendLowWaterMark;\n const listening = new AbortController();\n const closed = () => {\n if (listening.signal.aborted) return;\n listening.abort();\n channel.onClose?.();\n };\n\n const channel: FrameChannel = {\n send(data) {\n if (dc.readyState !== \"open\") throw new Error(\"Data link is not open\");\n if (typeof data === \"string\") dc.send(data);\n else dc.send(data as unknown as ArrayBuffer);\n },\n get bufferedAmount() {\n return dc.bufferedAmount;\n },\n drained() {\n if (dc.bufferedAmount <= LIMITS.sendLowWaterMark || dc.readyState !== \"open\" || listening.signal.aborted) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const done = () => {\n dc.removeEventListener(\"bufferedamountlow\", done);\n listening.signal.removeEventListener(\"abort\", done);\n resolve();\n };\n dc.addEventListener(\"bufferedamountlow\", done);\n listening.signal.addEventListener(\"abort\", done);\n });\n },\n close() {\n dc.close();\n },\n binary: true,\n onMessage: null,\n onClose: null,\n };\n\n const { signal } = listening;\n dc.addEventListener(\"message\", (event) => {\n const data = event.data;\n if (typeof data === \"string\") channel.onMessage?.(data);\n else if (data instanceof ArrayBuffer) channel.onMessage?.(new Uint8Array(data));\n }, { signal });\n dc.addEventListener(\"close\", closed, { signal });\n ended?.addEventListener(\"abort\", closed, { signal });\n return channel;\n}\n\n/**\n * Resolves once the channel has room for a body's next chunk; undefined when it has now. A channel with a send budget\n * (native and iroh ones throw past 120 KiB) gives a body a quarter of it, as files/3 keeps to, so a ping or a message\n * still fits beside it; others keep under the high water mark.\n */\nfunction bodyRoom(channel: FrameChannel, isCancelled: () => boolean): Promise<void> | undefined {\n if (!channel.sendBudget) return channel.bufferedAmount > LIMITS.sendHighWaterMark ? channel.drained() : undefined;\n const line = channel.sendBudget / 4;\n if (channel.bufferedAmount < line) return;\n return (async () => {\n while (!isCancelled() && channel.bufferedAmount >= line) {\n await channel.drained().catch(() => {});\n // A drain that resolved above the line (a low water mark higher than it) is not waited on in a loop of promises.\n if (!isCancelled() && channel.bufferedAmount >= line) await new Promise((resolve) => setTimeout(resolve, 20));\n }\n })();\n}\n\n/** Writes a body as chunks, honouring backpressure. Always ends with an END chunk. */\nexport async function sendBody(\n channel: FrameChannel,\n kind: ChunkKind,\n id: number,\n body: AsyncIterable<Uint8Array> | Iterable<Uint8Array>,\n isCancelled: () => boolean = () => false,\n): Promise<void> {\n for await (const part of body) {\n for (let offset = 0; offset < part.length; offset += MAX_CHUNK_PAYLOAD_BYTES) {\n if (isCancelled()) return;\n const room = bodyRoom(channel, isCancelled);\n if (room) {\n await room;\n if (isCancelled()) return;\n }\n const payload = part.subarray(offset, offset + MAX_CHUNK_PAYLOAD_BYTES);\n channel.send(encodeChunk({ kind, id, end: false, payload }));\n }\n }\n if (isCancelled()) return;\n channel.send(encodeChunk({ kind, id, end: true, payload: new Uint8Array(0) }));\n}\n","import { concatBytes, utf8Encode } from \"./bytes\";\nimport {\n CHUNK_KIND,\n LIMITS,\n encodeControl,\n sendBody,\n type ChunkFrame,\n type FrameChannel,\n type HeaderList,\n type HttpRequestFrame,\n type HttpResponseFrame,\n type ResetFrame,\n} from \"./frames\";\n\n/**\n * HTTP over the Ghostly data link (`ghostly-http/1`).\n *\n * The client names a service id and an origin-form path. The host owns the\n * mapping from service id to a loopback target the user configured; nothing a\n * remote peer sends can change where a request goes.\n */\n\n// ---------------------------------------------------------------------------\n// Local targets\n// ---------------------------------------------------------------------------\n\nexport interface LocalTarget {\n /** e.g. `http://localhost:3400` */\n origin: string;\n /** Path prefix without trailing slash, `\"\"` for the root. */\n basePath: string;\n}\n\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** Accepts `localhost:3400`, `http://127.0.0.1:8080/app`, … and nothing that is not loopback. */\nexport function parseLocalTarget(input: string): LocalTarget {\n let text = input.trim();\n if (!/^[a-z][a-z0-9+.-]*:\\/\\//i.test(text)) text = `http://${text}`;\n let url: URL;\n try {\n url = new URL(text);\n } catch {\n throw new Error(\"Not a valid URL\");\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") throw new Error(\"Only http and https targets are supported\");\n if (url.username || url.password) throw new Error(\"Credentials in the target URL are not supported\");\n if (!LOOPBACK_HOSTS.has(url.hostname)) {\n throw new Error(\"Only services on this machine can be shared (localhost, 127.0.0.1 or [::1])\");\n }\n if (url.search || url.hash) throw new Error(\"The target cannot contain a query or fragment\");\n // Port 0 asks the system for any free port when listening: nothing ever answers on it, so every contact who opened\n // the service got a failure that said nothing about why.\n if (url.port === \"0\") throw new Error(\"Port 0 is not a port a web app can listen on\");\n return { origin: url.origin, basePath: url.pathname.replace(/\\/+$/, \"\") };\n}\n\nexport function formatLocalTarget(target: LocalTarget): string {\n return `${target.origin}${target.basePath}`;\n}\n\n/**\n * Whether one segment of a path may read as `..` (or `.`, or hold a separator) on some server, though the URL parser\n * kept it: servers that drop a segment's `;params` before they normalize (Tomcat, Jetty, older Spring) read `..;` and\n * `..;jsessionid=1` as `..`, and one that decodes twice (a proxy in front of the app) reads `%252e%252e` as `..`.\n */\nfunction climbsOut(segment: string): boolean {\n // A plain `.` or `..` is the URL parser's to resolve, and the base path check below sees where it lands.\n if (segment === \".\" || segment === \"..\") return false;\n let text = segment;\n for (let round = 0; round < 4; round++) {\n const bare = text.split(\";\")[0];\n if (bare === \".\" || bare === \"..\" || /[/\\\\]/.test(text)) return true;\n let decoded: string;\n try {\n decoded = decodeURIComponent(text);\n } catch {\n return false;\n }\n if (decoded === text) return false;\n text = decoded;\n }\n return true;\n}\n\n/**\n * Resolves a peer-supplied path against the configured target. Returns null\n * unless the result stays on the target origin and under its base path.\n */\nexport function resolveTargetUrl(target: LocalTarget, path: string): string | null {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) return null;\n for (const char of path) {\n const code = char.codePointAt(0) ?? 0;\n if (code <= 32 || code === 127) return null;\n }\n const queryAt = path.indexOf(\"?\");\n const pathPart = queryAt === -1 ? path : path.slice(0, queryAt);\n // Some servers read `\\` in the path as `/`. In the query a browser's fetch leaves it raw (`?path=C:\\x`), so it passes.\n if (pathPart.includes(\"\\\\\")) return null;\n // Encoded separators survive URL normalization here but not in every server:\n // one that decodes `%2f` before routing would take `/app/..%2fadmin` to `/admin`.\n if (/%(2f|5c|2e)/i.test(pathPart)) return null;\n if (pathPart.split(\"/\").some(climbsOut)) return null;\n let url: URL;\n try {\n url = new URL(`${target.origin}${target.basePath}${path}`);\n } catch {\n return null;\n }\n if (url.origin !== target.origin || url.username || url.password) return null;\n if (target.basePath && url.pathname !== target.basePath && !url.pathname.startsWith(`${target.basePath}/`)) {\n return null;\n }\n return url.href;\n}\n\n// ---------------------------------------------------------------------------\n// Header hygiene\n// ---------------------------------------------------------------------------\n\nconst HOP_BY_HOP = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"proxy-connection\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/** Set by the host's own HTTP stack, or meaningless once proxied. */\nconst DROPPED_REQUEST_HEADERS = new Set([\n \"host\",\n \"origin\",\n \"referer\",\n \"content-length\",\n \"accept-encoding\",\n \"forwarded\",\n \"via\",\n // Frameworks trust these from a proxy in front of them: they rewrite the\n // client address, the routed URL or the method the app sees.\n \"x-real-ip\",\n \"x-client-ip\",\n \"x-cluster-client-ip\",\n \"true-client-ip\",\n \"cf-connecting-ip\",\n \"fastly-client-ip\",\n \"x-original-url\",\n \"x-original-uri\",\n \"x-original-host\",\n \"x-original-method\",\n \"x-rewrite-url\",\n \"x-host\",\n \"x-http-method-override\",\n \"x-http-method\",\n \"x-method-override\",\n]);\n\n/** `X-Forwarded-For/Host/Proto/Port/Prefix/Server/…`: all of them describe a proxy we are not. */\nconst DROPPED_REQUEST_HEADER_PREFIXES = [\"sec-\", \"proxy-\", \"x-forwarded-\"];\n\n/** The local fetch decodes the body, so the encoding headers no longer apply. */\nconst DROPPED_RESPONSE_HEADERS = new Set([\n \"content-encoding\",\n \"content-length\",\n \"strict-transport-security\",\n \"alt-svc\",\n \"public-key-pins\",\n]);\n\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nfunction isCleanHeaderValue(value: string): boolean {\n for (const char of value) {\n const code = char.codePointAt(0) ?? 0;\n if (code === 0 || code === 10 || code === 13) return false;\n }\n return true;\n}\n\nexport function sanitizeRequestHeaders(headers: HeaderList): HeaderList {\n return headers.filter(([name, value]) => {\n const lower = name.toLowerCase();\n if (!HEADER_NAME.test(name) || !isCleanHeaderValue(value)) return false;\n if (HOP_BY_HOP.has(lower) || DROPPED_REQUEST_HEADERS.has(lower)) return false;\n return !DROPPED_REQUEST_HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix));\n });\n}\n\n/** `from`: the local URL of the request answered, the one a relative `Location` is read against. */\nexport function sanitizeResponseHeaders(headers: HeaderList, target: LocalTarget, from?: string): HeaderList {\n const out: HeaderList = [];\n for (const [name, value] of headers) {\n const lower = name.toLowerCase();\n if (!HEADER_NAME.test(name) || !isCleanHeaderValue(value)) continue;\n if (HOP_BY_HOP.has(lower) || DROPPED_RESPONSE_HEADERS.has(lower)) continue;\n if (lower === \"location\" || lower === \"content-location\") {\n // Off-target locations are dropped, never disclosed.\n const location = relativizeLocation(value, target, from);\n if (location !== null) out.push([name, location]);\n } else if (lower === \"set-cookie\") {\n // The cookie belongs to the virtual origin on the client, not to localhost.\n out.push([name, value.replace(/;\\s*domain\\s*=[^;]*/gi, \"\")]);\n } else {\n out.push([name, value]);\n }\n }\n return out;\n}\n\n/**\n * The contact's headers a viewer does not pass on: each makes the browser send something to a place it names, outside\n * `connect-src` (violation and network-error reports, and the endpoints they go to; `Link` preloads, prefetches and\n * early connections). With Hide my IP from contacts on, that place would learn this device's address. The same list\n * as the CLI's `OPENED_SERVICE_DROPPED_HEADERS` and Desktop's `DROPPED_HEADERS`.\n */\nexport const VIEWER_DROPPED_HEADERS = [\"content-security-policy-report-only\", \"reporting-endpoints\", \"report-to\", \"nel\", \"link\"];\n\n/** The directives of a contact's policy that send reports to a URL it names, dropped from it (`OPENED_SERVICE_DROPPED_DIRECTIVES`). */\nexport const VIEWER_DROPPED_DIRECTIVES = [\"report-uri\", \"report-to\"];\n\n/** A contact's `Content-Security-Policy` value (one policy or several joined by commas) without its report directives. */\nfunction withoutReports(value: string): string {\n return value.split(\",\")\n .map((policy) => policy.split(\";\").filter((directive) => !VIEWER_DROPPED_DIRECTIVES.includes(directive.trim().split(/\\s+/)[0].toLowerCase())).join(\";\").trim())\n .filter((policy) => policy.replace(/;/g, \"\").trim())\n .join(\", \");\n}\n\n/**\n * A contact's response headers as a viewer serves them to the page (the extension's viewer tab, Desktop's viewer\n * window, the web app's view).\n * The contact's app decides them, and the wire checks only that they are strings, so a header whose name\n * is not a token or whose value carries CR, LF or NUL is dropped: it could otherwise add headers of its own. Each\n * `Set-Cookie` stays on the exact origin it came from (no `Domain=`), and one holding several cookies on separate\n * lines becomes one header per cookie. No header or policy directive that sends a report or an early request elsewhere\n * (`VIEWER_DROPPED_HEADERS`, `VIEWER_DROPPED_DIRECTIVES`); a policy left empty goes.\n */\nexport function viewerResponseHeaders(headers: HeaderList): HeaderList {\n const out: HeaderList = [];\n for (const [name, value] of headers) {\n if (typeof name !== \"string\" || typeof value !== \"string\" || !HEADER_NAME.test(name)) continue;\n const lower = name.toLowerCase();\n if (VIEWER_DROPPED_HEADERS.includes(lower)) continue;\n if (lower === \"set-cookie\") {\n for (const cookie of value.split(/\\r?\\n/)) {\n const scoped = cookie.replace(/;\\s*domain\\s*=[^;]*/gi, \"\");\n if (scoped.trim() && isCleanHeaderValue(scoped)) out.push([name, scoped]);\n }\n } else if (lower === \"content-security-policy\") {\n const policy = withoutReports(value);\n if (policy && isCleanHeaderValue(policy)) out.push([name, policy]);\n } else if (isCleanHeaderValue(value)) {\n out.push([name, value]);\n }\n }\n return out;\n}\n\n/**\n * Ghostly's connection policy for a contact's app in a viewer: its requests and forms reach only its own origin, the\n * contact's service; its scripts, pictures, frames and the rest its own origin and public https sites (and inline,\n * data: and blob: content), never plain http, so not a service on this machine or the local network. The same value as\n * Desktop's `SERVICE_CSP` (apps/desktop/src/viewer.rs) and `OPENED_SERVICE_CSP` (`service open`,\n * packages/cli/src/services.ts).\n */\nexport const VIEWER_SERVICE_CSP = \"default-src 'self' https: data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; form-action 'self'\";\n\n/**\n * The policy while Hide my IP from contacts is on (`relayOnly`, WISP 100 § Relay only): `VIEWER_SERVICE_CSP` without\n * `https:`, so the app loads nothing but its own origin (and inline, data: and blob: content). A picture, script or\n * frame from a server the contact names would show that server this device's address. The same value as Desktop's\n * `SERVICE_CSP_RELAY_ONLY` and `OPENED_SERVICE_CSP_RELAY_ONLY`.\n */\nexport const VIEWER_SERVICE_CSP_RELAY_ONLY = \"default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; form-action 'self'\";\n\n/** Ghostly's policy for a contact's app, by whether Hide my IP from contacts is on. */\nexport function viewerServicePolicy(relayOnly: boolean): string {\n return relayOnly ? VIEWER_SERVICE_CSP_RELAY_ONLY : VIEWER_SERVICE_CSP;\n}\n\n/**\n * The browser features a contact's app in the extension's viewer tab may not use. Its tab is a site of its own, so\n * what the person granted it (camera, microphone, location, a device) would be a site setting of the browser's, which\n * no Delete chat, Clear all data or Delete profile reaches; denied here, the browser never asks and ignores a grant\n * made before. The web app's view is a frame of another site, which gets none of them, and Desktop's window grants none\n * and is served the same value (`PERMISSIONS_POLICY` in `apps/desktop/src/viewer.rs`).\n */\nexport const VIEWER_PERMISSIONS_POLICY = [\n \"camera\", \"microphone\", \"display-capture\", \"geolocation\", \"midi\", \"usb\", \"serial\", \"hid\", \"clipboard-read\",\n \"clipboard-write\", \"idle-detection\", \"local-fonts\", \"window-management\", \"storage-access\", \"publickey-credentials-create\",\n].map((feature) => `${feature}=()`).join(\", \");\n\n/** A contact's headers that would set the page's features: the viewer's own policy takes their place. */\nconst VIEWER_FEATURE_HEADERS = [\"permissions-policy\", \"feature-policy\"];\n\n/**\n * `headers` with Ghostly's policy after the contact's own, all in one `content-security-policy` joined by commas: a\n * browser enforces every policy of the list, so the contact's can narrow Ghostly's but never widen it. The page's\n * features are Ghostly's alone (`VIEWER_PERMISSIONS_POLICY`): a contact's permissions policy could allow them, and one\n * the browser cannot read would void the whole header, Ghostly's part with it.\n */\nexport function withViewerPolicy(headers: HeaderList, relayOnly = false): HeaderList {\n const policies: string[] = [];\n const out: HeaderList = [];\n for (const [name, value] of headers) {\n const lower = name.toLowerCase();\n if (lower === \"content-security-policy\") policies.push(value);\n else if (!VIEWER_FEATURE_HEADERS.includes(lower)) out.push([name, value]);\n }\n out.push([\"content-security-policy\", [...policies, viewerServicePolicy(relayOnly)].join(\", \")]);\n out.push([\"permissions-policy\", VIEWER_PERMISSIONS_POLICY]);\n return out;\n}\n\n/**\n * Turns `http://localhost:3400/base/x` into `/x` so the client never learns or\n * follows the local address. Null when the location is not on the target origin\n * and under its base path. A relative one (`edit`, `?page=2`, `../x`) is read\n * against `from`, the local URL of the request it answers, as a browser reads it;\n * without one, against the base path.\n */\nexport function relativizeLocation(location: string, target: LocalTarget, from?: string): string | null {\n let url: URL;\n try {\n url = new URL(location, from ?? `${target.origin}${target.basePath}/`);\n } catch {\n return null;\n }\n if (url.origin !== target.origin || url.username || url.password) return null;\n let path = url.pathname;\n if (target.basePath) {\n if (path !== target.basePath && !path.startsWith(`${target.basePath}/`)) return null;\n path = path.slice(target.basePath.length) || \"/\";\n }\n // `//host/x` would read as another origin on the client.\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) return null;\n return `${path}${url.search}${url.hash}`;\n}\n\nfunction isRedirectBlocked(response: LocalResponse, target: LocalTarget, from: string): boolean {\n if (response.status < 300 || response.status > 399) return false;\n const location = response.headers.find(([name]) => name.toLowerCase() === \"location\");\n return location !== undefined && relativizeLocation(location[1], target, from) === null;\n}\n\n// ---------------------------------------------------------------------------\n// Host\n// ---------------------------------------------------------------------------\n\nexport interface HostedHttpService {\n id: string;\n target: LocalTarget;\n /**\n * Aborts once this peer may no longer reach the service (stopped, removed,\n * or the contact taken off its list): the requests still open are reset, not\n * answered.\n */\n revoked?: AbortSignal;\n}\n\nexport interface LocalRequest {\n url: string;\n method: string;\n headers: HeaderList;\n body: Uint8Array | null;\n signal: AbortSignal;\n}\n\nexport interface LocalResponse {\n status: number;\n headers: HeaderList;\n body: AsyncIterable<Uint8Array> | Iterable<Uint8Array> | null;\n /**\n * Final URL when the local stack followed redirects itself (a browser's\n * fetch: its manual mode hides where a redirect goes). Desktop never follows\n * and returns the 3xx as it is.\n */\n finalUrl?: string;\n}\n\n/** Performs the request against the local service. Browser: `fetch`. Desktop: the Rust side. */\nexport type LocalFetch = (request: LocalRequest) => Promise<LocalResponse>;\n\nconst ALLOWED_METHODS = new Set([\"GET\", \"HEAD\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\"]);\nconst BODYLESS_METHODS = new Set([\"GET\", \"HEAD\"]);\n\ninterface HostStream {\n frame: HttpRequestFrame;\n service: HostedHttpService;\n url: string;\n body: Uint8Array[];\n bodyBytes: number;\n /** Body bytes since the pace was last checked. */\n movedBytes: number;\n abort: AbortController;\n started: boolean;\n paceTimer?: ReturnType<typeof setTimeout>;\n}\n\nexport class HttpHost {\n private readonly streams = new Map<number, HostStream>();\n /**\n * Streams in the map plus those reset while their local fetch still runs. A\n * local stack may not honour the abort signal (Desktop's Rust fetch doesn't),\n * so a stream counts toward the limit until its fetch has settled.\n */\n private readonly live = new Set<HostStream>();\n /** Body bytes of the streams in `live`: a peer cannot make the host hold more than `maxHostBodyBytesPerPeer`. */\n private heldBodyBytes = 0;\n /** One listener per `revoked` signal of the open streams, not one per stream: a page opens dozens at once. */\n private readonly revokedListeners = new Map<AbortSignal, () => void>();\n\n constructor(\n private readonly channel: FrameChannel,\n private readonly getService: (id: string) => HostedHttpService | undefined,\n private readonly localFetch: LocalFetch,\n ) {}\n\n get activeRequests(): number {\n return this.live.size;\n }\n\n handleRequest(frame: HttpRequestFrame): void {\n if (this.streams.has(frame.id)) return;\n\n const method = frame.m.toUpperCase();\n const service = this.getService(frame.s);\n if (!service || service.revoked?.aborted) return this.fail(frame.id, 404, \"unknown-service\", \"This peer does not share that service.\");\n if (!ALLOWED_METHODS.has(method)) return this.fail(frame.id, 405, \"method-not-allowed\", \"Method not allowed.\");\n if (this.live.size >= LIMITS.maxConcurrentRequestsPerPeer) {\n return this.fail(frame.id, 503, \"busy\", \"Too many concurrent requests.\");\n }\n const url = resolveTargetUrl(service.target, frame.p);\n if (!url) return this.fail(frame.id, 400, \"bad-path\", \"Invalid request path.\");\n\n const stream: HostStream = {\n frame: { ...frame, m: method },\n service,\n url,\n body: [],\n bodyBytes: 0,\n movedBytes: 0,\n abort: new AbortController(),\n started: false,\n };\n this.streams.set(frame.id, stream);\n this.live.add(stream);\n if (service.revoked) this.watchRevoked(service.revoked);\n\n if (frame.b && !BODYLESS_METHODS.has(method)) this.watchPace(stream);\n else void this.run(stream);\n }\n\n handleChunk(chunk: ChunkFrame): void {\n const stream = this.streams.get(chunk.id);\n if (!stream || stream.started) return;\n\n const bytes = chunk.payload.length;\n if (stream.bodyBytes + bytes > LIMITS.maxRequestBodyBytes) {\n this.end(stream);\n return this.fail(chunk.id, 413, \"request-too-large\", \"Request body too large.\");\n }\n if (this.heldBodyBytes + bytes > LIMITS.maxHostBodyBytesPerPeer) {\n this.end(stream);\n return this.fail(chunk.id, 503, \"busy\", \"Too many request bodies at once.\");\n }\n stream.bodyBytes += bytes;\n this.heldBodyBytes += bytes;\n stream.movedBytes += bytes;\n if (chunk.payload.length > 0) stream.body.push(chunk.payload.slice());\n if (chunk.end) void this.run(stream);\n }\n\n handleReset(frame: ResetFrame): void {\n const stream = this.streams.get(frame.id);\n if (stream) this.end(stream);\n }\n\n closeAll(): void {\n for (const stream of [...this.streams.values()]) this.end(stream);\n }\n\n /** A body that brings less than `minRequestBodyBytesPerIdle` in a `bodyIdleTimeoutMs` is let go, even if it trickles. */\n private watchPace(stream: HostStream): void {\n stream.paceTimer = setTimeout(() => {\n if (stream.movedBytes >= LIMITS.minRequestBodyBytesPerIdle) {\n stream.movedBytes = 0;\n return this.watchPace(stream);\n }\n this.end(stream);\n this.fail(stream.frame.id, 408, \"request-timeout\", \"Request body timed out.\");\n }, LIMITS.bodyIdleTimeoutMs);\n }\n\n /** Ids are reused after a reset, so a stream is current only if it is the one in the map. */\n private isCurrent(stream: HostStream): boolean {\n return this.streams.get(stream.frame.id) === stream;\n }\n\n private end(stream: HostStream): void {\n clearTimeout(stream.paceTimer);\n stream.abort.abort();\n if (this.isCurrent(stream)) this.streams.delete(stream.frame.id);\n if (!stream.started) this.release(stream);\n const revoked = stream.service.revoked;\n const listener = revoked && this.revokedListeners.get(revoked);\n if (listener && ![...this.streams.values()].some((s) => s.service.revoked === revoked)) {\n revoked.removeEventListener(\"abort\", listener);\n this.revokedListeners.delete(revoked);\n }\n }\n\n /** An answer still on its way would reach someone the app is no longer shared with: those streams are reset. */\n private watchRevoked(revoked: AbortSignal): void {\n if (this.revokedListeners.has(revoked)) return;\n const listener = () => {\n this.revokedListeners.delete(revoked);\n for (const stream of [...this.streams.values()]) {\n if (stream.service.revoked !== revoked) continue;\n this.end(stream);\n try {\n this.channel.send(encodeControl({ t: \"rst\", id: stream.frame.id, d: \"s\", e: \"The app is no longer shared with you.\" }));\n } catch {\n // channel already closed\n }\n }\n };\n this.revokedListeners.set(revoked, listener);\n revoked.addEventListener(\"abort\", listener, { once: true });\n }\n\n /** The stream no longer counts toward the limits: its body is dropped, or its local fetch has settled. */\n private release(stream: HostStream): void {\n this.live.delete(stream);\n this.heldBodyBytes -= stream.bodyBytes;\n stream.bodyBytes = 0;\n }\n\n private fail(id: number, status: number, code: string, message: string): void {\n const body = utf8Encode(`${message}\\n`);\n try {\n this.channel.send(\n encodeControl({\n t: \"res\",\n id,\n st: status,\n h: [\n [\"content-type\", \"text/plain; charset=utf-8\"],\n [\"x-ghostly-error\", code],\n ],\n b: true,\n }),\n );\n void sendBody(this.channel, CHUNK_KIND.responseBody, id, [body]).catch(() => {});\n } catch {\n // channel already closed\n }\n }\n\n private async run(stream: HostStream): Promise<void> {\n stream.started = true;\n clearTimeout(stream.paceTimer);\n const { frame, service } = stream;\n const timeout = setTimeout(() => stream.abort.abort(), LIMITS.requestTimeoutMs);\n let headersSent = false;\n // The chunks go once joined, so a body is held once while the local service reads it.\n const body = stream.body.length > 0 ? concatBytes(...stream.body) : null;\n stream.body = [];\n\n try {\n const response = await this.localFetch({\n url: stream.url,\n method: frame.m,\n headers: sanitizeRequestHeaders(frame.h),\n body,\n signal: stream.abort.signal,\n });\n clearTimeout(timeout);\n if (!this.isCurrent(stream)) return;\n\n if (response.finalUrl && response.finalUrl !== stream.url) {\n // A browser followed a redirect. Hand it back to the client so its\n // address bar and relative URLs stay right, but never off the target.\n const location = relativizeLocation(response.finalUrl, service.target);\n this.end(stream);\n if (location === null) return this.fail(frame.id, 502, \"redirect-blocked\", \"The service redirected outside of the shared target.\");\n this.channel.send(\n encodeControl({ t: \"res\", id: frame.id, st: BODYLESS_METHODS.has(frame.m) ? 302 : 303, h: [[\"location\", location]], b: false }),\n );\n return;\n }\n\n // Redirects reach the client as they are, with a relative Location, and\n // only when they stay on the target. Anything else is neither followed\n // nor disclosed.\n if (isRedirectBlocked(response, service.target, stream.url)) {\n this.end(stream);\n return this.fail(frame.id, 502, \"redirect-blocked\", \"The service redirected outside of the shared target.\");\n }\n\n const hasBody = response.body !== null && frame.m !== \"HEAD\";\n const res: HttpResponseFrame = {\n t: \"res\",\n id: frame.id,\n st: response.status,\n h: sanitizeResponseHeaders(response.headers, service.target, stream.url),\n b: hasBody,\n };\n this.channel.send(encodeControl(res));\n headersSent = true;\n if (hasBody && response.body) {\n await sendBody(this.channel, CHUNK_KIND.responseBody, frame.id, response.body, () => !this.isCurrent(stream));\n }\n this.end(stream);\n } catch (error) {\n clearTimeout(timeout);\n if (!this.isCurrent(stream)) return;\n // Read before end(), which aborts the signal itself.\n const timedOut = stream.abort.signal.aborted;\n this.end(stream);\n if (headersSent) {\n try {\n this.channel.send(encodeControl({ t: \"rst\", id: frame.id, d: \"s\", e: \"The local service dropped the response.\" }));\n } catch {\n // channel already closed\n }\n } else if (timedOut && (error as Error)?.name === \"AbortError\") {\n this.fail(frame.id, 504, \"timeout\", \"The local service did not answer in time.\");\n } else {\n this.fail(frame.id, 502, \"unreachable\", \"The local service is not reachable.\");\n }\n } finally {\n this.release(stream);\n }\n }\n}\n\n/** `LocalFetch` on top of the web `fetch` API, for any host that has one. */\nexport const webLocalFetch: LocalFetch = async (request) => {\n const headers = new Headers();\n for (const [name, value] of request.headers) {\n try {\n headers.append(name, value);\n } catch {\n // header rejected by the platform\n }\n }\n const response = await fetch(request.url, {\n method: request.method,\n headers,\n body: request.body as BodyInit | null,\n signal: request.signal,\n // Never the host user's own cookies or HTTP auth: a remote peer must not\n // inherit the session the host has with its local application.\n credentials: \"omit\",\n cache: \"no-store\",\n // Browsers hide where a manual redirect goes, so a same-app redirect\n // (`/docs` → `/docs/`, a login's 303) could only be refused. Followed\n // redirects are checked afterwards and never leave the target for the\n // client; the local request itself has happened by then (docs/SECURITY-REVIEW.md).\n redirect: \"follow\",\n referrerPolicy: \"no-referrer\",\n });\n\n const responseHeaders: HeaderList = [];\n response.headers.forEach((value, name) => responseHeaders.push([name, value]));\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: response.body ? readStream(response.body) : null,\n finalUrl: response.redirected ? response.url : undefined,\n };\n};\n\nasync function* readStream(stream: ReadableStream<Uint8Array>): AsyncIterable<Uint8Array> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n if (value && value.length > 0) yield value;\n }\n } finally {\n reader.cancel().catch(() => {});\n }\n}\n\n// ---------------------------------------------------------------------------\n// Client\n// ---------------------------------------------------------------------------\n\nexport interface ClientRequest {\n method: string;\n path: string;\n headers?: HeaderList;\n body?: Uint8Array | null;\n signal?: AbortSignal;\n maxResponseBytes?: number;\n}\n\nexport interface ClientResponse {\n status: number;\n headers: HeaderList;\n body: AsyncIterable<Uint8Array>;\n /** Collects the whole body, bounded by `maxResponseBytes`. */\n bytes(): Promise<Uint8Array>;\n}\n\nexport class GhostlyHttpError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface ClientStream {\n resolve: (response: ClientResponse) => void;\n reject: (error: Error) => void;\n headersTimer?: ReturnType<typeof setTimeout>;\n idleTimer?: ReturnType<typeof setTimeout>;\n unreadCheck?: ReturnType<typeof setTimeout>;\n queue: BodyQueue | null;\n received: number;\n maxBytes: number;\n}\n\nclass BodyQueue implements AsyncIterable<Uint8Array> {\n private chunks: Uint8Array[] = [];\n private done = false;\n private error: Error | null = null;\n private wake: (() => void) | null = null;\n /** Bytes received and not yet read. */\n held = 0;\n /** Bytes read so far, all told. */\n taken = 0;\n\n /** `all`: what every queue of the same client holds, kept with this one's. */\n constructor(private readonly all: { held: number }) {}\n\n push(chunk: Uint8Array): void {\n this.chunks.push(chunk);\n this.held += chunk.length;\n this.all.held += chunk.length;\n this.wake?.();\n }\n\n finish(error?: Error): void {\n if (this.done) return;\n this.done = true;\n this.error = error ?? null;\n this.wake?.();\n }\n\n /** Lets go of what was not read yet, ended or not: the reader gets `error` in its place. */\n drop(error: Error): void {\n this.chunks = [];\n this.all.held -= this.held;\n this.held = 0;\n this.done = true;\n this.error = error;\n this.wake?.();\n }\n\n async *[Symbol.asyncIterator](): AsyncIterator<Uint8Array> {\n for (;;) {\n while (this.chunks.length > 0) {\n const chunk = this.chunks.shift()!;\n this.held -= chunk.length;\n this.all.held -= chunk.length;\n this.taken += chunk.length;\n yield chunk;\n }\n if (this.error) throw this.error;\n if (this.done) return;\n await new Promise<void>((resolve) => (this.wake = resolve));\n this.wake = null;\n }\n }\n}\n\nexport class HttpClient {\n private nextId = 1;\n private readonly streams = new Map<number, ClientStream>();\n private readonly waiting: (() => void)[] = [];\n private waitingBytes = 0;\n private inFlight = 0;\n private closed = false;\n /** Response-body bytes all this client's responses hold before their readers took them. */\n private readonly unread = { held: 0 };\n\n constructor(private readonly channel: FrameChannel) {}\n\n async request(serviceId: string, request: ClientRequest): Promise<ClientResponse> {\n if (this.closed) throw new GhostlyHttpError(\"closed\", \"Data link is closed\");\n if (this.inFlight >= LIMITS.maxClientInFlight) {\n const bytes = request.body?.length ?? 0;\n if (this.waiting.length >= LIMITS.maxClientWaiting || this.waitingBytes + bytes > LIMITS.maxClientWaitingBodyBytes) {\n throw new GhostlyHttpError(\"busy\", \"Too many requests waiting\");\n }\n this.waitingBytes += bytes;\n // Aborted while it waits: it leaves the queue at once, and lets go of its body.\n let leave = () => {};\n try {\n await new Promise<void>((resolve, reject) => {\n const wake = () => { request.signal?.removeEventListener(\"abort\", leave); resolve(); };\n leave = () => {\n const at = this.waiting.indexOf(wake);\n if (at >= 0) this.waiting.splice(at, 1);\n reject(new GhostlyHttpError(\"aborted\", \"Request aborted\"));\n };\n if (request.signal?.aborted) return leave();\n this.waiting.push(wake);\n request.signal?.addEventListener(\"abort\", leave, { once: true });\n });\n } finally {\n this.waitingBytes -= bytes;\n }\n if (this.closed) throw new GhostlyHttpError(\"closed\", \"Data link is closed\");\n }\n this.inFlight++;\n\n const id = this.nextId++;\n const body = request.body && request.body.length > 0 ? request.body : null;\n if (body && body.length > LIMITS.maxRequestBodyBytes) {\n this.release();\n throw new GhostlyHttpError(\"request-too-large\", \"Request body too large\");\n }\n\n return new Promise<ClientResponse>((resolve, reject) => {\n const stream: ClientStream = {\n resolve,\n reject,\n queue: null,\n received: 0,\n maxBytes: request.maxResponseBytes ?? LIMITS.maxResponseBodyBytes,\n };\n this.streams.set(id, stream);\n stream.headersTimer = setTimeout(\n () => this.abort(id, new GhostlyHttpError(\"timeout\", \"The peer did not answer in time\")),\n LIMITS.requestTimeoutMs + 5_000,\n );\n request.signal?.addEventListener(\"abort\", () => this.abort(id, new GhostlyHttpError(\"aborted\", \"Request aborted\")));\n // Aborted before this point (while it waited for a slot, or before the call): the listener never fires.\n if (request.signal?.aborted) {\n this.abort(id, new GhostlyHttpError(\"aborted\", \"Request aborted\"), false);\n return;\n }\n\n try {\n this.channel.send(\n encodeControl({\n t: \"req\",\n id,\n s: serviceId,\n m: request.method.toUpperCase(),\n p: request.path,\n h: request.headers ?? [],\n b: body !== null,\n }),\n );\n if (body) {\n sendBody(this.channel, CHUNK_KIND.requestBody, id, [body], () => !this.streams.has(id)).catch((error) =>\n this.abort(id, error as Error),\n );\n }\n } catch (error) {\n this.abort(id, error as Error, false);\n }\n });\n }\n\n handleResponse(frame: HttpResponseFrame): void {\n const stream = this.streams.get(frame.id);\n if (!stream || stream.queue) return;\n clearTimeout(stream.headersTimer);\n\n const queue = new BodyQueue(this.unread);\n stream.queue = queue;\n if (frame.b) this.armIdleTimer(frame.id, stream);\n else this.finish(frame.id);\n\n stream.resolve({\n status: frame.st,\n headers: frame.h,\n body: queue,\n bytes: async () => {\n const parts: Uint8Array[] = [];\n for await (const part of queue) parts.push(part);\n return concatBytes(...parts);\n },\n });\n }\n\n handleChunk(chunk: ChunkFrame): void {\n const stream = this.streams.get(chunk.id);\n if (!stream?.queue) return;\n\n stream.received += chunk.payload.length;\n if (stream.received > stream.maxBytes) {\n return this.abort(chunk.id, new GhostlyHttpError(\"response-too-large\", \"Response body too large\"));\n }\n if (chunk.payload.length > 0) stream.queue.push(chunk.payload.slice());\n if (stream.queue.held > LIMITS.maxUnreadResponseBytes) {\n // Many responses read slowly add up: past the client's bound, one over its own is let go without a turn.\n if (this.unread.held > LIMITS.maxClientUnreadResponseBytes) return this.dropUnread(chunk.id, stream.queue);\n this.checkUnread(chunk.id, stream, stream.queue);\n }\n if (chunk.end) this.finish(chunk.id);\n else this.armIdleTimer(chunk.id, stream);\n }\n\n /**\n * Nothing tells the peer to slow down, and its last chunk frees the slot: a reader that stalls (a contact's page that\n * never reads what it fetched) would have the whole body held here, one per request it leaves unread. Past the bound\n * the reader gets `unreadStallMs`, as a link that hands over many chunks at once leaves it no turn: one that took\n * something in it is looked at again, one that took nothing has the response reset and what it held let go.\n */\n private checkUnread(id: number, stream: ClientStream, queue: BodyQueue): void {\n if (stream.unreadCheck) return;\n const taken = queue.taken;\n stream.unreadCheck = setTimeout(() => {\n stream.unreadCheck = undefined;\n if (queue.held <= LIMITS.maxUnreadResponseBytes) return;\n if (queue.taken > taken) return this.checkUnread(id, stream, queue);\n this.dropUnread(id, queue);\n }, LIMITS.unreadStallMs);\n }\n\n private dropUnread(id: number, queue: BodyQueue): void {\n const error = new GhostlyHttpError(\"unread\", \"Response body not read in time\");\n queue.drop(error);\n this.abort(id, error);\n }\n\n handleReset(frame: ResetFrame): void {\n this.abort(frame.id, new GhostlyHttpError(\"reset\", frame.e || \"Request reset by peer\"), false);\n }\n\n close(): void {\n this.closed = true;\n for (const id of [...this.streams.keys()]) {\n this.abort(id, new GhostlyHttpError(\"closed\", \"Data link closed\"), false);\n }\n for (const wake of this.waiting.splice(0)) wake();\n }\n\n private armIdleTimer(id: number, stream: ClientStream): void {\n clearTimeout(stream.idleTimer);\n stream.idleTimer = setTimeout(\n () => this.abort(id, new GhostlyHttpError(\"timeout\", \"Response body timed out\")),\n LIMITS.bodyIdleTimeoutMs,\n );\n }\n\n private finish(id: number): void {\n const stream = this.streams.get(id);\n if (!stream) return;\n clearTimeout(stream.headersTimer);\n clearTimeout(stream.idleTimer);\n this.streams.delete(id);\n stream.queue?.finish();\n this.release();\n }\n\n private abort(id: number, error: Error, notifyPeer = true): void {\n const stream = this.streams.get(id);\n if (!stream) return;\n clearTimeout(stream.headersTimer);\n clearTimeout(stream.idleTimer);\n this.streams.delete(id);\n if (stream.queue) stream.queue.finish(error);\n else stream.reject(error);\n if (notifyPeer) {\n try {\n this.channel.send(encodeControl({ t: \"rst\", id, d: \"q\", e: error.message }));\n } catch {\n // channel already closed\n }\n }\n this.release();\n }\n\n private release(): void {\n this.inFlight--;\n this.waiting.shift()?.();\n }\n}\n","import { fromBase64Url, utf8Encode } from \"./bytes\";\nimport { identityFromSeedB64, type Identity } from \"./identity\";\nimport type { LinkParams } from \"./invite\";\nimport {\n buildLinkRecords,\n isEmptyLinkPacket,\n parseLinkRecords,\n type CompactMessage,\n type ResolvedLink,\n type ResolvedMessage,\n} from \"./records\";\nimport { PKARR_FUTURE_SKEW_MS } from \"./pkarr\";\nimport type { ServiceAd } from \"./services\";\nimport type { SignalSight } from \"./signal\";\nimport { RelaysFailedError } from \"./relay\";\nimport { budgetRetryMs, isDiscoveryBudgetError, type PkarrTransport } from \"./transport\";\nimport { traceLink } from \"./linkTrace\";\n\n/**\n * The Pkarr side of a link: publish my records, poll the peer's. This is the\n * loop Ghostly Desktop runs in `useChat`, without React, so every client can\n * share it.\n */\nexport interface PollIntervals {\n /** The user is looking at the link. */\n active: number;\n /** …but nothing happened for a minute. */\n idle: number;\n /** Signaling in progress. */\n fast: number;\n /** Nobody is looking. */\n background: number;\n /** The data link is up and carries everything; Pkarr only has to notice re-offers. */\n connected: number;\n}\n\n/** What Ghostly Desktop uses against the DHT. */\nexport const DHT_POLL_INTERVALS: PollIntervals = {\n active: 2_000,\n idle: 8_000,\n fast: 700,\n background: 20_000,\n connected: 30_000,\n};\n\n/** Relays rate limit by IP, and several peers may sit behind one address. */\nexport const RELAY_POLL_INTERVALS: PollIntervals = {\n active: 4_000,\n idle: 10_000,\n fast: 2_000,\n background: 30_000,\n connected: 60_000,\n};\n\n/** Signaling that has not finished by then is not going to; stop polling fast. */\nconst FAST_POLL_MAX_MS = 45_000;\n/**\n * An offer to a saved contact (a chat, a group's edge) is looked at fast for an answer this long after it went out,\n * then less often (`OFFER_STEP_MAX`) for the rest of its window. A contact that is there answers within seconds;\n * one that still holds the session this app had before it restarted answers only once that session goes (about 20 s\n * with node-datachannel, 45 s where liveness finds out). An app back with several chats and edges, each looking every\n * 2 s meanwhile, spent the relays' minute in those seconds and could not read the answers when they came: a group's\n * edges were live again 75 and 110 s after a restart (bug hunt r5a, 2026-09-29).\n */\nexport const OFFER_FAST_MS = 10_000;\n/**\n * The longest wait between looks for an answer to an offer once it has been out `OFFER_FAST_MS`, in fast paces: 8 s on\n * the relays (fast 2 s), 2.8 s on the DHT (0.7 s), which costs no relay budget.\n */\nexport const OFFER_STEP_MAX = 4;\n/** An offer to a saved contact is looked at for an answer as long as its attempt lasts (`CONNECT_TIMEOUT_MS`), not 45 s. */\nexport const OFFER_LOOK_MS = 90_000;\n/**\n * The first fast reads after a new offer or answer of this side's went out are signaling (`PkarrRequestOptions.signal`),\n * as the reads for the answer to an offer to a saved contact are all along. An answer's: the offer it answered may be\n * given up by then (its attempt ended before it read the answer, or the answer was refused), and the offerer's next one,\n * made at once, is what both sides wait on. 3 at the relays' fast pace cover 6 s. As plain reads, an extension back\n * from Offline with its relay minute spent never read its contact's new offer and answered the old one again: the\n * matrix's chat stayed \"On DHT · retrying live\" for 45 s (E2E full, 2026-10-30).\n */\nexport const SIGNAL_OUT_READS = 3;\n/**\n * The first fast reads once the contact's offer is due now (`expectPeer(…, true)`: the chat just left DHT only, on\n * both sides) are signaling too, as many as after an answer, until one finds a new signal of the contact's. As plain\n * reads, an extension whose relay minute was spent read its contact once as it came back from DHT only, and the next\n * read waited 41 s: the offer out since then was never read, and the matrix's chat stayed \"On DHT · retrying live\" for\n * 45 s (E2E full, 2026-11-05).\n */\nexport const SIGNAL_DUE_READS = SIGNAL_OUT_READS;\n/**\n * How long a link looks fast when its peer, or the peer's offer, is due any moment. The peer that\n * dials does so as soon as it sees the other one here, and its offer lands in its packet a moment\n * after its presence did: without this the side that answers left the offer to a background poll\n * (30 s on the relays), once on a group's entry session and once more per member edge.\n */\nexport const EXPECT_PEER_MS = 30_000;\n/**\n * How long a link keeps looking at the active pace after its contact went away from a live session (it said goodbye,\n * or the session dropped): an app that restarts is back within this, and its dial or offer is seen in seconds.\n */\nexport const WATCH_PEER_MS = 2 * 60_000;\n/**\n * A CLI daemon (a bot) reads a contact that went away from a live session at the idle pace, not its background one, from\n * the end of `WATCH_PEER_MS` until this long after it left (`LinkSession.watchPeer`). A phone that put the app to sleep is\n * often back after more than 2 minutes, and where WebRTC is all there is between them its offer waits for the daemon's\n * read: every 30 s past 2 minutes, a web app at phone size was live again 18.3 s after 5 minutes asleep (the lab,\n * 2026-11-01). Cost, a contact away the whole 5 minutes: from 2 to 5 minutes, a read every 10 s and not every 30 s, 12\n * more. A key's reads take turns between the two default relays (`readOrder` in relay.ts), 6 more on each: at 12 such\n * absences an hour, 72 more an hour on a relay, 4% of the 1,800 this client allows itself there (`REQUESTS_PER_MINUTE`).\n * At the active pace for the whole 5 minutes instead, 39 more an absence: 13%.\n */\nexport const DAEMON_WATCH_PEER_IDLE_MS = 5 * 60_000;\n/**\n * The longest a link reads fast for a data link whose connection went `disconnected` (`setDataLinkStalled`): a little\n * past the 12 s such a connection is given (`DISCONNECT_GRACE_MS`), by when it is back or the session is gone.\n */\nexport const STALLED_LOOK_MS = 15_000;\n/**\n * For this long after its contact went away from a live session, a chat's reads of it say so (`PkarrRequestOptions.departed`):\n * a few may go over the relays' budget (`DEPARTED_READS` in relay.ts). The fast window that follows a goodbye\n * (`EXPECT_PEER_MS`): an app that restarts has its offer out well within it (2.5 to 10 s after its goodbye in the lab of\n * #1441, on a loaded host), and past it the race's DHT dial has brought the chat back anyway.\n */\nexport const DEPARTED_READ_MS = EXPECT_PEER_MS;\n/** A chat whose contact was never seen (an invite just sent) keeps looking at the active pace this long. */\nexport const AWAITING_PEER_MS = 10 * 60_000;\n/**\n * An invite this side made that nobody used, once no longer awaited (`AWAITING_PEER_MS`), is read less often the older\n * it is: a fifth of its age between reads, up to this. Read at the background pace instead, 15 unused invites (their\n * keys and their mailboxes) asked the relays for 60 reads a minute for as long as the app ran: the relays' minute went\n * to invites nobody may ever open, and a join on one was noticed 90 s later (bug hunt 1013-1642, 2026-10-13).\n */\nexport const UNUSED_INVITE_WAIT_MAX_MS = 3 * 60_000;\n/**\n * The reads a minute the unused invites of an app (their keys and their mailboxes) take between them, half the relays'\n * background share: the slower reads stretch only as far as their count needs. Slowed whatever the count, a single\n * invite opened 20 minutes later was noticed 136 s after the join, where the background pace takes 30 s at most (bug\n * hunt 1014-0136, 2026-10-14).\n */\nexport const UNUSED_INVITE_READS_PER_MINUTE = 10;\n/**\n * An invite this side made that nobody used, once no longer awaited, puts its key and its mailbox out this often, not\n * every `PRESENCE_HEARTBEAT`: 20 of them added about 17 relay writes a minute for as long as the app ran (bug hunt,\n * 2026-10-30). Not longer: a joiner goes live sooner while it finds both still good, the packet within `PRESENCE_WINDOW`\n * and the envelope unexpired. At 30 minutes the slowest of 6 joins took 235 s, against 86 s of 9 at the heartbeat's pace.\n */\nexport const UNUSED_INVITE_UPKEEP_MS = 8 * 60_000;\n/** The keys and mailboxes of unused invites read slowly over each transport (an app's relays). */\nconst unusedInviteReaders = new WeakMap<PkarrTransport, Set<object>>();\n/** Counts `reader` (an invite's key or mailbox) among the unused ones read over `transport` while `unused`, or no longer: how many there are. */\nexport function countUnusedInvite(transport: PkarrTransport, reader: object, unused: boolean): number {\n let readers = unusedInviteReaders.get(transport);\n if (!readers) unusedInviteReaders.set(transport, readers = new Set());\n if (unused) readers.add(reader); else readers.delete(reader);\n return readers.size;\n}\n/**\n * The wait between reads of an unused invite of age `age`, one of `readers` read over the same relays: a fifth of its\n * age, up to `UNUSED_INVITE_WAIT_MAX_MS`, but no longer than their count needs (`UNUSED_INVITE_READS_PER_MINUTE`), and\n * never shorter than the pace's `interval`.\n */\nexport function unusedInviteWait(age: number, interval: number, readers: number): number {\n const share = Math.round(readers * 60_000 / UNUSED_INVITE_READS_PER_MINUTE);\n return Math.max(interval, Math.min(UNUSED_INVITE_WAIT_MAX_MS, Math.round(age / 5), share));\n}\n/**\n * A group link's peer whose packet advertises and carries no `_tr` on every read for this long publishes none: what it\n * said before is forgotten (WISP 902 § Transports). Not at the first such packet: an app with no WebRTC (a Linux\n * Desktop) publishes its `_tr` only once a native endpoint is up, seconds after its first packet of a run, and what it\n * said in the run before still holds meanwhile. On this side's clock, from the first read that found it so.\n */\nexport const TRANSPORTS_GONE_MS = 2 * 60_000;\nconst PUBLISH_RETRY_MS = 4_000;\n/**\n * A packet the relays' request budget held back goes again when the budget frees a request, and at least this often\n * meanwhile: each refusal keeps it first in line for that request (`WRITE_FIRST_MS`), and costs no request itself.\n */\nconst BUDGET_RETRY_MIN_MS = 250;\n/**\n * A background write the budget held back (`{ background: true }`) is not first in line for anything (`WRITE_FIRST_MS`\n * is a chat's or a group's write): it goes again when the budget frees one of its share, up to this long. Tried every\n * 4 s, an idle admin's daemon built and signed 1,041 packets in 9 minutes that the budget refused again (bug hunt,\n * 2026-10-19). Anything new to say goes at once all the same (`publish`).\n */\nconst BACKGROUND_RETRY_MAX_MS = 60_000;\n/** Two reads are never closer than this, however long the last one took. */\nconst MIN_POLL_GAP_MS = 250;\nexport const IDLE_THRESHOLD = 60_000;\nexport const MAX_DHT_TEXT_BYTES = 500;\n/** Presence is a fresh packet: advertising peers republish this often… */\nexport const PRESENCE_HEARTBEAT = 4 * 60_000;\n/** …and are considered gone once their packet is older than this. */\nexport const PRESENCE_WINDOW = 10 * 60_000;\n\n/** When this device first read the peer's latest packet, by its own clock (`PeerPresence.seenAt`). */\nexport const presenceSeenAt = (presence: Pick<PeerPresence, \"lastPacketAt\" | \"seenAt\">): number => presence.seenAt ?? presence.lastPacketAt;\n\nexport type LinkStatus = \"connecting\" | \"online\" | \"offline\" | \"error\";\n\nexport interface PeerPresence {\n /** Peer advertises services and its packet is fresh. */\n online: boolean;\n /** Timestamp of the peer's latest packet (ms), 0 if none was ever seen. The peer's clock: it names the packet, and is never compared with this one's. */\n lastPacketAt: number;\n /**\n * When this device first read that packet, by its own clock: what \"how long ago\" is measured from (`presenceSeenAt`).\n * A packet is dated by its own time, held between the read of this run before the one that found it and that one: a\n * few seconds apart while a link is being made, so the peer's clock no longer matters. The first read has no read\n * before it: a peer whose clock is behind looks that much older until its next packet, and no peer's clock makes a\n * packet look newer than the read that found it.\n */\n seenAt?: number;\n nick?: string;\n /** `null` for peers that do not advertise (legacy clients, or offline). */\n services: ServiceAd[] | null;\n}\n\nexport interface LinkSessionEvents {\n onDiscoveryError?(error: string | null): void;\n onMessages?(messages: ResolvedMessage[], batch: ResolvedLink): void;\n onPresence?(presence: PeerPresence): void;\n onPeerAck?(ackTimestamp: number): void;\n onCallSignal?(signal: string): void;\n /**\n * `sight`: a read of the peer's record that the network answered, earlier in this run, did not have the signal\n * (`SignalSight`): when that read began, and the time of the peer's packet it found, if any. Absent for a signal\n * the first such read found.\n */\n onRtcSignal?(signal: string, sight?: SignalSight): void;\n /**\n * The peer's packet, dated `packetAt` by the peer's clock, was not there at this run's read of `readBefore` and is\n * there at `readAt` (this clock): what its clock says against this one (`ClockWatch.peer`).\n */\n onPeerClock?(packetAt: number, readBefore: number, readAt: number): void;\n /** The peer's packet carries a new `_tr` value (a group link's transports, `parsePacketTransports`). */\n onPeerTransports?(value: string): void;\n /** The peer's packet has said no `_tr` for `TRANSPORTS_GONE_MS`: the peer publishes none (any more). Once per such stretch. */\n onPeerTransportsGone?(): void;\n /** The peer's packet that advertises carries no `_tr` (`true`) where the last read did, or carries one again (`false`). */\n onPeerTransportsUnsaid?(unsaid: boolean): void;\n onStatus?(status: LinkStatus): void;\n /** A poll started, or finished with the next one due in `nextInMs`. */\n onPoll?(poll: { polling: boolean; nextInMs: number }): void;\n /**\n * A publish finished: how long it took, and whether it carried an `_rtc` signal. `error` when it failed; `waiting`\n * when the relays' request budget held it back (nothing went out, and it goes again once the budget frees a request,\n * in about `retryInMs`). `signalOut` when it is the first to carry the current `_rtc` signal: an offer or an answer went out now.\n */\n onPublish?(result: { ms: number; rtc: boolean; error?: string; waiting?: boolean; retryInMs?: number; signalOut?: boolean }): void;\n /** The first read of the peer's key is done (with `firstPublish: \"after-first-poll\"`, what to publish is decided now). */\n onFirstPoll?(): void;\n}\n\nexport interface LinkSessionOptions {\n params: LinkParams;\n transport: PkarrTransport;\n nick?: string;\n /** Highest peer message timestamp already stored locally. */\n lastSeenTimestamp?: number;\n /** Services to advertise right now. Return undefined to advertise nothing. */\n getServices?: () => ServiceAd[] | undefined;\n pollIntervals?: PollIntervals;\n events?: LinkSessionEvents;\n /**\n * When this side's first packet goes out. `at-start` (default): as the session starts. `after-first-poll`:\n * once the peer's key was read, unless whoever asked publishes something better by then (a first\n * pairing's joiner, who dials the moment it sees the inviter: its offer then travels in its first packet\n * instead of a second one right behind it, which relays hold back for seconds), and in any case within\n * `FIRST_PUBLISH_MAX_MS`.\n */\n firstPublish?: \"at-start\" | \"after-first-poll\";\n /**\n * Back after a restart with the contact live when this app last ran (`GhostLinkOptions.resume`): its reads say so\n * (`PkarrRequestOptions.resume`) until one is answered.\n */\n resumed?: boolean;\n /**\n * When the chat was made, for a saved one: the wait for a peer never seen (`AWAITING_PEER_MS`) counts from then, not\n * from this start. Counted from each start of the app, every saved chat whose contact had no packet at the relays\n * (away for a day) was an invite just sent again: 50 of them read every 4 s for ten minutes, not in the background,\n * and spent both relays' minute in the first seconds of a start, so nothing the app wrote (its DID record, a message\n * sent at once) went out for a minute (2026-10-08).\n */\n awaitingSince?: number;\n /**\n * Whether this is an invite this side made that nobody used yet, or one it joined whose inviter never answered: once no\n * longer awaited, read less often while nobody is there (`unusedInviteWait`).\n */\n invite?: () => boolean;\n /** Whether this is an invite this side made that nobody used yet (not one it joined): its upkeep slows too (`UNUSED_INVITE_UPKEEP_MS`). */\n ownInvite?: () => boolean;\n}\n\n/** With `firstPublish: \"after-first-poll\"`, the first packet goes out by then whatever happened. */\nexport const FIRST_PUBLISH_MAX_MS = 2_000;\n\nexport class LinkSession {\n readonly identity: Identity;\n readonly peerPubKeyZ32: string;\n private readonly encKey: Uint8Array;\n private readonly transport: PkarrTransport;\n private readonly events: LinkSessionEvents;\n private readonly getServices: () => ServiceAd[] | undefined;\n\n private nick?: string;\n private sentBuffer: CompactMessage[] = [];\n private myAck: number;\n private lastSeenTimestamp: number;\n private callSignal: string | null = null;\n private rtcSignal: string | null = null;\n private lastCallSignalIn: string | null = null;\n /** The `_rtc` signal the last packet that went out carried. */\n private rtcSignalOut: string | null = null;\n /** Counts the signals taken back (`setRtcSignal(null)`): each ends an attempt. */\n private rtcAttempt = 0;\n /** A publish that went out carried a signal of this attempt (since the last take-back). */\n private rtcAttemptOut = false;\n private lastRtcSignalIn: string | null = null;\n /** The `_rtc` signal the peer's packet carried as last read (null: none), whether or not it was new. */\n private peerRtcSignal: string | null = null;\n /** A group link's `_tr` value this side publishes (`setTransports`), and the last the peer's packet carried. */\n private transports: string | null = null;\n private lastTransportsIn: string | null = null;\n /** When a read first found the peer's packet advertising with no `_tr` (0: the last packet that said carried one). */\n private transportsAbsentSince = 0;\n private transportsGone = false;\n /** The peer's packet carried a `_tr` and the last read found none (`onPeerTransportsUnsaid`). */\n private transportsUnsaid = false;\n\n private running = false;\n /** Stopped without a last packet (`stop(false)`): nothing more goes out. */\n private silent = false;\n private polling = false;\n /** `lookNow` came during a read: the next one follows it at once. */\n private pollAgain = false;\n private publishing: Promise<void> | null = null;\n private publishAgain = false;\n /** What waits to go out is the presence heartbeat alone (`PRESENCE_HEARTBEAT`): nothing in the packet changed. */\n private upkeepOnly = false;\n /** The last write this link asked for was a background one (`retryDelay`). */\n private wroteInBackground = false;\n /** The records built for a packet that did not go out, and what they say: a try again of the same reuses them (`publishOnce`). */\n private unsent: { says: string; built: ReturnType<typeof buildLinkRecords> } | null = null;\n private pollTimer: ReturnType<typeof setTimeout> | null = null;\n private heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n private lastActivity = Date.now();\n private readonly startedAt = Date.now();\n /** From when a peer never seen is awaited (`AWAITING_PEER_MS`): never later than this start, whatever the clock said when the chat was made. */\n private readonly awaitingSince: number;\n /** This side's invite, nobody used yet (`LinkSessionOptions.invite`). */\n private readonly invite: () => boolean;\n /** This side's own invite, nobody used yet (`LinkSessionOptions.ownInvite`). */\n private readonly ownInvite: () => boolean;\n private readonly intervals: PollIntervals;\n private fastPollUntil = 0;\n /** An offer to a saved contact is out: from then on its fast window looks less often (`OFFER_FAST_MS`); 0 for none. */\n private fastStepsAfter = 0;\n /** Fast reads still signaling since this side's last new offer or answer went out (`SIGNAL_OUT_READS`). */\n private signalReadsLeft = 0;\n /** Fast reads still signaling while the contact's offer is due (`SIGNAL_DUE_READS`). */\n private dueSignalReadsLeft = 0;\n /** This side just left DHT only and its presence is not out yet: the contact dials on it (`presenceDue`). */\n private presenceDueOut = false;\n /** When the last `expectPeer` window ends (or ended): the pace slows down from there step by step. */\n private expectUntil = 0;\n /**\n * Until when this link's reads go as a resume's (`PkarrRequestOptions.resume`: a group edge's on the relays' floor):\n * the peer is due now and nothing reaches it until its packet is read (`expectPeer(true)`: the edge to a member a hub\n * just let in). As plain fast reads, a hub's admissions in a row spent the budget and the newcomer's edge waited for it:\n * 22-39 s before it could send, receive or leave (agents#1740). Ends once a read finds the peer's packet.\n */\n private awaitedUntil = 0;\n private watchUntil = 0;\n /** The time of the peer's packet read last when it went away (`watchPeer`): a newer one that advertises says it is back. */\n private watchFrom = 0;\n /** Until when a contact that went away is read at the idle pace once `watchUntil` passed (`watchPeer`'s `idleMs`). */\n private lingerUntil = 0;\n /** Until when the reads of a contact that went away are its first ones (`DEPARTED_READ_MS`). */\n private departedUntil = 0;\n private publishRetryTimer: ReturnType<typeof setTimeout> | null = null;\n private active = false;\n private connected = false;\n /** The open data link's connection is `disconnected`, and read fast until then (`setDataLinkStalled`). */\n private stalledUntil = 0;\n private readonly firstPublish: \"at-start\" | \"after-first-poll\";\n private firstPublishTimer: ReturnType<typeof setTimeout> | null = null;\n private firstPollDone = false;\n /** Back after a restart, and no read of the contact answered yet in this run (`LinkSessionOptions.resumed`). */\n private resumeReads: boolean;\n /** When this side last published (0: never). */\n lastPublishedAt = 0;\n /** A publish is in flight, or finished this recently: another packet now would only queue behind it at the relays. */\n publishedRecently(withinMs: number): boolean {\n return this.publishing !== null || this.firstPublishTimer !== null || Date.now() - this.lastPublishedAt < withinMs;\n }\n private discoveryErrors: Partial<Record<\"publish\" | \"read\", string>> = {};\n /** The last read was not answered by the network: it failed, or the transport handed back a copy it kept (`discoveryRecovered`). */\n private readMissed = false;\n private unsubscribe: (() => void) | null = null;\n private presence: PeerPresence = { online: false, lastPacketAt: 0, services: null };\n /**\n * When the last read of the peer's record that the network answered began (0: none yet in this run). A read that\n * handed back a copy kept from before (`PkarrTransport.readAnsweredAt`) is not one: it says nothing of what the\n * record holds now.\n */\n private lastReadAt = 0;\n /** The latest time of the peer's own packets those reads found, by the peer's clock (0: none; the inviter's empty packet is not the peer's). */\n private peerPacketAt = 0;\n\n constructor(options: LinkSessionOptions) {\n this.identity = identityFromSeedB64(options.params.seedB64);\n this.peerPubKeyZ32 = options.params.peerPubKeyZ32;\n this.encKey = fromBase64Url(options.params.encKeyB64);\n this.transport = options.transport;\n this.nick = options.nick;\n this.lastSeenTimestamp = options.lastSeenTimestamp ?? 0;\n this.myAck = this.lastSeenTimestamp;\n this.getServices = options.getServices ?? (() => undefined);\n this.intervals = options.pollIntervals ?? DHT_POLL_INTERVALS;\n this.events = options.events ?? {};\n this.firstPublish = options.firstPublish ?? \"at-start\";\n this.resumeReads = !!options.resumed;\n this.awaitingSince = Math.min(options.awaitingSince ?? this.startedAt, this.startedAt);\n this.invite = options.invite ?? (() => false);\n this.ownInvite = options.ownInvite ?? (() => false);\n }\n\n get peerPresence(): PeerPresence {\n return this.presence;\n }\n\n /**\n * The relays took a WebRTC signal of this attempt: its answer, or an earlier one of it. Not an earlier attempt's still\n * in the packet out: its take-back, a background write, is the first the relays' budget holds back.\n */\n get rtcSignalPublished(): boolean { return this.rtcAttemptOut; }\n\n /** The `_rtc` signal the peer's packet carries, as last read: null when it carries none. */\n get peerSignal(): string | null {\n return this.peerRtcSignal;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n this.silent = false;\n this.events.onStatus?.(\"connecting\");\n // Presence: a peer that advertises services says so as soon as it is up…\n if (this.getServices() !== undefined || this.myAck > 0) {\n if (this.firstPublish === \"at-start\") void this.publish().catch(() => {});\n // …or right after its first look, and by FIRST_PUBLISH_MAX_MS whatever came of it.\n else this.firstPublishTimer = setTimeout(() => { this.firstPublishTimer = null; this.ensureAdvertised(); }, FIRST_PUBLISH_MAX_MS);\n }\n this.scheduleHeartbeat();\n // A relay that answers again after failing: look and publish now, not at this link's pace (which may be minutes).\n this.unsubscribe = this.transport.subscribe?.(change => { if (change === \"recovered\") this.discoveryRecovered(); }) ?? null;\n void this.poll();\n }\n\n /**\n * A relay answers again after failing. What this link could not do meanwhile goes now: a publish that waits, and a\n * read when its last one was not answered by the network (it failed, or handed back a copy kept from before) or when\n * the link is looking for its peer (anything but the background and connected paces). A link whose last read was\n * answered missed nothing: it reads at its pace. Every link heard this, so a read each one made the cost of a relay\n * that keeps flipping between throttled and answering grow with the number of chats: 42 reads a flip on a profile\n * whose contacts are mostly away, for nothing those reads could find.\n */\n private discoveryRecovered(): void {\n if (!this.running) return;\n const publish = !!(this.publishRetryTimer || this.discoveryErrors.publish);\n const pace = this.pace(), read = this.readMissed || (pace !== \"background\" && pace !== \"connected\");\n if (!publish && !read) return;\n traceLink(this.identity.pubKeyZ32, \"discovery-recovered\", { publishWaiting: !!this.publishRetryTimer, read });\n if (publish) void this.publish().catch(() => {});\n if (read) this.pollNow();\n }\n\n /** This side's packet goes out now, unless one already did. */\n ensureAdvertised(): void {\n if (!this.running || this.lastPublishedAt > 0 || this.publishing) return;\n void this.publish().catch(() => {});\n }\n\n /** 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. */\n republish(): void {\n if (this.running) void this.publish().catch(() => {});\n }\n\n /** Stops the loops. With `announce`, first tells the peer we are gone. */\n async stop(announce = true): Promise<void> {\n if (!this.running) return;\n this.running = false;\n this.silent = !announce;\n this.unsubscribe?.();\n this.unsubscribe = null;\n if (this.pollTimer) clearTimeout(this.pollTimer);\n if (this.heartbeatTimer) clearTimeout(this.heartbeatTimer);\n if (this.publishRetryTimer) clearTimeout(this.publishRetryTimer);\n if (this.firstPublishTimer) clearTimeout(this.firstPublishTimer);\n this.pollTimer = this.heartbeatTimer = this.publishRetryTimer = this.firstPublishTimer = null;\n countUnusedInvite(this.transport, this, false);\n this.rtcSignal = null;\n this.callSignal = null;\n this.presenceDueOut = false;\n this.events.onStatus?.(\"offline\");\n if (announce) {\n try {\n await this.publishOnce(false);\n } catch {\n // best effort, the packet goes stale on its own\n }\n }\n }\n\n setNick(nick: string | undefined): void {\n this.nick = nick || undefined;\n }\n\n /** The user is looking at this link: poll at chat speed. */\n setActive(active: boolean): void {\n this.active = active;\n if (active) this.pollNow();\n }\n\n /**\n * Signaling in progress: look fast. `offer`: this side's offer to a saved contact, whose answer may be a while\n * (`OFFER_FAST_MS`): fast at first, then less often.\n */\n setFastPoll(fast: boolean, offer = false): void {\n this.fastPollUntil = fast ? Date.now() + (offer ? OFFER_LOOK_MS : FAST_POLL_MAX_MS) : 0;\n this.fastStepsAfter = fast && offer ? Date.now() + OFFER_FAST_MS : 0;\n // The signal this window is for goes out next (`SIGNAL_OUT_READS`): the reads left for the last one end, and so do\n // those for the contact's (`SIGNAL_DUE_READS`).\n this.signalReadsLeft = this.dueSignalReadsLeft = 0;\n if (fast) this.pollNow();\n }\n\n /**\n * The peer, or its offer, is due any moment: poll fast for `EXPECT_PEER_MS` (never cutting a longer fast window short),\n * then slow down step by step (`nextInterval`) rather than at once. `signal`: its offer is due now (it may be out\n * already): a read goes at once, even inside a window already looking fast, and the first reads that look for it are\n * signaling (`SIGNAL_DUE_READS`).\n */\n expectPeer(awaited = false, signal = false): void {\n const until = Date.now() + EXPECT_PEER_MS;\n this.expectUntil = Math.max(this.expectUntil, until);\n if (awaited) this.awaitedUntil = Math.max(this.awaitedUntil, until);\n if (signal) this.dueSignalReadsLeft = SIGNAL_DUE_READS;\n // Due now: an offer of mine that was looking less often looks fast again, as long as this window.\n const stepping = this.fastStepsAfter > 0 && Date.now() >= this.fastStepsAfter;\n if (this.fastStepsAfter) this.fastStepsAfter = Math.max(this.fastStepsAfter, until);\n if (until <= this.fastPollUntil) { if (stepping || signal) this.pollNow(); return; }\n this.fastPollUntil = until;\n this.pollNow();\n }\n\n /**\n * The contact just left a live session, and is likely coming back (an app restarting): fast for `EXPECT_PEER_MS`,\n * then the active pace until `WATCH_PEER_MS` passed, whatever the chat's pace would be. `idleMs` (a daemon's,\n * `DAEMON_WATCH_PEER_IDLE_MS`): then no slower than the idle pace until that long after now.\n */\n watchPeer(idleMs = 0): void {\n this.watchUntil = Math.max(this.watchUntil, Date.now() + WATCH_PEER_MS);\n this.lingerUntil = Math.max(this.lingerUntil, Date.now() + idleMs);\n this.watchFrom = this.presence.lastPacketAt;\n this.departedUntil = Date.now() + DEPARTED_READ_MS;\n this.expectPeer();\n }\n\n /**\n * Nothing a read finds can be acted on for a while (a dial waiting out its backoff, whose end has a look of its own):\n * the windows that look fast for the contact (`expectPeer`, `watchPeer`) end, and the link reads at its pace from the\n * next read on. An offer of this side's out keeps its window.\n */\n /**\n * This side just left DHT only: the contact that dials waits on its next packet that advertises, so that one is\n * signaling (`PkarrRequestOptions.signal`). As a plain write, an app that had spent its relay minute held it 55 s,\n * and the contact dialled only then.\n */\n presenceDue(): void {\n this.presenceDueOut = true;\n }\n\n calm(): void {\n if (this.rtcSignal !== null) return;\n this.fastPollUntil = this.fastStepsAfter = this.expectUntil = this.watchUntil = this.lingerUntil = this.dueSignalReadsLeft = 0;\n }\n\n /** The data link carries chat and services while it is up. */\n setDataLinkOpen(open: boolean): void {\n this.connected = open;\n this.stalledUntil = 0;\n if (!open) this.pollNow();\n }\n\n /**\n * The open data link's connection went `disconnected` (true), or came back: the contact's app may have crashed, and\n * once it starts again its offer is on Pkarr, which nothing on a dead data link says. Read fast for as long as it\n * lasts (the connection is given up or back within seconds), not at the connected pace. One read as it went\n * `disconnected` found only an offer already out: an app back a moment later (a tab opened again by hand) waited for\n * the connection's grace to run out (web/restart-relink.spec.ts, 20 s on a busy machine). Never longer than\n * `STALLED_LOOK_MS`, whatever becomes of the connection.\n */\n setDataLinkStalled(stalled: boolean): void {\n if (stalled === Date.now() < this.stalledUntil) return;\n this.stalledUntil = stalled ? Date.now() + STALLED_LOOK_MS : 0;\n if (stalled) this.pollNow();\n }\n\n async setCallSignal(signal: string | null): Promise<void> {\n this.callSignal = signal;\n this.lastActivity = Date.now();\n await this.publish().catch(() => {});\n this.pollNow();\n }\n\n /** Includes encryption, DNS encoding and the actual concurrent record budget. */\n fitsRtcSignal(signal: string): boolean {\n try {\n buildLinkRecords(this.identity.pubKeyZ32, { messages: this.sentBuffer, ackTimestamp: this.myAck,\n nick: this.nick, callSignal: this.callSignal, rtcSignal: signal, services: this.getServices(), transports: this.transports }, this.encKey);\n return true;\n } catch { return false; }\n }\n\n /**\n * A group link's transports and how to dial them (`_tr`, `encodePacketTransports`): published with the next packet,\n * now if it changed. `null` publishes none, which is what every link but a group's with an app lacking WebRTC does.\n */\n setTransports(value: string | null): void {\n if (this.transports === value) return;\n this.transports = value;\n if (!this.running) return;\n // A first packet still held back (`firstPublish`) carries it when it goes; one already out does not.\n if (this.firstPublishTimer && !this.lastPublishedAt && !this.publishing) return;\n void this.publish().catch(() => {});\n }\n\n async setRtcSignal(signal: string | null, reportFailure = false): Promise<void> {\n if (this.rtcSignal === signal) return;\n this.rtcSignal = signal;\n if (signal === null) { this.rtcAttempt++; this.rtcAttemptOut = false; }\n // A signal taken back (the session opened, or the attempt ended) is nothing the contact waits for: upkeep.\n if (reportFailure) await this.publish(signal === null);\n else await this.publish(signal === null).catch(() => {});\n if (signal) this.pollNow();\n }\n\n /**\n * Hands over the messages the peer has not acknowledged, for delivery over\n * the data link. That channel is reliable, so they leave the Pkarr buffer.\n */\n takeUnacknowledged(): CompactMessage[] {\n const pending = this.sentBuffer;\n if (pending.length === 0) return [];\n this.sentBuffer = [];\n this.events.onPeerAck?.(Math.max(...pending.map((m) => m.t)));\n void this.publish().catch(() => {});\n return pending;\n }\n\n /** Call after the list of shared services changed. A first publish still being held back will say it all. */\n async refreshAdvertisement(): Promise<void> {\n if (this.firstPublishTimer) return;\n await this.publish().catch(() => {});\n }\n\n /** Sends a chat message through Pkarr. Returns an error string, or null on success. */\n async sendMessage(text: string, timestamp = Date.now()): Promise<string | null> {\n const byteLength = utf8Encode(text).length;\n if (byteLength > MAX_DHT_TEXT_BYTES) {\n return `Message too large for DHT (${byteLength} bytes, max ${MAX_DHT_TEXT_BYTES}). Try a shorter message or share a link instead.`;\n }\n this.lastActivity = Date.now();\n this.sentBuffer = [...this.sentBuffer, { t: timestamp, m: text }];\n this.upkeepOnly = false;\n try {\n const kept = await this.publishOnce(true);\n if (kept === 0) return \"Message could not be published — DHT payload limit exceeded.\";\n } catch (error) {\n // The message stays in the buffer; keep trying instead of losing it.\n if (this.publishRetryTimer) clearTimeout(this.publishRetryTimer);\n this.publishRetryTimer = setTimeout(() => void this.publish(true).catch(() => {}), this.retryDelay(error));\n // Not an error for the sender: it is queued, and the connection status shows the trouble (a wait for the\n // relays' budget is none).\n if (!isDiscoveryBudgetError(error)) this.events.onStatus?.(\"error\");\n return null;\n }\n this.pollNow();\n return null;\n }\n\n pollNow(): void {\n if (!this.running) return;\n if (this.pollTimer) clearTimeout(this.pollTimer);\n this.pollTimer = null;\n void this.poll();\n }\n\n /**\n * The peer's packet is at hand now (a member of the group carried it, `CarriedTransport`): read it. A read under way\n * may be past the point where it would see it, so another follows that one at once rather than at the pace's wait.\n */\n lookNow(): void {\n if (!this.running) return;\n if (this.polling) { this.pollAgain = true; return; }\n this.pollNow();\n }\n\n /**\n * The next poll's wait. After a window that looked fast for the peer (`expectPeer`), the wait grows with the time\n * since the window ended (on the relays: 4, 4, 8, 16 s, then 30 s) up to the pace's own. A\n * peer's offer held back by its relays' budget lands whenever that frees a request: it used to land seconds after\n * the window, and wait out a whole background poll (30 s) there (2026-09-27). About three more reads a window that\n * ends with no offer.\n */\n private nextInterval(): number {\n const pace = this.pace();\n const interval = this.intervals[pace];\n const since = Date.now() - this.expectUntil;\n // An offer out a while: 4, 4, 8 s… between looks (on the relays), as long as its window lasts.\n const stepping = this.fastStepsAfter ? Date.now() - this.fastStepsAfter : -1;\n // Counted among the app's unused invites while read as one (below).\n const unused = countUnusedInvite(this.transport, this, pace === \"background\" && since >= 0 && !this.presence.online && this.invite());\n if (pace === \"fast\" && stepping >= 0) return Math.min(OFFER_STEP_MAX * interval, Math.max(2 * interval, stepping));\n if (pace === \"fast\" || pace === \"connected\" || since < 0) return interval;\n // An invite nobody used, or a joined one whose inviter never came, no longer awaited: the older it is, the less often\n // it is read, as far as their count needs. Nobody there: an inviter gone may have left a packet, its goodbye, before the join.\n if (pace === \"background\" && !this.presence.online && this.invite()) return unusedInviteWait(Date.now() - this.awaitingSince, interval, unused);\n return Math.min(interval, Math.max(2 * this.intervals.fast, since));\n }\n\n /**\n * Looking for a contact that went away (`watchPeer`) and has not shown itself back: no signal of mine is out, and no\n * packet of the contact's since then advertises (the one it leaves on its way out does not). The relays' budget gives\n * these reads a share of its own (`PkarrRequestOptions.watch`), so a member watching several that left still reads\n * the one that comes back.\n */\n private watching(): boolean {\n return Date.now() < this.watchUntil && this.rtcSignal === null && !(this.presence.online && this.presence.lastPacketAt > this.watchFrom);\n }\n\n /** A contact never seen, whose invite was sent lately (`AWAITING_PEER_MS`): its join is due. */\n private awaitingPeer(): boolean {\n return this.presence.lastPacketAt === 0 && Date.now() - this.awaitingSince < AWAITING_PEER_MS;\n }\n\n /** How urgently this link looks right now. */\n private pace(): keyof PollIntervals {\n // Connected peers signal over the data link; no reason to hurry Pkarr, unless it stopped answering.\n if (Date.now() < this.stalledUntil) return \"fast\";\n if (this.connected) return \"connected\";\n if (Date.now() < this.fastPollUntil) return \"fast\";\n if (Date.now() < this.watchUntil) return \"active\";\n // Someone who just sent an invite may look elsewhere while waiting: the join still comes in quickly.\n if (!this.active && this.awaitingPeer()) return \"active\";\n // A contact that went away, still not back, a daemon's minutes after `watchUntil` (`watchPeer`'s `idleMs`).\n if (!this.active && Date.now() < this.lingerUntil && !(this.presence.online && this.presence.lastPacketAt > this.watchFrom)) return \"idle\";\n if (!this.active) return \"background\";\n return Date.now() - this.lastActivity > IDLE_THRESHOLD ? \"idle\" : \"active\";\n }\n\n private scheduleHeartbeat(): void {\n if (this.heartbeatTimer) clearTimeout(this.heartbeatTimer);\n this.heartbeatTimer = setTimeout(() => {\n if (!this.running) return;\n if (this.getServices() !== undefined && !this.upkeepWaits()) void this.publish(true).catch(() => {});\n this.scheduleHeartbeat();\n }, PRESENCE_HEARTBEAT);\n }\n\n /** An unused invite of this side's, no longer awaited, whose packet went out less than `UNUSED_INVITE_UPKEEP_MS` ago. */\n private upkeepWaits(): boolean {\n const now = Date.now();\n return this.ownInvite() && !this.presence.online && !this.connected && now - this.awaitingSince >= AWAITING_PEER_MS && now - this.lastPublishedAt < UNUSED_INVITE_UPKEEP_MS - PRESENCE_HEARTBEAT / 2;\n }\n\n /**\n * Coalesces publishes: at most one in flight and one queued behind it. `upkeep`: nothing new to say (the heartbeat, a\n * retry of what waits): with nothing else asked for since, the packet goes as upkeep (`publishOnce`).\n */\n private publish(upkeep = false): Promise<void> {\n if (this.silent) return Promise.resolve();\n if (!upkeep) this.upkeepOnly = false;\n else if (!this.publishing && !this.publishRetryTimer) this.upkeepOnly = true;\n if (this.publishing) {\n this.publishAgain = true;\n return this.publishing;\n }\n if (this.publishRetryTimer) clearTimeout(this.publishRetryTimer);\n this.publishRetryTimer = null;\n this.publishing = (async () => {\n try {\n do {\n this.publishAgain = false;\n await this.publishOnce(this.running, this.upkeepOnly);\n } while (this.publishAgain && this.running);\n } catch (error) {\n // A signal that is not published is a call that never rings: try again. Held back by the relays' request\n // budget, it goes as soon as the budget frees a request, and nothing is wrong meanwhile.\n if (this.running) {\n if (!isDiscoveryBudgetError(error)) this.discoveryResult(\"publish\", error);\n this.publishRetryTimer = setTimeout(() => void this.publish(true).catch(() => {}), this.retryDelay(error));\n }\n throw error;\n } finally {\n this.publishing = null;\n }\n })();\n return this.publishing;\n }\n\n private async publishOnce(advertise: boolean, upkeep = false): Promise<number> {\n const rtcSignal = advertise ? this.rtcSignal : null;\n const attempt = this.rtcAttempt;\n const started = Date.now();\n let keptMessages: number;\n try {\n // An offer or answer not out yet is what the contact waits for (`PkarrRequestOptions.signal`). Written while this\n // link watches for a contact that went away, the packet is what that contact, back, looks for first (`watch`).\n // The heartbeat of a chat whose data link is up is upkeep nobody waits on: a background write, from the share the\n // relays' budget keeps for those, so it never takes a request a group's door or edges need. As a chat's write,\n // the budget refusing it held the groups back for its reserve: a daemon with 30 live chats sat at the budget\n // while idle, and people joining its group by link waited 80 s to 9 min (bug hunt, 2026-10-08).\n // So is a packet with nothing in it a contact waits for (no signal, no text) while the contact is not there: its\n // last read found it away, or none was made yet in this run (an invite just sent awaits its peer: not that). As a\n // chat's write, the presence of the chats whose contacts were long gone took the relays' minute as the app started,\n // ahead of the chats whose contacts were online and offering (`CHAT_RESERVE_PER_CHAT` in relay.ts). And so is a\n // packet that only takes a signal back (`setRtcSignal`): as a chat's write, the 30 chats that went live as the app\n // started took their offers and answers back in a minute the start had spent, and each, first in line once refused,\n // held back every read of the chats still waiting for an answer until the minute freed.\n const awaited = this.connected || this.presence.online || this.sentBuffer.length > 0 || this.callSignal !== null || this.awaitingPeer();\n const takesBack = !rtcSignal && this.rtcSignalOut !== null;\n const options = (rtcSignal && rtcSignal !== this.rtcSignalOut) || (advertise && this.presenceDueOut) ? { signal: true } : this.watching() ? { watch: true }\n : (upkeep && (this.connected || takesBack)) || (!rtcSignal && !awaited) ? { background: true } : undefined;\n this.wroteInBackground = options?.background === true;\n // No relay takes it now: refused before it is built, as before it is signed (`RelayTransport.publishDated`). With\n // 200 chats on the web, the packets built for that were a quarter of the script of a page left alone.\n const held = this.transport.publishHeld?.(this.identity.pubKeyZ32, options);\n if (held) throw held;\n const state = {\n messages: this.sentBuffer,\n ackTimestamp: this.myAck,\n nick: this.nick,\n callSignal: this.callSignal,\n rtcSignal,\n services: advertise ? this.getServices() : undefined,\n transports: advertise ? this.transports : null,\n };\n // A try again of a packet that did not go out, saying the same: the records built for it, not sealed anew. Each\n // sealing is new bytes, and a group edge that is down hands every new packet to members (`CarriedTransport`): an\n // edge to a member who left handed two of them the same packet again at each try the relays' budget held, every\n // few seconds (35 KB a minute on an idle web app with two such edges, bug hunt 2026-11-08).\n const says = JSON.stringify(state);\n const built = this.unsent?.says === says ? this.unsent.built : buildLinkRecords(this.identity.pubKeyZ32, state, this.encKey);\n this.unsent = { says, built };\n keptMessages = built.keptMessages;\n await this.transport.publish(this.identity, built.records, options);\n this.unsent = null;\n } catch (error) {\n const ms = Date.now() - started, waiting = isDiscoveryBudgetError(error);\n traceLink(this.identity.pubKeyZ32, \"publish\", { ms, rtc: !!rtcSignal, error: String(error), ...(waiting && { waiting, retryInMs: error.retryInMs }) });\n this.events.onPublish?.({ ms, rtc: !!rtcSignal, error: error instanceof Error ? error.message : String(error), ...(waiting && { waiting, retryInMs: error.retryInMs }) });\n throw error;\n }\n const ms = Date.now() - started;\n this.lastPublishedAt = Date.now();\n if (advertise) this.presenceDueOut = false;\n // Signaling's fast window counts from when its signal went out: one the relays' budget held back for most of the\n // window (an offer held 50 s) would otherwise have its answer read at the background pace (2026-09-27).\n const signalOut = !!rtcSignal && rtcSignal !== this.rtcSignalOut;\n this.signalReadsLeft = signalOut ? SIGNAL_OUT_READS : rtcSignal ? this.signalReadsLeft : 0;\n if (signalOut && this.fastPollUntil > 0) {\n const lapsed = this.fastPollUntil <= Date.now() || (this.fastStepsAfter > 0 && this.fastStepsAfter <= Date.now());\n this.fastPollUntil = Math.max(this.fastPollUntil, Date.now() + (this.fastStepsAfter ? OFFER_LOOK_MS : FAST_POLL_MAX_MS));\n // An offer's first seconds of fast looks count from then too.\n if (this.fastStepsAfter) this.fastStepsAfter = Date.now() + OFFER_FAST_MS;\n // Its next look was put off to a slower pace: it comes at the fast one now.\n if (lapsed) this.pollNow();\n }\n this.rtcSignalOut = rtcSignal;\n if (rtcSignal && attempt === this.rtcAttempt) this.rtcAttemptOut = true;\n traceLink(this.identity.pubKeyZ32, \"publish\", { ms, rtc: !!rtcSignal, advertise });\n this.events.onPublish?.({ ms, rtc: !!rtcSignal, ...(signalOut && { signalOut }) });\n this.discoveryResult(\"publish\");\n return keptMessages;\n }\n\n /**\n * When a publish that failed goes again: when the relays' budget frees a request, if that held it back; a chat's or a\n * group's write within `PUBLISH_RETRY_MS` meanwhile, which keeps it first in line, a background one when its share frees.\n */\n private retryDelay(error: unknown): number {\n if (!isDiscoveryBudgetError(error)) return PUBLISH_RETRY_MS;\n return budgetRetryMs(error, BUDGET_RETRY_MIN_MS, this.wroteInBackground ? BACKGROUND_RETRY_MAX_MS : PUBLISH_RETRY_MS);\n }\n\n private discoveryResult(operation: \"publish\" | \"read\", error?: unknown): void {\n if (error !== undefined) this.discoveryErrors[operation] = `Could not ${operation} discovery: ${error instanceof Error ? error.message : String(error)}`;\n else delete this.discoveryErrors[operation];\n this.events.onDiscoveryError?.(Object.values(this.discoveryErrors).join(\". \") || null);\n }\n\n private async poll(): Promise<void> {\n if (!this.running || this.polling) return;\n this.polling = true;\n this.events.onPoll?.({ polling: true, nextInMs: 0 });\n const started = Date.now();\n // A read the relays' budget held back: the next one goes when the budget frees a request.\n let heldBackMs: number | undefined;\n /** This read is one of `SIGNAL_DUE_READS`: one the budget held back asked nothing of the relays, and is not counted. */\n let dueRead = false;\n try {\n // A look that can wait (nobody watching, nothing expected) says so: a transport with a request\n // budget spends only part of it on those, and keeps the rest for links that are signaling.\n const pace = this.pace();\n // This side's offer is out, and this read looks for its answer, or its offer or answer just went out\n // (`SIGNAL_OUT_READS`), or the contact's offer is due now (`SIGNAL_DUE_READS`): signaling (`PkarrRequestOptions.signal`).\n const signalOut = pace === \"fast\" && this.rtcSignalOut !== null && (this.fastStepsAfter > 0 || this.signalReadsLeft > 0);\n const signal = signalOut || (pace === \"fast\" && this.dueSignalReadsLeft > 0);\n if (signalOut) { if (!this.fastStepsAfter) this.signalReadsLeft--; }\n else if (signal) { this.dueSignalReadsLeft--; dueRead = true; }\n const watch = !signal && this.watching();\n // In its first seconds, when an app that restarts has its offer out (`PkarrRequestOptions.departed`). Not `watch`\n // alone: a packet the contact put just before its goodbye, read only after it, advertises, and looks like it is back.\n const departed = !signal && Date.now() < this.departedUntil;\n // An invite this side made, its joiner due: the knock is read here (`PkarrRequestOptions.awaited`).\n const awaited = !signal && this.ownInvite() && this.awaitingPeer();\n // A daemon's idle-pace reads of a contact long gone (`watchPeer`'s `idleMs`) can wait as much.\n const background = pace === \"background\" || pace === \"connected\" || (pace === \"idle\" && !this.active);\n // Back after a restart: the offer waits on this read (`PkarrRequestOptions.resume`).\n const resume = !signal && !watch && (this.resumeReads || Date.now() < this.awaitedUntil);\n // Every relay out of reach: what they gave last still stands for the contact, but the read says it failed. Taken as\n // the answer, the link never said it could not read its contact, and the engine let a gone contact's HyperDHT\n // listener go for the whole outage (`contactUnread`), where only that listener could bring the contact back.\n let unread: RelaysFailedError | undefined;\n const packet = await this.transport.resolve(this.peerPubKeyZ32, { background, urgent: pace === \"fast\", ...(signal && { signal }), ...(watch && { watch }), ...(departed && { departed }), ...(awaited && { awaited }), ...(resume && { resume }) }, false)\n .catch((error: unknown) => { if (!(error instanceof RelaysFailedError)) throw error; unread = error; return error.kept; });\n if (!this.running) return;\n this.discoveryResult(\"read\", unread);\n const ms = Date.now() - started;\n const wasOnline = this.presence.online, wasSeen = this.presence.lastPacketAt;\n // What this read finds that the read before did not have came in between, by this device's clock.\n const readBefore = this.lastReadAt, peerPacketBefore = this.peerPacketAt;\n const answered = this.transport.readAnsweredAt?.(this.peerPubKeyZ32);\n const read = answered !== undefined && answered >= started;\n if (read) this.lastReadAt = started;\n if (read || !this.transport.readAnsweredAt) this.resumeReads = false;\n if (packet && (read || !this.transport.readAnsweredAt)) this.awaitedUntil = 0;\n this.readMissed = !!this.transport.readAnsweredAt && !read;\n if (this.readMissed) heldBackMs = this.transport.readHeldBackFor?.(this.peerPubKeyZ32);\n\n let receivedNew = false;\n // The packet an inviter puts under the contact's key before they join (`emptyLinkRecords`), so\n // their first packet lands faster, says nobody is there yet.\n const batch = packet ? parseLinkRecords(packet, this.encKey) : null;\n if (batch && isEmptyLinkPacket(batch)) {\n if ((globalThis as { __ghostlyLinkTrace?: boolean }).__ghostlyLinkTrace) traceLink(this.identity.pubKeyZ32, \"poll\", { ms, pace, placeholder: true });\n } else if (batch) {\n if (batch.peerAck > 0) {\n this.sentBuffer = this.sentBuffer.filter((m) => m.t > batch.peerAck);\n this.events.onPeerAck?.(batch.peerAck);\n }\n\n if (batch.latestTimestamp > 0 && batch.latestTimestamp > this.lastSeenTimestamp) {\n const fresh = batch.messages.filter((m) => m.timestamp > this.lastSeenTimestamp);\n this.lastSeenTimestamp = batch.latestTimestamp;\n this.myAck = batch.latestTimestamp;\n this.lastActivity = Date.now();\n receivedNew = true;\n if (fresh.length > 0) this.events.onMessages?.(fresh, batch);\n }\n\n // No further ahead than readers take a date (`newerPacket`): anyone holding the invite can date a packet under the\n // peer's key, and a later offer dated before this one does not read as seen arriving (`offerIsFresh`).\n if (read && batch.packetTimestamp > this.peerPacketAt) this.peerPacketAt = Math.min(batch.packetTimestamp, Date.now() + PKARR_FUTURE_SKEW_MS);\n // How long ago the peer published is measured on this clock, from when its packet was first read here.\n const seenAt = batch.packetTimestamp === wasSeen ? presenceSeenAt(this.presence) : Math.max(readBefore, Math.min(batch.packetTimestamp, Date.now()));\n const online = batch.services !== null && Date.now() - seenAt < PRESENCE_WINDOW;\n this.presence = {\n online,\n lastPacketAt: batch.packetTimestamp,\n seenAt,\n nick: batch.nick,\n services: online ? batch.services : null,\n };\n // Before presence: a dial that presence starts ranks with them.\n if (batch.transports !== null) {\n this.transportsAbsentSince = 0; this.transportsGone = false;\n if (batch.transports !== this.lastTransportsIn) {\n this.lastTransportsIn = batch.transports;\n this.events.onPeerTransports?.(batch.transports);\n }\n if (this.transportsUnsaid) { this.transportsUnsaid = false; this.events.onPeerTransportsUnsaid?.(false); }\n } else if (batch.services !== null && !this.transportsGone) {\n // It advertises, and `_tr` is left out for size only after `_svc` is (`buildLinkRecords`): it set none.\n this.transportsAbsentSince ||= Date.now();\n if (!this.transportsUnsaid && this.lastTransportsIn !== null) { this.transportsUnsaid = true; this.events.onPeerTransportsUnsaid?.(true); }\n if (Date.now() - this.transportsAbsentSince >= TRANSPORTS_GONE_MS) {\n this.transportsGone = true;\n // The value it said before, said again later, is news again.\n this.lastTransportsIn = null;\n this.events.onPeerTransportsGone?.();\n }\n }\n this.events.onPresence?.(this.presence);\n if (read && readBefore && batch.packetTimestamp !== wasSeen) this.events.onPeerClock?.(batch.packetTimestamp, readBefore, Date.now());\n\n if (batch.callSignal !== null && batch.callSignal !== this.lastCallSignalIn) {\n this.lastCallSignalIn = batch.callSignal;\n this.events.onCallSignal?.(batch.callSignal);\n }\n this.peerRtcSignal = batch.rtcSignal;\n const newSignal = batch.rtcSignal !== null && batch.rtcSignal !== this.lastRtcSignalIn;\n // A slow read, the contact's first packet, or a signal: the steps of a pairing, timed. Every\n // read when a measurement asked for the whole trace.\n if (ms > 1_500 || (online && !wasOnline) || batch.packetTimestamp !== wasSeen || newSignal || (globalThis as { __ghostlyLinkTrace?: boolean }).__ghostlyLinkTrace)\n traceLink(this.identity.pubKeyZ32, \"poll\", { ms, pace, online, age: Date.now() - batch.packetTimestamp, seen: Date.now() - seenAt, rtc: newSignal, first: wasSeen === 0 });\n if (newSignal) {\n // The offer that was due is here: what follows it reads as its answer's (`SIGNAL_OUT_READS`).\n this.dueSignalReadsLeft = 0;\n this.lastRtcSignalIn = batch.rtcSignal!;\n this.events.onRtcSignal?.(batch.rtcSignal!, readBefore ? { since: readBefore, after: peerPacketBefore || null } : undefined);\n }\n } else if (ms > 1_500 || (globalThis as { __ghostlyLinkTrace?: boolean }).__ghostlyLinkTrace) traceLink(this.identity.pubKeyZ32, \"poll\", { ms, pace, packet: false });\n\n if (receivedNew) await this.publish().catch(() => {});\n this.events.onStatus?.(\"online\");\n if (!this.firstPollDone) { this.firstPollDone = true; this.events.onFirstPoll?.(); }\n } catch (error) {\n this.readMissed = true;\n if (this.running) {\n traceLink(this.identity.pubKeyZ32, \"poll\", { ms: Date.now() - started, error: String(error) });\n // A read the relays' request budget held back (nothing known yet to answer from) is a wait: the next poll reads.\n if (isDiscoveryBudgetError(error)) heldBackMs = error.retryInMs; else {\n this.discoveryResult(\"read\", error);\n this.events.onStatus?.(\"error\");\n }\n if (!this.firstPollDone) { this.firstPollDone = true; this.events.onFirstPoll?.(); }\n }\n } finally {\n this.polling = false;\n if (dueRead && heldBackMs !== undefined) this.dueSignalReadsLeft++;\n if (this.running && this.pollAgain) {\n this.pollAgain = false;\n if (this.pollTimer) clearTimeout(this.pollTimer);\n this.pollTimer = null;\n void this.poll();\n } else if (this.running && !this.pollTimer) {\n const interval = this.nextInterval();\n // The interval is a period, counted from the start of this read: a read that took long (a key\n // nobody has yet, a relay asking its DHT) does not push the next one further out. A read the budget held back\n // reads again when it frees a request, where the relays take it in turn per key (`READ_TURN_MS` in relay.ts):\n // at the next poll, the chats that had just taken a request took the next.\n const wait = heldBackMs !== undefined ? Math.min(interval, Math.max(BUDGET_RETRY_MIN_MS, heldBackMs)) : Math.max(MIN_POLL_GAP_MS, interval - (Date.now() - started));\n this.events.onPoll?.({ polling: false, nextInMs: wait });\n this.pollTimer = setTimeout(() => {\n this.pollTimer = null;\n void this.poll();\n }, wait);\n }\n }\n }\n}\n","/**\n * Whether this device's own WebRTC attempts say that direct connections do not get through its network: a VPN that\n * takes every packet through its tunnel, a firewall that drops UDP, a carrier's NAT. The app cannot see a VPN; it can\n * see that its attempts keep failing the same way, and say so where people look at the connection (the chat's\n * connection panel, Settings → Network). Chats still go live through a relayed transport, or carry short texts on the\n * DHT.\n *\n * What an attempt says (`DataLink` tells, per attempt):\n * - `open`: a WebRTC connection opened (`closed`: that one ended). Direct connections work here, whatever failed before.\n * - `no-public`: the attempt did not connect, and this device had gathered no public candidate for it (none at all, or\n * host addresses only: no STUN server answered). Its own evidence: nothing of the contact's is in it.\n * - `symmetric`: it did not connect, and this device's public address was a different port for each STUN server it\n * asked (`symmetricNat`): its network maps every destination apart, so a contact cannot reach the port it was told.\n * Its own evidence too.\n * - `no-path`: this device's offer was answered, it had public candidates that read as reachable, and no pair\n * connected. The contact may be the one behind the network that blocks; several contacts are this device.\n *\n * The rule, on purpose slow to say yes: no WebRTC connection open now and none opened since, and either\n * `DIRECT_OWN_ATTEMPTS` attempts with this device's own evidence, or attempts that failed with `DIRECT_PEERS`\n * different contacts (a contact who is also a member of a group counts under each key, so two is not enough). One\n * failed dial never shows anything. It clears by itself: on the first connection that opens, when the network changes\n * (`reset`), and once the evidence is older than `DIRECT_EVIDENCE_MS` (a network that changed without the app hearing\n * of it).\n */\nexport type DirectEvidence = \"open\" | \"closed\" | \"no-public\" | \"symmetric\" | \"no-path\";\n\n/** Evidence older than this says nothing about the network now. */\nexport const DIRECT_EVIDENCE_MS = 30 * 60_000;\n/** Attempts with this device's own evidence (`no-public`, `symmetric`) that it takes. */\nexport const DIRECT_OWN_ATTEMPTS = 2;\n/** Different contacts the attempts must have failed with, whatever their kind. */\nexport const DIRECT_PEERS = 3;\n/** Failures kept: the rule needs a few, and a group's edges may bring many. */\nconst KEPT = 64;\n/** Server reflexive candidates on one address with this many different ports: a mapping per destination. */\nconst SYMMETRIC_PORTS = 3;\n\nexport interface DirectFailure { peer: string; kind: \"no-public\" | \"symmetric\" | \"no-path\"; at: number }\n\n/**\n * Whether a local description shows a NAT that maps each destination apart: the app asks several STUN servers from one\n * socket, and a NAT that keeps one mapping answers with one address and port (the browser lists it once). Three ports\n * on one address, not two: a device on two interfaces behind one router (Wi-Fi and a cable) has two.\n */\nexport function symmetricNat(sdp: string | undefined | null): boolean {\n const ports = new Map<string, Set<string>>();\n for (const [, address, port] of (sdp ?? \"\").matchAll(/^a=candidate:\\S+ \\d+ udp \\d+ (\\S+) (\\d+) typ srflx\\b/gim)) {\n const seen = ports.get(address) ?? new Set<string>();\n ports.set(address, seen.add(port));\n }\n return [...ports.values()].some(seen => seen.size >= SYMMETRIC_PORTS);\n}\n\n/** The rule alone: whether `failures` (every one after the last `open`) say direct connections are blocked at `now`. */\nexport function directBlocked(failures: readonly DirectFailure[], now: number): boolean {\n const fresh = failures.filter(f => now - f.at < DIRECT_EVIDENCE_MS);\n if (fresh.filter(f => f.kind !== \"no-path\").length >= DIRECT_OWN_ATTEMPTS) return true;\n return new Set(fresh.map(f => f.peer)).size >= DIRECT_PEERS;\n}\n\nexport class DirectPathWatch {\n private failures: DirectFailure[] = [];\n /** Contacts a WebRTC connection is open with now. */\n private readonly open = new Set<string>();\n private was = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n /** `onChange`: `blocked` changed (evidence came, a connection opened, the network changed, the evidence aged out). */\n constructor(private readonly onChange: (blocked: boolean) => void = () => {}, private readonly now: () => number = Date.now) {}\n\n /** One WebRTC attempt with `peer` ended this way (or its open connection closed). */\n note(peer: string, evidence: DirectEvidence): void {\n if (evidence === \"open\") { this.open.add(peer); this.failures = []; }\n else if (evidence === \"closed\") this.open.delete(peer);\n else this.failures = [...this.failures, { peer, kind: evidence, at: this.now() }].slice(-KEPT);\n this.settle();\n }\n\n /** The network changed: what failed on the old one says nothing about this one. */\n reset(): void {\n this.failures = [];\n this.settle();\n }\n\n get blocked(): boolean { return !this.open.size && directBlocked(this.failures, this.now()); }\n\n /** Stops the timer that lets the evidence age out. */\n close(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n\n private settle(): void {\n this.close();\n const blocked = this.blocked;\n if (blocked) {\n // Looked at again when the oldest evidence ages out: what is left may no longer be enough.\n const oldest = Math.min(...this.failures.map(f => f.at));\n this.timer = setTimeout(() => { this.failures = this.failures.filter(f => this.now() - f.at < DIRECT_EVIDENCE_MS); this.settle(); },\n Math.max(1_000, oldest + DIRECT_EVIDENCE_MS - this.now()));\n (this.timer as { unref?: () => void }).unref?.();\n }\n if (blocked === this.was) return;\n this.was = blocked;\n this.onChange(blocked);\n }\n}\n","import { keepsToRelays, sdpHasCandidates, waitForIceGathering } from \"./callSignal\";\nimport { symmetricNat, type DirectEvidence } from \"./directPath\";\nimport { wrapDataChannel, type FrameChannel } from \"./frames\";\nimport { traceLink } from \"./linkTrace\";\nimport {\n DATA_CHANNEL_ID,\n DATA_CHANNEL_LABEL,\n RTC_SIGNAL_FUTURE_MS,\n buildDataSdp,\n extractRtcParams,\n offerIsFresh,\n type SignalSight,\n parseRtcSignal,\n type RtcSignal,\n} from \"./signal\";\n\n/**\n * The WebRTC data link of one link: a single RTCPeerConnection carrying the\n * negotiated `ghostly/1` DataChannel. Offer and answer travel through the\n * `_rtc` record; once the channel is open Pkarr is out of the picture and all\n * application traffic flows peer to peer (or through TURN, if ICE needs it).\n */\nexport type DataLinkState = \"idle\" | \"offering\" | \"answering\" | \"connecting\" | \"open\";\n\nexport interface DataLinkOptions {\n myPubKeyZ32: string;\n peerPubKeyZ32: string;\n createPeerConnection: () => RTCPeerConnection;\n /** Publishes (or clears, with null) my `_rtc` record. */\n publishSignal: (signal: string | null) => void;\n /**\n * Whether a signal of this side went out in this attempt: a relay (or the authenticated channel) took it. An answer\n * the relays' budget held back the whole attempt never reached the offerer, so its failing says nothing of the\n * network (agents#1637). Left out: every signal counts as out.\n */\n signalOut?: () => boolean;\n /** Signaling in progress (or over): look fast for the peer's signal. `offer`: for the answer to this side's offer. */\n setFastPoll: (fast: boolean, offer?: boolean) => void;\n onOpen: (channel: FrameChannel) => void;\n onClose: () => void;\n onState?: (state: DataLinkState) => void;\n /**\n * How long an attempt (offer or answer out, channel not yet open) may take before it is given up, so the\n * next one can start, asked as each one starts. Default `CONNECT_TIMEOUT_MS`; a first pairing, whose contact\n * is right there reading its invite, uses a short one until it is over.\n */\n attemptTimeoutMs?: () => number | undefined;\n /**\n * The open connection went `disconnected` (true: ICE consent checks unanswered, the contact may be gone or its app\n * restarted; the connection is given `DISCONNECT_GRACE_MS`), or came back from it (false).\n */\n onDisconnected?: (disconnected: boolean) => void;\n /**\n * Whether the peer's packet, as last read, still carries its offer of that time (`RtcSignal.ts`). An answer to it\n * that did not connect is then made again (`REANSWERS`); without this, never.\n */\n offerStanding?: (offerTs: number) => boolean;\n /**\n * This side's attempt was given up because the answerer answered its offer again (its connection for the answer\n * applied here is gone), or because its answer could not be applied (`ANSWER_REFUSED_REDIALS`): the answerer is\n * there, so the caller may dial again now rather than at its next look.\n */\n onAnswerReplaced?: () => void;\n /**\n * This side's answers were refused more times in a row than it offers again at once for (`ANSWER_REFUSED_REDIALS`):\n * the WebRTC of this device takes none now (libdatachannel's race, on a loaded core), and the next offer would wait\n * the caller's backoff, minutes after a few failures. Nothing about the network: the answerer was there each time.\n */\n onAnswersRefused?: () => void;\n /**\n * What an attempt said about direct connections from this device (`directPath.ts`): it opened (and, later, closed);\n * it did not connect and this device had no public candidate for it, or a public port per STUN server; or this\n * side's offer was answered and no path connected.\n */\n onDirect?: (evidence: DirectEvidence) => void;\n}\n\n/**\n * An attempt ended from outside (another transport went live first) that had both descriptions for this long and no\n * connection says what one that failed does: a path that exists connects within a second or two.\n */\nexport const STALLED_EVIDENCE_MS = 5_000;\n/** A candidate another network can reach: server reflexive (STUN answered), relayed (TURN), or learnt from the peer. */\nconst PUBLIC_CANDIDATE = /^a=candidate:.* typ (srflx|relay|prflx)\\b/m;\n\nexport const CONNECT_TIMEOUT_MS = 90_000;\nconst ICE_GATHERING_TIMEOUT_MS = 5_000;\n/**\n * An offer with its host candidates waits this long at most for a server reflexive one (STUN answered), not\n * `ICE_GATHERING_TIMEOUT_MS`. Where the STUN servers answer, they do in some 50 ms (0.44 s an offer took here, with the\n * settle); where they do not, every offer of a first pairing waited the full 5 s, twice when the inviter offered too\n * (One's e2e runs: 13 offers of 89 at 5 s, 9 more at 1.3-3 s, 2026-10-05). An offer without one still connects to most\n * contacts (their checks learn this side's address from its own); behind a restricted NAT on the contact's side it may\n * not, and the next offer of the chat then waits as long as it takes (`fullGather`). An answer is bounded the same way:\n * it waited the full 5 s, and two CLI daemons whose STUN server swallowed every request went live 10 s after the offer\n * rather than 2 s (calls bug hunt, 2026-10-12).\n */\nexport const OFFER_HOST_GATHER_MS = 2_000;\n/** The data link keeps collecting this long after the candidate it waited for came (a call too). */\nexport const DATA_SETTLE_MS = 150;\n/**\n * A connection with no candidate at all by then has stalled: Chromium, rarely and under load, gathers none, and an\n * offer or answer without one can never connect. It is made again in its place, up to `GATHER_ATTEMPTS` in all.\n */\nexport const GATHER_STALL_MS = 3_000;\nexport const GATHER_ATTEMPTS = 3;\n/** How long a connection may stay `disconnected` before it is given up. */\nconst DISCONNECT_GRACE_MS = 12_000;\n/**\n * An answer whose connection failed, while the peer still offers (`offerStanding`), is made again for the same offer,\n * up to this many times. The offerer's connection waits for an answer for its whole attempt (`CONNECT_TIMEOUT_MS`), and\n * its read of the answer may be held back by its relays' budget; the answerer's ICE gives up after about 30 s of no\n * reply. Going idle then left the link with an offer this side had answered once and would not answer again, until the\n * offerer's attempt ran out: a community's edge was live again 110 s after a member restarted (2026-09-30).\n */\nexport const REANSWERS = 2;\n/**\n * An answer to this side's offer that could not be applied, its connection failing as it was (libdatachannel 0.24.5,\n * in node-datachannel 0.33.4: the answerer's DTLS handshake can end inside setRemoteDescription, before the answer's\n * fingerprint is in, and the connection closes), is followed by a new offer at once, up to this many times until a\n * connection opens. The answerer is there; it was the dial after it that waited: its backoff, 40 s, then its next\n * look (a member let in to a group reached one of its members 72 s after its welcome on CI, 2026-10-06). Two were\n * not enough: on CI the race refused an answer again right after two others, and the edge waited 160 s for its\n * backoff (meshSignals, PR #1363). Offers through members cost no relay request; over the relays four is still a few.\n */\nexport const ANSWER_REFUSED_REDIALS = 4;\n/**\n * The same race a moment later: setRemoteDescription resolves, and the connection closes right after it (8 ms on a\n * loaded core). A connection that ends within this long of its answer going in was refused too: no network fails one\n * that soon (ICE gives up after tens of seconds), so it says nothing about direct connections (`DirectEvidence`).\n * Taken for a network that lets none through, an edge between two CLIs left WebRTC for the run, and a member whose\n * app has WebRTC alone (one from before native group links) was never reached again (groupCompat, 2026-10-12).\n */\nconst ANSWER_REFUSED_AFTER_MS = 1_000;\n/** An offer this close to the end of the offerer's attempt is not answered again: the new answer would come too late. */\nconst REANSWER_MARGIN_MS = 15_000;\n/**\n * An answer to this side's offer that comes this long or more after the offer reached the relays was read late (the\n * relays' request budget held the read back, a restart's first minute), and an attempt that ends after this side made\n * its answer again (`REANSWERS`) this long after it took an offer that still stands answered one the offerer has not\n * read yet. Neither says anything about direct connections (`DirectEvidence`): the answering side's ICE gives up about\n * 30 s after its answer with no reply, so the answer that went in late found nobody there, and the offerer gives up on\n * the attempt and offers again. Taken for a network that lets nothing through, a group's edge went native on both\n * sides, and past the native slots members stayed unreachable for the rest of a restart lab (agents#971, 2026-11-03):\n * of 38 answers read 60 s or more after their offer, 13 connected nothing; of 78 read within 20 s, none failed.\n */\nexport const LATE_ANSWER_MS = 20_000;\n\n/**\n * Traces the candidate pair an opened data link uses, by type only (host, srflx, prflx, relay; never an address): two\n * devices on one network should meet host to host. A connection without stats (a test's fake) traces nothing.\n */\nasync function tracePair(me: string, pc: RTCPeerConnection): Promise<void> {\n try {\n if (typeof pc.getStats !== \"function\") return;\n const stats = await pc.getStats();\n const byId = new Map<string, Record<string, unknown>>();\n stats.forEach((s: Record<string, unknown>) => byId.set(s.id as string, s));\n let pairId: unknown;\n for (const s of byId.values()) if (s.type === \"transport\" && s.selectedCandidatePairId) pairId = s.selectedCandidatePairId;\n const pair = pairId !== undefined ? byId.get(pairId as string)\n : [...byId.values()].find((s) => s.type === \"candidate-pair\" && s.nominated && s.state === \"succeeded\");\n if (!pair) return;\n const kind = (id: unknown) => byId.get(id as string)?.candidateType ?? \"?\";\n const rtt = typeof pair.currentRoundTripTime === \"number\" ? Math.round(pair.currentRoundTripTime * 1000) : undefined;\n traceLink(me, \"rtc-pair\", { local: kind(pair.localCandidateId), remote: kind(pair.remoteCandidateId), ...(rtt !== undefined && { rttMs: rtt }) });\n } catch { /* the trace must not fail the link */ }\n}\n\nexport class DataLink {\n state: DataLinkState = \"idle\";\n private pc: RTCPeerConnection | null = null;\n /** Each connection's listeners, and its data channel's (`wrapDataChannel`), dropped once it is closed. */\n private readonly ends = new WeakMap<RTCPeerConnection, AbortController>();\n private myOfferTs = 0;\n /** When this side's offer reached the relays, as far as this link knows (`signalWentOut`). */\n private myOfferOutAt = 0;\n /** The answer to this side's offer came `LATE_ANSWER_MS` or more after the offer went out. */\n private answerCameLate = false;\n /**\n * An offer or answer of this side's that went without a public candidate came to nothing (both descriptions were\n * exchanged, and no path connected): the next one waits for its STUN servers as long as it takes\n * (`ICE_GATHERING_TIMEOUT_MS`).\n */\n private fullGather = false;\n /** The offer or answer out has no public candidate (as it went: the connection's description gains any that come later). */\n private sentLacksPublic = false;\n /** Connections the gathering under way replaced for finding no candidate at all (`gathered`); 0 when none is under way. */\n private gatherStalls = 0;\n private lastSignalTs = 0;\n /** The peer's description as this connection was given it: Chrome shows it as `remoteDescription` only once applied. */\n private remoteSdp: string | null = null;\n /** When the connection had both descriptions (`connecting`). */\n private connectingSince = 0;\n private connectTimer: ReturnType<typeof setTimeout> | null = null;\n private disconnectTimer: ReturnType<typeof setTimeout> | null = null;\n /** The offer this side answered in the current attempt, when it took it (this clock), and how many times it answered it again. */\n private answered: { offer: RtcSignal; at: number; again: number } | null = null;\n /** Answers refused since a connection last opened, each followed by a new offer at once (`ANSWER_REFUSED_REDIALS`). */\n private refusedAnswers = 0;\n /** The last answer dropped as not for this side's offer (`answer-dropped`): each is said once. */\n private droppedAnswerTs = 0;\n\n constructor(private readonly options: DataLinkOptions) {}\n\n /** Offers a connection to the peer. Resolves once the offer is published. */\n /**\n * Makes an offer and publishes it. `gate`: gathered ahead, while the caller still finds out whether the peer is there\n * (a joiner reading the inviter's record): the link stays idle meanwhile, and the offer goes once the gate says yes.\n * On no, the connection is dropped, nothing having been said, and `\"held\"` is the answer.\n */\n async connect(gate?: Promise<boolean>): Promise<\"held\" | void> {\n if (this.state !== \"idle\") return;\n this.answered = null;\n if (!gate) { this.setState(\"offering\"); this.options.setFastPoll(true, true); }\n try {\n const pc = await this.gathered(true, async (pc) => { await pc.setLocalDescription(await pc.createOffer()); });\n if (!pc) return;\n if (gate) {\n const go = await gate;\n // The peer's offer came meanwhile (it was answered), or the link was closed.\n if (this.pc !== pc || this.state !== \"idle\") return;\n if (!go) { this.teardown(); return \"held\"; }\n this.setState(\"offering\");\n this.options.setFastPoll(true, true);\n }\n\n this.myOfferTs = this.myOfferOutAt = Date.now();\n this.answerCameLate = false;\n this.sentLacksPublic = !PUBLIC_CANDIDATE.test(pc.localDescription?.sdp ?? \"\");\n const signal: RtcSignal = { t: \"o\", ts: this.myOfferTs, ...extractRtcParams(pc.localDescription!.sdp, { relayOnly: keepsToRelays(pc) }) };\n this.options.publishSignal(JSON.stringify(signal));\n } catch {\n this.reset();\n }\n }\n\n /**\n * Feeds a decrypted `_rtc` value from the peer's packet. `sight`: how this device saw it come (`SignalSight`): the\n * peer's record did not carry it at a read the network answered, or it came on a live session just now.\n *\n * The peer's `ts` orders its signals (a later one replaces an earlier one, and an answer names the offer it is for).\n * It is not what says a signal is recent when this device saw it come: two clocks a few minutes apart are common, and\n * every signal of such a peer was dropped here, without a word. An answer is for the offer it names, which this side\n * made in this attempt, so it has no age to check. An offer is as old as the time since the read that did not have it\n * (`offerIsFresh`); only one the first read finds is judged by its own time, as nothing else dates it.\n *\n * A signal dated more than `RTC_SIGNAL_FUTURE_MS` ahead of this clock is not taken at all: taken, its time would\n * be the latest this link knows of the peer, and every signal the peer makes after it would read as older.\n */\n async handleSignal(json: string, sight?: SignalSight): Promise<void> {\n const signal = parseRtcSignal(json);\n if (!signal || signal.ts <= this.lastSignalTs) return;\n if (signal.ts > Date.now() + RTC_SIGNAL_FUTURE_MS) {\n traceLink(this.options.myPubKeyZ32, \"signal-ahead\", { aheadMs: signal.ts - Date.now() });\n return;\n }\n if (signal.t === \"o\" && !offerIsFresh(signal.ts, sight)) {\n traceLink(this.options.myPubKeyZ32, \"offer-stale\", { ageMs: Date.now() - signal.ts, ...(sight && { sinceMs: Date.now() - sight.since, ...(sight.after !== null && { beforePacketMs: sight.after - signal.ts }) }) });\n return;\n }\n\n if (signal.t === \"o\") {\n if (this.state === \"offering\") {\n // Both sides offered at once: the lower public key keeps its offer.\n if (this.options.myPubKeyZ32 < this.options.peerPubKeyZ32) return;\n }\n // A fresh offer while connected means the peer lost the old connection. One that comes while an earlier one is\n // still being answered takes its place too: the peer gave that one up (its answer was refused there, say, and\n // it offered again at once), and a signal is fed once, so a newer offer left aside here was never answered.\n this.lastSignalTs = signal.ts;\n const wasOpen = this.state === \"open\";\n const unpublic = this.gatherStalled;\n this.teardown();\n if (wasOpen) { this.options.onDirect?.(\"closed\"); this.options.onClose(); }\n if (unpublic) this.options.onDirect?.(\"no-public\");\n this.answered = { offer: signal, at: Date.now(), again: 0 };\n await this.answer(signal);\n } else if (this.state === \"connecting\" && this.myOfferTs && signal.o === this.myOfferTs && this.pc) {\n // A newer answer to the offer this side already took an answer for: the answerer made it again (`REANSWERS`),\n // its connection for the one applied here is gone, and this one can never come up. It is given up now, rather\n // than at the end of its attempt (a hub that read a member's first answer late held a dead one 40 s, 2026-09-30).\n traceLink(this.options.myPubKeyZ32, \"answer-replaced\", { appliedMs: signal.ts - this.lastSignalTs });\n this.lastSignalTs = signal.ts;\n this.reset();\n this.options.onAnswerReplaced?.();\n } else if (this.state === \"offering\" && signal.o === this.myOfferTs && this.pc) {\n this.lastSignalTs = signal.ts;\n const pc = this.pc;\n const sinceOffer = Date.now() - this.myOfferOutAt;\n this.answerCameLate = sinceOffer >= LATE_ANSWER_MS;\n if (this.answerCameLate) traceLink(this.options.myPubKeyZ32, \"answer-late\", { ms: sinceOffer });\n try {\n this.remoteSdp = buildDataSdp(signal);\n await pc.setRemoteDescription({ type: \"answer\", sdp: this.remoteSdp });\n // On a quick path the channel is open before this resolves: never step back from open.\n if (this.pc === pc && this.state === \"offering\") this.setState(\"connecting\");\n } catch (error) {\n if (this.pc === pc) this.answerRefused(error);\n }\n } else if (signal.t === \"a\" && signal.ts !== this.droppedAnswerTs) {\n // An answer to an offer this side no longer waits on (one it made before, given up when its answer was refused),\n // or one that came while this side was not offering: dropped, and said once, or a link that waited on its next\n // answer after it showed nothing of why (meshSignals on CI, 2026-10-09).\n this.droppedAnswerTs = signal.ts;\n traceLink(this.options.myPubKeyZ32, \"answer-dropped\", { state: this.state, ...(this.myOfferTs && signal.o !== undefined ? { offerMs: signal.o - this.myOfferTs } : {}) });\n }\n }\n\n /**\n * On a quick path the channel opens before setRemoteDescription resolves (see `handleSignal`), when the connection\n * does not show the answer yet: the one it was given counts, as DTLS already checked the peer against it.\n */\n get fingerprints(): [string, string] | null {\n const local = this.pc?.localDescription?.sdp;\n const remote = this.pc?.remoteDescription?.sdp ?? (this.pc ? this.remoteSdp : null);\n if (!local || !remote) return null;\n try { return [extractRtcParams(local).f.toLowerCase(), extractRtcParams(remote).f.toLowerCase()]; }\n catch { return null; }\n }\n\n /**\n * The answer this side's offer is connecting on came `LATE_ANSWER_MS` or more after the offer went out: if it connects\n * nothing, that says nothing about direct connections, and the link offers again (`GhostLink`'s stall of a group link).\n */\n get answerLate(): boolean { return this.state === \"connecting\" && !!this.myOfferTs && this.answerCameLate; }\n\n /**\n * This side answered, and no answer of its went out in this attempt (`signalOut`: the relays' budget held every one\n * back): the offerer never had one to try (agents#1637). The answering side's twin of `answerLate`.\n */\n private get answerNotOut(): boolean { return this.state === \"connecting\" && !this.myOfferTs && this.options.signalOut?.() === false; }\n\n /**\n * This attempt, if it ends now without opening, says nothing about direct connections: the answer to this side's offer\n * was read late (`answerLate`), or this side's answer never went out (`answerNotOut`). An answer made again and still\n * unread `LATE_ANSWER_MS` on (`failed`) is the same case, seen from the offer that still stands.\n */\n private get saysNothing(): boolean { return this.answerLate || this.answerNotOut; }\n\n /** The peer connection this link holds now (null when idle): a later one is another attempt. */\n get connection(): RTCPeerConnection | null { return this.pc; }\n\n close(): void {\n // Given up for another transport that went live while this one had long had both descriptions: evidence all the same.\n const stalled = Date.now() - this.connectingSince >= STALLED_EVIDENCE_MS;\n // Or still gathering, with nothing found on every connection but the last (`gatherStalled`).\n const evidence = (stalled ? this.directEvidence() : null) ?? (this.gatherStalled ? \"no-public\" : null);\n this.noteNoPublic(stalled);\n this.answered = null;\n this.reset();\n if (evidence) this.options.onDirect?.(evidence);\n }\n\n /**\n * Given up for a reason that is not the network's (an answer made while the app was away, `WAKE_ANSWER_GRACE_MS`):\n * as `close`, with nothing learnt about direct connections from it.\n */\n abandon(): void {\n this.answered = null;\n this.reset();\n }\n\n /**\n * This side's offer went with no public candidate and was answered, or its answer went with none, and it came to\n * nothing: the next offer or answer gathers for as long as it takes.\n */\n private noteNoPublic(ended: boolean): void {\n if (ended && !this.saysNothing && (this.myOfferTs || this.answered) && this.sentLacksPublic && this.state === \"connecting\") this.fullGather = true;\n }\n\n /**\n * What this attempt says about direct connections if it ends now without opening: nothing unless both descriptions\n * were exchanged (this side's offer answered, or its answer out). Then, what this device gathered: no public\n * candidate, a public port per STUN server, or (for the side that offered) candidates that read as reachable.\n */\n private directEvidence(): DirectEvidence | null {\n if (this.state !== \"connecting\" || !this.pc || this.saysNothing) return null;\n const local = this.pc.localDescription?.sdp ?? \"\";\n return !PUBLIC_CANDIDATE.test(local) ? \"no-public\" : symmetricNat(local) ? \"symmetric\" : this.myOfferTs ? \"no-path\" : null;\n }\n\n /**\n * The gathering under way found no candidate on every connection but the one it waits on now (`GATHER_ATTEMPTS` - 1\n * stalls): ended from outside now (another transport went live, the contact's offer took its place), it says what\n * one that ran out says, `no-public`. Saying nothing held the note back on a network that blocks direct connections:\n * a browser there gathers none, its chats went live over Iroh before the third stall, and only a later attempt, if\n * any came, said it (direct-blocked e2e, 2026-11-13).\n */\n private get gatherStalled(): boolean { return this.gatherStalls >= GATHER_ATTEMPTS - 1; }\n\n /**\n * The attempt on this connection failed (it timed out, ICE failed or closed, its channel closed). An answer the\n * offerer may not have read yet is made again for the same offer while it still stands (`REANSWERS`); anything\n * else goes back to idle. `byConnection`: the connection said so itself, rather than a timer of this link's.\n */\n private failed(byConnection = false): void {\n // The connection failed while the answer to this side's offer was being applied: as if it was refused.\n if (this.state === \"offering\" && this.remoteSdp) { this.answerRefused(\"failed\"); return; }\n // The same when the connection ends a moment after the answer went in (`ANSWER_REFUSED_AFTER_MS`).\n if (byConnection && this.state === \"connecting\" && this.myOfferTs && Date.now() - this.connectingSince < ANSWER_REFUSED_AFTER_MS) { this.answerRefused(\"failed\"); return; }\n const answered = this.state === \"connecting\" ? this.answered : null;\n // How long the offerer's attempt still runs, counted on this clock from when its offer was taken (its `ts` is its clock's).\n const left = answered ? CONNECT_TIMEOUT_MS - (Date.now() - answered.at) : 0;\n // An answer to an offer the offerer has given up since (its packet no longer carries it: the answer was refused\n // there, say) connected nothing because nobody was on the other end, whatever the network lets through.\n const givenUp = !!answered && this.options.offerStanding?.(answered.offer.ts) === false;\n // This side's answer made again, and the offer it answers still stands `LATE_ANSWER_MS` after it took it: the\n // offerer has not read an answer in time (an offerer that read one and found no path gives the attempt up).\n const unread = !!answered && answered.again > 0 && Date.now() - answered.at >= LATE_ANSWER_MS && this.options.offerStanding?.(answered.offer.ts) === true;\n if (unread) traceLink(this.options.myPubKeyZ32, \"answer-unread\", { again: answered.again, sinceMs: Date.now() - answered.at });\n const evidence = givenUp || unread ? null : this.directEvidence();\n this.noteNoPublic(!givenUp && !unread);\n if (answered && answered.again < REANSWERS && left > REANSWER_MARGIN_MS && this.options.offerStanding?.(answered.offer.ts)) {\n answered.again++;\n traceLink(this.options.myPubKeyZ32, \"reanswer\", { again: answered.again, leftMs: left });\n this.teardown();\n void this.answer(answered.offer);\n return;\n }\n this.reset();\n if (evidence) this.options.onDirect?.(evidence);\n }\n\n /** The answer to this side's offer did not go in (`ANSWER_REFUSED_REDIALS`): the attempt ends, and the caller may offer again now. */\n private answerRefused(error: unknown): void {\n const again = this.refusedAnswers < ANSWER_REFUSED_REDIALS;\n traceLink(this.options.myPubKeyZ32, \"answer-refused\", { error: error instanceof Error ? error.message : String(error), again });\n this.reset();\n if (!again) { this.options.onAnswersRefused?.(); return; }\n this.refusedAnswers++;\n this.options.onAnswerReplaced?.();\n }\n\n private async answer(offer: RtcSignal): Promise<void> {\n this.setState(\"answering\");\n this.options.setFastPoll(true);\n try {\n const pc = await this.gathered(false, async (pc) => {\n await pc.setRemoteDescription({ type: \"offer\", sdp: buildDataSdp(offer) });\n await pc.setLocalDescription(await pc.createAnswer());\n });\n if (!pc) return;\n\n this.sentLacksPublic = !PUBLIC_CANDIDATE.test(pc.localDescription?.sdp ?? \"\");\n const signal: RtcSignal = {\n t: \"a\",\n ts: Date.now(),\n o: offer.ts,\n ...extractRtcParams(pc.localDescription!.sdp, { relayOnly: keepsToRelays(pc) }),\n };\n this.options.publishSignal(JSON.stringify(signal));\n this.setState(\"connecting\");\n } catch {\n // A newer offer took this one's place meanwhile (its connection was closed under it): that attempt goes on.\n if (this.answered?.offer === offer) this.reset();\n }\n }\n\n /**\n * Makes the connection (`describe` sets its description) and waits for its candidates. One that found none by\n * `GATHER_STALL_MS` is replaced by a new one, up to `GATHER_ATTEMPTS` in all; when none finds any, the link goes back\n * to idle at once rather than hold, for its whole timeout, an attempt that cannot connect. Null when the link moved\n * on meanwhile (closed, or another signal took over) or gave up.\n */\n private async gathered(offer: boolean, describe: (pc: RTCPeerConnection) => Promise<void>): Promise<RTCPeerConnection | null> {\n let stalled: RTCPeerConnection | null = null;\n this.gatherStalls = 0;\n for (let attempt = 1; ; attempt++) {\n // The new connection takes the old one's place first: closing that one then resets nothing.\n const pc = this.createConnection();\n if (stalled) this.closeConnection(stalled);\n await describe(pc);\n if (this.pc !== pc) return null;\n const gathering = Date.now();\n await waitForIceGathering(pc, ICE_GATHERING_TIMEOUT_MS,\n { stallMs: GATHER_STALL_MS, settleMs: DATA_SETTLE_MS, ...(!this.fullGather ? { hostBoundMs: OFFER_HOST_GATHER_MS } : {}) });\n if (this.pc !== pc) return null;\n const ms = Date.now() - gathering;\n if (sdpHasCandidates(pc.localDescription?.sdp)) {\n traceLink(this.options.myPubKeyZ32, \"ice-gathered\", { ms, offer, ...(attempt > 1 ? { attempt } : {}) });\n this.gatherStalls = 0;\n return pc;\n }\n traceLink(this.options.myPubKeyZ32, \"ice-stalled\", { ms, offer, attempt });\n if (attempt >= GATHER_ATTEMPTS) { this.reset(); this.options.onDirect?.(\"no-public\"); return null; }\n stalled = pc;\n this.gatherStalls = attempt;\n }\n }\n\n private createConnection(): RTCPeerConnection {\n const pc = this.options.createPeerConnection();\n this.pc = pc;\n const ended = new AbortController();\n this.ends.set(pc, ended);\n const { signal } = ended;\n\n // Negotiated channel: both sides declare it, no in-band open handshake.\n const dc = pc.createDataChannel(DATA_CHANNEL_LABEL, { negotiated: true, id: DATA_CHANNEL_ID, ordered: true });\n dc.addEventListener(\"open\", () => {\n if (this.pc !== pc) return;\n this.clearTimers();\n this.answered = null;\n this.refusedAnswers = 0;\n this.fullGather = false;\n this.setState(\"open\");\n this.options.setFastPoll(false);\n this.options.publishSignal(null);\n this.options.onDirect?.(\"open\");\n this.options.onOpen(wrapDataChannel(dc, signal));\n void tracePair(this.options.myPubKeyZ32, pc);\n }, { signal });\n dc.addEventListener(\"close\", () => {\n if (this.pc === pc) this.failed(true);\n }, { signal });\n\n pc.addEventListener(\"connectionstatechange\", () => {\n if (this.pc !== pc) return;\n if (this.disconnectTimer) { clearTimeout(this.disconnectTimer); if (pc.connectionState === \"connected\") this.options.onDisconnected?.(false); }\n this.disconnectTimer = null;\n if (pc.connectionState === \"failed\" || pc.connectionState === \"closed\") this.failed(true);\n else if (pc.connectionState === \"disconnected\") {\n if (this.state === \"open\") this.options.onDisconnected?.(true);\n this.disconnectTimer = setTimeout(() => {\n if (this.pc === pc) this.failed();\n }, DISCONNECT_GRACE_MS);\n }\n }, { signal });\n\n this.startAttemptTimer(pc);\n return pc;\n }\n\n /** The attempt on `pc` gives up this long from now (`CONNECT_TIMEOUT_MS`) unless it opens. */\n private startAttemptTimer(pc: RTCPeerConnection): void {\n if (this.connectTimer) clearTimeout(this.connectTimer);\n this.connectTimer = setTimeout(() => {\n if (this.pc === pc && this.state !== \"open\") {\n traceLink(this.options.myPubKeyZ32, \"attempt-timeout\", { state: this.state });\n this.failed();\n }\n }, this.options.attemptTimeoutMs?.() ?? CONNECT_TIMEOUT_MS);\n }\n\n /**\n * This side's offer or answer reached the relays only now (their budget, or an outage, held it back): the attempt\n * counts from here, so the other side has as long to read it as if it had gone out at once.\n */\n signalWentOut(): void {\n if (this.state === \"offering\" && this.myOfferTs) this.myOfferOutAt = Date.now();\n if (this.pc && this.connectTimer && this.state !== \"open\" && this.state !== \"idle\") this.startAttemptTimer(this.pc);\n }\n\n private clearTimers(): void {\n if (this.connectTimer) clearTimeout(this.connectTimer);\n if (this.disconnectTimer) clearTimeout(this.disconnectTimer);\n this.connectTimer = this.disconnectTimer = null;\n }\n\n private teardown(): boolean {\n this.clearTimers();\n const pc = this.pc;\n this.pc = null;\n this.myOfferTs = this.myOfferOutAt = 0;\n this.answerCameLate = false;\n this.remoteSdp = null;\n this.gatherStalls = 0;\n if (!pc) return false;\n this.closeConnection(pc);\n return true;\n }\n\n /**\n * Closes `pc` and drops its listeners and its data channel's. The channel tells it closed (`wrapDataChannel`) a\n * microtask later, after the link's own `onClose`, as when the data channel said so itself: node-datachannel does not\n * always report a closed connection's channel closed, and the listeners it kept would hold the link for good.\n */\n private closeConnection(pc: RTCPeerConnection): void {\n pc.close();\n const ended = this.ends.get(pc);\n if (ended) queueMicrotask(() => ended.abort());\n }\n\n private reset(): void {\n const wasOpen = this.state === \"open\";\n const hadConnection = this.teardown();\n if (this.state === \"idle\" && !hadConnection) return;\n this.setState(\"idle\");\n this.options.setFastPoll(false);\n this.options.publishSignal(null);\n if (wasOpen) { this.options.onDirect?.(\"closed\"); this.options.onClose(); }\n }\n\n private setState(state: DataLinkState): void {\n if (this.state === state) return;\n this.state = state;\n if (state === \"connecting\") this.connectingSince = Date.now();\n this.options.onState?.(state);\n }\n}\n","import { ed25519, x25519 } from \"@noble/curves/ed25519.js\";\nimport { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { concatBytes, fromBase64Url, randomBytes, toBase64Url, utf8Encode } from \"./bytes\";\nimport { publicKeyFromZ32 } from \"./identity\";\n\n/**\n * The ratchet of a 1:1 chat's stored paths (WISP 4xx-ratchet, reserved number 407): what goes on the DHT floor\n * (WISP 403) and what is held (WISP 404) is sealed with a key used once, from a double ratchet in the manner of\n * Signal's (an X25519 step each time the turn passes, a one-way chain per message), so a participation key stolen\n * later opens none of it once the turn has passed. The live session needs none: its transports agree fresh keys on\n * every connection.\n *\n * Pure: every call takes a state and returns the next one. The caller holds one lock per chat from reading the state\n * to saving the next (an open's until what it opened is stored), and saves a seal's state before the sealed bytes\n * leave the device. Nothing here reads a clock or the network but through its options.\n */\nexport const RATCHET_CAPABILITY = \"ratchet/1\" as const;\nexport type RatchetLane = \"floor\" | \"hold\";\nconst LANE: Record<RatchetLane, number> = { floor: 1, hold: 2 };\nconst VERSION = 1;\nconst SID_BYTES = 8;\n/** version, lane, session id, the sender's ratchet key, the hold lane's previous chain length, the message number. */\nexport const RATCHET_HEADER_BYTES = 1 + 1 + SID_BYTES + 32 + 4 + 4;\n/** What sealing adds to a plaintext: the header and the 16-byte tag (the nonce is derived, never sent). */\nexport const RATCHET_OVERHEAD = RATCHET_HEADER_BYTES + 16;\n/**\n * How far a message may be ahead of the last one opened on its chain. A mailbox shows only its newest envelope, so the\n * floor's between were replaced unread: their keys are stepped over and never kept. A held item's are kept. A sender\n * whose chain reaches the bound without the turn passing starts a new session rather than seal past it.\n */\nexport const MAX_SKIP: Record<RatchetLane, number> = { floor: 4096, hold: 512 };\n/** Keys kept for held items not opened yet, at most, oldest dropped first. */\nexport const MAX_SKIPPED_KEYS = 512;\n/** A kept key, and a session only received on, is dropped this long after it was last of use: a held item lives 7 days. */\nexport const RATCHET_KEEP_MS = 8 * 24 * 60 * 60_000;\n/**\n * A session that lost (`lost`) becomes current when its floor envelopes keep rising in sequence while the current one\n * has opened no floor envelope for this long: two that started at once settle within one keep-alive (about four\n * minutes), and a contact that lost its state meanwhile seals in its own session from then on.\n */\nexport const FOLLOW_MS = 10 * 60_000;\n/** Session ids no longer in use, kept so a replayed envelope of one cannot start it again. */\nconst MAX_RETIRED = 16;\n\ninterface Chain { k: string; n: number }\ninterface Lanes { floor: Chain; hold: Chain }\nexport interface RatchetSession {\n /** 8 random bytes, base64url: the session, chosen by the side that started it. */\n sid: string;\n rk: string;\n /** This side's ratchet secret; null while it is still the participation key's (the second side, before its first step). */\n dhs: string | null;\n dhsPub: string;\n /** The contact's ratchet key; null until its first message (the second side). */\n dhr: string | null;\n send: Lanes;\n /** How many held items the previous sending chain used: said in every header. */\n pnHold: number;\n recv: Lanes | null;\n /** A message of the contact's opened under this session. */\n heard: boolean;\n /**\n * The highest floor sequence (WISP 403's, signed by the contact and kept across its restores) of an envelope opened\n * under this session: what orders the contact's sessions, so an envelope from before both settled never wins.\n */\n floorSeq?: number;\n /** When a floor envelope was last opened under it. */\n floorAt?: number;\n /** A session that lost when both started at once, or came from before both settled: only opened with (but `FOLLOW_MS`). */\n lost?: true;\n /** When this side made or first opened it. */\n made: number;\n /**\n * The turn passed both ways: this side stepped on a key of the contact's with a ratchet secret of its own, so what\n * either side seals from now on needs secrets that are deleted after use, not the participation keys.\n */\n fs: boolean;\n at: number;\n}\ninterface Skipped { s: string; d: string; n: number; k: string; at: number }\nexport interface RatchetState {\n v: 1;\n /** The session this side seals with. */\n current?: RatchetSession;\n /**\n * Sessions this side only opens with, newest last, at most `MAX_OTHERS`: the contact's that lost to this side's, this\n * side's before the contact started anew, or one the contact had left.\n */\n others: RatchetSession[];\n /** Hold lane only. */\n skipped: Skipped[];\n retired: string[];\n /** A ratcheted item from the contact was opened on this lane: from then on a plain one is refused there. */\n heard: { floor?: true; hold?: true };\n}\nexport const emptyRatchetState = (): RatchetState => ({ v: 1, others: [], skipped: [], retired: [], heard: {} });\n/** Sessions only opened with, at most. */\nconst MAX_OTHERS = 2;\n\n/** What both sides of one chat derive the ratchet from: never stored in the state. */\nexport interface RatchetKeys {\n /** This side's participation seed (Ed25519, 32 bytes). */\n seed: Uint8Array;\n /** Both participation keys, z-base-32. */\n self: string;\n peer: string;\n /** The chat's two rendezvous keys, z-base-32, in either order. */\n rendezvous: [string, string];\n /** The invite's secret (`LinkParams.encKeyB64`). */\n secret: Uint8Array;\n}\nexport interface RatchetOptions {\n now?: number;\n /** For test vectors only: where random bytes come from. */\n random?: (bytes: number) => Uint8Array;\n}\n\nconst b64 = toBase64Url, unb64 = fromBase64Url;\nconst label = (text: string) => utf8Encode(`ghostly-ratchet/1 ${text}`);\nconst mac = (key: Uint8Array, text: string) => hmac(sha256, key, label(text));\n\nfunction u32(n: number): Uint8Array {\n if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff) throw new Error(\"Ratchet counter out of range\");\n return new Uint8Array([n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);\n}\nconst readU32 = (b: Uint8Array, at: number) => ((b[at] << 24) >>> 0) + (b[at + 1] << 16) + (b[at + 2] << 8) + b[at + 3];\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return a[i] - b[i];\n return a.length - b.length;\n}\n/** X25519, or null for a key that gives no secret (a low-order point): such an item does not open. */\nfunction agree(secret: Uint8Array, pub: Uint8Array): Uint8Array | null {\n try { return x25519.getSharedSecret(secret, pub); } catch { return null; }\n}\n\n/** One chat's fixed keys, computed once per call. */\ninterface Context { keys: RatchetKeys; first: boolean; secret: Uint8Array; pub: Uint8Array; peer: Uint8Array }\nfunction context(keys: RatchetKeys): Context {\n const secret = ed25519.utils.toMontgomerySecret(keys.seed);\n return { keys, secret, pub: x25519.getPublicKey(secret), peer: ed25519.utils.toMontgomery(publicKeyFromZ32(keys.peer)),\n // The side whose participation key sorts first starts like Signal's first sender; the other like its second.\n first: compareBytes(publicKeyFromZ32(keys.self), publicKeyFromZ32(keys.peer)) < 0 };\n}\n\nfunction root(c: Context, sid: Uint8Array): Uint8Array {\n const { keys } = c;\n const info = utf8Encode(JSON.stringify([\"ghostly-ratchet/1\", [...keys.rendezvous].sort(), [keys.self, keys.peer].sort()]));\n const salt = hkdf(sha256, keys.secret, info, label(\"salt\"), 32);\n return hkdf(sha256, x25519.getSharedSecret(c.secret, c.peer), salt, concatBytes(label(\"root\"), sid), 32);\n}\n/** The root key a session starts from: the two participation keys' agreement, salted by the invite and the chat, per session id. */\nexport const ratchetRoot = (keys: RatchetKeys, sid: Uint8Array): Uint8Array => root(context(keys), sid);\n\n/** A ratchet step: the next root key and the chain key it gives, from an X25519 output. */\nfunction stepRoot(rk: Uint8Array, dh: Uint8Array): [Uint8Array, Uint8Array] {\n const okm = hkdf(sha256, dh, rk, label(\"step\"), 64);\n return [okm.slice(0, 32), okm.slice(32)];\n}\nconst lanes = (ck: Uint8Array): Lanes => ({ floor: { k: b64(mac(ck, \"lane floor\")), n: 0 }, hold: { k: b64(mac(ck, \"lane hold\")), n: 0 } });\n/** One message key off a chain, and the chain moved past it. */\nfunction advance(chain: Chain): [Uint8Array, Chain] {\n const ck = unb64(chain.k);\n return [hmac(sha256, ck, new Uint8Array([1])), { k: b64(hmac(sha256, ck, new Uint8Array([2]))), n: chain.n + 1 }];\n}\n\nfunction newSession(c: Context, sid: Uint8Array, random: (n: number) => Uint8Array, now: number): RatchetSession {\n const rk0 = root(c, sid);\n const initial = lanes(mac(rk0, \"initial\"));\n const base = { sid: b64(sid), pnHold: 0, heard: false, fs: false, at: now, made: now };\n // The second side: its first messages go on a chain from the root alone; its first step comes with the contact's first message.\n if (!c.first) return { ...base, rk: b64(rk0), dhs: null, dhsPub: b64(c.pub), dhr: null, send: initial, recv: null };\n // The first side takes its first step at once, against the contact's participation key, and reads the contact's first\n // messages on the chain from the root alone.\n const dhs = random(32);\n const [rk, ck] = stepRoot(rk0, x25519.getSharedSecret(dhs, c.peer));\n return { ...base, rk: b64(rk), dhs: b64(dhs), dhsPub: b64(x25519.getPublicKey(dhs)), dhr: b64(c.peer), send: lanes(ck), recv: initial };\n}\n\nfunction messageKeys(mk: Uint8Array): { key: Uint8Array; nonce: Uint8Array } {\n const okm = hkdf(sha256, mk, new Uint8Array(32), label(\"message\"), 56);\n return { key: okm.slice(0, 32), nonce: okm.slice(32) };\n}\nfunction aad(lane: RatchetLane, sender: string, recipient: string, header: Uint8Array): Uint8Array {\n return concatBytes(utf8Encode(\"ghostly-ratchet/1\"), new Uint8Array([LANE[lane]]), publicKeyFromZ32(sender), publicKeyFromZ32(recipient), header);\n}\n\nfunction header(lane: RatchetLane, session: RatchetSession, n: number): Uint8Array {\n return concatBytes(new Uint8Array([VERSION, LANE[lane]]), unb64(session.sid), unb64(session.dhsPub), u32(session.pnHold), u32(n));\n}\ninterface Header { lane: RatchetLane; sid: string; dh: string; pnHold: number; n: number }\nfunction parseHeader(sealed: Uint8Array): Header | null {\n if (sealed.length < RATCHET_OVERHEAD || sealed[0] !== VERSION || (sealed[1] !== 1 && sealed[1] !== 2)) return null;\n const at = 2 + SID_BYTES + 32;\n return { lane: sealed[1] === 1 ? \"floor\" : \"hold\", sid: b64(sealed.slice(2, 2 + SID_BYTES)), dh: b64(sealed.slice(2 + SID_BYTES, at)), pnHold: readU32(sealed, at), n: readU32(sealed, at + 4) };\n}\n\nfunction prune(state: RatchetState, now: number): void {\n state.skipped = state.skipped.filter(k => k.at + RATCHET_KEEP_MS > now).slice(-MAX_SKIPPED_KEYS);\n for (const old of state.others.filter(o => o.at + RATCHET_KEEP_MS <= now)) retire(state, old);\n state.others = state.others.filter(o => o.at + RATCHET_KEEP_MS > now);\n}\nfunction retire(state: RatchetState, session: RatchetSession | undefined): void {\n if (!session) return;\n if (!state.retired.includes(session.sid)) state.retired = [...state.retired, session.sid].slice(-MAX_RETIRED);\n state.skipped = state.skipped.filter(k => k.s !== session.sid);\n}\n/** `session` is only opened with from now on; past `MAX_OTHERS`, the one used least lately is retired. */\nfunction demote(state: RatchetState, session: RatchetSession): void {\n state.others = [...state.others.filter(o => o.sid !== session.sid), session].sort((a, b) => a.at - b.at);\n while (state.others.length > MAX_OTHERS) retire(state, state.others.shift());\n}\n\n/**\n * Seals one item for the contact on a lane, with the current session (started here when there is none, or when its\n * chain on this lane reached `MAX_SKIP` without the turn passing: past it the contact could not step over to it). The\n * state returned MUST be saved before the sealed bytes leave the device: a key is used once, and a crash between the\n * two that kept the old state would use it again on other bytes.\n */\nexport function ratchetSeal(prev: RatchetState, keys: RatchetKeys, lane: RatchetLane, plaintext: Uint8Array, options: RatchetOptions = {}): { state: RatchetState; sealed: Uint8Array } {\n const now = options.now ?? Date.now(), random = options.random ?? randomBytes;\n const state = structuredClone(prev);\n prune(state, now);\n if (state.current && state.current.send[lane].n >= MAX_SKIP[lane]) { demote(state, state.current); delete state.current; }\n const session = state.current ??= newSession(context(keys), random(SID_BYTES), random, now);\n const [mk, next] = advance(session.send[lane]);\n const head = header(lane, session, session.send[lane].n);\n session.send[lane] = next; session.at = now;\n const { key, nonce } = messageKeys(mk);\n return { state, sealed: concatBytes(head, xchacha20poly1305(key, nonce, aad(lane, keys.self, keys.peer, head)).encrypt(plaintext)) };\n}\n\n/**\n * Opens `sealed` under `session`, changing it and `state` in place (both are a copy the caller throws away on null).\n * Every bound is checked before any X25519 or chain step.\n */\nfunction openWith(state: RatchetState, session: RatchetSession, c: Context, h: Header, sealed: Uint8Array, random: (n: number) => Uint8Array, now: number): Uint8Array | null {\n const decrypt = (mk: Uint8Array) => {\n const { key, nonce } = messageKeys(mk);\n try { return xchacha20poly1305(key, nonce, aad(h.lane, c.keys.peer, c.keys.self, sealed.subarray(0, RATCHET_HEADER_BYTES))).decrypt(sealed.subarray(RATCHET_HEADER_BYTES)); }\n catch { return null; }\n };\n if (h.lane === \"hold\") {\n const i = state.skipped.findIndex(k => k.s === session.sid && k.d === h.dh && k.n === h.n);\n if (i >= 0) {\n const plain = decrypt(unb64(state.skipped[i].k));\n if (plain) state.skipped.splice(i, 1);\n return plain;\n }\n }\n const keep = (lane: RatchetLane, dh: string, from: Chain, until: number): Chain => {\n let chain = from;\n while (chain.n < until) {\n const [mk, next] = advance(chain);\n // A hold chain's keys stepped over wait for their items; a floor's are dropped (replaced unread).\n if (lane === \"hold\") state.skipped.push({ s: session.sid, d: dh, n: chain.n, k: b64(mk), at: now });\n chain = next;\n }\n return chain;\n };\n const bound = MAX_SKIP[h.lane];\n if (h.dh !== session.dhr) {\n // The contact took a step. Bounds first: the new chain starts at 0, and what is left of the previous hold chain is\n // kept as far as the contact says it went.\n const old = session.recv && session.dhr ? session.recv.hold : null;\n if (h.n > bound || (old && h.pnHold > old.n && h.pnHold - old.n > MAX_SKIP.hold)) return null;\n const ours = session.dhs ? unb64(session.dhs) : c.secret;\n const received = agree(ours, unb64(h.dh));\n if (!received) return null;\n if (old && session.dhr) keep(\"hold\", session.dhr, old, h.pnHold);\n let [rk, ck] = stepRoot(unb64(session.rk), received);\n const steppedWithOwn = session.dhs !== null;\n session.recv = lanes(ck); session.dhr = h.dh;\n session.pnHold = session.send.hold.n;\n const dhs = random(32);\n [rk, ck] = stepRoot(rk, x25519.getSharedSecret(dhs, unb64(h.dh)));\n session.rk = b64(rk); session.dhs = b64(dhs); session.dhsPub = b64(x25519.getPublicKey(dhs)); session.send = lanes(ck);\n if (steppedWithOwn && h.dh !== b64(c.peer)) session.fs = true;\n }\n if (!session.recv) return null;\n const chain = session.recv[h.lane];\n // Only forward: an older floor envelope was read already or replaced; an older held one opened from a kept key above.\n if (h.n < chain.n || h.n - chain.n > bound) return null;\n const [mk, next] = advance(keep(h.lane, h.dh, chain, h.n));\n const plain = decrypt(mk);\n if (!plain) return null;\n session.recv[h.lane] = next; session.heard = true; session.at = now;\n return plain;\n}\n\n/**\n * Opens an item the contact sealed. Null: not a ratcheted item of this chat on this lane, or one already opened, or\n * past the bounds. Otherwise the plaintext, and `finish`, which gives the state to save once the item is stored and\n * passed its path's own checks (a newer DHT sequence, a held item not taken before): those, not the ratchet, are what\n * refuse a replay. `order`: a floor envelope's sequence, read from the body once opened. `fresh`: it came under a\n * session this side did not know.\n */\nexport function ratchetOpen(prev: RatchetState, keys: RatchetKeys, lane: RatchetLane, sealed: Uint8Array, options: RatchetOptions = {}): { plaintext: Uint8Array; fresh: boolean; finish(order?: number): RatchetState } | null {\n const now = options.now ?? Date.now(), random = options.random ?? randomBytes;\n const h = parseHeader(sealed);\n if (!h || h.lane !== lane) return null;\n const state = structuredClone(prev);\n prune(state, now);\n const c = context(keys);\n const seen = (session: RatchetSession, order: number | undefined) => {\n if (lane !== \"floor\" || order === undefined || !Number.isSafeInteger(order)) return false;\n const rising = session.floorSeq !== undefined && order > session.floorSeq;\n session.floorSeq = Math.max(session.floorSeq ?? 0, order); session.floorAt = now;\n return rising;\n };\n const done = () => { state.heard[lane] = true; prune(state, now); return state; };\n const known = state.current?.sid === h.sid ? state.current : state.others.find(o => o.sid === h.sid);\n if (known) {\n const plaintext = openWith(state, known, c, h, sealed, random, now);\n if (!plaintext) return null;\n return { plaintext, fresh: false, finish: order => {\n const rising = seen(known, order), current = state.current;\n // The contact keeps speaking in a session that lost, and not in this side's: it lost its state just as both settled.\n if (rising && known.lost && current && known !== current && current.floorSeq === undefined && now - (current.floorAt ?? current.made) > FOLLOW_MS) {\n state.others = state.others.filter(o => o.sid !== known.sid);\n delete known.lost;\n demote(state, current); state.current = known;\n }\n return done();\n } };\n }\n if (state.retired.includes(h.sid)) return null;\n // Bounds before any work: a session's chains start at 0.\n if (h.n > MAX_SKIP[lane] || h.pnHold > MAX_SKIP.hold) return null;\n const fresh = newSession(c, unb64(h.sid), random, now);\n const plaintext = openWith(state, fresh, c, h, sealed, random, now);\n if (!plaintext) return null;\n return { plaintext, fresh: true, finish: order => {\n seen(fresh, order);\n const current = state.current;\n if (!current) state.current = fresh;\n else if (current.floorSeq === undefined) {\n // Both started at once (no floor envelope of the contact's opened in this side's session yet): the larger session\n // id wins on both sides; the one that lost is kept to open what came under it, never to seal or win again.\n if (compareBytes(unb64(h.sid), unb64(current.sid)) > 0) { current.lost = true; demote(state, current); state.current = fresh; }\n else { fresh.lost = true; demote(state, fresh); }\n } else if (lane === \"floor\" && fresh.floorSeq !== undefined && fresh.floorSeq > current.floorSeq) {\n // A floor envelope newer, by the contact's own sequence, than any it put out in this side's session: the contact\n // lost its state, or its chain reached its bound. Its session becomes current.\n demote(state, current); state.current = fresh;\n } else if (lane === \"floor\") {\n // Older than what the contact said in this side's session: from before both settled. Kept only to open with.\n fresh.lost = true; demote(state, fresh);\n } else {\n // A held item of a session the contact left (it came late): opened, and its session forgotten.\n state.skipped = state.skipped.filter(k => k.s !== fresh.sid);\n }\n return done();\n } };\n}\n\n/** Whether `sealed` is shaped as a ratcheted item of this lane (it may still not open). */\nexport const isRatcheted = (sealed: Uint8Array, lane: RatchetLane) => parseHeader(sealed)?.lane === lane;\n/** The session a ratcheted item of this lane names (its `sid`, base64url), as its header says; undefined for anything else. */\nexport const ratchetSessionOf = (sealed: Uint8Array, lane: RatchetLane): string | undefined => {\n const h = parseHeader(sealed);\n return h?.lane === lane ? h.sid : undefined;\n};\n/**\n * Whether `sealed` names a session this side has no state of and did not retire: neither the current one nor one of the\n * others. What the contact sealed in the session it shares with a device this profile was on before (a Move, a restore:\n * WISP 4xx § Several devices) is such an item, once the turn passed there; so is anything under a made-up `sid`. It says\n * nothing of whether the item is genuine: only that this side could not tell, having never had the session.\n */\nexport function ratchetUnknownSession(state: RatchetState | undefined, sealed: Uint8Array, lane: RatchetLane): boolean {\n const h = parseHeader(sealed);\n if (!h || h.lane !== lane) return false;\n const s = state ?? emptyRatchetState();\n return s.current?.sid !== h.sid && !s.others.some(o => o.sid === h.sid) && !s.retired.includes(h.sid);\n}\n/** Whether forward secrecy is on for this chat: the turn passed both ways in the session this side seals with. */\nexport const ratchetOn = (state: RatchetState | undefined) => !!state?.current?.fs;\n/** Whether a lane refuses plain items from the contact: a ratcheted one opened there (WISP 4xx § Downgrade). */\nexport const ratchetHeard = (state: RatchetState | undefined, lane: RatchetLane) => !!state?.heard[lane];\n\n/**\n * One chat's ratchet, shared by its two lanes (the DHT floor and held items): the one lock per chat of WISP 4xx §\n * Saving state, and the order of saving. Every change goes through `lock`, so a seal and an open never start from the\n * same state.\n */\nexport class RatchetBox {\n private chain: Promise<unknown> = Promise.resolve();\n constructor(private readonly keys: () => RatchetKeys, private state: RatchetState, private readonly save: (state: RatchetState) => Promise<void>) {}\n /** Runs `fn` alone among this chat's ratchet changes; `seal` and `open` are called inside it only. */\n lock<T>(fn: (box: RatchetTransaction) => Promise<T>): Promise<T> {\n const run = this.chain.then(() => fn(this.transaction()));\n this.chain = run.then(() => {}, () => {});\n return run;\n }\n private transaction(): RatchetTransaction {\n return {\n // Seal, save, send: the state is saved before the bytes are handed back.\n seal: async (lane, plaintext) => {\n const { state, sealed } = ratchetSeal(this.state, this.keys(), lane, plaintext);\n await this.save(state); this.state = state;\n return sealed;\n },\n // Open, store, save: the caller stores what opened, then commits; without a commit nothing moved.\n open: (lane, sealed) => {\n const opened = ratchetOpen(this.state, this.keys(), lane, sealed);\n if (!opened) return null;\n return { plaintext: opened.plaintext, fresh: opened.fresh, commit: async order => { const state = opened.finish(order); await this.save(state); this.state = state; } };\n },\n };\n }\n /**\n * Opens without keeping anything, and without the lock: a look from another profile, or the first half of a receive\n * whose content is then stored with no lock held (`commitOpen` keeps it).\n */\n peek(lane: RatchetLane, sealed: Uint8Array): Uint8Array | null { return ratchetOpen(this.state, this.keys(), lane, sealed)?.plaintext ?? null; }\n /**\n * The second half of a receive, once what `peek` gave is stored: opened again under the lock on the state as it is now\n * (a seal or another open may have moved it meanwhile), and that state saved. False: it no longer opens (taken by a\n * receive of the same item meanwhile), and nothing moved. So the lock is never held while content is stored, which\n * may call back into the other lane.\n */\n commitOpen(lane: RatchetLane, sealed: Uint8Array, order?: number): Promise<boolean> {\n return this.lock(async tx => {\n const opened = tx.open(lane, sealed);\n if (!opened) return false;\n await opened.commit(order);\n return true;\n });\n }\n heard(lane: RatchetLane): boolean { return ratchetHeard(this.state, lane); }\n /** A ratcheted item from the contact opened on either lane: this side seals with the ratchet whatever the contact's record says. */\n get heardAny(): boolean { return this.heard(\"floor\") || this.heard(\"hold\"); }\n get on(): boolean { return ratchetOn(this.state); }\n /** The session this side seals with now, if any (its `sid`). */\n get session(): string | undefined { return this.state.current?.sid; }\n /** `ratchetUnknownSession` on the state as it is: an item under a session this side never had. */\n unknownSession(lane: RatchetLane, sealed: Uint8Array): boolean { return ratchetUnknownSession(this.state, sealed, lane); }\n}\nexport interface RatchetTransaction {\n seal(lane: RatchetLane, plaintext: Uint8Array): Promise<Uint8Array>;\n /** `commit(order)`: a floor envelope's sequence, as `ratchetOpen`'s `finish`. */\n open(lane: RatchetLane, sealed: Uint8Array): { plaintext: Uint8Array; fresh: boolean; commit(order?: number): Promise<void> } | null;\n}\n","import { ed25519, x25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { hmac } from \"@noble/hashes/hmac.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { bytesEqual, concatBytes, fromBase64Url, randomBytes, toBase64Url, utf8Decode, utf8Encode } from \"./bytes\";\nimport { identityFromSeed, publicKeyFromZ32 } from \"./identity\";\nimport type { LinkParams } from \"./invite\";\n\n/**\n * The cryptography of the `group-mesh/1` profile (WISP 900 / 902 group mesh).\n *\n * One random 32-byte **epoch secret** per membership state. It never travels in\n * the clear: the committer seals it to each member of the new roster with an\n * ephemeral X25519 key against the member's Ed25519 member key. From it come\n * the message key of the epoch and the key of the confirmation tag that binds\n * the secret to its commit. Messages are XChaCha20-Poly1305 with the epoch\n * message key and the message header as associated data, and are signed by\n * the sender's member key, since the message key alone is shared by everyone.\n *\n * This is not MLS: there is no ratchet tree, member keys are static for the\n * life of the group, and the only source of post-compromise security is a\n * fresh random secret that a removed member is never sent.\n */\nexport const GROUP_PROFILE = \"group-mesh/1\" as const;\nconst NONCE_LENGTH = 24;\n\nconst info = (label: string) => utf8Encode(`ghostly-group/1 ${label}`);\n\n/** The keys of one epoch, from its secret. */\nexport function epochKeys(secret: Uint8Array, groupId: string, epoch: number): { message: Uint8Array; confirm: Uint8Array } {\n if (secret.length !== 32) throw new Error(\"Invalid epoch secret\");\n const salt = utf8Encode(`${groupId}/${epoch}`);\n return { message: hkdf(sha256, secret, salt, info(\"message\"), 32), confirm: hkdf(sha256, secret, salt, info(\"confirm\"), 32) };\n}\n\n/**\n * The key that seals a `group-community/1` group's call media end to end (WISP 602): the epoch's secret and salt, under\n * its own label, so it is never a message key. Every member of the epoch derives the same one; a member taken out gets\n * no later secret, so not the next key either.\n */\nexport function groupCallKey(secret: Uint8Array, groupId: string, epoch: number): Uint8Array {\n if (secret.length !== 32) throw new Error(\"Invalid epoch secret\");\n return hkdf(sha256, secret, utf8Encode(`${groupId}/${epoch}`), utf8Encode(`ghostly-group-call/1 g_${groupId}`), 32);\n}\n\nexport function newEpochSecret(): Uint8Array { return randomBytes(32); }\n\nexport interface SealedSecret { e: string; n: string; c: string }\n\n/** The epoch secret for one member: an ephemeral X25519 exchange against the member's Ed25519 key. */\nexport function sealSecret(recipientZ32: string, secret: Uint8Array, aad: string): SealedSecret {\n const ephemeral = x25519.utils.randomSecretKey();\n const ephemeralPublic = x25519.getPublicKey(ephemeral);\n const recipient = ed25519.utils.toMontgomery(publicKeyFromZ32(recipientZ32));\n const key = sealKey(x25519.getSharedSecret(ephemeral, recipient), ephemeralPublic, recipientZ32);\n const nonce = randomBytes(NONCE_LENGTH);\n return { e: toBase64Url(ephemeralPublic), n: toBase64Url(nonce), c: toBase64Url(xchacha20poly1305(key, nonce, utf8Encode(aad)).encrypt(secret)) };\n}\n\n/** Null when the box was not sealed to this seed with this associated data. */\nexport function openSecret(mySeed: Uint8Array, myZ32: string, sealed: SealedSecret, aad: string): Uint8Array | null {\n try {\n const ephemeralPublic = fromBase64Url(sealed.e), nonce = fromBase64Url(sealed.n), box = fromBase64Url(sealed.c);\n if (ephemeralPublic.length !== 32 || nonce.length !== NONCE_LENGTH) return null;\n const key = sealKey(x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(mySeed), ephemeralPublic), ephemeralPublic, myZ32);\n const secret = xchacha20poly1305(key, nonce, utf8Encode(aad)).decrypt(box);\n return secret.length === 32 ? secret : null;\n } catch { return null; }\n}\n\nfunction sealKey(shared: Uint8Array, ephemeralPublic: Uint8Array, recipientZ32: string): Uint8Array {\n return hkdf(sha256, shared, ephemeralPublic, concatBytes(info(\"seal\"), utf8Encode(recipientZ32)), 32);\n}\n\n/**\n * Something for one member only, from another, inside a frame the whole group carries (`group-community/1`\n * pair payloads: payments between two members relayed by hubs). The key mixes an ephemeral X25519 exchange\n * against the recipient's member key with the static exchange between sender and recipient: only the\n * recipient can open it, only the sender (or the recipient) can have made it, and a later leak of the\n * sender's seed alone opens nothing. The associated data binds it to the frame that carries it.\n */\nexport function sealPair(senderSeed: Uint8Array, senderZ32: string, recipientZ32: string, plaintext: Uint8Array, aad: string): SealedSecret {\n const ephemeral = x25519.utils.randomSecretKey();\n const ephemeralPublic = x25519.getPublicKey(ephemeral);\n const recipient = ed25519.utils.toMontgomery(publicKeyFromZ32(recipientZ32));\n const key = pairKey(x25519.getSharedSecret(ephemeral, recipient), x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(senderSeed), recipient), ephemeralPublic, senderZ32, recipientZ32);\n const nonce = randomBytes(NONCE_LENGTH);\n return { e: toBase64Url(ephemeralPublic), n: toBase64Url(nonce), c: toBase64Url(xchacha20poly1305(key, nonce, utf8Encode(aad)).encrypt(plaintext)) };\n}\n\n/** Null unless `senderZ32` sealed it to this seed with this associated data. */\nexport function openPair(mySeed: Uint8Array, myZ32: string, senderZ32: string, sealed: SealedSecret, aad: string): Uint8Array | null {\n try {\n const ephemeralPublic = fromBase64Url(sealed.e), nonce = fromBase64Url(sealed.n);\n if (ephemeralPublic.length !== 32 || nonce.length !== NONCE_LENGTH) return null;\n const mine = ed25519.utils.toMontgomerySecret(mySeed);\n const key = pairKey(x25519.getSharedSecret(mine, ephemeralPublic), x25519.getSharedSecret(mine, ed25519.utils.toMontgomery(publicKeyFromZ32(senderZ32))), ephemeralPublic, senderZ32, myZ32);\n return xchacha20poly1305(key, nonce, utf8Encode(aad)).decrypt(fromBase64Url(sealed.c));\n } catch { return null; }\n}\n\nfunction pairKey(ephemeralShared: Uint8Array, staticShared: Uint8Array, ephemeralPublic: Uint8Array, senderZ32: string, recipientZ32: string): Uint8Array {\n return hkdf(sha256, concatBytes(ephemeralShared, staticShared), ephemeralPublic, concatBytes(utf8Encode(\"ghostly-group/2 pair\"), utf8Encode(senderZ32), utf8Encode(recipientZ32)), 32);\n}\n\n/** Text under the epoch message key, bound to its header. */\nexport function encryptText(messageKey: Uint8Array, aad: string, text: string): { n: string; c: string } {\n const nonce = randomBytes(NONCE_LENGTH);\n return { n: toBase64Url(nonce), c: toBase64Url(xchacha20poly1305(messageKey, nonce, utf8Encode(aad)).encrypt(utf8Encode(text))) };\n}\n\nexport function decryptText(messageKey: Uint8Array, aad: string, nonceB64: string, boxB64: string): string | null {\n try {\n const nonce = fromBase64Url(nonceB64);\n if (nonce.length !== NONCE_LENGTH) return null;\n return utf8Decode(xchacha20poly1305(messageKey, nonce, utf8Encode(aad)).decrypt(fromBase64Url(boxB64)));\n } catch { return null; }\n}\n\n/** Proves the committer holds the secret the commit distributes: HMAC of the commit's untagged hash. */\nexport function confirmationTag(confirmKey: Uint8Array, untaggedHashHex: string): string {\n return toBase64Url(hmac(sha256, confirmKey, utf8Encode(untaggedHashHex)));\n}\nexport function confirmationMatches(confirmKey: Uint8Array, untaggedHashHex: string, tag: string): boolean {\n try { return bytesEqual(fromBase64Url(tag), hmac(sha256, confirmKey, utf8Encode(untaggedHashHex))); } catch { return false; }\n}\n\nexport function sha256Hex(data: Uint8Array): string {\n return Array.from(sha256(data), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * The pairwise link two members of a group run between them, derived by both\n * from the X25519 secret of their member keys and nothing else: rendezvous\n * identities for each side and the symmetric key of their discovery records.\n * No third party, the admin included, can compute it; a member who left keeps\n * only the edges it was part of, and those are closed by the remaining side.\n */\nexport function edgeParams(groupId: string, mySeed: Uint8Array, myZ32: string, peerZ32: string): LinkParams {\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(mySeed), ed25519.utils.toMontgomery(publicKeyFromZ32(peerZ32)));\n const salt = utf8Encode(groupId);\n const seed = (owner: string) => hkdf(sha256, shared, salt, concatBytes(info(\"edge seed\"), utf8Encode(owner)), 32);\n return {\n seedB64: toBase64Url(seed(myZ32)),\n peerPubKeyZ32: identityFromSeed(seed(peerZ32)).pubKeyZ32,\n encKeyB64: toBase64Url(hkdf(sha256, shared, salt, info(\"edge key\"), 32)),\n profile: \"paired-chat/1\",\n };\n}\n","import { fromBase64Url, isZ32Key, toBase64Url, utf8Encode } from \"./bytes\";\nimport { publicKeyFromZ32, sign, verify } from \"./identity\";\nimport { sha256Hex } from \"./groupCrypto\";\n\n/**\n * Membership of a `group-mesh/1` group is a chain of signed commits. Each\n * commit carries the whole roster after it, so any member can name the roster\n * of any epoch from the chain alone; the chain, from its genesis, is what\n * authenticates a roster to a member who was not there for the changes.\n *\n * Exactly one admin per epoch (the coordinator of WISP 900): every commit is\n * signed by the admin of the previous epoch, and admission of a new member,\n * removal, transfer of the admin role and a bare rotation each advance the\n * epoch by one. Two different commits after the same epoch are a fork, which\n * halts the group rather than picking a winner.\n */\nexport type GroupRole = \"admin\" | \"member\";\nexport type CommitKind = \"create\" | \"add\" | \"remove\" | \"role\" | \"rotate\";\nexport type Roster = [key: string, role: GroupRole][];\n\nexport interface GroupCommit {\n v: 1;\n /** Group id: 22 base64url characters. */\n g: string;\n /** Epoch: the commit's index in the chain, from 0. */\n e: number;\n /** Hash of the previous commit; empty for the genesis. */\n p: string;\n k: CommitKind;\n /** The roster after this commit, sorted by key. */\n m: Roster;\n /** The committer. */\n by: string;\n /** The member added, removed or made admin. */\n s?: string;\n ts: number;\n /** Confirmation tag: HMAC of the untagged commit under the new epoch's confirm key. */\n c: string;\n sig: string;\n}\n\n/**\n * Members a roster may hold. Apps from before revision 0.9 of the profile refuse a commit whose roster is larger than\n * `LEGACY_GROUP_MEMBERS` (as malformed), so an admin grows a group past that only when every member's app said it can\n * (`paired-groups` version `GROUP_VERSION_LARGE`).\n */\nexport const MAX_GROUP_MEMBERS = 32;\nexport const LEGACY_GROUP_MEMBERS = 8;\n/**\n * The cap the chain rules and the engine apply: `MAX_GROUP_MEMBERS`, always, in the apps. Only the scale harness raises\n * it, to measure what hubs would cost past 32 (WISP 902 · Group Mesh § Cost per member); an app never does.\n */\nexport const GROUP_MEMBER_CAP = { max: MAX_GROUP_MEMBERS as number };\n/** The `paired-groups` version an app announces when it takes mesh rosters of up to `MAX_GROUP_MEMBERS`. */\nexport const GROUP_VERSION_LARGE = 3;\nexport const MAX_GROUP_CHAIN = 1024;\nexport const GROUP_ID = /^[A-Za-z0-9_-]{22}$/;\n/**\n * A member's key, in its one canonical spelling (`isZ32Key`): a roster names members by string, so a key respelled in\n * its last character would be a second member for one key, and `publicKeyFromZ32` would throw on it past this check.\n */\nexport const MEMBER_KEY = { test: isZ32Key };\nconst TAG = /^[A-Za-z0-9_-]{43}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst HASH = /^[a-f0-9]{64}$/;\n\nconst tuple = (c: Omit<GroupCommit, \"sig\">, tag = c.c) => JSON.stringify([c.v, c.g, c.e, c.p, c.k, c.m, c.by, c.s ?? \"\", c.ts, tag]);\n\nexport function commitHash(commit: Omit<GroupCommit, \"sig\">): string { return sha256Hex(utf8Encode(tuple(commit))); }\n/** What the confirmation tag covers: the commit with an empty tag. */\nexport function commitUntaggedHash(commit: Omit<GroupCommit, \"sig\" | \"c\">): string { return sha256Hex(utf8Encode(tuple({ ...commit, c: \"\" }, \"\"))); }\n\nexport function signCommit(commit: Omit<GroupCommit, \"sig\">, seed: Uint8Array): GroupCommit {\n return { ...commit, sig: toBase64Url(sign(utf8Encode(tuple(commit)), seed)) };\n}\n\nexport function rosterAdmin(roster: Roster): string | undefined { return roster.find(([, role]) => role === \"admin\")?.[0]; }\nexport function rosterHas(roster: Roster, key: string): boolean { return roster.some(([k]) => k === key); }\nexport const sortRoster = (roster: Roster): Roster => [...roster].sort((a, b) => a[0] < b[0] ? -1 : 1);\n\nfunction parseCommit(raw: unknown): GroupCommit | null {\n if (!raw || typeof raw !== \"object\") return null;\n const c = raw as Record<string, unknown>;\n if (c.v !== 1 || typeof c.g !== \"string\" || !GROUP_ID.test(c.g) || !Number.isSafeInteger(c.e) || (c.e as number) < 0 ||\n typeof c.p !== \"string\" || (c.p !== \"\" && !HASH.test(c.p)) || ![\"create\", \"add\", \"remove\", \"role\", \"rotate\"].includes(c.k as string) ||\n !Array.isArray(c.m) || c.m.length === 0 || c.m.length > GROUP_MEMBER_CAP.max ||\n !c.m.every(entry => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === \"string\" && MEMBER_KEY.test(entry[0]) && (entry[1] === \"admin\" || entry[1] === \"member\")) ||\n typeof c.by !== \"string\" || !MEMBER_KEY.test(c.by) || (c.s !== undefined && (typeof c.s !== \"string\" || !MEMBER_KEY.test(c.s))) ||\n !Number.isSafeInteger(c.ts) || (c.ts as number) <= 0 || typeof c.c !== \"string\" || !TAG.test(c.c) || typeof c.sig !== \"string\" || !SIG.test(c.sig)) return null;\n const m = c.m as Roster;\n if (new Set(m.map(([k]) => k)).size !== m.length || m.filter(([, r]) => r === \"admin\").length !== 1) return null;\n for (let i = 1; i < m.length; i++) if (!(m[i - 1][0] < m[i][0])) return null;\n return { v: 1, g: c.g, e: c.e as number, p: c.p, k: c.k as CommitKind, m, by: c.by, ...(c.s !== undefined ? { s: c.s as string } : {}), ts: c.ts as number, c: c.c, sig: c.sig };\n}\n\n/** Only shape, no signature or parent: a commit as kept, its fields alone (anything else it carried dropped); null when malformed. */\nexport const parseGroupCommit = parseCommit;\n\n/** The roster a commit must carry, given the previous one; null when the change is not allowed. */\nexport function expectedRoster(previous: Roster | null, kind: CommitKind, by: string, subject?: string): Roster | null {\n if (kind === \"create\") return previous === null && !subject ? [[by, \"admin\"]] : null;\n if (!previous || rosterAdmin(previous) !== by) return null;\n switch (kind) {\n case \"add\":\n if (!subject || subject === by || rosterHas(previous, subject) || previous.length >= GROUP_MEMBER_CAP.max) return null;\n return sortRoster([...previous, [subject, \"member\"]]);\n case \"remove\":\n if (!subject || subject === by || !rosterHas(previous, subject)) return null;\n return previous.filter(([k]) => k !== subject);\n case \"role\":\n if (!subject || subject === by || !rosterHas(previous, subject)) return null;\n return previous.map(([k]) => [k, k === subject ? \"admin\" : \"member\"]);\n case \"rotate\":\n return subject ? null : previous;\n }\n}\n\nconst sameRoster = (a: Roster, b: Roster) => a.length === b.length && a.every(([k, r], i) => b[i][0] === k && b[i][1] === r);\n\n/**\n * Checks one commit against the chain so far (`previous` is its last commit,\n * or null for a genesis): index, link, authority, roster arithmetic and\n * signature. The confirmation tag is checked separately, once the secret is known.\n */\nexport function verifyCommit(raw: unknown, previous: GroupCommit | null, groupId?: string): { commit: GroupCommit } | { error: string } {\n const commit = parseCommit(raw);\n if (!commit) return { error: \"Malformed membership commit\" };\n if (groupId && commit.g !== groupId) return { error: \"Commit for another group\" };\n if (previous) {\n if (commit.g !== previous.g) return { error: \"Commit for another group\" };\n if (commit.e !== previous.e + 1) return { error: \"Commit out of sequence\" };\n if (commit.p !== commitHash(previous)) return { error: \"Commit does not follow the last known membership\" };\n } else if (commit.e !== 0 || commit.p !== \"\" || commit.k !== \"create\") return { error: \"The chain does not start with the creation of the group\" };\n const expected = expectedRoster(previous?.m ?? null, commit.k, commit.by, commit.s);\n if (!expected || !sameRoster(expected, commit.m)) return { error: \"Unauthorized or inconsistent membership change\" };\n if (!verify(fromBase64Url(commit.sig), utf8Encode(tuple(commit)), publicKeyFromZ32(commit.by))) return { error: \"Membership commit signature is invalid\" };\n return { commit };\n}\n\n/** Only shape and signature: evidence that `by` signed this, whatever chain it belongs to. */\nexport function verifyCommitSignature(raw: unknown): GroupCommit | null {\n const commit = parseCommit(raw);\n return commit && verify(fromBase64Url(commit.sig), utf8Encode(tuple(commit)), publicKeyFromZ32(commit.by)) ? commit : null;\n}\n\n/** A whole chain, from genesis. */\nexport function verifyChain(raw: unknown, groupId?: string): { chain: GroupCommit[] } | { error: string } {\n if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_GROUP_CHAIN) return { error: \"Malformed membership chain\" };\n const chain: GroupCommit[] = [];\n for (const entry of raw) {\n const result = verifyCommit(entry, chain[chain.length - 1] ?? null, groupId);\n if (\"error\" in result) return result;\n chain.push(result.commit);\n }\n return { chain };\n}\n\n/**\n * What a commit is refused with while admin work is off on this device (WISP 06 § Forced takeover: after a forced\n * takeover or a restore, until the person turns on \"Manage groups from this device\").\n */\n/**\n * The highest sequence number a frame of my own key, sent by another copy of my profile, may make me adopt (WISP 06):\n * the highest floor a copy can have (2^32 - 2^24) and room above it. The community beacon packs the counter in 32 bits.\n */\nexport const OWN_FRAME_LIMIT = 2 ** 32 - 2 ** 23;\n\n/**\n * Frames said again (WISP 902, both profiles): a member's own frames that no edge took when it said them are\n * remembered (`kept`, the latest) and, once the chain it follows is newer than such a frame's and has not moved for\n * `settledMs`, looked at once for saying again where the members let in while it was behind can read them. A catch-up\n * brings commits one by one, and a frame said again at the first of them would still miss those let in by the next.\n */\nexport const SAID_AGAIN = { settledMs: 5_000, kept: 64 } as const;\n\n/** `alone` with `key` added last, keeping only keys still `present` (frames still in the log), the latest `kept`. */\nexport function rememberAlone(alone: readonly string[] | undefined, key: string, present: (key: string) => boolean): string[] {\n return [...(alone ?? []).filter(k => k !== key && present(k)), key].slice(-SAID_AGAIN.kept);\n}\n\nexport const GROUP_ADMIN_OFF_ERROR = \"Managing this group is off on this device. Turn on Manage groups from this device first.\";\n","/**\n * How far ahead of this device's clock a number a peer made from its clock may be (a pin's number, a status card's\n * times): clocks drift, but a time past this is the peer's choice, not its clock.\n */\nexport const MESSAGE_CLOCK_SKEW_MS = 5 * 60_000;\n\n/**\n * The time a line of a group's history is kept under (a membership change, a rename): what its commit says, but at\n * most `MESSAGE_CLOCK_SKEW_MS` past this clock, and now when it is not a positive number. Messages do not use it:\n * they are placed where they arrive (below).\n */\nexport function receivedTimestamp(ts: number, now = Date.now()): number {\n if (!Number.isFinite(ts) || ts <= 0) return now;\n return Math.min(ts, now + MESSAGE_CLOCK_SKEW_MS);\n}\n\n/** The latest moment a date can hold. */\nconst MAX_DATE_MS = 8.64e15;\n\n/*\n * A received message has two times (WISP 400, requirement 10).\n *\n * Its place: when it was first stored on this device, kept as the row's `timestamp`. A history is sorted by it, so a\n * conversation reads in the order things happened here: what came is where it came, and what I send next goes\n * below it, whatever the sender's clock says. A peer picks the time it sends, so that time never orders anything.\n *\n * The sender's claim: kept beside it (`sentAt`) and shown on the bubble, never later than the place: a message does\n * not show a time that has not come yet.\n */\n\n/** The time a sender says, as it is kept: a positive time a date can hold, or nothing. */\nexport function claimedTime(ts: unknown): number | undefined {\n return typeof ts === \"number\" && Number.isFinite(ts) && ts > 0 && ts <= MAX_DATE_MS ? ts : undefined;\n}\n\n/**\n * The place of a row stored now: this clock, and past the last place given in its chat, so rows that come in the\n * same millisecond (a hold pickup, a group's catch-up) keep the order they came in.\n */\nexport function arrivalKey(now: number, last = 0): number {\n return Math.max(now, last + 1);\n}\n\n/** The time a message shows: what its sender said, never later than when it came. A row of mine shows its own time. */\nexport function shownTime(message: { timestamp: number; sentAt?: number }): number {\n return message.sentAt === undefined ? message.timestamp : Math.min(message.sentAt, message.timestamp);\n}\n\n/**\n * When something a peer dated happened (an edit), for this device: what the peer says, now at the latest, and now\n * when it says nothing a date can hold.\n */\nexport function heardTime(ts: unknown, now = Date.now()): number {\n return Math.min(claimedTime(ts) ?? now, now);\n}\n","import { utf8Encode } from \"./bytes\";\nimport { isAppHash, isAppRef } from \"./appStatements\";\nimport { MESSAGE_CLOCK_SKEW_MS } from \"./messageTime\";\nimport { sanitizeDisplayText } from \"./text\";\n\n/*\n * Status cards (WISP 405 · Status Cards): a bot's task or routine, shown as a small card instead of a text. A card rides\n * as `sc` beside the text of a message on every path that carries text with fields of its own (the live session's\n * `paired-message` and `paired-edit`, a private group's sealed box, a community's payload and its edit frame), and the\n * text is its fallback: what an app without cards, the DHT floor and a held item show. The bot keeps a card current by\n * editing its message; the highest edit number wins, as for any edit, and a card belongs to the version it came with.\n *\n * {\"kind\":\"task\",\"id\":\"relay-rotation\",\"title\":\"Fix relay rotation\",\"status\":\"running\",\"progress\":40,\n * \"step\":\"Running the e2e\",\"pr\":{\"url\":\"https://github.com/o/r/pull/612\",\"number\":612,\"additions\":123,\"deletions\":45}}\n *\n * Cards are display only: nothing on one runs anything, and its links are https, shown with their host. Every string\n * is one line of plain text without control, invisible or direction characters; every list and number is bounded.\n * `readStatusCard` is the reader's rule (what does not hold is left out, a card that cannot stand is dropped, never the\n * message); `checkStatusCard` is the sender's (anything out of bounds is refused, so nothing is lost silently).\n */\n\nexport const STATUS_CARD_LIMITS = {\n /** A card's JSON, as sent (UTF-8 bytes): with the fallback text it stays well inside every message bound. */\n bytes: 8 * 1024,\n /** The sender's id for the card: stable across its updates. */\n id: 64,\n title: 120,\n /** The current step, a list item, a run's summary. */\n line: 200,\n branch: 120,\n schedule: 80,\n cron: 64,\n linkLabel: 40,\n url: 512,\n items: 20,\n links: 4,\n runs: 10,\n /** Any count on a card (a PR's number, lines, files; steps). */\n count: 1_000_000_000,\n /** How far ahead a routine's next run may be. */\n nextRunMs: 366 * 24 * 60 * 60_000,\n /** Edits a message with a card takes (a text takes `MAX_EDITS_PER_MESSAGE`): a bot updates a long task often. */\n edits: 5_000,\n /** Labels on a task, and a label's length in characters. */\n tags: 3,\n tag: 24,\n /** Buttons on a message (WISP 406 · Message Buttons). */\n buttons: 6,\n /** A button's id: what a press names. */\n buttonId: 32,\n /** A button's label, in characters. */\n buttonLabel: 40,\n /** An app card's title and version, in characters (WISP 405 § An app): the manifest's bounds. */\n appTitle: 40,\n appVersion: 32,\n /** A usage card's label (\"Claude\") and account, in characters (WISP 405 § Usage). */\n usageLabel: 24,\n /** A usage window's name (\"5 h\", \"week\"), in characters. */\n usageWindow: 16,\n /** Windows beside a usage card's own, shown in its details. */\n usageWindows: 3,\n} as const;\n\n/** How a button looks: `primary` is the one highlighted, `danger` warns; `neutral` when none is said. */\nexport const BUTTON_STYLES = [\"primary\", \"neutral\", \"danger\"] as const;\nexport type ButtonStyle = typeof BUTTON_STYLES[number];\n\nexport const TASK_STATUSES = [\"queued\", \"running\", \"blocked\", \"done\", \"failed\", \"cancelled\"] as const;\nexport type TaskStatus = typeof TASK_STATUSES[number];\n/** A task that is still going: shown first, and counted on the chat's Tasks button. */\nexport const ACTIVE_TASK_STATUSES: readonly TaskStatus[] = [\"queued\", \"running\", \"blocked\"];\nexport const ITEM_STATES = [\"pending\", \"running\", \"done\", \"failed\", \"skipped\"] as const;\nexport type ItemState = typeof ITEM_STATES[number];\nexport const ROUTINE_STATES = [\"active\", \"paused\"] as const;\nexport type RoutineState = typeof ROUTINE_STATES[number];\nexport const RUN_RESULTS = [\"ok\", \"failed\", \"skipped\"] as const;\nexport type RunResult = typeof RUN_RESULTS[number];\n\n/**\n * Where a task's pull request stands: `draft` (not ready for review), `open` (ready for review), `merged`, `closed`\n * (closed without a merge). A reader that does not know the field shows the pull request as before.\n */\nexport const PR_STATES = [\"draft\", \"open\", \"merged\", \"closed\"] as const;\nexport type PrState = typeof PR_STATES[number];\n/** How a pull request's checks stand. */\nexport const PR_CHECKS = [\"passing\", \"failing\", \"pending\"] as const;\nexport type PrChecks = typeof PR_CHECKS[number];\n\nexport interface CardLink { url: string; label?: string }\nexport interface TaskItem { text: string; state: ItemState }\nexport interface TaskPr { url: string; number?: number; additions?: number; deletions?: number; files?: number; state?: PrState; checks?: PrChecks }\n\nexport interface TaskCard {\n kind: \"task\";\n id: string;\n title: string;\n status: TaskStatus;\n /** 0 to 100. */\n progress?: number;\n /** Steps done of `total`. */\n done?: number;\n total?: number;\n /** What it is doing now. */\n step?: string;\n pr?: TaskPr;\n branch?: string;\n startedAt?: number;\n updatedAt?: number;\n items?: TaskItem[];\n links?: CardLink[];\n /** Up to `STATUS_CARD_LIMITS.tags` short labels (an area, a repository), shown as chips. */\n tags?: string[];\n /** The id of another task of the same sender in the same chat that this one is a part of. */\n parent?: string;\n}\n\nexport interface RoutineRun { at: number; result: RunResult; summary?: string }\n\nexport interface RoutineCard {\n kind: \"routine\";\n id: string;\n name: string;\n /** When it runs, as people say it (\"every day 01:00\"). */\n schedule: string;\n cron?: string;\n state: RoutineState;\n lastRun?: RoutineRun;\n nextRunAt?: number;\n /** Recent runs, newest first. */\n runs?: RoutineRun[];\n links?: CardLink[];\n}\n\n/**\n * A button under a bot's message (WISP 406 · Message Buttons). `once`: a press on it answers the question for that\n * person, and their app offers none of the buttons again; a button without it may be pressed again.\n */\nexport interface CardButton { id: string; label: string; style?: ButtonStyle; once?: true }\n\n/**\n * Buttons under a bot's message (WISP 406 · Message Buttons): unlike a task or a routine, the message's text shows\n * with them, and is also what an app without buttons shows (so it should say how to answer in words). `chosen` is the\n * answer the bot took, marked for everyone; `closed`: no button takes a press any more.\n */\nexport interface ButtonsCard {\n kind: \"buttons\";\n id: string;\n buttons: CardButton[];\n chosen?: string;\n closed?: true;\n}\n\n/**\n * A mini-app the sender shared in the chat, or opened in it (WISP 405 § An app, WISP 1200 § Apps sent in a chat): what a\n * contact needs to install the same app and check it. Every field is the sender's claim, unsigned; nothing is fetched to\n * show it. `id` is made from `ref` (`appCardId`); `opened` only for \"Ana opened Chess\".\n */\nexport interface AppCard {\n kind: \"app\";\n id: string;\n ref: string;\n digest: string;\n sequence: number;\n title: string;\n version?: string;\n url?: string;\n opened?: true;\n}\n\n/** Another window of a usage card (\"week\"): how much of it is left, and when it starts again. */\nexport interface UsageWindow { window: string; left: number; resetsAt?: number }\n\n/**\n * How much of a quota a bot has left (WISP 405 § Usage): \"Claude, 62% left of the 5 h window, resets 18:00\". `left` is\n * the percent left, 0 to 100; a bot that counts can say `used` of `limit` instead, and the percent is worked out\n * (`usageLeft`). `windows`: other windows of the same quota (a week), shown in the details. One per chat stands: the\n * latest a sender changed. Display only, like every card.\n */\nexport interface UsageCard {\n kind: \"usage\";\n id: string;\n /** 0 to 100: how much is left, in percent. */\n left?: number;\n used?: number;\n limit?: number;\n /** What the quota is of (\"Claude\"). */\n label?: string;\n /** Which of the bot's accounts it is, short. */\n account?: string;\n /** The quota's window, as people say it (\"5 h\", \"week\"). */\n window?: string;\n /** When the window starts again: milliseconds. */\n resetsAt?: number;\n /** When the bot read the numbers: milliseconds. */\n updatedAt?: number;\n windows?: UsageWindow[];\n}\n\n/** The kinds a sender may take back (WISP 405 § Removing a card). */\nexport const REMOVABLE_KINDS = [\"task\", \"routine\"] as const;\nexport type RemovableKind = typeof REMOVABLE_KINDS[number];\n\n/**\n * A task or routine its sender took back (WISP 405 § Removing a card): the edit of the card's message that retracts it.\n * Not a task nor a routine, so no Tasks view counts it; an app without this kind drops it and shows the text.\n */\nexport interface RemovedCard {\n kind: \"removed\";\n /** The id of the card taken back. */\n id: string;\n of: RemovableKind;\n}\n\nexport type StatusCard = TaskCard | RoutineCard | ButtonsCard | AppCard | UsageCard | RemovedCard;\nexport type StatusCardKind = StatusCard[\"kind\"];\n\nconst ID = /^[A-Za-z0-9_.:][A-Za-z0-9_.:-]{0,63}$/;\n/** A button's id: 1 to 32 of `A-Z a-z 0-9 _ . : -`, not starting with `-`. */\nexport const BUTTON_ID = /^[A-Za-z0-9_.:][A-Za-z0-9_.:-]{0,31}$/;\n/** A routine's cron line, trimmed: 1 to 64 of `0-9 A-Z a-z * , / ? # -` and spaces (shown, never run). */\nexport const CRON_LINE = /^[0-9A-Za-z*,/?#\\- ]{1,64}$/;\n\n/**\n * Whether a typed answer is a button's label or id (WISP 406 · Message Buttons): ignoring case and spaces at the ends.\n * Not the device's locale's case: the presser's and the author's apps must agree (\"I\" is not \"ı\" anywhere).\n */\nexport const sameButtonText = (a: string, b: string): boolean => a.trim().toLowerCase() === b.trim().toLowerCase();\n\n/**\n * Two buttons a typed answer could not tell apart, or none: a label that reads as an earlier label (`label`), or a\n * label that reads as another button's id (`id`), both as `sameButtonText` compares them. The labels as a reader keeps\n * them (one line, cleaned). `at` is the button that clashes, `with` the one it clashes with.\n */\nexport function buttonLabelClash(buttons: readonly unknown[]): { at: number; with: number; kind: \"label\" | \"id\" } | undefined {\n const labels = buttons.map(button => (isObject(button) ? cardLine(button.label, Infinity) : undefined));\n const ids = buttons.map(button => (isObject(button) && typeof button.id === \"string\" ? button.id : undefined));\n for (const [at, label] of labels.entries()) {\n if (!label) continue;\n const twin = labels.findIndex((other, i) => i < at && !!other && sameButtonText(other, label));\n if (twin !== -1) return { at, with: twin, kind: \"label\" };\n const named = ids.findIndex((id, i) => i !== at && id !== undefined && sameButtonText(id, label));\n if (named !== -1) return { at, with: named, kind: \"id\" };\n }\n return undefined;\n}\n\n/** An app card's id, made from its reference: the app's name, a dot, the first 16 characters of the publisher key. */\nexport function appCardId(ref: string): string {\n return `${ref.slice(53)}.${ref.slice(0, 16)}`;\n}\n\n/** An app card's `sequence`: a whole number from 0 to 2^53 - 1. */\nconst appSequence = (value: unknown): value is number => typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** One line of display text: runs of space (line breaks included) become one space, then the display rules for names. */\nexport function cardLine(value: unknown, max: number): string | undefined {\n if (typeof value !== \"string\") return undefined;\n return sanitizeDisplayText(value.replace(/\\s+/gu, \" \"), max);\n}\n\n/**\n * An https link a card may show: no credentials, a host, no spaces or control characters, at most\n * `STATUS_CARD_LIMITS.url` characters. Returned as the parser writes it (a non-ASCII host in punycode).\n */\nexport function cardUrl(value: unknown): string | undefined {\n if (typeof value !== \"string\" || !value || value.length > STATUS_CARD_LIMITS.url || /[\\s\\p{Cc}\\p{Cf}]/u.test(value)) return undefined;\n let url: URL;\n try { url = new URL(value); } catch { return undefined; }\n if (url.protocol !== \"https:\" || !url.hostname || url.username || url.password) return undefined;\n return url.href.length <= STATUS_CARD_LIMITS.url ? url.href : undefined;\n}\n\n/**\n * The link an app card names, sent or read (WISP 405 § An app): a card's link without its query or fragment. A\n * private file's read token rides in a query, and a card goes to a contact; a bundle is pinned by its digest, not its link.\n */\nexport function appCardUrl(value: unknown): string | undefined {\n const href = cardUrl(value);\n if (!href) return undefined;\n const url = new URL(href);\n url.search = \"\";\n url.hash = \"\";\n return url.href;\n}\n\n/** The host a card shows beside a link, so the reader sees where it goes before following it. */\nexport function cardLinkHost(url: string): string {\n try { return new URL(url).host; } catch { return \"\"; }\n}\n\nconst count = (value: unknown, min = 0): number | undefined =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= min && value <= STATUS_CARD_LIMITS.count ? value : undefined;\n\n/** A time on a card as a reader keeps it: a positive whole number, never later than `latest`. */\nconst time = (value: unknown, latest: number): number | undefined =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? Math.min(value, latest) : undefined;\n\nconst oneOf = <T extends string>(values: readonly T[], value: unknown): T | undefined =>\n typeof value === \"string\" && (values as readonly string[]).includes(value) ? value as T : undefined;\n\nfunction readLinks(raw: unknown): CardLink[] {\n if (!Array.isArray(raw)) return [];\n const links: CardLink[] = [];\n for (const entry of raw.slice(0, STATUS_CARD_LIMITS.links)) {\n if (!isObject(entry)) continue;\n const url = cardUrl(entry.url);\n if (!url) continue;\n const label = cardLine(entry.label, STATUS_CARD_LIMITS.linkLabel);\n links.push({ url, ...(label && { label }) });\n }\n return links;\n}\n\n/** A task's labels as a reader keeps them: the first `STATUS_CARD_LIMITS.tags` that hold, each one clean line, none twice. */\nfunction readTags(raw: unknown): string[] {\n if (!Array.isArray(raw)) return [];\n const tags: string[] = [];\n for (const entry of raw) {\n const tag = cardLine(entry, STATUS_CARD_LIMITS.tag);\n if (tag && !tags.includes(tag)) tags.push(tag);\n if (tags.length === STATUS_CARD_LIMITS.tags) break;\n }\n return tags;\n}\n\nfunction readRun(raw: unknown, now: number): RoutineRun | undefined {\n if (!isObject(raw)) return undefined;\n const at = time(raw.at, now + MESSAGE_CLOCK_SKEW_MS), result = oneOf(RUN_RESULTS, raw.result);\n if (!at || !result) return undefined;\n const summary = cardLine(raw.summary, STATUS_CARD_LIMITS.line);\n return { at, result, ...(summary && { summary }) };\n}\n\n/** A percent as a reader keeps it: a finite number, rounded and clamped into 0 to 100. */\nconst percent = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? Math.round(Math.min(100, Math.max(0, value))) : undefined;\n\n/** A time ahead of the reader (a reset, a next run) as it keeps it: whole, positive, at most a year ahead. */\nconst ahead = (value: unknown, now: number): number | undefined =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 && value <= now + STATUS_CARD_LIMITS.nextRunMs ? value : undefined;\n\n/** A usage card as a reader keeps it (WISP 405 § Usage): dropped without a percent left or a used of limit. */\nfunction readUsage(raw: Record<string, unknown>, id: string, now: number): UsageCard | undefined {\n const left = percent(raw.left);\n let used = count(raw.used), limit = count(raw.limit, 1);\n if (used === undefined || limit === undefined || used > limit) used = limit = undefined;\n if (left === undefined && limit === undefined) return undefined;\n const label = cardLine(raw.label, STATUS_CARD_LIMITS.usageLabel), account = cardLine(raw.account, STATUS_CARD_LIMITS.usageLabel);\n const window = cardLine(raw.window, STATUS_CARD_LIMITS.usageWindow);\n const resetsAt = ahead(raw.resetsAt, now), updatedAt = time(raw.updatedAt, now + MESSAGE_CLOCK_SKEW_MS);\n const windows: UsageWindow[] = [];\n if (Array.isArray(raw.windows)) for (const entry of raw.windows.slice(0, STATUS_CARD_LIMITS.usageWindows)) {\n if (!isObject(entry)) continue;\n const name = cardLine(entry.window, STATUS_CARD_LIMITS.usageWindow), share = percent(entry.left);\n if (!name || share === undefined) continue;\n const at = ahead(entry.resetsAt, now);\n windows.push({ window: name, left: share, ...(at && { resetsAt: at }) });\n }\n return {\n kind: \"usage\", id,\n ...(left !== undefined && { left }), ...(used !== undefined && limit !== undefined && { used, limit }),\n ...(label && { label }), ...(account && { account }), ...(window && { window }),\n ...(resetsAt && { resetsAt }), ...(updatedAt && { updatedAt }), ...(windows.length && { windows }),\n };\n}\n\n/** How much of a usage card's quota is left, 0 to 100: its own percent, else worked out from used of limit. */\nexport function usageLeft(card: Pick<UsageCard, \"left\" | \"used\" | \"limit\">): number {\n if (card.left !== undefined) return card.left;\n return card.used !== undefined && card.limit ? Math.round((card.limit - card.used) / card.limit * 100) : 0;\n}\n\n/** The bytes a card takes on the wire: what `STATUS_CARD_LIMITS.bytes` bounds. */\nexport function statusCardBytes(card: unknown): number {\n try { return utf8Encode(JSON.stringify(card) ?? \"\").length; } catch { return Infinity; }\n}\n\n/**\n * A card as a reader takes it from the wire (`sc`), or undefined when it cannot stand: not an object, past\n * `STATUS_CARD_LIMITS.bytes`, a kind this app does not know, no valid id, title or name, status or state. Fields that do\n * not hold are left out and lists are cut to their bound; times are kept no later than the reader's clock allows (a\n * routine's next run up to a year ahead). The message is always kept: without a card it shows its text.\n */\nexport function readStatusCard(raw: unknown, now = Date.now()): StatusCard | undefined {\n if (!isObject(raw) || statusCardBytes(raw) > STATUS_CARD_LIMITS.bytes) return undefined;\n const id = typeof raw.id === \"string\" && ID.test(raw.id) ? raw.id : undefined;\n if (!id) return undefined;\n if (raw.kind === \"app\") {\n // Dropped unless the app it names holds: the reference, its id, the digest, the sequence and a title.\n if (!isAppRef(raw.ref) || id !== appCardId(raw.ref) || !isAppHash(raw.digest) || !appSequence(raw.sequence)) return undefined;\n const title = cardLine(raw.title, STATUS_CARD_LIMITS.appTitle);\n if (!title) return undefined;\n const version = cardLine(raw.version, STATUS_CARD_LIMITS.appVersion), url = appCardUrl(raw.url);\n return { kind: \"app\", id, ref: raw.ref, digest: raw.digest, sequence: raw.sequence, title,\n ...(version && { version }), ...(url && { url }), ...(raw.opened === true && { opened: true as const }) };\n }\n if (raw.kind === \"removed\") {\n const of = oneOf(REMOVABLE_KINDS, raw.of);\n return of && { kind: \"removed\", id, of };\n }\n const latest = now + MESSAGE_CLOCK_SKEW_MS;\n if (raw.kind === \"usage\") return readUsage(raw, id, now);\n const links = readLinks(raw.links);\n if (raw.kind === \"task\") {\n const title = cardLine(raw.title, STATUS_CARD_LIMITS.title), status = oneOf(TASK_STATUSES, raw.status);\n if (!title || !status) return undefined;\n const progress = typeof raw.progress === \"number\" && Number.isFinite(raw.progress) ? Math.round(Math.min(100, Math.max(0, raw.progress))) : undefined;\n let done = count(raw.done), total = count(raw.total, 1);\n if (done === undefined || total === undefined || done > total) done = total = undefined;\n const step = cardLine(raw.step, STATUS_CARD_LIMITS.line), branch = cardLine(raw.branch, STATUS_CARD_LIMITS.branch);\n let pr: TaskPr | undefined;\n if (isObject(raw.pr)) {\n const url = cardUrl(raw.pr.url);\n if (url) {\n const number = count(raw.pr.number, 1), additions = count(raw.pr.additions), deletions = count(raw.pr.deletions), files = count(raw.pr.files);\n const state = oneOf(PR_STATES, raw.pr.state), checks = oneOf(PR_CHECKS, raw.pr.checks);\n pr = { url, ...(number !== undefined && { number }), ...(additions !== undefined && { additions }), ...(deletions !== undefined && { deletions }), ...(files !== undefined && { files }),\n ...(state && { state }), ...(checks && { checks }) };\n }\n }\n const items: TaskItem[] = [];\n if (Array.isArray(raw.items)) for (const entry of raw.items.slice(0, STATUS_CARD_LIMITS.items)) {\n if (!isObject(entry)) continue;\n const text = cardLine(entry.text, STATUS_CARD_LIMITS.line);\n if (text) items.push({ text, state: oneOf(ITEM_STATES, entry.state) ?? \"pending\" });\n }\n const startedAt = time(raw.startedAt, latest), updatedAt = time(raw.updatedAt, latest);\n const tags = readTags(raw.tags);\n // A task is never a part of itself.\n const parent = typeof raw.parent === \"string\" && ID.test(raw.parent) && raw.parent !== id ? raw.parent : undefined;\n return {\n kind: \"task\", id, title, status,\n ...(progress !== undefined && { progress }), ...(done !== undefined && total !== undefined && { done, total }),\n ...(step && { step }), ...(pr && { pr }), ...(branch && { branch }),\n ...(startedAt && { startedAt }), ...(updatedAt && { updatedAt }),\n ...(items.length && { items }), ...(links.length && { links }),\n ...(tags.length && { tags }), ...(parent && { parent }),\n };\n }\n if (raw.kind === \"routine\") {\n const name = cardLine(raw.name, STATUS_CARD_LIMITS.title), schedule = cardLine(raw.schedule, STATUS_CARD_LIMITS.schedule), state = oneOf(ROUTINE_STATES, raw.state);\n if (!name || !schedule || !state) return undefined;\n const cron = typeof raw.cron === \"string\" && CRON_LINE.test(raw.cron.trim()) ? raw.cron.trim() : undefined;\n const lastRun = readRun(raw.lastRun, now);\n const nextRunAt = typeof raw.nextRunAt === \"number\" && Number.isSafeInteger(raw.nextRunAt) && raw.nextRunAt > 0 && raw.nextRunAt <= now + STATUS_CARD_LIMITS.nextRunMs ? raw.nextRunAt : undefined;\n const runs: RoutineRun[] = [];\n if (Array.isArray(raw.runs)) for (const entry of raw.runs.slice(0, STATUS_CARD_LIMITS.runs)) {\n const run = readRun(entry, now);\n if (run) runs.push(run);\n }\n return {\n kind: \"routine\", id, name, schedule, state,\n ...(cron && { cron }), ...(lastRun && { lastRun }), ...(nextRunAt && { nextRunAt }),\n ...(runs.length && { runs }), ...(links.length && { links }),\n };\n }\n if (raw.kind === \"buttons\") {\n if (!Array.isArray(raw.buttons)) return undefined;\n const buttons: CardButton[] = [], seen = new Set<string>();\n for (const entry of raw.buttons.slice(0, STATUS_CARD_LIMITS.buttons)) {\n if (!isObject(entry) || typeof entry.id !== \"string\" || !BUTTON_ID.test(entry.id) || seen.has(entry.id)) continue;\n const label = cardLine(entry.label, STATUS_CARD_LIMITS.buttonLabel);\n if (!label) continue;\n seen.add(entry.id);\n const style = oneOf(BUTTON_STYLES, entry.style);\n buttons.push({ id: entry.id, label, ...(style && style !== \"neutral\" && { style }), ...(entry.once === true && { once: true as const }) });\n }\n if (!buttons.length) return undefined;\n const chosen = typeof raw.chosen === \"string\" && seen.has(raw.chosen) ? raw.chosen : undefined;\n return { kind: \"buttons\", id, buttons, ...(chosen && { chosen }), ...(raw.closed === true && { closed: true as const }) };\n }\n return undefined;\n}\n\n/**\n * A card as a sender may send it, or why not: the reader's rule, but anything it would leave out or cut is refused\n * here instead (an unknown status, a link that is not https, a list past its bound, a line too long), so a bot learns\n * at once and nothing it said is lost on the way. Line breaks and invisible characters are cleaned, as a reader would.\n */\nexport function checkStatusCard(raw: unknown, now = Date.now()): { card: StatusCard } | { error: string } {\n if (!isObject(raw)) return { error: \"A card is an object\" };\n const bytes = statusCardBytes(raw);\n if (bytes > STATUS_CARD_LIMITS.bytes) return { error: `The card takes ${bytes} bytes; at most ${STATUS_CARD_LIMITS.bytes}` };\n if (raw.kind !== \"task\" && raw.kind !== \"routine\" && raw.kind !== \"buttons\" && raw.kind !== \"app\" && raw.kind !== \"usage\" && raw.kind !== \"removed\") return { error: \"kind is task, routine, buttons, app, usage or removed\" };\n if (typeof raw.id !== \"string\" || !ID.test(raw.id)) return { error: `id is 1 to ${STATUS_CARD_LIMITS.id} of A-Z a-z 0-9 _ . : - and does not start with -` };\n const line = (field: string, value: unknown, max: number, required = false): string | null => {\n if (value === undefined && !required) return null;\n if (typeof value !== \"string\" || !cardLine(value, Infinity)) return `${field} is text`;\n if ([...cardLine(value, Infinity)!].length > max) return `${field} is at most ${max} characters`;\n return null;\n };\n const url = (field: string, value: unknown) => (cardUrl(value) ? null : `${field} must be an https link of at most ${STATUS_CARD_LIMITS.url} characters`);\n const whole = (field: string, value: unknown, min = 0) => (value === undefined || count(value, min) !== undefined ? null : `${field} is a whole number from ${min}`);\n const errors: (string | null)[] = [];\n if (raw.links !== undefined) {\n if (!Array.isArray(raw.links) || raw.links.length > STATUS_CARD_LIMITS.links) errors.push(`links is a list of at most ${STATUS_CARD_LIMITS.links}`);\n else for (const [i, link] of raw.links.entries()) {\n if (!isObject(link)) { errors.push(`links[${i}] is an object`); continue; }\n errors.push(url(`links[${i}].url`, link.url), line(`links[${i}].label`, link.label, STATUS_CARD_LIMITS.linkLabel));\n }\n }\n const share = (field: string, value: unknown) => (value === undefined || (typeof value === \"number\" && Number.isFinite(value) && value >= 0 && value <= 100) ? null : `${field} is a number from 0 to 100`);\n const reset = (field: string, value: unknown) => (value === undefined || ahead(value, now) !== undefined ? null : `${field} is a time in milliseconds, within a year`);\n if (raw.kind === \"removed\") {\n // The id and what it was, nothing more: a reader keeps nothing else of it.\n if (!oneOf(REMOVABLE_KINDS, raw.of)) errors.push(`of is one of ${REMOVABLE_KINDS.join(\", \")}`);\n const extra = Object.keys(raw).find(key => key !== \"kind\" && key !== \"id\" && key !== \"of\");\n if (extra) errors.push(`a removed card takes only kind, id and of, not ${extra}`);\n } else if (raw.kind === \"usage\") {\n if (raw.links !== undefined) errors.push(\"a usage card takes no links\");\n if (raw.left === undefined && raw.used === undefined) errors.push(\"left (a percent) or used and limit\");\n errors.push(share(\"left\", raw.left));\n if ((raw.used === undefined) !== (raw.limit === undefined)) errors.push(\"used and limit go together\");\n else if (raw.used !== undefined) {\n errors.push(whole(\"used\", raw.used), whole(\"limit\", raw.limit, 1));\n if (typeof raw.used === \"number\" && typeof raw.limit === \"number\" && raw.used > raw.limit) errors.push(\"used is at most limit\");\n }\n errors.push(line(\"label\", raw.label, STATUS_CARD_LIMITS.usageLabel), line(\"account\", raw.account, STATUS_CARD_LIMITS.usageLabel), line(\"window\", raw.window, STATUS_CARD_LIMITS.usageWindow), reset(\"resetsAt\", raw.resetsAt));\n if (raw.updatedAt !== undefined && !(typeof raw.updatedAt === \"number\" && Number.isSafeInteger(raw.updatedAt) && raw.updatedAt > 0 && raw.updatedAt <= now + MESSAGE_CLOCK_SKEW_MS)) errors.push(\"updatedAt is a time in milliseconds, not in the future\");\n if (raw.windows !== undefined) {\n if (!Array.isArray(raw.windows) || raw.windows.length > STATUS_CARD_LIMITS.usageWindows) errors.push(`windows is a list of at most ${STATUS_CARD_LIMITS.usageWindows}`);\n else for (const [i, entry] of raw.windows.entries()) {\n if (!isObject(entry)) { errors.push(`windows[${i}] is an object`); continue; }\n errors.push(line(`windows[${i}].window`, entry.window, STATUS_CARD_LIMITS.usageWindow, true));\n errors.push(entry.left === undefined ? `windows[${i}].left is a number from 0 to 100` : share(`windows[${i}].left`, entry.left), reset(`windows[${i}].resetsAt`, entry.resetsAt));\n }\n }\n } else if (raw.kind === \"app\") {\n if (raw.links !== undefined) errors.push(\"an app card takes no links\");\n if (!isAppRef(raw.ref)) errors.push(\"ref is <publisher key in z-base32>/<name>\");\n else if (raw.id !== appCardId(raw.ref)) errors.push(`id is ${appCardId(raw.ref)}, made from ref`);\n if (!isAppHash(raw.digest)) errors.push(\"digest is a SHA-256 in base64url without padding\");\n if (!appSequence(raw.sequence)) errors.push(\"sequence is a whole number from 0 to 2^53 - 1\");\n errors.push(line(\"title\", raw.title, STATUS_CARD_LIMITS.appTitle, true), line(\"version\", raw.version, STATUS_CARD_LIMITS.appVersion));\n if (raw.url !== undefined) errors.push(url(\"url\", raw.url));\n if (raw.opened !== undefined && raw.opened !== true) errors.push(\"opened is true or left out\");\n } else if (raw.kind === \"buttons\") {\n if (raw.links !== undefined) errors.push(\"buttons take no links\");\n if (!Array.isArray(raw.buttons) || !raw.buttons.length || raw.buttons.length > STATUS_CARD_LIMITS.buttons) errors.push(`buttons is a list of 1 to ${STATUS_CARD_LIMITS.buttons}`);\n else {\n const ids = new Set<string>();\n for (const [i, button] of raw.buttons.entries()) {\n if (!isObject(button)) { errors.push(`buttons[${i}] is an object`); continue; }\n if (typeof button.id !== \"string\" || !BUTTON_ID.test(button.id)) errors.push(`buttons[${i}].id is 1 to ${STATUS_CARD_LIMITS.buttonId} of A-Z a-z 0-9 _ . : - and does not start with -`);\n else if (ids.has(button.id)) errors.push(`buttons[${i}].id \"${button.id}\" is used twice`);\n else ids.add(button.id);\n errors.push(line(`buttons[${i}].label`, button.label, STATUS_CARD_LIMITS.buttonLabel, true));\n if (button.style !== undefined && !oneOf(BUTTON_STYLES, button.style)) errors.push(`buttons[${i}].style is one of ${BUTTON_STYLES.join(\", \")}`);\n if (button.once !== undefined && button.once !== true) errors.push(`buttons[${i}].once is true or left out`);\n }\n // A typed answer is matched by label or id: two buttons it could not tell apart are refused (a reader takes the first).\n const clash = buttonLabelClash(raw.buttons);\n if (clash) errors.push(`buttons[${clash.at}].label ${JSON.stringify(cardLine((raw.buttons[clash.at] as Record<string, unknown>).label, Infinity))} ${clash.kind === \"label\" ? `repeats buttons[${clash.with}].label` : `is buttons[${clash.with}].id`} (ignoring case and spaces at the ends)`);\n if (raw.chosen !== undefined && !(typeof raw.chosen === \"string\" && ids.has(raw.chosen))) errors.push(\"chosen names one of the buttons\");\n }\n if (raw.closed !== undefined && raw.closed !== true) errors.push(\"closed is true or left out\");\n } else if (raw.kind === \"task\") {\n errors.push(line(\"title\", raw.title, STATUS_CARD_LIMITS.title, true));\n if (!oneOf(TASK_STATUSES, raw.status)) errors.push(`status is one of ${TASK_STATUSES.join(\", \")}`);\n if (raw.progress !== undefined && !(typeof raw.progress === \"number\" && Number.isFinite(raw.progress) && raw.progress >= 0 && raw.progress <= 100)) errors.push(\"progress is a number from 0 to 100\");\n if ((raw.done === undefined) !== (raw.total === undefined)) errors.push(\"done and total go together\");\n else if (raw.done !== undefined) {\n errors.push(whole(\"done\", raw.done), whole(\"total\", raw.total, 1));\n if (typeof raw.done === \"number\" && typeof raw.total === \"number\" && raw.done > raw.total) errors.push(\"done is at most total\");\n }\n errors.push(line(\"step\", raw.step, STATUS_CARD_LIMITS.line), line(\"branch\", raw.branch, STATUS_CARD_LIMITS.branch));\n if (raw.pr !== undefined) {\n if (!isObject(raw.pr)) errors.push(\"pr is an object\");\n else {\n errors.push(url(\"pr.url\", raw.pr.url), whole(\"pr.number\", raw.pr.number, 1), whole(\"pr.additions\", raw.pr.additions), whole(\"pr.deletions\", raw.pr.deletions), whole(\"pr.files\", raw.pr.files));\n if (raw.pr.state !== undefined && !oneOf(PR_STATES, raw.pr.state)) errors.push(`pr.state is one of ${PR_STATES.join(\", \")}`);\n if (raw.pr.checks !== undefined && !oneOf(PR_CHECKS, raw.pr.checks)) errors.push(`pr.checks is one of ${PR_CHECKS.join(\", \")}`);\n }\n }\n if (raw.tags !== undefined) {\n if (!Array.isArray(raw.tags) || raw.tags.length > STATUS_CARD_LIMITS.tags) errors.push(`tags is a list of at most ${STATUS_CARD_LIMITS.tags}`);\n else {\n const seen = new Set<string>();\n for (const [i, tag] of raw.tags.entries()) {\n const problem = line(`tags[${i}]`, tag, STATUS_CARD_LIMITS.tag, true);\n errors.push(problem);\n if (problem) continue;\n const clean = cardLine(tag, Infinity)!;\n if (seen.has(clean)) errors.push(`tags[${i}] ${JSON.stringify(clean)} is there twice`);\n seen.add(clean);\n }\n }\n }\n if (raw.parent !== undefined) {\n if (typeof raw.parent !== \"string\" || !ID.test(raw.parent)) errors.push(`parent is another task's id: 1 to ${STATUS_CARD_LIMITS.id} of A-Z a-z 0-9 _ . : - and does not start with -`);\n else if (raw.parent === raw.id) errors.push(\"parent is another task's id, not its own\");\n }\n for (const field of [\"startedAt\", \"updatedAt\"] as const) {\n const value = raw[field];\n if (value !== undefined && !(typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 && value <= now + MESSAGE_CLOCK_SKEW_MS)) errors.push(`${field} is a time in milliseconds, not in the future`);\n }\n if (raw.items !== undefined) {\n if (!Array.isArray(raw.items) || raw.items.length > STATUS_CARD_LIMITS.items) errors.push(`items is a list of at most ${STATUS_CARD_LIMITS.items}`);\n else for (const [i, item] of raw.items.entries()) {\n if (!isObject(item)) { errors.push(`items[${i}] is an object`); continue; }\n errors.push(line(`items[${i}].text`, item.text, STATUS_CARD_LIMITS.line, true));\n if (item.state !== undefined && !oneOf(ITEM_STATES, item.state)) errors.push(`items[${i}].state is one of ${ITEM_STATES.join(\", \")}`);\n }\n }\n } else {\n errors.push(line(\"name\", raw.name, STATUS_CARD_LIMITS.title, true), line(\"schedule\", raw.schedule, STATUS_CARD_LIMITS.schedule, true));\n if (!oneOf(ROUTINE_STATES, raw.state)) errors.push(`state is one of ${ROUTINE_STATES.join(\", \")}`);\n if (raw.cron !== undefined && !(typeof raw.cron === \"string\" && CRON_LINE.test(raw.cron.trim()))) errors.push(`cron is a cron line of at most ${STATUS_CARD_LIMITS.cron} characters`);\n if (raw.nextRunAt !== undefined && !(typeof raw.nextRunAt === \"number\" && Number.isSafeInteger(raw.nextRunAt) && raw.nextRunAt > 0 && raw.nextRunAt <= now + STATUS_CARD_LIMITS.nextRunMs)) errors.push(\"nextRunAt is a time in milliseconds, within a year\");\n const run = (field: string, value: unknown) => {\n if (!isObject(value)) return errors.push(`${field} is an object`);\n if (!(typeof value.at === \"number\" && Number.isSafeInteger(value.at) && value.at > 0 && value.at <= now + MESSAGE_CLOCK_SKEW_MS)) errors.push(`${field}.at is a time in milliseconds, not in the future`);\n if (!oneOf(RUN_RESULTS, value.result)) errors.push(`${field}.result is one of ${RUN_RESULTS.join(\", \")}`);\n errors.push(line(`${field}.summary`, value.summary, STATUS_CARD_LIMITS.line));\n };\n if (raw.lastRun !== undefined) run(\"lastRun\", raw.lastRun);\n if (raw.runs !== undefined) {\n if (!Array.isArray(raw.runs) || raw.runs.length > STATUS_CARD_LIMITS.runs) errors.push(`runs is a list of at most ${STATUS_CARD_LIMITS.runs}`);\n else raw.runs.forEach((entry, i) => run(`runs[${i}]`, entry));\n }\n }\n const error = errors.find((e): e is string => typeof e === \"string\");\n if (error) return { error };\n const card = readStatusCard(raw, now);\n return card ? { card } : { error: \"The card does not hold\" };\n}\n\n/** The progress a task shows, 0 to 100: its own, else its steps done of total; undefined when it says neither. */\nexport function taskProgress(card: Pick<TaskCard, \"progress\" | \"done\" | \"total\">): number | undefined {\n if (card.progress !== undefined) return card.progress;\n return card.done !== undefined && card.total ? Math.round(card.done / card.total * 100) : undefined;\n}\n\nconst TASK_MARK: Record<TaskStatus, string> = { queued: \"⏳\", running: \"🔄\", blocked: \"⛔\", done: \"✅\", failed: \"❌\", cancelled: \"🚫\" };\nconst STATUS_WORD: Record<TaskStatus, string> = { queued: \"Queued\", running: \"Running\", blocked: \"Blocked\", done: \"Done\", failed: \"Failed\", cancelled: \"Cancelled\" };\nconst RESULT_WORD: Record<RunResult, string> = { ok: \"ok\", failed: \"failed\", skipped: \"skipped\" };\n\n/** A time as the fallback text says it: in UTC, to the minute (\"2026-09-30 01:00 UTC\"). */\nexport function cardTimeUtc(ms: number): string {\n return `${new Date(ms).toISOString().slice(0, 16).replace(\"T\", \" \")} UTC`;\n}\n\n/**\n * The text a removed card's message carries (WISP 405 § Removing a card): \"🗑 Task removed\", with the card's title or\n * name when the sender knows it (\"🗑 Task removed: Fix relay rotation\"). An app without the `removed` kind shows it.\n */\nexport function removedCardText(of: RemovableKind, title?: string): string {\n return `🗑 ${of === \"task\" ? \"Task\" : \"Routine\"} removed${title ? `: ${title}` : \"\"}`;\n}\n\n/**\n * A message's text without the line that is its app card's link (`statusCardText` puts it on a line of its own for an\n * older app): what a line quoting the message says where the card is not drawn, never the bundle's raw link. Any other\n * message's text as it is.\n */\nexport function withoutAppLink(text: string, card: StatusCard | undefined): string {\n const url = card?.kind === \"app\" ? card.url : undefined;\n return url ? text.split(\"\\n\").filter(line => line.trim() !== url).join(\"\\n\") : text;\n}\n\n/**\n * The text a card's message carries: what an app without cards shows, the DHT floor carries, the chat list previews\n * and search finds. Plain lines, the first naming the card, no bars or layout that would read badly elsewhere.\n */\nexport function statusCardText(card: StatusCard): string {\n // A sender that knows the title says it (\"🗑 Task removed: Fix relay rotation\"); this is the text without one.\n if (card.kind === \"removed\") return removedCardText(card.of);\n // An app card names the app, and its url on a line of its own so an older app shows a link (WISP 405 § An app).\n if (card.kind === \"app\") {\n const named = `${card.title}${card.version ? ` ${card.version}` : \"\"}`, url = appCardUrl(card.url);\n return [card.opened ? `🧩 Opened ${named} in this chat (Ghostly app)` : `🧩 ${named} (Ghostly app)`, ...(url ? [url] : [])].join(\"\\n\");\n }\n // One line: what an older app shows, and the chat list's line (WISP 405 § Usage).\n if (card.kind === \"usage\") {\n const left = `${usageLeft(card)}% left${card.window ? ` (${card.window})` : \"\"}`;\n return [`📊 ${card.label ?? \"Usage\"}`, ...(card.account ? [card.account] : []), left,\n ...(card.used !== undefined && card.limit !== undefined ? [`${card.used} of ${card.limit} used`] : []),\n ...(card.resetsAt ? [`resets ${cardTimeUtc(card.resetsAt)}`] : []),\n ...(card.windows ?? []).map((w) => `${w.window} ${w.left}%`)].join(\" · \");\n }\n // Buttons show with the bot's own text; this is only what goes when it gave none.\n if (card.kind === \"buttons\") return `Reply: ${card.buttons.map(b => b.label).join(\" / \")}`;\n if (card.kind === \"task\") {\n const progress = taskProgress(card);\n const state = [STATUS_WORD[card.status], ...(progress !== undefined ? [`${progress}%`] : []), ...(card.done !== undefined && card.total ? [`${card.done} of ${card.total} steps`] : [])].join(\" · \");\n // \"PR #612 +123 -45 (open, checks passing): https://…\": the state and the checks only when the card says them.\n const standing = card.pr && [...(card.pr.state ? [card.pr.state] : []), ...(card.pr.checks ? [`checks ${card.pr.checks}`] : [])].join(\", \");\n const pr = card.pr && [`PR${card.pr.number !== undefined ? ` #${card.pr.number}` : \"\"}`,\n ...(card.pr.additions !== undefined || card.pr.deletions !== undefined ? [`+${card.pr.additions ?? 0} -${card.pr.deletions ?? 0}`] : []),\n ...(standing ? [`(${standing})`] : [])].join(\" \") + `: ${card.pr.url}`;\n // \"Now:\" only while the task is going: a finished one's last step is not what it does now (the card hides it too).\n const now = card.step && ACTIVE_TASK_STATUSES.includes(card.status) ? [`Now: ${card.step}`] : [];\n return [`${TASK_MARK[card.status]} ${card.title}`, state, ...now, ...(pr ? [pr] : []),\n ...(card.tags?.length ? [`Tags: ${card.tags.join(\", \")}`] : []), ...(card.parent ? [`Part of: ${card.parent}`] : [])].join(\"\\n\");\n }\n const last = card.lastRun && `Last run: ${RESULT_WORD[card.lastRun.result]}, ${cardTimeUtc(card.lastRun.at)}${card.lastRun.summary ? ` · ${card.lastRun.summary}` : \"\"}`;\n return [`🔁 ${card.name}`, `${card.schedule} · ${card.state === \"active\" ? \"active\" : \"paused\"}`, ...(last ? [last] : []),\n ...(card.nextRunAt && card.state === \"active\" ? [`Next run: ${cardTimeUtc(card.nextRunAt)}`] : [])].join(\"\\n\");\n}\n\n/** Whether a message's edit number holds: a text's bound, or a card message's when the edit carries a card. */\nexport function cardEditNumber(e: unknown): e is number {\n return Number.isSafeInteger(e) && (e as number) >= 1 && (e as number) <= STATUS_CARD_LIMITS.edits;\n}\n","import { MEMBER_KEY } from \"./groupCommits\";\nimport { BUTTON_ID } from \"./statusCards\";\nimport { sanitizeDisplayText } from \"./text\";\n\n/*\n * A reply to a message (WISP 400 § Replies): which earlier message of the same chat a new one answers, with a short\n * line of it and who wrote it, so the reply still reads when the receiver no longer has the original (deleted here,\n * or never received). The receiver shows the line only as the replier's app saw it; the original it finds in its own\n * history, by id, is what it trusts. An app without replies ignores the field and shows the text alone.\n */\n\n/**\n * On the wire (`r`): `i` the original's id in this chat, `s` a line of it, `f` who wrote it. In a paired chat `f` is\n * `\"sender\"` (the reply's author wrote the original) or `\"recipient\"` (the reader did); in a group, a member key.\n * `b`: a button press (WISP 406 · Message Buttons), the id of the original's button this reply presses; its text is\n * the button's label. An app from before buttons drops `b` and shows an ordinary reply.\n */\nexport interface WireReply { i: string; s: string; f: string; b?: string }\n\nexport const REPLY_LIMITS = {\n /** Code points of the line of the original, an ellipsis included when it was cut. */\n snippet: 120,\n /** Characters of the original's id. */\n id: 128,\n /** Characters of a line as it arrives, before it is cleaned: anything longer is not a line of a message. */\n raw: 2048,\n} as const;\n\n/** A paired chat's message id, a payment id or a file's wire id; a group message's `sender:epoch:seq`. */\nexport const REPLY_ID = /^[A-Za-z0-9_:.-]{1,128}$/;\n/** The two authors a paired chat has, from the reply author's side. */\nexport const PAIRED_REPLY_AUTHORS = [\"sender\", \"recipient\"] as const;\n\n/** A picture sent inline has no line worth quoting. */\nconst INLINE_PICTURE = /^data:image\\//i;\n\n/** What a spoiler reads as in a line of it: nothing of what it hides (the chat list's `SPOILER_PLAIN` in apps/ui). */\nconst SPOILER_COVER = \"▒▒▒\";\n\nconst PIPES = /\\|{2,}/gu;\nconst SPACE = /\\s/u;\nconst PUNCT = /[\\p{P}\\p{S}]/u;\n\n/**\n * A line of text with its spoilers (`||hidden||`, WISP 400 § Formatting) as `SPOILER_COVER`. The bubble's parser\n * (apps/ui lib/parse) is not here, so this covers at least what it hides: from the first `||` on the line that may\n * open one to the last that may close one, by the parser's word-edge rules without its exceptions. Two spoilers on a\n * line read as one, with the words between them. `open`: the line goes on past this text, so a spoiler opened on it\n * runs to its end.\n */\nfunction coverSpoilers(line: string, open: boolean): string {\n let start = -1, end = -1;\n for (const run of line.matchAll(PIPES)) {\n const at = run.index, after = line[at + run[0].length], before = line[at - 1];\n // A run of three or more is text to the parser, unless one end of it is a code span's or a link's.\n const long = run[0].length > 2;\n if (start < 0) {\n if (long || (after !== undefined && !SPACE.test(after) && (before === undefined || SPACE.test(before) || PUNCT.test(before)))) start = at;\n } else if (long || (before !== undefined && !SPACE.test(before) && (after === undefined || SPACE.test(after) || PUNCT.test(after)))) {\n end = at + run[0].length;\n }\n }\n if (start < 0) return line;\n if (open) return line.slice(0, start) + SPOILER_COVER;\n return end < 0 ? line : line.slice(0, start) + SPOILER_COVER + line.slice(end);\n}\n\n/**\n * A line of a message to quote: plain text on one line (line breaks and runs of spaces become one space), its\n * spoilers covered, without control, invisible or direction characters (WISP 400, as for names), at most\n * `REPLY_LIMITS.snippet` code points, the last of them an ellipsis when it was cut.\n */\nexport function replySnippet(text: string): string {\n if (INLINE_PICTURE.test(text.trimStart())) return \"🖼️ Picture\";\n const head = text.slice(0, REPLY_LIMITS.raw * 2);\n // Spoilers pair within a line, so each is covered before the lines are joined.\n const lines = head.split(\"\\n\");\n const covered = lines.map((line, i) => coverSpoilers(line, head.length < text.length && i === lines.length - 1)).join(\"\\n\");\n const flat = covered.replace(/\\s+/gu, \" \");\n const clean = sanitizeDisplayText(flat, REPLY_LIMITS.snippet + 1) ?? \"\";\n const points = [...clean];\n return points.length > REPLY_LIMITS.snippet ? `${points.slice(0, REPLY_LIMITS.snippet - 1).join(\"\").trimEnd()}…` : clean;\n}\n\n/**\n * A reply as a receiver takes it: an object with an id of this chat's shape, a line (cleaned and cut again here,\n * whatever the sender did) and an author `author` accepts. Anything else is no reply: the message stays, without it.\n */\nexport function readReply(raw: unknown, author: (f: string) => boolean): WireReply | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const { i, s, f, b } = raw as Record<string, unknown>;\n if (typeof i !== \"string\" || !REPLY_ID.test(i)) return undefined;\n if (typeof s !== \"string\" || s.length > REPLY_LIMITS.raw) return undefined;\n if (typeof f !== \"string\" || !author(f)) return undefined;\n // A press that does not hold is only a reply.\n return { i, s: replySnippet(s), f, ...(typeof b === \"string\" && BUTTON_ID.test(b) && { b }) };\n}\n\n/** Who may have written the original in a paired chat. */\nexport const pairedReplyAuthor = (f: string): boolean => (PAIRED_REPLY_AUTHORS as readonly string[]).includes(f);\n/** Who may have written the original in a group: a member key (whether they are still a member is the reader's to see). */\nexport const groupReplyAuthor = (f: string): boolean => MEMBER_KEY.test(f);\n\n/** Only the wire fields, in a fixed order, the line cleaned: what the sender puts on a frame. */\nexport const wireReply = (reply: WireReply): WireReply => ({ i: reply.i, s: replySnippet(reply.s), f: reply.f, ...(reply.b && { b: reply.b }) });\n","import { utf8Encode } from \"./bytes\";\nimport { REPLY_ID } from \"./replies\";\n\n/**\n * Reactions to messages (WISP 400 § Reactions): one emoji per person per message, like WhatsApp. Whoever reacts says\n * which message (the id both sides know it by, as a reply names it), the emoji, and a number of its own that only\n * grows; an empty emoji takes the reaction back. For each person and message the highest number wins, whatever order\n * the frames arrive in, so a new reaction replaces the old one and a late frame changes nothing.\n *\n * A 1:1 chat says it on the live session once both sides list `react/1` in `paired-capabilities`, and the contact\n * confirms each number it took:\n *\n * {\"t\":\"paired-reaction\",\"id\":\"<message id>\",\"e\":\"❤️\",\"n\":1790000000000}\n * {\"t\":\"paired-reacted\",\"n\":1790000000000}\n *\n * Off the live session they ride on the DHT envelopes (WISP 403 § Reactions). Groups carry them in their own frames\n * (WISP 902 § Reactions). Older apps drop all of these: a `t` they do not know, or a trailing element they skip.\n */\n\nexport const REACTION_FRAME = \"paired-reaction\";\nexport const REACTED_FRAME = \"paired-reacted\";\n/** A reaction in a private group, over the edge from the member who reacts (WISP 902 group mesh § Reactions). */\nexport const GROUP_REACTION_FRAME = \"group-react\";\n/** A reaction in a community, as an application frame sealed to the group (WISP 903 group community § Reactions). */\nexport const COMMUNITY_REACTION_FRAME = \"reaction\";\n\n/** The quick bar, in order: what most reactions are. Any other emoji comes from the picker. */\nexport const QUICK_REACTIONS = [\"👍\", \"❤️\", \"😂\", \"😮\", \"😢\", \"🙏\"] as const;\n\nexport const REACTION_LIMITS = {\n /** UTF-8 bytes of one emoji: a family or a subdivision flag fits, a run of emoji does not. */\n emojiBytes: 32,\n /**\n * Reaction frames a receiver takes per window on one chat; the rest are dropped unconfirmed and come again. In a\n * group nothing comes again (a community's catch-up hands a frame once), so there the rest wait for the next window.\n */\n receive: 30,\n /** Group members' reactions past a window, kept per group until it has room: as many as a community's store hands back. */\n held: 256,\n /** Reactions a sender says per window on one chat; the newest of each message waits for room. */\n send: 20,\n windowMs: 10_000,\n /**\n * A reaction to a message not here yet waits this long for it, at most `buffer` of them per sender in each chat: a\n * member back in a busy group hears every member's latest reactions as their edges open, before the catch-up (over a\n * minute for a full log) brings what they name.\n */\n bufferMs: 300_000,\n buffer: 64,\n /** Reactions of this side not confirmed yet, per chat: the oldest is dropped past it. */\n pending: 32,\n /** Reactions one DHT envelope carries at most, room allowing. */\n dht: 8,\n} as const;\n\n/** One reaction as it goes on the wire: the message's id, the emoji (\"\" takes it back) and the reactor's number. */\nexport interface WireReaction { id: string; e: string; n: number }\n\nconst PICTOGRAPH = /\\p{Extended_Pictographic}|\\p{Regional_Indicator}{2}|\\u20E3/u;\n/** Emoji_Component holds the joiner, the selector, the keycap, skin tones, tags and regional indicators. */\nconst EMOJI_POINT = /^[\\p{Emoji}\\p{Emoji_Component}]$/u;\nconst PRESENTATION = /^\\p{Emoji_Presentation}$/u;\n\ntype Segmenter = { segment(input: string): Iterable<{ segment: string }> };\nlet segmenter: Segmenter | null | undefined;\nfunction graphemes(text: string): string[] {\n if (segmenter === undefined) {\n const Ctor = (globalThis as { Intl?: { Segmenter?: new (locale?: string, options?: { granularity: string }) => Segmenter } }).Intl?.Segmenter;\n segmenter = Ctor ? new Ctor(undefined, { granularity: \"grapheme\" }) : null;\n }\n if (segmenter) return Array.from(segmenter.segment(text), s => s.segment);\n // Without a segmenter (none of the apps' runtimes): a sequence joined by ZWJ, modifiers or tags counts as one.\n return text ? [text] : [];\n}\n\n/**\n * The emoji a reaction may carry, in one form (so the same emoji from two apps is one chip), or null when it is not\n * one: exactly one grapheme, made of emoji code points only, with a pictograph in it, at most\n * `REACTION_LIMITS.emojiBytes`. A single pictograph drawn as text by default gets the emoji selector (❤ → ❤️); one\n * drawn as emoji by default loses a redundant one (👍️ → 👍). Sequences keep their selectors as sent.\n */\nexport function reactionEmoji(raw: unknown): string | null {\n if (typeof raw !== \"string\" || !raw || raw.length > REACTION_LIMITS.emojiBytes) return null;\n let emoji = raw.normalize(\"NFC\");\n const points = [...emoji.replace(/\\uFE0F/g, \"\")];\n if (points.length === 1) emoji = PRESENTATION.test(points[0]) ? points[0] : `${points[0]}\\uFE0F`;\n if (utf8Encode(emoji).length > REACTION_LIMITS.emojiBytes) return null;\n if (![...emoji].every(point => EMOJI_POINT.test(point)) || !PICTOGRAPH.test(emoji)) return null;\n return graphemes(emoji).length === 1 ? emoji : null;\n}\n\n/** A reactor's number: valid on the wire (a positive safe integer). */\nexport function validReactionNumber(n: unknown): n is number {\n return typeof n === \"number\" && Number.isSafeInteger(n) && n > 0;\n}\n\n/**\n * The number for this side's next reaction in a chat: the clock in milliseconds, or one past the last, whichever is\n * higher. It only grows, even when the clock goes back.\n */\nexport function nextReactionNumber(last = 0, now = Date.now()): number {\n return Math.max(Math.floor(now), last + 1);\n}\n\n/** Whether a reaction numbered `n` replaces what a person's reaction to that message is now. */\nexport function reactionIsNewer(current: { n: number } | undefined, n: number): boolean {\n return !current || n > current.n;\n}\n\n/**\n * A reaction as a receiver takes it, or null: a message id of a chat's shape (as a reply names it), an emoji that\n * holds or \"\" (taken back), and a valid number. Anything else says nothing and is not confirmed.\n */\nexport function readReaction(raw: unknown): WireReaction | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const { id, e, n } = raw as Record<string, unknown>;\n if (typeof id !== \"string\" || !REPLY_ID.test(id) || !validReactionNumber(n)) return null;\n if (e === \"\") return { id, e: \"\", n };\n const emoji = reactionEmoji(e);\n return emoji ? { id, e: emoji, n } : null;\n}\n\n/** Only the wire fields, in a fixed order. */\nexport const wireReaction = (r: WireReaction): WireReaction => ({ id: r.id, e: r.e, n: r.n });\n\nexport function reactionFrame(r: WireReaction): string {\n return JSON.stringify({ t: REACTION_FRAME, ...wireReaction(r) });\n}\n\nexport function reactedFrame(n: number): string {\n return JSON.stringify({ t: REACTED_FRAME, n });\n}\n\n/** The reaction a `paired-reaction` frame says, or null when it is malformed. */\nexport function parseReactionFrame(frame: Record<string, unknown>): WireReaction | null {\n return frame?.t === REACTION_FRAME ? readReaction(frame) : null;\n}\n\n/** The number a `paired-reacted` frame confirms, or null when it is malformed. */\nexport function parseReactedFrame(frame: Record<string, unknown>): number | null {\n return frame?.t === REACTED_FRAME && validReactionNumber(frame.n) ? frame.n : null;\n}\n\n/**\n * A DHT envelope's reactions (its thirteenth element): `[[id, emoji, n], …]`. What does not hold is skipped, never the\n * envelope; at most `REACTION_LIMITS.dht` are read.\n */\nexport function readDhtReactions(raw: unknown): WireReaction[] {\n if (!Array.isArray(raw)) return [];\n const out: WireReaction[] = [];\n for (const entry of raw.slice(0, REACTION_LIMITS.dht)) {\n if (!Array.isArray(entry) || entry.length !== 3) continue;\n const reaction = readReaction({ id: entry[0], e: entry[1], n: entry[2] });\n if (reaction) out.push(reaction);\n }\n return out;\n}\n\n/**\n * This side's reactions not confirmed yet, after one more: the newest per message (a new one replaces a pending one\n * for the same message), in the order of their numbers, the oldest dropped past `REACTION_LIMITS.pending`.\n */\nexport function queueReaction(pending: readonly WireReaction[], reaction: WireReaction): WireReaction[] {\n return [...pending.filter(p => p.id !== reaction.id), wireReaction(reaction)].sort((a, b) => a.n - b.n).slice(-REACTION_LIMITS.pending);\n}\n\n/** A sliding window of `limit` events per `windowMs`: a sender's pace and a receiver's limit. */\nexport class ReactionWindow {\n private recent: number[] = [];\n\n constructor(private readonly limit: number, private readonly windowMs: number = REACTION_LIMITS.windowMs, private readonly now: () => number = Date.now) {}\n\n /** Counts one now; false (and not counted) when the window is full. */\n take(): boolean {\n const now = this.now();\n this.recent = this.recent.filter(at => now - at < this.windowMs);\n if (this.recent.length >= this.limit) return false;\n this.recent.push(now);\n return true;\n }\n\n /** Milliseconds until the window has room again; 0 when it has room now. */\n wait(): number {\n const now = this.now();\n this.recent = this.recent.filter(at => now - at < this.windowMs);\n return this.recent.length < this.limit ? 0 : this.recent[0] + this.windowMs - now;\n }\n\n reset(): void { this.recent = []; }\n}\n","/*\n * A forwarded message (WISP 400 § Forwards): a text or a file someone sends on from another chat, as a new message of\n * theirs. Only the content goes, never who wrote it first or where it came from; what travels with it is a hop count,\n * how many times it has been forwarded, so the reader can say \"Forwarded\" and, past a few hops, \"Forwarded many times\".\n * An app without forwards ignores the field and shows a message like any other.\n */\n\nexport const FORWARD_LIMITS = {\n /** The count stops here: a message forwarded more often still says it was forwarded many times. */\n max: 255,\n /** From this many hops on, the reader says \"Forwarded many times\". */\n many: 5,\n} as const;\n\n/** A hop count as a receiver takes it: a whole number from 1 to `FORWARD_LIMITS.max`. Anything else is not forwarded. */\nexport function readForwarded(raw: unknown): number | undefined {\n return typeof raw === \"number\" && Number.isSafeInteger(raw) && raw >= 1 && raw <= FORWARD_LIMITS.max ? raw : undefined;\n}\n\n/** The count a message carries once forwarded again: one more hop than it had (none for a message never forwarded). */\nexport function forwardedAgain(hops?: number): number {\n return Math.min(FORWARD_LIMITS.max, (readForwarded(hops) ?? 0) + 1);\n}\n\n/** Whether a message has come far enough to be called \"Forwarded many times\". */\nexport function forwardedMany(hops?: number): boolean {\n return (readForwarded(hops) ?? 0) >= FORWARD_LIMITS.many;\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, utf8Encode } from \"./bytes\";\nimport { LIMITS } from \"./frames\";\nimport { parseLinkPreview, type LinkPreview } from \"./linkPreview\";\nimport { STATUS_CARD_LIMITS, cardEditNumber, readStatusCard, type StatusCard } from \"./statusCards\";\n\n/**\n * Editing a sent text in a 1:1 chat (WISP 401 § Edits). The sender says the whole new text of one of its own\n * messages, with a sequence number of its own per message, and the contact confirms the number it now shows:\n *\n * {\"t\":\"paired-edit\",\"id\":\"<the message's wire id>\",\"e\":3,\"ts\":1790000000000,\"m\":\"Done: 12 of 12\"}\n * {\"t\":\"paired-edited\",\"id\":\"<the message's wire id>\",\"e\":3}\n *\n * It needs `edit/1` in `paired-capabilities` on both sides. Only the contact's own messages can be edited from its\n * side: the frame comes on the session authenticated with the pinned contact, and the receiver looks the id up among\n * that contact's messages only. The highest `e` wins, whatever order frames arrive in; an edit that is not newer is\n * confirmed and changes nothing. A preview (`pv`, WISP 401 § Link previews) may come with the new text, as with a\n * message. A status card (`sc`, WISP 405 · Status Cards) may come with it too; a card message takes up to\n * `STATUS_CARD_LIMITS.edits` edits, a number past `MAX_EDITS_PER_MESSAGE` holding only with a card. Older apps drop\n * both frames: they have an id, but a `t` they do not know.\n *\n * A removal (WISP 400 § Delete for everyone) is the message's last edit, flagged `rm`, with a fallback text and\n * nothing else beside it; an app from before removals shows that text as the edit:\n *\n * {\"t\":\"paired-edit\",\"id\":\"<the message's wire id>\",\"e\":4,\"ts\":1790000000000,\"m\":\"🗑 Message removed\",\"rm\":true}\n */\n\nexport const EDIT_FRAME = \"paired-edit\";\nexport const EDITED_FRAME = \"paired-edited\";\n\n/** Edits one message takes; the sender refuses the next one and the receiver ignores a higher number. */\nexport const MAX_EDITS_PER_MESSAGE = 100;\n\n/** A removal is numbered one past the message's last edit, so it may pass a card message's bound by one. */\nexport const MAX_REMOVAL_NUMBER = STATUS_CARD_LIMITS.edits + 1;\n\n/** The text a removal carries: only what an app from before removals shows in the message's place. */\nexport const REMOVED_TEXT = \"🗑 Message removed\";\n\n/** A sender says at most this many edits per `EDIT_RATE_WINDOW_MS` in one chat; the newest text of each message waits. */\nexport const EDIT_SEND_LIMIT = 10;\n/** A receiver takes at most this many edit frames per window; the rest are dropped unconfirmed, so they come again. */\nexport const EDIT_RECEIVE_LIMIT = 30;\nexport const EDIT_RATE_WINDOW_MS = 10_000;\n\n/** An edit of a message not here yet waits this long for it, at most `EDIT_BUFFER_MAX` of them per chat. */\nexport const EDIT_BUFFER_MS = 60_000;\nexport const EDIT_BUFFER_MAX = 32;\n\nconst ID = /^[A-Za-z0-9_-]{22}$/;\n/** A removal may name a file too (WISP 401 § Edits): its offer's id, as a file's id holds (`files.ts`). */\nconst REMOVAL_ID = /^[A-Za-z0-9_-]{8,64}$/;\n\n/** One edit as it goes on the wire. */\nexport interface WireEdit {\n /** The edited message's wire id. */\n id: string;\n /** Its edit number, 1 for the first edit. */\n e: number;\n /** When the sender made the edit (milliseconds). */\n ts: number;\n /** The whole new text. */\n m: string;\n pv?: LinkPreview;\n /** The status card of this version (WISP 405 · Status Cards): a message with a card takes an edit with one. */\n sc?: StatusCard;\n /** The author deleted the message for everyone (WISP 400 § Delete for everyone): `m` is only a fallback. */\n rm?: true;\n}\n\n/** Largest edit frame sent with a preview: the preview is left out past it, as with a message. */\nconst MAX_EDIT_FRAME = 56 * 1024;\n\n/**\n * A `paired-edit` frame; the preview is left out when the frame would be too large with it. A card (`sc`) always\n * goes: it is bounded well under what the frame has room for, and it is what a card message is.\n */\nexport function editFrame(edit: WireEdit): string {\n if (edit.rm) return JSON.stringify({ t: EDIT_FRAME, id: edit.id, e: edit.e, ts: edit.ts, m: edit.m, rm: true });\n const base = { t: EDIT_FRAME, id: edit.id, e: edit.e, ts: edit.ts, m: edit.m, ...(edit.sc && { sc: edit.sc }) };\n const plain = JSON.stringify(base);\n if (!edit.pv) return plain;\n const withPreview = JSON.stringify({ ...base, pv: edit.pv });\n return withPreview.length <= MAX_EDIT_FRAME ? withPreview : plain;\n}\n\n/** The frame that confirms edit `e` of message `id`. */\nexport function editedFrame(id: string, e: number): string {\n return JSON.stringify({ t: EDITED_FRAME, id, e });\n}\n\n/** An edit number a message can have. */\nexport function validEditNumber(e: unknown): e is number {\n return Number.isSafeInteger(e) && (e as number) >= 1 && (e as number) <= MAX_EDITS_PER_MESSAGE;\n}\n\n/** A removal's number: any up to one past a card message's bound, card or not. */\nexport function validRemovalNumber(e: unknown): e is number {\n return Number.isSafeInteger(e) && (e as number) >= 1 && (e as number) <= MAX_REMOVAL_NUMBER;\n}\n\n/** A message's new text: not empty, no space around it, within a chat message's bytes. The same on a session and on the DHT. */\nexport function validEditMessage(m: unknown): m is string {\n return typeof m === \"string\" && !!m.trim() && m === m.trim() && utf8Encode(m).length <= LIMITS.maxChatMessageBytes;\n}\n\n/**\n * The edit a `paired-edit` frame says, or null when it is malformed (then it says nothing and is not confirmed). A\n * preview or a card that does not hold is dropped, never the edit; an edit numbered past `MAX_EDITS_PER_MESSAGE`\n * holds only with a card. A removal carries its fallback text alone, and a `rm` other than `true` is no edit.\n */\nexport function parseEditFrame(frame: Record<string, unknown>, now = Date.now()): WireEdit | null {\n if (frame?.t !== EDIT_FRAME) return null;\n const { id, e, ts, m, rm } = frame;\n if (rm !== undefined && rm !== true) return null;\n if (typeof id !== \"string\" || !(rm ? REMOVAL_ID : ID).test(id) || typeof e !== \"number\" || !(rm ? validRemovalNumber(e) : cardEditNumber(e))) return null;\n if (typeof ts !== \"number\" || !Number.isSafeInteger(ts) || ts <= 0) return null;\n if (!validEditMessage(m)) return null;\n if (rm) return { id, e, ts, m, rm };\n const sc = frame.sc === undefined ? undefined : readStatusCard(frame.sc, now);\n if (!validEditNumber(e) && !sc) return null;\n const pv = frame.pv === undefined ? undefined : parseLinkPreview(frame.pv, m);\n return { id, e, ts, m, ...(pv && { pv }), ...(sc && { sc }) };\n}\n\n/** The confirmation a `paired-edited` frame says, or null when it is malformed. */\nexport function parseEditedFrame(frame: Record<string, unknown>): { id: string; e: number } | null {\n if (frame?.t !== EDITED_FRAME) return null;\n return typeof frame.id === \"string\" && REMOVAL_ID.test(frame.id) && validRemovalNumber(frame.e) ? { id: frame.id, e: frame.e } : null;\n}\n\n/**\n * The id an edit goes by on the DHT floor (WISP 403 § Edits): a text of its own there, with the edited message's id and\n * the edit's number beside it. The same for every send of the same edit, so its retries and its receipt match.\n */\nexport function dhtEditId(id: string, e: number): string {\n return toBase64Url(sha256(utf8Encode(`ghostly-edit/1:${id}:${e}`)).slice(0, 16));\n}\n\n/**\n * A sliding window of `limit` events per `windowMs`: the sender's pace and the receiver's limit. A time later than now\n * (the device clock went back) is long gone, or the window would stay full for as long as the clock went back.\n */\nexport class RateWindow {\n private recent: number[] = [];\n\n constructor(private readonly limit: number, private readonly windowMs: number, private readonly now: () => number = Date.now) {}\n\n /** Counts one now; false (and not counted) when the window is full. */\n take(): boolean {\n const now = this.now();\n this.recent = this.recent.filter(at => at <= now && now - at < this.windowMs);\n if (this.recent.length >= this.limit) return false;\n this.recent.push(now);\n return true;\n }\n\n /** Milliseconds until the window has room again; 0 when it has room now. */\n wait(): number {\n const now = this.now();\n this.recent = this.recent.filter(at => at <= now && now - at < this.windowMs);\n return this.recent.length < this.limit ? 0 : this.recent[0] + this.windowMs - now;\n }\n\n reset(): void { this.recent = []; }\n}\n","import { fromBase64Url } from \"./bytes\";\nimport { imageSize } from \"./image\";\n\n/**\n * Videos. A video is an ordinary file (files/2, files/3 or a held item) whose announcement may also carry a\n * `video` description: how long it is, its size in pixels and a small JPEG of its first frame, so the\n * receiver shows a picture and a length before a byte of it has arrived. A peer that does not know `video`\n * ignores it and shows a file; a bad description only means no poster.\n */\nexport interface VideoMeta {\n /** Milliseconds. */\n duration: number;\n /** Pixels, as it plays (rotation applied). */\n width: number;\n height: number;\n /** A JPEG of an early frame, base64url, at most `VIDEO_LIMITS.maxPosterBytes`. */\n poster?: string;\n}\n\nexport const VIDEO_LIMITS = {\n /** The poster's bytes: with the rest of an offer, a frame stays far below the 60 KiB a session carries. */\n maxPosterBytes: 12 * 1024,\n /** The poster's longest side, in pixels, as the sender draws it. */\n posterEdge: 320,\n /** Ten hours: longer is a mistake, not a video. */\n maxDurationMs: 10 * 60 * 60_000,\n /** Pixels on either side (8K and a bit). */\n maxEdge: 16_384,\n} as const;\n\n/**\n * Video a player may be handed as it is. None of these runs anything in the page's origin, so received bytes\n * of these types are served with their type (see `safeBlobType`): WebKit will not play what is typed as bytes.\n */\nexport const PLAYABLE_VIDEO = /^video\\/(mp4|webm|quicktime|ogg|x-m4v)$/;\n\n/** Whether a file is a video, by its type: shown in a video bubble whether or not it came with a description. */\nexport function isVideoMime(mime: string): boolean {\n return mime.split(\";\")[0]!.trim().toLowerCase().startsWith(\"video/\");\n}\n\n/**\n * Whether a file is shown as a video (a poster, a player): a type a player may be handed. Other video types\n * (Matroska, AVI) are files, saved to be played elsewhere.\n */\nexport function isPlayableVideoType(mime: string): boolean {\n return PLAYABLE_VIDEO.test(mime.split(\";\")[0]!.trim().toLowerCase());\n}\n\nconst BASE64URL = /^[A-Za-z0-9_-]+$/;\nconst JPEG_START = [0xff, 0xd8, 0xff];\n\n/**\n * A peer's `video` description, or undefined when it is not one. It never refuses the file. A poster that is\n * too large, not a JPEG, or says it is more pixels than a sender draws (`posterEdge`) is dropped on its own; the\n * length and size are kept. It is shown before the file is accepted, so a few bytes must not ask for a huge bitmap.\n */\nexport function parseVideoMeta(value: unknown, mime?: string): VideoMeta | undefined {\n if (mime !== undefined && !isVideoMime(mime)) return undefined;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const { duration, width, height, poster } = value as { duration?: unknown; width?: unknown; height?: unknown; poster?: unknown };\n if (typeof duration !== \"number\" || !Number.isSafeInteger(duration) || duration <= 0 || duration > VIDEO_LIMITS.maxDurationMs) return undefined;\n const edge = (n: unknown): n is number => typeof n === \"number\" && Number.isSafeInteger(n) && n > 0 && n <= VIDEO_LIMITS.maxEdge;\n if (!edge(width) || !edge(height)) return undefined;\n const meta: VideoMeta = { duration, width, height };\n if (typeof poster === \"string\" && poster.length <= Math.ceil((VIDEO_LIMITS.maxPosterBytes * 4) / 3) && BASE64URL.test(poster)) {\n try {\n const bytes = fromBase64Url(poster);\n const size = bytes.length <= VIDEO_LIMITS.maxPosterBytes && JPEG_START.every((b, i) => bytes[i] === b) ? imageSize(bytes) : undefined;\n if (size && Math.max(size.width, size.height) <= VIDEO_LIMITS.posterEdge) meta.poster = poster;\n } catch { /* no poster */ }\n }\n return meta;\n}\n\n/** `0:07`, `12:45`, `1:02:03`: as a player shows a video's length. */\nexport function formatVideoDuration(ms: number): string {\n const total = Math.max(0, Math.floor((Number.isFinite(ms) ? ms : 0) / 1000));\n const hours = Math.floor(total / 3600), minutes = Math.floor((total % 3600) / 60), seconds = String(total % 60).padStart(2, \"0\");\n return hours ? `${hours}:${String(minutes).padStart(2, \"0\")}:${seconds}` : `${minutes}:${seconds}`;\n}\n","import { formatVideoDuration, type VideoMeta } from \"./video\";\n\n/**\n * Voice messages. A voice message is an ordinary file (files/2, or a held item) whose\n * announcement also carries a `voice` description: how long it is and the shape of its\n * sound. The shape is measured once, while recording, so no player ever decodes audio\n * to draw it. A peer that does not know `voice` ignores it and shows an audio file.\n */\nexport interface VoiceMeta {\n /** Milliseconds. */\n duration: number;\n /** Loudness per bar, 0-255, in playing order. */\n peaks: number[];\n}\n\nexport const VOICE_LIMITS = {\n /** Fifteen minutes: at the bitrate recorded (32 kbit/s) about 3.6 MB, well inside a held item's 8 MiB. */\n maxDurationMs: 15 * 60_000,\n /** Bars drawn for a recording. */\n bars: 64,\n /** Bars accepted from a peer. */\n maxBars: 128,\n /** Asked of the recorder; opus speech is clear well below it. */\n audioBitsPerSecond: 32_000,\n} as const;\n\n/**\n * Audio a player may be handed as it is. None of these runs anything in the page's origin,\n * so received bytes of these types are served with their type (see `safeBlobType`).\n */\nexport const PLAYABLE_AUDIO = /^audio\\/(webm|ogg|opus|mp4|mpeg|mp3|aac|x-m4a|wav|x-wav|wave|flac|x-flac)$/;\n\n/**\n * Whether a file sent as a file (not a voice message) is shown with a player: a type a player may be handed.\n * Other audio types (MIDI, AIFF, WMA) are files, saved to be played elsewhere.\n */\nexport function isPlayableAudioType(mime: string): boolean {\n return PLAYABLE_AUDIO.test(baseMime(mime));\n}\n\n/** The part of a type before its parameters, in lower case: `audio/webm;codecs=opus` → `audio/webm`. */\nexport function baseMime(mime: string): string {\n return mime.split(\";\")[0]!.trim().toLowerCase();\n}\n\n/**\n * A peer's `voice` description, or undefined when it is not one. It never refuses the file:\n * a bad description only means the file is shown as a file.\n */\nexport function parseVoiceMeta(value: unknown, mime?: string): VoiceMeta | undefined {\n if (mime !== undefined && !PLAYABLE_AUDIO.test(baseMime(mime))) return undefined;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const { duration, peaks } = value as { duration?: unknown; peaks?: unknown };\n // A recorder stops a moment after the limit, never minutes after it.\n if (typeof duration !== \"number\" || !Number.isSafeInteger(duration) || duration <= 0 || duration > VOICE_LIMITS.maxDurationMs + 5_000) return undefined;\n if (!Array.isArray(peaks) || peaks.length === 0 || peaks.length > VOICE_LIMITS.maxBars) return undefined;\n if (!peaks.every((peak) => typeof peak === \"number\" && Number.isInteger(peak) && peak >= 0 && peak <= 255)) return undefined;\n return { duration, peaks: [...peaks] };\n}\n\n/**\n * How the level is metered while recording (apps/ui/src/lib/voiceRecorder.ts): every `intervalMs`, the RMS of the last\n * `window` samples an AnalyserNode holds (at a 48 kHz context, about 21 ms of sound).\n */\nexport const VOICE_METER = { intervalMs: 50, window: 1024, windowRate: 48_000 } as const;\n\n/** One reading of the meter, 0-1: the RMS of the samples, lifted because speech sits low on a linear scale. */\nexport function voiceLevel(samples: ArrayLike<number>): number {\n if (samples.length === 0) return 0;\n let sum = 0;\n for (let i = 0; i < samples.length; i++) sum += samples[i]! * samples[i]!;\n return Math.min(1, Math.sqrt(sum / samples.length) * 4);\n}\n\n/**\n * The readings the recorder would have taken of this sound (mono, -1 to 1), for a recording made elsewhere: one\n * every `intervalMs` of it, each over the window that ends there, as long in time as the analyser's.\n */\nexport function voiceLevelsOf(mono: Float32Array, sampleRate: number): number[] {\n if (!(sampleRate > 0) || mono.length === 0) return [];\n const window = Math.max(1, Math.round((VOICE_METER.window * sampleRate) / VOICE_METER.windowRate));\n const levels: number[] = [];\n for (let step = 1; ; step++) {\n const end = Math.round((step * VOICE_METER.intervalMs * sampleRate) / 1000);\n if (end > mono.length) break;\n levels.push(voiceLevel(mono.subarray(Math.max(0, end - window), end)));\n }\n return levels;\n}\n\n/** The waveform sent with a recording made elsewhere, drawn as the recorder draws its own. */\nexport function voicePeaksOf(mono: Float32Array, sampleRate: number, bars: number = VOICE_LIMITS.bars): number[] {\n return downsamplePeaks(voiceLevelsOf(mono, sampleRate), bars);\n}\n\n/** Below this a recording is silence, and is drawn flat rather than stretched to fill the bars. */\nconst QUIET = 0.02;\n\n/**\n * Bars from the loudness measured while recording (RMS, 0-1, oldest first): the loudest\n * sample of each stretch, scaled so the loudest bar is full height.\n */\nexport function downsamplePeaks(levels: ArrayLike<number>, bars: number = VOICE_LIMITS.bars): number[] {\n const count = Math.max(1, Math.min(VOICE_LIMITS.maxBars, Math.floor(bars)));\n const clean = Array.from(levels, (level) => (Number.isFinite(level) ? Math.min(1, Math.max(0, level)) : 0));\n if (clean.length === 0) return new Array<number>(count).fill(0);\n const loudest = Math.max(QUIET, ...clean);\n const out: number[] = [];\n for (let bar = 0; bar < count; bar++) {\n const from = Math.floor((bar * clean.length) / count);\n // Fewer samples than bars: each bar takes the sample under it.\n const to = Math.max(from + 1, Math.floor(((bar + 1) * clean.length) / count));\n let peak = 0;\n for (let i = from; i < to && i < clean.length; i++) peak = Math.max(peak, clean[i]!);\n out.push(Math.round((peak / loudest) * 255));\n }\n return out;\n}\n\n/**\n * What to record in, by preference: opus in WebM plays on Chromium, Firefox, Safari 15+ and\n * WebKitGTK; older WebKit (WKWebView on macOS before Safari 18.4) records only AAC in MP4,\n * which Chrome, Edge and Safari play. `recorder` is asked of MediaRecorder, `file` is sent.\n */\nexport const RECORDING_TYPES = [\"audio/webm;codecs=opus\", \"audio/ogg;codecs=opus\", \"audio/mp4;codecs=mp4a.40.2\", \"audio/mp4\", \"audio/webm\"] as const;\n\nexport function recordingMime(isTypeSupported: (mime: string) => boolean): { recorder: string; file: string } | null {\n for (const type of RECORDING_TYPES) {\n let supported = false;\n try { supported = isTypeSupported(type); } catch { /* an engine that throws for a type does not have it */ }\n if (supported) return { recorder: type, file: baseMime(type) };\n }\n return null;\n}\n\n/** One for each type of `PLAYABLE_AUDIO`: a voice message may be any of them (the CLI sends a FLAC as one). */\nconst EXTENSIONS: Record<string, string> = {\n \"audio/webm\": \"webm\", \"audio/ogg\": \"ogg\", \"audio/opus\": \"opus\", \"audio/mp4\": \"m4a\", \"audio/x-m4a\": \"m4a\", \"audio/mpeg\": \"mp3\", \"audio/mp3\": \"mp3\",\n \"audio/aac\": \"aac\", \"audio/wav\": \"wav\", \"audio/x-wav\": \"wav\", \"audio/wave\": \"wav\", \"audio/flac\": \"flac\", \"audio/x-flac\": \"flac\",\n};\n\n/** A time no date can hold (past Date's end, NaN) makes a name without one, never \"NaN-NaN-NaN\". */\nfunction voiceName(prefix: string, mime: string, timestamp: number): string {\n const date = new Date(timestamp), extension = EXTENSIONS[baseMime(mime)] ?? \"audio\";\n if (Number.isNaN(date.getTime())) return `${prefix}.${extension}`;\n const pad = (n: number) => String(n).padStart(2, \"0\");\n const stamp = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}.${pad(date.getMinutes())}.${pad(date.getSeconds())}`;\n return `${prefix} ${stamp}.${extension}`;\n}\n\n/** A name for the file, for whoever saves it or runs a Ghostly that shows it as a file. */\nexport function voiceFileName(mime: string, timestamp: number): string {\n return voiceName(\"Voice message\", mime, timestamp);\n}\n\n/**\n * The name a downloaded voice message is saved under, made here from the message's time and its\n * type (the sender's own name for it is not used): \"Ghostly voice 2026-09-27 14.01.30.webm\".\n */\nexport function voiceDownloadName(mime: string, timestamp: number): string {\n return voiceName(\"Ghostly voice\", mime, timestamp);\n}\n\n/** `0:07`, `12:45`: minutes and seconds, as a player shows them. */\nexport function formatVoiceDuration(ms: number): string {\n const total = Math.max(0, Math.floor((Number.isFinite(ms) ? ms : 0) / 1000));\n const minutes = Math.floor(total / 60);\n return `${minutes}:${String(total % 60).padStart(2, \"0\")}`;\n}\n\n/** The line a file message shows in the chat list and in notifications. */\nexport function fileMessageText(file: { name: string; voice?: VoiceMeta; video?: VideoMeta }): string {\n if (file.voice) return `🎤 Voice message (${formatVoiceDuration(file.voice.duration)})`;\n if (file.video) return `🎬 Video (${formatVideoDuration(file.video.duration)})`;\n return `📎 ${file.name}`;\n}\n","import {\n CHUNK_KIND,\n LIMITS,\n encodeControl,\n sendBody,\n type ChunkFrame,\n type FileFrame,\n type FrameChannel,\n type ResetFrame,\n} from \"./frames\";\nimport type { WireReply } from \"./replies\";\nimport type { ImageMeta } from \"./image\";\nimport { PLAYABLE_VIDEO, type VideoMeta } from \"./video\";\nimport { PLAYABLE_AUDIO, type VoiceMeta } from \"./voice\";\n\n/**\n * Files over the data link. A `file` frame announces name, size and type, the\n * bytes follow as chunks, and the receiver only keeps the file if exactly the\n * announced number of bytes arrived. Nothing touches Pkarr: files go peer to\n * peer or not at all.\n */\nexport interface FileInfo {\n /** Chosen by the sender. */\n id: string;\n name: string;\n size: number;\n mime: string;\n timestamp: number;\n /** A voice message: its length and the shape of its sound (files/2 and held items only). */\n voice?: VoiceMeta;\n /** A video: its length, size and a small first frame (optional; old apps ignore it). */\n video?: VideoMeta;\n /** A picture: its size as it is shown, so its box is laid out before it arrives (optional; old apps ignore it). */\n image?: ImageMeta;\n /** The message this file answers (`r`, WISP 401 § Replies): files/2, files/3 and held items; older apps ignore it. */\n reply?: WireReply;\n /** How many times it has been forwarded (`fw`, WISP 401 § Forwards): files/2, files/3 and held items; older apps ignore it. */\n forwarded?: number;\n /**\n * The chat app id of the mini-app that sent this file ahead (`app`, WISP 1200 § Sending a film ahead): files/3 only;\n * older apps ignore it and keep the file as any file.\n */\n app?: string;\n}\n\n/** Where a platform puts incoming bytes: memory, IndexedDB, disk. */\nexport interface FileSink {\n write(chunk: Uint8Array): void | Promise<void>;\n close(digest?: string): void | Promise<void>;\n abort(): void;\n}\n\nexport interface FileTransferEvents {\n /** Return a sink to accept the file, null to refuse it, or the reason for refusing it. */\n onIncoming(file: FileInfo): FileSink | string | null;\n onProgress?(fileId: string, transferred: number, direction: \"in\" | \"out\"): void;\n onComplete?(fileId: string, direction: \"in\" | \"out\"): void;\n onFailed?(fileId: string, reason: string, direction: \"in\" | \"out\"): void;\n}\n\nconst FILE_ID = /^[A-Za-z0-9_-]{8,64}$/;\nconst MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}\\/[a-z0-9][a-z0-9!#$&^_.+-]{0,63}$/i;\nconst MAX_NAME_LENGTH = 200;\n\n/**\n * Invisible and direction-changing characters: bidi overrides turn\n * \"invoice\\u202Efdp.exe\" into what reads as \"invoiceexe.pdf\", zero-width ones hide\n * text. Cf covers both; line and paragraph separators break the layout.\n */\nconst INVISIBLE = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu;\n\n/**\n * Characters that draw as blank but are not spaces: the Hangul fillers, the braille blank, the combining grapheme\n * joiner. A run of them, or of spaces (em space and the like), would push the real extension out of view:\n * \"Invoice.pdf\" + 120 blanks + \".exe\" reads as a PDF in a truncated bubble.\n */\nconst BLANK = /[\\u034F\\u115F\\u1160\\u2800\\u3164\\uFFA0]/gu;\n\n/**\n * A run of whitespace, with the marks that sit on it: a mark that draws nothing (a variation selector, a Mongolian or\n * Khmer one) between two spaces must not keep them apart, or \" \\uFE0F\" repeated is a blank run again.\n */\nconst SPACE_RUN = /(?:\\s\\p{M}*)+/gu;\n\n/**\n * A run of characters meant to draw nothing (variation selectors, the Khmer inherent vowels, the Mongolian free\n * variation selectors). WebKit draws some of them as wide blanks after a letter, so \"Invoice.pdf\" + 150 of one +\n * \".exe\" reads as a PDF there. A letter keeps one variation selector (its variant form); the rest go.\n */\nconst IGNORABLE_RUN = /\\p{Default_Ignorable_Code_Point}+/gu;\nconst VARIATION_SELECTOR = /^\\p{Variation_Selector}/u;\n\nfunction dropIgnorable(run: string, offset: number, text: string): string {\n const kept = VARIATION_SELECTOR.exec(run)?.[0];\n return kept && offset > 0 && !/\\s/u.test(text[offset - 1]) ? kept : \"\";\n}\n\n/**\n * Names Windows keeps for devices, whatever the case, with any extension, and with spaces before the dot:\n * \"CON\", \"nul.txt\", \"COM1 .log\" open a device there, not a file.\n */\nconst WINDOWS_DEVICE = /^(CON|PRN|AUX|NUL|CONIN\\$|CONOUT\\$|COM[0-9¹²³]|LPT[0-9¹²³])\\s*(\\.|$)/i;\n\n/**\n * At most `MAX_NAME_LENGTH` characters. A longer name loses the end of its stem, not its extension (up to 15\n * characters after the last dot): \"…report.pdf\" stays a PDF to the system it is saved on.\n */\nfunction shorten(name: string): string {\n const chars = [...name];\n if (chars.length <= MAX_NAME_LENGTH) return name;\n const extension = [.../\\.[^.\\s]{1,15}$/u.exec(name)?.[0] ?? \"\"];\n return chars.slice(0, MAX_NAME_LENGTH - extension.length).join(\"\").trimEnd() + extension.join(\"\");\n}\n\n/** A file name is display text and a download suggestion, never a path. */\nexport function sanitizeFileName(name: string): string {\n const visible = name.replace(INVISIBLE, \"\").replace(BLANK, \"\").replace(/[/\\\\:]/g, \"\")\n .replace(IGNORABLE_RUN, dropIgnorable).replace(SPACE_RUN, \" \");\n // Whitespace before the dots must not hide them: \" .bashrc\" is a dotfile too.\n const clean = shorten(visible.replace(/^[\\s.]+/, \"\").trim());\n if (WINDOWS_DEVICE.test(clean)) return shorten(\"_\" + clean);\n return clean || \"file\";\n}\n\nexport function sanitizeMime(mime: string): string {\n return MIME.test(mime) ? mime.toLowerCase() : \"application/octet-stream\";\n}\n\n/** A size for people: B, KB, MB, GB, TB (powers of 1024), one decimal from KB up. */\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n const units = [\"KB\", \"MB\", \"GB\", \"TB\"];\n let value = bytes / 1024, unit = 0;\n while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }\n return `${value.toFixed(1)} ${units[unit]}`;\n}\n\n/** Raster images a UI may show inline. SVG is left out on purpose: it can carry scripts. */\nexport const PREVIEWABLE_IMAGE = /^image\\/(png|jpe?g|gif|webp)$/;\n\n/**\n * The type received bytes are served with. The peer picks the announced type,\n * and a blob: URL typed text/html or image/svg+xml would run in the app's\n * origin, so anything but a previewable image or playable audio or video is opaque bytes.\n * Audio and video keep their type because WebKit will not play what is typed as bytes.\n */\nexport function safeBlobType(mime: string): string {\n const clean = sanitizeMime(mime);\n return PREVIEWABLE_IMAGE.test(clean) || PLAYABLE_AUDIO.test(clean) || PLAYABLE_VIDEO.test(clean) ? clean : \"application/octet-stream\";\n}\n\ninterface Incoming {\n file: FileInfo;\n sink: FileSink;\n received: number;\n idleTimer?: ReturnType<typeof setTimeout>;\n /** Writes are chained so a slow sink cannot reorder chunks. */\n queue: Promise<void>;\n}\n\nexport class FileTransfers {\n private nextStreamId = 1;\n private readonly incoming = new Map<number, Incoming>();\n private readonly outgoing = new Map<number, { fileId: string; cancelled: boolean }>();\n\n constructor(\n private readonly channel: FrameChannel,\n private readonly events: FileTransferEvents,\n ) {}\n\n /** Streams a file to the peer. Resolves once every byte is handed to the channel. */\n async send(file: FileInfo, source: AsyncIterable<Uint8Array>): Promise<void> {\n if (file.size > LIMITS.maxFileBytes) throw new Error(\"File is too large\");\n const id = this.nextStreamId++;\n const state = { fileId: file.id, cancelled: false };\n this.outgoing.set(id, state);\n\n try {\n this.channel.send(\n encodeControl({\n t: \"file\",\n id,\n f: file.id,\n ts: file.timestamp,\n n: sanitizeFileName(file.name),\n s: file.size,\n m: sanitizeMime(file.mime),\n }),\n );\n let sent = 0;\n const counted = async function* (this: FileTransfers) {\n for await (const part of source) {\n sent += part.length;\n yield part;\n this.events.onProgress?.(file.id, sent, \"out\");\n }\n }.call(this);\n await sendBody(this.channel, CHUNK_KIND.fileBody, id, counted, () => state.cancelled);\n if (state.cancelled) throw new Error(\"The peer refused the file\");\n if (sent !== file.size) throw new Error(\"File changed while it was being sent\");\n this.events.onComplete?.(file.id, \"out\");\n } catch (error) {\n if (!state.cancelled) {\n try {\n this.channel.send(encodeControl({ t: \"rst\", id, d: \"f\", e: \"aborted\" }));\n } catch {\n // channel already closed\n }\n }\n this.events.onFailed?.(file.id, error instanceof Error ? error.message : String(error), \"out\");\n throw error;\n } finally {\n this.outgoing.delete(id);\n }\n }\n\n handleFile(frame: FileFrame): void {\n if (this.incoming.has(frame.id)) return;\n const refuse = (reason: string) => {\n try {\n this.channel.send(encodeControl({ t: \"rst\", id: frame.id, d: \"f\", e: reason }));\n } catch {\n // channel already closed\n }\n };\n if (!FILE_ID.test(frame.f)) return refuse(\"invalid file id\");\n if (frame.s > LIMITS.maxFileBytes) return refuse(\"file too large\");\n if (this.incoming.size >= LIMITS.maxIncomingFilesPerPeer) return refuse(\"too many transfers\");\n\n const file: FileInfo = {\n id: frame.f,\n name: sanitizeFileName(frame.n),\n size: frame.s,\n mime: sanitizeMime(frame.m),\n timestamp: frame.ts,\n };\n const sink = this.events.onIncoming(file);\n if (!sink || typeof sink === \"string\") return refuse(sink || \"refused\");\n\n const entry: Incoming = { file, sink, received: 0, queue: Promise.resolve() };\n this.incoming.set(frame.id, entry);\n this.armIdleTimer(frame.id, entry);\n }\n\n handleChunk(chunk: ChunkFrame): void {\n const entry = this.incoming.get(chunk.id);\n if (!entry) return;\n\n entry.received += chunk.payload.length;\n if (entry.received > entry.file.size) return this.failIncoming(chunk.id, \"more data than announced\", true);\n\n if (chunk.payload.length > 0) {\n const payload = chunk.payload.slice();\n entry.queue = entry.queue.then(() => entry.sink.write(payload));\n this.events.onProgress?.(entry.file.id, entry.received, \"in\");\n }\n if (!chunk.end) return this.armIdleTimer(chunk.id, entry);\n\n if (entry.received !== entry.file.size) return this.failIncoming(chunk.id, \"incomplete file\", false);\n clearTimeout(entry.idleTimer);\n this.incoming.delete(chunk.id);\n entry.queue\n .then(() => entry.sink.close())\n .then(\n () => this.events.onComplete?.(entry.file.id, \"in\"),\n () => {\n entry.sink.abort();\n this.events.onFailed?.(entry.file.id, \"could not store the file\", \"in\");\n },\n );\n }\n\n handleReset(frame: ResetFrame): void {\n if (this.incoming.has(frame.id)) this.failIncoming(frame.id, frame.e || \"cancelled by the sender\", false);\n const sending = this.outgoing.get(frame.id);\n if (sending) sending.cancelled = true;\n }\n\n /** The link went away: nothing in flight can finish. */\n closeAll(): void {\n for (const id of [...this.incoming.keys()]) this.failIncoming(id, \"connection lost\", false);\n for (const sending of this.outgoing.values()) sending.cancelled = true;\n }\n\n private armIdleTimer(id: number, entry: Incoming): void {\n clearTimeout(entry.idleTimer);\n entry.idleTimer = setTimeout(() => this.failIncoming(id, \"transfer stalled\", true), LIMITS.bodyIdleTimeoutMs);\n }\n\n private failIncoming(id: number, reason: string, notifyPeer: boolean): void {\n const entry = this.incoming.get(id);\n if (!entry) return;\n clearTimeout(entry.idleTimer);\n this.incoming.delete(id);\n entry.sink.abort();\n if (notifyPeer) {\n try {\n this.channel.send(encodeControl({ t: \"rst\", id, d: \"f\", e: reason }));\n } catch {\n // channel already closed\n }\n }\n this.events.onFailed?.(entry.file.id, reason, \"in\");\n }\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, utf8Encode } from \"./bytes\";\nimport { sanitizeFileName, sanitizeMime } from \"./files\";\nimport { parseImageMeta, type ImageMeta } from \"./image\";\nimport { parseVideoMeta, type VideoMeta } from \"./video\";\nimport { downsamplePeaks, parseVoiceMeta, type VoiceMeta } from \"./voice\";\n\n/**\n * A file's bubble on the DHT floor (WISP 403 § Files): while the contact is away, a file's offer (its name, size, type,\n * id and the sender's time, with its picture, voice or video size when it has one) rides an envelope like a text, so\n * it takes its place among the texts written around it. Its bytes never do: they follow on the live session (files/3).\n *\n * Only to a contact whose capability record (WISP 03) lists this: an app from before would show the file's name as a\n * text of its own.\n */\nexport const DHT_FILE_CAPABILITY = \"dht-file/1\" as const;\n\n/** The id a file's offer has on the floor (22 characters, like a text's): every send of it and its receipt match. */\nexport function dhtFileId(wireId: string): string {\n return toBase64Url(sha256(utf8Encode(`ghostly-file/1:${wireId}`)).slice(0, 16));\n}\n\n/** A file's id on the live session (files/3): what the floor's sixteenth element names. */\nconst WIRE_ID = /^[A-Za-z0-9_-]{8,64}$/;\n\n/** What a picture, a voice note or a video says of itself on the floor: a video's poster never rides. */\nexport interface DhtFileMeta { voice?: VoiceMeta; image?: ImageMeta; video?: Omit<VideoMeta, \"poster\"> }\n/** The signed body's sixteenth element: `[wire id, size, type, meta]`. The name is the envelope's text. */\nexport type DhtFileElement = [wireId: string, size: number, mime: string, meta: DhtFileMeta | null];\n\n/** A file to say on the floor, as the sender has it. */\nexport interface DhtFileOffer {\n wireId: string;\n name: string;\n size: number;\n mime: string;\n voice?: VoiceMeta;\n image?: ImageMeta;\n video?: VideoMeta;\n}\n/** A file the contact said on the floor, checked: its bubble waits for the bytes. */\nexport interface DhtFileAnnouncement extends DhtFileOffer { video?: Omit<VideoMeta, \"poster\"> }\n\n/**\n * The sixteenth elements to try for a file, the most it can say first: its whole meta, a voice note's waveform thinned\n * to fewer bars, no meta. The sender takes the first whose envelope fits the packet.\n */\nexport function dhtFileElements(file: DhtFileOffer): DhtFileElement[] {\n const base = (meta: DhtFileMeta | null): DhtFileElement => [file.wireId, file.size, file.mime, meta];\n const out: DhtFileElement[] = [];\n if (file.voice) {\n out.push(base({ voice: file.voice }));\n for (const bars of [32, 16, 8]) if (file.voice.peaks.length > bars) out.push(base({ voice: { duration: file.voice.duration, peaks: downsamplePeaks(file.voice.peaks, bars) } }));\n } else if (file.video) out.push(base({ video: { duration: file.video.duration, width: file.video.width, height: file.video.height } }));\n else if (file.image) out.push(base({ image: file.image }));\n out.push(base(null));\n return out;\n}\n\n/**\n * The sixteenth element as a reader takes it, with the envelope's message (`[id, time, name]`). Null when it is not a\n * file's offer, or not one that holds: the envelope's id must be the one its wire id gives, so a receipt names it.\n */\nexport function readDhtFile(raw: unknown, message: [id: string, timestamp: number, text: string]): DhtFileAnnouncement | null {\n if (!Array.isArray(raw) || raw.length !== 4) return null;\n const [wireId, size, mime, meta] = raw as unknown[];\n if (typeof wireId !== \"string\" || !WIRE_ID.test(wireId) || message[0] !== dhtFileId(wireId)) return null;\n if (typeof size !== \"number\" || !Number.isSafeInteger(size) || size < 0) return null;\n if (typeof mime !== \"string\" || mime.length > 130) return null;\n if (meta !== null && (typeof meta !== \"object\" || Array.isArray(meta))) return null;\n const name = sanitizeFileName(message[2]), type = sanitizeMime(mime);\n const out: DhtFileAnnouncement = { wireId, name, size, mime: type };\n const said = (meta ?? {}) as Record<string, unknown>;\n const voice = parseVoiceMeta(said.voice, type), image = parseImageMeta(said.image, type), video = parseVideoMeta(said.video, type);\n if (voice) out.voice = voice;\n else if (video) { const { poster: _poster, ...shown } = video; out.video = shown; }\n else if (image) out.image = image;\n return out;\n}\n","import { ed25519, x25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { fromBase64, fromBase64Url, toBase64, toBase64Url, utf8Decode, utf8Encode } from \"./bytes\";\nimport { encrypt, sealedLength, tryDecrypt } from \"./crypto\";\nimport { RATCHET_OVERHEAD, RatchetBox, type RatchetState } from \"./ratchet\";\nimport { identityFromSeed, identityFromSeedB64, publicKeyFromZ32, sign, verify, type Identity } from \"./identity\";\nimport type { LinkParams } from \"./invite\";\nimport type { PairingCredentials } from \"./pairedSession\";\nimport { measureRecords, MAX_DNS_PACKET_BYTES, PKARR_FUTURE_SKEW_MS, type GhostRecord, type SignedPacket } from \"./pkarr\";\nimport { budgetRetryMs, isDiscoveryBudgetError, publishedNowhere, type PkarrRequestOptions, type PkarrTransport } from \"./transport\";\nimport { traceLink } from \"./linkTrace\";\nimport { AWAITING_PEER_MS, countUnusedInvite, PRESENCE_WINDOW, UNUSED_INVITE_UPKEEP_MS, unusedInviteWait } from \"./link\";\nimport { REACTION_LIMITS, readDhtReactions, validReactionNumber, type WireReaction } from \"./reactions\";\nimport { readForwarded } from \"./forwards\";\nimport { validEditNumber } from \"./pairedEdits\";\nimport { dhtFileElements, dhtFileId, readDhtFile, type DhtFileAnnouncement, type DhtFileElement, type DhtFileOffer } from \"./dhtFiles\";\n\nexport type DeliveryMode = \"stream\" | \"dht\";\nexport const DHT_TEXT_BYTES = 256;\nexport const DHT_MESSAGE_TTL = 5 * 60_000;\nexport const DHT_TEXT_TOO_LONG = `DHT text is limited to ${DHT_TEXT_BYTES} UTF-8 bytes. Shorten it or choose a live connection.`;\nexport const DHT_PACKET_BUDGET = \"Text and authentication exceed the DHT packet budget. Shorten the message.\";\nconst CONTROL_TTL = 10 * 60_000;\n/**\n * How far apart two devices' clocks may be for an envelope's expiry: a reader takes one until this long after `expires`\n * by its own clock. A device's clock a few minutes off is common; an envelope's lifetime is five or ten minutes, so a\n * sender that far behind had every envelope expired on arrival, with nothing on screen on either side. Its `issued` is\n * refused for nothing: what stops an old envelope from being taken again is its `sequence`, which the reader keeps.\n */\nexport const DHT_EXPIRY_SKEW_MS = PKARR_FUTURE_SKEW_MS;\n/**\n * How far before its own clock a sender dates an envelope (`issued`), never before the envelope's lifetime began nor\n * 30 s before its text's time. Apps up to 1.0.2 refuse an envelope dated more than 30 s past their clock, so every\n * envelope of a clock two minutes ahead was dropped by them: no first contact, no text, no receipt. Dated back, a\n * control envelope from a clock up to two and a half minutes ahead is taken by them at once, and a text once it has\n * been going out for as long as the clock is ahead.\n */\nexport const DHT_ISSUED_BACK_MS = 2 * 60_000;\nconst MAX_ATTEMPTS = 8;\n/**\n * Envelope sequences are set aside this many at a time (`DhtDeliveryState.sequence` is the highest set aside): a\n * keep-alive, every four minutes per chat, and one the relays' budget turns away, every 30 s on a profile idling at\n * it, then cost no disk write of their own. A reader only needs the sequence to grow, so those a restart skips cost\n * nothing; one the budget turned away is not used again, as it may have gone out on the DHT (the CLI puts there too).\n */\nconst SEQUENCE_BLOCK = 64;\n/** The longest the relays' request budget holds publications back (`budgetUntil`). */\nconst BUDGET_HOLD_MAX_MS = 60_000;\n/** The longest wait `backoff` gives. */\nconst BACKOFF_MAX_MS = 60_000;\n/** The wait before publication attempt `attempts + 1` of a text, or of a receipt the contact still asks for. */\nconst backoff = (attempts: number) => Math.min(BACKOFF_MAX_MS, 4_000 * 2 ** attempts);\n/**\n * A time this side set by its clock, at most `ms` after the moment it was set, read back `now`. One further ahead was set\n * before the device clock went back (an NTP step, a clock that ran ahead set right): it counts from now, not for as long\n * as the clock went back, as `relay.ts` counts its budget times. One already past (the clock set forward) stays past:\n * what it timed ends early, never late.\n */\nconst bounded = (at: number, now: number, ms = 0): number => Math.min(at, now + ms);\n/**\n * The contact's mailbox is read this often while this side is DHT-only, unless that contact is away with nothing of\n * ours waiting on it (`dhtOnlyIdle`; a contact that chose it is read at the chat's pace: `ACTIVE_DHT_POLL_MS` open,\n * or on a daemon, `peerDhtPollMs`), and otherwise…\n */\nconst DHT_POLL_MS = 4_000;\nconst STREAM_POLL_MS = 30_000;\n/**\n * …except for this long after this side leaves DHT-only while the contact is still there: its own\n * switch then shows in seconds, not at the next 30 s read (both sides are blocked from a live link until\n * each has seen the other leave).\n */\nexport const LEAVING_DHT_FAST_MS = 2 * 60_000;\n/**\n * Reads of a DHT-only contact's mailbox that go as signaling (`expect(ms, true)`) once something shows it leaving,\n * for as long as it still says DHT only. What shows it (a fresh packet on its link key, its offer) can reach this side\n * before the envelope saying so reaches the relays, and the first read then finds DHT only still. With the relays'\n * minute spent, every read after it was held back for 42 s, and the chat stayed \"On DHT · retrying live\" while its\n * contact had left (mx-d707d8d5, 2026-09-30). A few, not the whole window: the allowance they spend is also what this\n * side's offer and its reads for the answer go over the minute on (`SIGNALING_ALLOWANCE_SHARE` in relay.ts).\n */\nexport const LEAVING_SIGNAL_READS = 3;\n/**\n * How long a fresh link packet of a contact that still says DHT only after the reads it started waits before it may\n * start them again (`peerLinkPacket`), doubling up to `LEAVING_PROBE_MAX_GAP_MS`. One that really left says so in\n * seconds; one that stays (or anyone holding the invite) cannot keep this side reading its mailbox at the DHT pace.\n */\nexport const LEAVING_PROBE_GAP_MS = 2 * 60_000;\nexport const LEAVING_PROBE_MAX_GAP_MS = 16 * 60_000;\n/** Only this often while layer 1 carries the chat (WISP 403, Q7): the relays' per-IP budget is shared by every chat. */\nexport const LIVE_POLL_MS = 5 * 60_000;\n/**\n * On the DHT with the chat open, the mailbox is read this often (WISP 403 proposes 4 s). The relays' per-IP budget\n * (30 requests a minute per relay here, reads and publishes together) is shared with presence polling, which is at its\n * fastest right then, while layer 1 is redialled; 4 s starved the publications of held items in the store-and-forward\n * e2e. A text of ours awaiting its receipt still reads at 4 s, and a drop reads once, at once.\n */\nexport const ACTIVE_DHT_POLL_MS = 10_000;\nconst ID = /^[A-Za-z0-9_-]{22}$/;\n/** What a text may reply to over the DHT: a message, file or payment id of this chat (WISP 401 § Replies). */\nconst REPLY_TO = /^[A-Za-z0-9_-]{8,64}$/;\ntype Message = [id: string, timestamp: number, text: string];\n/**\n * The ninth element, the author's capability-record revision (WISP 03), is optional; readers ignore\n * trailing elements they do not know. The signature covers all of them. The tenth is the pinned mailbox\n * (WISP 403, revision 0.3): `1`, the author can use it; `2`, the author knows the reader can too, and reads\n * there first. A ninth element then goes as `null` when there is no revision to name. The eleventh, with a text only,\n * is the id of the message it replies to (WISP 403 § Replies): the id alone, which the reader looks up in its history.\n * The twelfth is kept for an edit (WISP 403 § Edits). The thirteenth, the author's reactions the reader has not confirmed\n * yet, `[[id, emoji, n], …]`, oldest first and as many as fit; the fourteenth, the highest number of the reader's\n * reactions the author took (WISP 403 § Reactions). The eleventh and twelfth then go as `null` when there is no reply\n * and no edit. The fifteenth, with a text only, is how many times it has been forwarded (WISP 403 § Forwards); the\n * four before it then go as `null`, `null`, `[]` and `null` when they have nothing to say. The sixteenth, a file's offer\n * (WISP 403 § Files): `[wire id, size, type, meta]`, the text being the file's name; the five before it are then\n * present, the fifteenth `null` when the file was never forwarded. Readers from before take a body of up to sixteen\n * elements: one past it needs a reader that says it takes it.\n */\ntype DhtReaction = [id: string, emoji: string, n: number];\ntype Body = [version: 1, sequence: number, issued: number, expires: number, author: string, mode: DeliveryMode, message: Message | null, receipt: string | null, capsRev?: number | null, pinnedMailbox?: 1 | 2, replyTo?: string | null, edit?: DhtEdit | null, reactions?: DhtReaction[], reactionsTaken?: number | null, forwarded?: number | null, file?: DhtFileElement];\n/** An envelope's plaintext past this is not read (`receive`): what rides along must stay under it. */\nconst MAX_ENVELOPE_PLAINTEXT = 900;\n/**\n * Every envelope's records carry this TTL, whatever it holds (WISP 403 § What a mailbox shows): a text's TTL used to\n * count down from its five minutes while a keep-alive's said ten, so a look at the mailbox told a text was pending.\n * Readers never read it; relays cache for at least this long anyway.\n */\nconst ENVELOPE_TTL = 300;\n/**\n * An envelope's packet, text or not, is padded to the largest plaintext that fits this. A few bytes under the DHT's\n * 1000: the Rust client splits TXT strings at 254 bytes, not 255, so the packet it builds can be a byte or two larger.\n */\nconst ENVELOPE_PACKET_BYTES = MAX_DNS_PACKET_BYTES - 8;\n/**\n * The twelfth element, with a text only: the text is an edit (WISP 403 § Edits), the new text of the message with this id,\n * edit number `e`. The eleventh then goes as `null` when the text replies to nothing. An app from before edits would show\n * the text as a message of its own: it is sent only to a contact whose capability record lists `edit/1`.\n */\ntype DhtEdit = [id: string, e: number];\n/**\n * Before the contact said it can use the pinned mailbox, the invite's mailbox is read. When that held a packet but\n * nothing from the contact (expired, or someone else's), the pinned one is looked in too, no more often than this:\n * the contact may have moved there while this side was away, and every read spends a relay request.\n */\nconst PINNED_PROBE_MS = 60_000;\nexport interface DhtDeliveryState {\n sequence: number;\n peerSequence: number;\n peerMode?: DeliveryMode;\n /**\n * How far the contact is in the pinned mailbox (WISP 403, revision 0.3), from its envelopes sealed to this side: it\n * `can` use it; it `reads` there first (it knows this side can); it was `seen` publishing there. This side reads\n * there first from `can` on and publishes there from `reads` on; from `seen` on it reads only there.\n */\n peerPinned?: \"can\" | \"reads\" | \"seen\";\n /** `reply`: the id of the message the text replies to, published with it (the eleventh element). */\n pending?: { message: Message; expires: number; attempts: number; next: number; reply?: string; edit?: DhtEdit; forwarded?: number; file?: DhtFileElement };\n /**\n * The receipt this side owes for the contact's last text. `next`: when it forces a publication again (absent: at\n * once). `settled`: the contact's newer envelope no longer carries that text (it has a receipt, on either path, or\n * gave up on it), so the receipt only rides along on envelopes that go out anyway.\n */\n receipt?: { id: string; expires: number; attempts: number; next?: number; settled?: boolean };\n confirmed?: string;\n /** The highest number of the contact's reactions taken from its envelopes: said back in every envelope. */\n reactionsTaken?: number;\n /**\n * The contact's envelope, by its hint the pinned (or expected) key's, is sealed to another key: the contact paired with\n * someone else who used the same invite first. Kept until an envelope of the contact's newer than the last read opens.\n */\n inviteTaken?: true;\n /**\n * Layer 1 carried this chat with the pinned key at least once: the contact pinned this side, for good. What reads as\n * \"the invite was taken\" from then on is not the contact's word (`sealedToAnother`).\n */\n wasLive?: true;\n /**\n * This side joined, and pinned the inviter from an envelope it put out before anyone joined (sealed with the invite's\n * key, not to this side): that envelope's sequence. Until the inviter shows it was there since (`DhtDelivery.unanswered`),\n * the chat is read as an invite nobody used (`unusedInviteWait`), counted from the join.\n */\n unanswered?: number;\n /**\n * A digest of the contact's last ratcheted envelope taken (WISP 4xx § The DHT floor): a reader reads more often than\n * the contact publishes, and a floor key once used is gone, so the same envelope read again is known by this.\n */\n lastDr?: string;\n}\nexport interface DhtDeliveryView {\n mode: DeliveryMode;\n peerMode?: DeliveryMode;\n authenticated: boolean;\n error?: string;\n pendingUntil?: number;\n maxTextBytes: number;\n /** The envelope last published from here, for a text's details; absent until one carried a text. */\n lastPublished?: DhtPacketFacts;\n /**\n * When an envelope or a connection signal signed by a participation key other than the pinned one last came in\n * over one of the chat's invite-derived keys. Anyone holding a copy of the invite can publish there, so it is\n * ignored, never a reason to stop the chat: a passive warning only.\n */\n foreignKeySeenAt?: number;\n /** The invite was used by someone else first (`DhtDeliveryState.inviteTaken`): this side's texts reach nobody. */\n inviteTaken?: boolean;\n /**\n * Forward secrecy of the floor (WISP 4xx): `on`, the turn passed both ways; `starting`, both apps have it and it is on\n * once both have written; `unsupported`, the contact's app does not have it; `stopped`, it was on and the contact's\n * app no longer says it has it (floor texts wait for the live session). Absent: this app does not run it here.\n */\n forwardSecrecy?: \"on\" | \"starting\" | \"unsupported\" | \"stopped\";\n}\n/**\n * What can be said about one DHT envelope without opening it: which text it carried, its sequence and times, the\n * signed packet's size, the sealed record's nonce (the first 24 bytes of the record, never a key) and the address\n * it was published under. All of it travels in the clear on the DHT already.\n */\nexport interface DhtPacketFacts {\n /** The text's stable id, when the envelope carried one. */\n id?: string;\n seq: number;\n issued: number;\n expires: number;\n packetBytes: number;\n nonce: string;\n recordKey: string;\n records: string[];\n}\nexport const emptyDhtDeliveryState = (): DhtDeliveryState => ({ sequence: 0, peerSequence: 0 });\n\n/** An invite is a secret capability, not an independently verified identity.\n * Participation signatures bind each encrypted envelope to both invite roles.\n * The same durable TOFU pin is required here and on all subsequent streams.\n * No forward-secrecy or guaranteed DHT retention claim is made. */\nexport class DhtDelivery {\n private state: DhtDeliveryState;\n /** The state as last saved: a save that would write the same row again is skipped. */\n private saved?: string;\n /** The sequence of the last envelope signed here; the state's is the highest set aside (`SEQUENCE_BLOCK`). */\n private sequence: number;\n private mode: DeliveryMode;\n private running = false;\n private ticking = false;\n private tickAgain = false;\n /** Until when this side, having left DHT-only, reads a contact still there at the fast pace. */\n private leavingUntil = 0;\n /** Until when the mailbox is read at the fast pace for any other reason (a drop, a first contact). */\n private fastUntil = 0;\n private live = false;\n private active = false;\n private readonly startedAt = Date.now();\n /**\n * When an envelope of the contact's newer than any before was last read here, in this run. A contact that is there\n * puts a keep-alive every four minutes: none in `PRESENCE_WINDOW`, it is away (`publish`).\n */\n private peerNewAt = -Infinity;\n /** The next read was asked for (a refresh, a fresh packet of the contact): it is not a background one. */\n private urgent = false;\n /** Reads left that are signaling: the contact is leaving DHT only, and the live link waits on them (`expect`). */\n private signalReads = 0;\n /** The read as this side leaves DHT only, before the signaling ones (`setMode`): a plain one. */\n private leavingRead = false;\n /** Until when a fresh link packet of the contact starts no signaling reads, and the wait it was held to (`peerLinkPacket`). */\n private probeAt = 0;\n private probeGap = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n /** The first control envelope of a start that waits (`firstControlAfterMs`). */\n private controlTimer: ReturnType<typeof setTimeout> | null = null;\n /** A new capability revision to name once the publication spacing allows (`announce`). */\n private announceTimer: ReturnType<typeof setTimeout> | null = null;\n private chain = Promise.resolve();\n private lastPublish = 0;\n /**\n * A withdrawn text's envelope may still be on the relays, and the one to replace it has not gone (`withdraw`): it is\n * tried again with a text's backoff, `MAX_ATTEMPTS` times at most, until `until` (when no reader takes the withdrawn\n * one any more), not at the next keep-alive four minutes on. Any envelope that goes out replaces it.\n */\n private withdrawal?: { until: number; attempts: number; next: number };\n /** When the last withdrawal's envelope went (its `lastPublish`), for `withdrawalWaits`. */\n private withdrewAt = -1;\n /** The sequence of the last envelope of the contact that was past its expiry (traced once). */\n private expiredSeen = 0;\n private controlDue = 0;\n /**\n * This side's envelope in the invite's mailbox is sealed with the invite key alone (published before the pin). Once the\n * contact is pinned, one sealed to it replaces it as soon as the publication spacing allows (`resealDue`): another\n * holder of the invite reads there that it was taken (`sealedToAnother`), instead of pinning this side on it.\n */\n private unsealedOut: boolean;\n /** Until when the relays' request budget holds publications back: what is due then goes at once. */\n private budgetUntil = 0;\n /**\n * This side left DHT only and no envelope saying so went out yet: the contact's live link waits on it (it holds this\n * side's offer until it reads that), so it goes as signaling (`PkarrRequestOptions.signal`).\n */\n private leavingOut = false;\n /**\n * Until when it held this side's last read of the contact's mailbox back: the read goes again then, not at the next\n * poll. A chat in the background reads every 30 s, and one held back while its link was redialling read the contact\n * 60 s after its live link dropped, the chat \"On DHT · retrying live\" all along while the contact had chosen DHT only.\n */\n private readHeldUntil = 0;\n private errors: Partial<Record<\"publish\" | \"read\", string>> = {};\n /** Texts whose last `send` went nowhere (`wentNowhereFor`), newest last. */\n private wentNowhere = new Set<string>();\n /** When the device's network last came back (`networkBack`): a read or publication started before failed for want of it. */\n private networkBackAt = -Infinity;\n private foreignKeySeenAt?: number;\n /** When the pinned mailbox was last looked in while the contact had not said it uses it. */\n private pinnedProbeAt = 0;\n private pinnedBoxes?: { peerKey: string; identity: Identity; peerAddress: string };\n private readonly identity;\n private readonly peerAddress: string;\n private readonly key: Uint8Array;\n private readonly from: string;\n private readonly to: string;\n private readonly participation;\n /** The capability-record revision the last envelope published here named. */\n private namedRev?: number;\n /** A reaction of this side waits to ride on an envelope, or the contact's reactions wait to be said taken. */\n private reactionsDue = false;\n /** The text on the floor whose envelope left the reactions no room (its id): they wait for the ones its backoff publishes. */\n private crowdedBy?: string;\n constructor(private readonly options: {\n params: LinkParams; mode: DeliveryMode; state?: DhtDeliveryState;\n credentials: PairingCredentials; transport: PkarrTransport;\n save(state: DhtDeliveryState): Promise<void>;\n pin(key: string): Promise<void>;\n /** `file`: the text is a file's name, and this its offer (WISP 403 § Files): a bubble, not a text. */\n message(message: { id: string; text: string; timestamp: number; reply?: { i: string }; edit?: { i: string; e: number }; forwarded?: number; file?: DhtFileAnnouncement }, packet: DhtPacketFacts): Promise<void>;\n receipt(id: string): Promise<void>;\n changed(view: DhtDeliveryView): void;\n /** This side's capability-record revision, told in every envelope (WISP 03). */\n capsRev?(): number | undefined;\n /** An envelope from the contact named this revision of its capability record. */\n peerCapsRev?(rev: number): void;\n /** Whether the contact's capability record accepts DHT text (`dht-text/1`); absent or unknown: it does. */\n peerAcceptsText?(): boolean;\n /** Whether the contact's capability record takes a file's offer on the floor (`dht-file/1`); absent: it does not. */\n peerAcceptsFile?(): boolean;\n /** This side's reactions the contact has not confirmed, oldest first: they ride on the envelopes (WISP 403 § Reactions). */\n reactions?(): readonly WireReaction[];\n /** A reaction of the contact's, from an envelope, already checked. */\n reaction?(reaction: WireReaction): Promise<void>;\n /** The contact took this side's reactions up to number `n`. */\n reactionsTaken?(n: number): Promise<void>;\n pollMs?: number;\n /**\n * How often a contact that chose DHT only is read with the chat in the background, where every chat counts as open\n * (a CLI daemon: `ACTIVE_DHT_POLL_MS`), while that contact is there (`pollMs`). Absent: at the background pace (WISP 403, poll pace).\n */\n peerDhtPollMs?: number;\n /**\n * A chat already paired, started again: its first control envelope goes this long after the start, not in the\n * burst of an app coming back (bug hunt r7a). A text, a receipt, a new mode or a new capability revision still go at once.\n */\n firstControlAfterMs?: number;\n /**\n * This side made the invite, or joined one, then: once no longer awaited, its mailbox is read less often while nobody\n * uses it, or while its inviter never answered the join (`unanswered`) (`unusedInviteWait`).\n */\n inviteMadeAt?: number;\n /**\n * The chat's ratchet (WISP 4xx), shared with its held items, and whether the contact's capability record lists\n * `ratchet/1`. Absent: every envelope is sealed as before.\n */\n ratchet?: { box: RatchetBox; peerSupports(): boolean };\n }) {\n // `peerRejected`, saved by apps before WISP 403 revision 0.3, stopped the chat for good on an envelope anyone\n // holding the invite could forge: it is dropped, not honoured.\n const { peerRejected: _peerRejected, ...state } = structuredClone(options.state ?? emptyDhtDeliveryState()) as DhtDeliveryState & { peerRejected?: boolean };\n this.state = state; this.mode = options.mode; this.sequence = state.sequence;\n if (options.state) this.saved = JSON.stringify(state);\n this.unsealedOut = state.sequence > 0 && !options.credentials.peerKey;\n this.from = identityFromSeedB64(options.params.seedB64).pubKeyZ32; this.to = options.params.peerPubKeyZ32;\n this.participation = identityFromSeedB64(options.credentials.seedB64);\n const secret = fromBase64Url(options.params.encKeyB64);\n const context = JSON.stringify([\"ghostly-dht-delivery/1\", [this.from, this.to].sort()]);\n const derive = (label: string) => hkdf(sha256, secret, utf8Encode(context), utf8Encode(label), 32);\n this.identity = identityFromSeed(derive(`mailbox:${this.from}`));\n this.peerAddress = identityFromSeed(derive(`mailbox:${this.to}`)).pubKeyZ32;\n this.key = derive(\"envelope\");\n }\n get view(): DhtDeliveryView {\n return { mode: this.mode, peerMode: this.state.peerMode, authenticated: !!this.options.credentials.peerKey,\n error: [this.errors.read, this.errors.publish].filter(Boolean).join(\". \") || undefined, pendingUntil: this.state.pending?.expires, maxTextBytes: DHT_TEXT_BYTES,\n ...(this.lastPublished && { lastPublished: this.lastPublished }), ...(this.foreignKeySeenAt && { foreignKeySeenAt: this.foreignKeySeenAt }),\n ...(this.state.inviteTaken && { inviteTaken: true }), ...(this.forwardSecrecy && { forwardSecrecy: this.forwardSecrecy }) };\n }\n private get forwardSecrecy(): DhtDeliveryView[\"forwardSecrecy\"] {\n const ratchet = this.options.ratchet;\n if (!ratchet || !this.options.credentials.peerKey) return undefined;\n const supports = ratchet.peerSupports();\n return ratchet.box.on && supports ? \"on\" : !supports ? (ratchet.box.heardAny ? \"stopped\" : \"unsupported\") : \"starting\";\n }\n /**\n * Whether an envelope to `recipient` is sealed with the ratchet: the contact is pinned and its record lists\n * `ratchet/1`, or a ratcheted envelope of its was opened here, after which nothing goes plain (WISP 4xx § Downgrade).\n * And the contact pinned this side too (an envelope of its sealed to this side read, or a live session had): a joiner\n * pins its inviter from the invite, and its first contact sealed with the ratchet would reach an inviter that has no key\n * to open it with, and so never pins it.\n */\n private ratcheted(recipient: string | undefined): boolean {\n const ratchet = this.options.ratchet, peer = this.options.credentials.peerKey;\n if (!ratchet || !peer || recipient !== peer) return false;\n if (ratchet.box.heardAny) return true;\n return ratchet.peerSupports() && (!!this.state.peerPinned || !!this.state.wasLive);\n }\n /**\n * This side joined, and its inviter never answered (`DhtDeliveryState.unanswered`): no envelope of its newer than the\n * one that pinned it, none sealed to this side, no text confirmed, never live (as `sealedToAnother` asks too).\n */\n get unanswered(): boolean {\n const pinnedAt = this.state.unanswered;\n return pinnedAt !== undefined && this.state.peerSequence <= pinnedAt && !this.state.peerPinned && !this.state.confirmed && !this.state.wasLive && !this.live;\n }\n /**\n * Something signed by a participation key other than the pinned one came in over the chat's invite-derived keys (this\n * mailbox, the link's signals, a connection to an endpoint whose address a copy of the invite could read): ignored,\n * and said in the view as a passive warning.\n */\n foreignKeySeen(path: \"dht\" | \"signal\" | \"stream\"): void {\n const first = !this.foreignKeySeenAt;\n this.foreignKeySeenAt = Date.now();\n traceLink(this.from, \"foreign-key-ignored\", { path });\n if (first) this.changed();\n }\n /**\n * The mailboxes once the contact is pinned (WISP 403, revision 0.3): derived from the secret only the two\n * participation keys share, so a copy of the invite can neither publish there nor overwrite the contact's texts.\n */\n private pinned(): { identity: Identity; peerAddress: string } | undefined {\n const peerKey = this.options.credentials.peerKey;\n if (!peerKey) return undefined;\n if (this.pinnedBoxes?.peerKey !== peerKey) {\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.participation.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peerKey)));\n const derive = (label: string) => hkdf(sha256, shared, this.key, utf8Encode(`ghostly-dht-pinned-mailbox/1:${label}`), 32);\n this.pinnedBoxes = { peerKey, identity: identityFromSeed(derive(this.from)), peerAddress: identityFromSeed(derive(this.to)).pubKeyZ32 };\n }\n return this.pinnedBoxes;\n }\n private lastPublished?: DhtPacketFacts;\n /** The envelope a trace line was last said for, per step: a packet read again says nothing new (a Desktop logs every line). */\n private traced = new Map<string, string>();\n private traceOnce(step: string, record: string, detail: Record<string, unknown>): void {\n const seen = record.slice(-24);\n if (this.traced.get(step) === seen) return;\n this.traced.set(step, seen);\n traceLink(this.from, step, detail);\n }\n /** The sealed record's nonce is its first 24 bytes: 32 characters of base64. */\n private static facts(body: Body, records: GhostRecord[], key: string): DhtPacketFacts {\n return { ...(body[6] && { id: body[6][0] }), seq: body[1], issued: body[2], expires: body[3], packetBytes: measureRecords(key, records),\n nonce: records[0].value.slice(0, 32), recordKey: key, records: records.map(r => r.label) };\n }\n get comparisonCode(): string | undefined {\n if (!this.options.credentials.peerKey) return undefined;\n const digest = sha256(utf8Encode(JSON.stringify([\"ghostly-dht-comparison/1\", [this.from, this.to].sort(), [this.participation.pubKeyZ32, this.options.credentials.peerKey].sort()])));\n return Array.from(digest, b => b.toString(16).padStart(2, \"0\")).join(\"\").slice(0, 24).match(/.{4}/g)!.join(\" \");\n }\n get peerMode(): DeliveryMode | undefined { return this.state.peerMode; }\n private changed(): void { this.options.changed(this.view); }\n private serialize<T>(run: () => Promise<T>): Promise<T> {\n const operation = this.chain.then(run); this.chain = operation.then(() => {}, () => {}); return operation;\n }\n private async persist(next: DhtDeliveryState): Promise<void> {\n const json = JSON.stringify(next);\n if (json !== this.saved) { await this.options.save(structuredClone(next)); this.saved = json; }\n this.state = next;\n }\n /** The key an envelope between this side and `peer` is sealed with: the same for the same contact, so derived once. */\n private sealedKeys?: { peer: string; key: Uint8Array };\n private sealedKey(peer: string): Uint8Array {\n if (this.sealedKeys?.peer !== peer) {\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.participation.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peer)));\n this.sealedKeys = { peer, key: hkdf(sha256, shared, this.key, utf8Encode(\"ghostly-dht-participation-envelope/1\"), 32) };\n }\n return this.sealedKeys.key;\n }\n private signed(body: Body, recipient = \"invite\"): Uint8Array { return utf8Encode(JSON.stringify([\"ghostly-dht-envelope\", this.from, this.to, recipient, body])); }\n private records(body: Body, recipient = this.options.credentials.peerKey): GhostRecord[] { return this.envelope(body, recipient).records; }\n /**\n * Whether an envelope to `recipient` whose plaintext is this many bytes fits the packet: its size depends on the\n * length alone, so it is measured on a placeholder, with no signature, key or encryption.\n */\n private fits(bytes: number, recipient: string | undefined): boolean {\n if (bytes > MAX_ENVELOPE_PLAINTEXT) return false;\n const ratchet = this.ratcheted(recipient);\n const sealed = ratchet ? 4 * Math.ceil((RATCHET_OVERHEAD + bytes) / 3) : sealedLength(bytes);\n // The `_dmk` hint's value is the participation key sealed with the chat key: as long as any other one.\n const hint = recipient ? [{ label: \"_dmk\", value: \"A\".repeat(sealedLength(utf8Encode(this.participation.pubKeyZ32).length)), ttl: ENVELOPE_TTL }] : [];\n return measureRecords(this.identity.pubKeyZ32, [{ label: ratchet ? \"_dr\" : \"_dm\", value: \"A\".repeat(sealed), ttl: ENVELOPE_TTL }, ...hint]) <= ENVELOPE_PACKET_BYTES;\n }\n /**\n * Whether `body` fits an envelope to `recipient`, as `envelope` would find it, without building one: the signature is\n * always 86 characters of base64url.\n */\n private bodyFits(body: Body, recipient: string | undefined): boolean {\n return this.fits(utf8Encode(JSON.stringify([body, \"x\".repeat(86)])).length, recipient);\n }\n /**\n * The envelope's records. Ratcheted (`ratcheted`), its `_dr` record is the right length but not sealed yet: `seal`\n * gives its bytes, under the chat's lock, once the publication is sure to go. Measuring a packet takes no key.\n */\n private envelope(body: Body, recipient = this.options.credentials.peerKey): { records: GhostRecord[]; plaintext?: string } {\n const signature = toBase64Url(sign(this.signed(body, recipient), this.participation.seed));\n const plaintext = JSON.stringify([body, signature]);\n const hint = recipient ? [{ label: \"_dmk\", value: encrypt(this.participation.pubKeyZ32, this.key), ttl: ENVELOPE_TTL }] : [];\n const ratchet = this.ratcheted(recipient);\n const sealedBytes = (bytes: number) => ratchet ? 4 * Math.ceil((RATCHET_OVERHEAD + bytes) / 3) : sealedLength(bytes);\n const label = ratchet ? \"_dr\" : \"_dm\";\n const fits = (bytes: number) => this.fits(bytes, recipient);\n const bytes = utf8Encode(plaintext).length;\n if (!fits(bytes)) throw new Error(DHT_PACKET_BUDGET);\n // Padded with spaces up to the largest that fits, so a keep-alive is as long as a text. JSON allows spaces after the\n // value: readers from before read the envelope as ever.\n let padded = bytes;\n for (let step = 512; step >= 1; step >>= 1) if (fits(padded + step)) padded += step;\n const full = plaintext + \" \".repeat(padded - bytes);\n if (ratchet) return { records: [{ label, value: \"A\".repeat(sealedBytes(padded)), ttl: ENVELOPE_TTL }, ...hint], plaintext: full };\n return { records: [{ label, value: encrypt(full, recipient ? this.sealedKey(recipient) : this.key), ttl: ENVELOPE_TTL }, ...hint] };\n }\n /**\n * The records to publish: a ratcheted one sealed now, its state saved first (seal, save, send), from the plaintext\n * the envelope was measured with.\n */\n private async sealed(envelope: { records: GhostRecord[]; plaintext?: string }): Promise<GhostRecord[]> {\n const { records, plaintext } = envelope;\n if (records[0]?.label !== \"_dr\") return records;\n if (plaintext === undefined) throw new Error(\"A ratcheted envelope without its plaintext\");\n const sealed = await this.options.ratchet!.box.lock(tx => tx.seal(\"floor\", utf8Encode(plaintext)));\n return [{ ...records[0], value: toBase64(sealed) }, ...records.slice(1)];\n }\n async start(): Promise<void> {\n if (this.running) return; this.running = true;\n const quiet = this.options.credentials.peerKey ? this.options.firstControlAfterMs ?? 0 : 0;\n if (quiet > 0) {\n this.controlDue = Math.max(this.controlDue, Date.now() + quiet);\n this.controlTimer = setTimeout(() => { this.controlTimer = null; void this.serialize(async () => { try { await this.publish(); } catch { /* the next tick */ } }); }, quiet);\n }\n if (this.state.confirmed) await this.options.receipt(this.state.confirmed);\n // A chat with no pinned contact is read at the signaling pace only once the contact shows up (`expect`, from its\n // fresh presence packet): an invite nobody opened yet, or one warmed ahead of time, spends no relay budget.\n this.changed(); void this.tick();\n }\n async stop(): Promise<void> {\n this.running = false;\n if (this.timer) clearTimeout(this.timer);\n if (this.controlTimer) clearTimeout(this.controlTimer);\n if (this.announceTimer) clearTimeout(this.announceTimer);\n this.timer = this.controlTimer = this.announceTimer = null;\n countUnusedInvite(this.options.transport, this, false);\n await this.chain;\n }\n async setMode(mode: DeliveryMode): Promise<void> {\n await this.serialize(async () => {\n // Preserve accepted DHT intent, its stable ID and original expiry across mode changes.\n await this.persist({ ...this.state });\n // The contact learns the new method from the next envelope: it goes out now, not after the publish spacing.\n this.mode = mode; this.controlDue = 0; this.lastPublish = 0;\n this.leavingUntil = mode === \"stream\" ? Date.now() + LEAVING_DHT_FAST_MS : 0;\n // DHT only here: no live link waits on the contact leaving it. Leaving it while the contact still says DHT only:\n // the live link waits on a read saying it left too, its envelope maybe a moment away, and the first reads go as\n // signaling (`LEAVING_SIGNAL_READS`). As plain reads, an extension whose relay minute was spent read its contact's\n // mailbox once as it left, just before the contact's envelope saying it left too got there, and the next read\n // waited 41 s: it never dialled, and the matrix's chat stayed \"On DHT · retrying live\" for 45 s (E2E full, 2026-11-05).\n // The read at the switch itself is a plain one: the contact seldom left in the same instant, and that read, as\n // signaling, took one of the few requests past a spent minute that the dialling side's read for the answer needed\n // (it read the answer 31 s late). Held back, it costs nothing, and the next read, signaling, comes at the fast pace.\n if (mode === \"dht\") this.signalReads = 0;\n else if (this.state.peerMode === \"dht\") { this.signalReads = LEAVING_SIGNAL_READS; this.leavingRead = true; }\n // The envelope saying it left goes as signaling, within the chat's allowance past the minute, so a hold that plain\n // writes ran into before does not keep it. As a plain write, an extension back from Offline that had spent its\n // minute held it 55 s: the contact held the offer until it read it, and the matrix's chat stayed \"On DHT ·\n // retrying live\" for 45 s (E2E full, 2026-11-07 and 2026-11-08).\n this.leavingOut = mode === \"stream\";\n if (this.leavingOut) this.budgetUntil = 0;\n this.changed();\n });\n void this.tick();\n }\n /** Reads the contact's mailbox now: something says it may have changed its delivery method. */\n refresh(): void { this.urgent = true; void this.tick(); }\n /**\n * The device's network came back: a read or publication error from while it was away says nothing now (No Pkarr\n * relay reachable). It goes at once, and the mailbox is read now: one that still fails says so again.\n */\n networkBack(): void {\n this.networkBackAt = Date.now();\n if (!this.errors.read && !this.errors.publish) return;\n delete this.errors.read; delete this.errors.publish;\n this.changed();\n void this.tick();\n }\n /**\n * Reads the contact's mailbox at the signaling pace for a while (a fresh packet of a contact not pinned yet).\n * `signal`: the contact is leaving DHT only (a fresh packet on its link key, or its offer), and the live link waits\n * on a read to say so: the next read goes now, and it and the next ones while the contact still says DHT only\n * (`LEAVING_SIGNAL_READS` in all) are signaling (`PkarrRequestOptions.signal`).\n */\n expect(ms = 2 * 60_000, signal = false): void {\n const until = Date.now() + ms;\n if (signal) this.signalReads = LEAVING_SIGNAL_READS;\n if (until <= this.fastUntil && !signal) return;\n this.fastUntil = Math.max(this.fastUntil, until); this.urgent = true; void this.tick();\n }\n /**\n * A fresh link packet of a contact still saying DHT only (`expect`, signaling). Nothing signed says it is the contact's,\n * and one that stays on DHT only (or anyone holding the invite) can put one before every read: the reads it starts are\n * then held to a wait that doubles from `LEAVING_PROBE_GAP_MS` to `LEAVING_PROBE_MAX_GAP_MS`, and start over once the\n * contact says it left. False when held. Its offer, signed by its pinned key, is not held (`expect` directly).\n */\n peerLinkPacket(ms: number): boolean {\n const now = Date.now();\n // A clock stepped back would hold it past the wait: that wait is over.\n if (now < this.probeAt && this.probeAt - now <= this.probeGap) return false;\n this.probeGap = Math.min(this.probeGap * 2 || LEAVING_PROBE_GAP_MS, LEAVING_PROBE_MAX_GAP_MS);\n this.probeAt = now + this.probeGap;\n this.expect(ms, true);\n return true;\n }\n /**\n * Layer 1 carries the chat, or no longer does. While it does, the mailbox is read every 5 minutes, after one\n * last look as it goes live: a text the contact put on the DHT in the seconds before (after this side's last\n * read) would otherwise wait for the next look. That look is a background request, which yields to links that\n * signal, and only for a contact that wrote in this mailbox already. The moment layer 1 is lost, at once\n * (WISP 403, poll pace), and then at the chat's pace.\n */\n setLive(live: boolean): void {\n if (live === this.live) return;\n this.live = live;\n if (!live) { this.urgent = true; void this.tick(); return; }\n this.fastUntil = 0; this.signalReads = 0;\n // Remembered past this session, and whatever said the invite was taken was not the contact (`sealedToAnother`).\n if (this.options.credentials.peerKey && (!this.state.wasLive || this.state.inviteTaken)) void this.serialize(async () => {\n const taken = this.state.inviteTaken;\n if (taken) traceLink(this.from, \"invite-untaken\", {});\n const { inviteTaken: _taken, ...kept } = this.state;\n await this.persist({ ...kept, wasLive: true });\n if (taken) this.changed();\n }).catch(() => { /* a failed save: said again at the next session */ });\n if (this.options.credentials.peerKey && this.state.peerMode) void this.tick(); else this.schedule();\n }\n get isLive(): boolean { return this.live; }\n /** Someone else used the invite first (`DhtDeliveryState.inviteTaken`). */\n get inviteTaken(): boolean { return !!this.state.inviteTaken; }\n /** The chat is open with the app in front: on the DHT, its mailbox is read at the signaling pace. */\n setActive(active: boolean): void {\n if (active === this.active) return;\n this.active = active;\n if (active && !this.live) void this.tick(); else this.schedule();\n }\n /**\n * The device clock now, with every time this side set by it kept no further ahead than it is ever set (`bounded`).\n * The outbox times a text's receipt on a timer, which a step of the clock does not move; these times are judged by\n * the clock. Taken as they were, a clock set back an hour (or one an hour ahead set right) while a text awaited its\n * receipt held every later text of the chat for that hour though the outbox showed the text failed at five minutes,\n * the text was not published again meanwhile and the chat read every 4 s; and a contact away counted as there, its\n * mailbox read every 4 s for most of the hour (bug hunt, 2026-11-08). Kept so in memory; the next save writes them.\n */\n private clock(): number {\n const now = Date.now(), { pending, receipt } = this.state;\n if (pending && (pending.expires > now + DHT_MESSAGE_TTL || pending.next > now + BACKOFF_MAX_MS))\n this.state = { ...this.state, pending: { ...pending, expires: bounded(pending.expires, now, DHT_MESSAGE_TTL), next: bounded(pending.next, now, BACKOFF_MAX_MS) } };\n if (receipt && (receipt.expires > now + DHT_MESSAGE_TTL || (receipt.next ?? 0) > now + BACKOFF_MAX_MS))\n this.state = { ...this.state, receipt: { ...receipt, expires: bounded(receipt.expires, now, DHT_MESSAGE_TTL), ...(receipt.next !== undefined && { next: bounded(receipt.next, now, BACKOFF_MAX_MS) }) } };\n this.peerNewAt = bounded(this.peerNewAt, now); this.lastPublish = bounded(this.lastPublish, now);\n if (this.withdrawal) this.withdrawal = { ...this.withdrawal, until: bounded(this.withdrawal.until, now, DHT_MESSAGE_TTL + DHT_EXPIRY_SKEW_MS), next: bounded(this.withdrawal.next, now, BACKOFF_MAX_MS) };\n this.networkBackAt = bounded(this.networkBackAt, now); this.pinnedProbeAt = bounded(this.pinnedProbeAt, now);\n this.controlDue = bounded(this.controlDue, now, Math.max(4 * 60_000, UNUSED_INVITE_UPKEEP_MS, this.options.firstControlAfterMs ?? 0));\n this.budgetUntil = bounded(this.budgetUntil, now, BUDGET_HOLD_MAX_MS);\n this.leavingUntil = bounded(this.leavingUntil, now, LEAVING_DHT_FAST_MS);\n return now;\n }\n validate(text: string, timestamp: number, id: string, reply?: string, edit?: DhtEdit): string | null {\n // Every chat's first contact runs here too (WISP 403): before the pin the text is sealed with the invite key.\n if (this.options.peerAcceptsText?.() === false) return DHT_TEXT_REFUSED;\n // Forward secrecy was on, and the contact's app no longer says it has it: nothing goes plain (WISP 4xx § Downgrade).\n if (this.forwardSecrecy === \"stopped\") return DHT_RATCHET_STOPPED;\n if (!ID.test(id) || !Number.isSafeInteger(timestamp) || timestamp <= 0 || (reply !== undefined && !REPLY_TO.test(reply))) return \"Invalid message.\";\n if (edit !== undefined && (reply !== undefined || !ID.test(edit[0]) || !validEditNumber(edit[1]))) return \"Invalid message.\";\n if (utf8Encode(text).length > DHT_TEXT_BYTES) return DHT_TEXT_TOO_LONG;\n if (/cashu[AB][A-Za-z0-9_-]+/i.test(text)) return \"Payment tokens cannot be sent through DHT delivery.\";\n const now = this.clock(), pending = this.state.pending, mine = pending?.message[0] === id && pending.expires > now ? pending : undefined;\n const next = mine ?? { message: [id, timestamp, text] as Message, expires: now + DHT_MESSAGE_TTL, attempts: 0, next: now, ...(reply && { reply }), ...(edit && { edit }) };\n // Validate the complete encrypted DNS packet before accepting local intent. A text near the bound goes without the\n // id of the message it replies to when both do not fit: the text is what matters. An edit never goes without its\n // element: it would read as a new message. Asked before the one-at-a-time rule: a text the packet never carries,\n // though within 256 bytes, would otherwise wait behind the one awaiting its receipt, and then for good.\n const error = this.packetError(next.message, next.expires, next.reply, next.edit);\n const tooBig = error && next.reply ? this.packetError(next.message, next.expires) : error;\n if (tooBig) return tooBig;\n if (pending && pending.expires > now && !mine) return \"One DHT text can await a receipt at a time. Wait for its receipt or expiry before sending another.\";\n if (mine && mine.attempts >= MAX_ATTEMPTS) return \"DHT retry budget exhausted. Wait for expiry before retrying this message.\";\n return null;\n }\n /**\n * Measured, not built (`bodyFits`): the outbox asks it of every waiting text at each look, and a text that waits as no\n * relay takes it would cost a signature and a seal each time, for an answer that does not change.\n */\n private packetError(message: Message, expires: number, reply?: string, edit?: DhtEdit): string | null {\n const body = this.body(this.sequence + 1, Date.now(), expires, message, this.state.receipt?.id ?? \"abcdefghijklmnopqrstuv\", reply, [], edit);\n return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32) ? null : DHT_PACKET_BUDGET;\n }\n /** Whether a text with its hop count fits the packet and what a reader reads (`MAX_ENVELOPE_PLAINTEXT`). */\n private roomForHops(message: Message, expires: number, reply: string | undefined, forwarded: number): boolean {\n const body = this.body(this.sequence + 1, Date.now(), expires, message, this.state.receipt?.id ?? \"abcdefghijklmnopqrstuv\", reply, [], undefined, forwarded);\n return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);\n }\n /**\n * `forwarded`: a forwarded text's hop count (WISP 403 § Forwards). Like a reply's id it goes only when the packet has\n * room for it: the text is what matters, and it then reads as written here.\n */\n async send(text: string, timestamp: number, id: string, reply?: string, edit?: DhtEdit, forwarded?: number): Promise<string | null> {\n return this.serialize(async () => {\n this.wentNowhere.delete(id);\n const error = this.validate(text, timestamp, id, reply, edit);\n if (error) return error;\n const now = Date.now(), pending = this.state.pending;\n const hops = edit ? undefined : readForwarded(forwarded);\n // Already the floor's text: an earlier publication of it may be out.\n const again = pending?.message[0] === id && pending.expires > now;\n let next = again ? pending! : { message: [id, timestamp, text] as Message, expires: now + DHT_MESSAGE_TTL, attempts: 0, next: now, ...(reply && { reply }), ...(edit && { edit }), ...(hops && { forwarded: hops }) };\n if (next.forwarded && !this.roomForHops(next.message, next.expires, next.reply, next.forwarded)) { const { forwarded: _dropped, ...alone } = next; next = alone; }\n if (next.reply && this.packetError(next.message, next.expires, next.reply)) { const { reply: _dropped, ...alone } = next; next = alone; }\n await this.persist({ ...this.state, pending: next }); this.changed();\n if (this.withdrawalWaits()) { this.schedule(); return null; }\n // The next read comes at the pace for a text awaiting its receipt.\n try { await this.publish(true); this.schedule(); return null; }\n catch (error) {\n // Held back by the relays' request budget: the text is queued and goes as soon as the budget frees a request.\n if (isDiscoveryBudgetError(error)) { this.schedule(); return null; }\n this.errors.publish = `DHT publication failed: ${String(error instanceof Error ? error.message : error)}. Bounded retry continues until expiry.`;\n // No relay holds this text (each refused it or was not asked), and it was not out before: it has not left this\n // device. (An edit keeps the floor: nothing else sends it again.)\n // It leaves the floor, so nothing publishes it behind the sender's back; the sender sends it again in its turn,\n // or drops it (`wentNowhere`).\n if (!again && !edit && publishedNowhere(error) && this.state.pending?.message[0] === id) {\n await this.persist({ ...this.state, pending: undefined });\n this.wentNowhere.add(id);\n if (this.wentNowhere.size > 64) this.wentNowhere.delete(this.wentNowhere.values().next().value!);\n }\n this.changed(); return this.errors.publish;\n }\n });\n }\n /**\n * The last `send` of this id failed with no relay holding it, and it was not out before (`PublishFailedError`): it\n * never left this device, and is no longer the floor's to publish.\n */\n wentNowhereFor(id: string): boolean { return this.wentNowhere.has(id); }\n /**\n * The envelope a file's offer would go in, as `send` builds a text's: the most it can say that fits the packet and\n * what a reader reads (`MAX_ENVELOPE_PLAINTEXT`). Its meta goes first (a voice note's waveform thinned if it must),\n * then the reply's id, then the hop count; the name, size, type and id always. A string: why it cannot go.\n */\n private fileEnvelope(file: DhtFileOffer, timestamp: number, reply?: string, forwarded?: number): NonNullable<DhtDeliveryState[\"pending\"]> | string {\n if (!this.options.peerAcceptsFile?.()) return DHT_FILE_REFUSED;\n const id = dhtFileId(file.wireId);\n if (reply !== undefined && !REPLY_TO.test(reply)) reply = undefined;\n const error = this.validate(file.name, timestamp, id);\n if (error) return error === DHT_TEXT_TOO_LONG ? DHT_FILE_TOO_LARGE : error;\n const now = Date.now(), pending = this.state.pending;\n if (pending?.message[0] === id && pending.expires > now) return pending;\n const message: Message = [id, timestamp, file.name], expires = now + DHT_MESSAGE_TTL;\n const hops = readForwarded(forwarded);\n const fits = (element: DhtFileElement, withReply: boolean, withHops: boolean) => {\n const body = this.body(this.sequence + 1, now, expires, message, this.state.receipt?.id ?? \"abcdefghijklmnopqrstuv\", withReply ? reply : undefined, [], undefined, withHops ? hops : undefined, element);\n return this.bodyFits(body, this.options.credentials.peerKey ?? this.participation.pubKeyZ32);\n };\n const elements = dhtFileElements(file), bare = elements[elements.length - 1];\n const tries: [DhtFileElement, boolean, boolean][] = [...elements.map(e => [e, !!reply, !!hops] as [DhtFileElement, boolean, boolean]), [bare, !!reply, false], [bare, false, false]];\n const found = tries.find(([element, withReply, withHops]) => fits(element, withReply, withHops));\n if (!found) return DHT_FILE_TOO_LARGE;\n const [element, withReply, withHops] = found;\n return { message, expires, attempts: 0, next: now, file: element, ...(withReply && reply && { reply }), ...(withHops && hops && { forwarded: hops }) };\n }\n /** Why a file's offer cannot go on the floor now (WISP 403 § Files), or null when it can. */\n fileError(file: DhtFileOffer, timestamp: number, reply?: string, forwarded?: number): string | null {\n const envelope = this.fileEnvelope(file, timestamp, reply, forwarded);\n return typeof envelope === \"string\" ? envelope : null;\n }\n /**\n * Says a file's offer on the floor (WISP 403 § Files): its bubble takes its place on the contact's side, and its bytes\n * follow on the live session. It takes the floor's one slot as a text does, under `dhtFileId(wireId)`, with the same\n * retries and expiry; a receipt names that id. Null once it is the floor's pending envelope (a publication that\n * failed is retried, as a text's is).\n */\n async announceFile(file: DhtFileOffer, timestamp: number, reply?: string, forwarded?: number): Promise<string | null> {\n return this.serialize(async () => {\n const next = this.fileEnvelope(file, timestamp, reply, forwarded);\n if (typeof next === \"string\") return next;\n await this.persist({ ...this.state, pending: next }); this.changed();\n if (this.withdrawalWaits()) { this.schedule(); return null; }\n try { await this.publish(true); }\n catch (error) {\n if (!isDiscoveryBudgetError(error)) { this.errors.publish = `DHT publication failed: ${String(error instanceof Error ? error.message : error)}. Bounded retry continues until expiry.`; this.changed(); }\n }\n this.schedule();\n return null;\n });\n }\n /** Whether the floor holds this text of mine, or an edit of it (`pending`), whatever its retries or expiry. */\n holds(wireId: string): boolean {\n const pending = this.state.pending;\n return !!pending && (pending.message[0] === wireId || pending.edit?.[0] === wireId);\n }\n /**\n * A text of mine (or an edit of it) deleted here while it waits on the floor leaves it: the state no longer holds it\n * (nor as `confirmed`: no receipt came), and, while its envelope was still in effect, a new one without it takes that\n * one's place on the relays, so a contact who looks later finds no text. Resolves once the state without it is saved;\n * the new envelope goes after. One that does not go (no relay reachable) is tried again within seconds (`withdrawal`):\n * a reader takes the withdrawn envelope until its expiry and the clock skew allowed past it (`DHT_EXPIRY_SKEW_MS`).\n * It goes at once, spacing or not: the deleted text is out of reach from then on. The text that takes the floor next\n * waits out the spacing instead (`withdrawalWaits`).\n */\n async withdraw(wireId: string): Promise<void> {\n const expires = await this.serialize(async () => {\n const pending = this.state.pending;\n if (!pending || (pending.message[0] !== wireId && pending.edit?.[0] !== wireId)) return 0;\n await this.persist({ ...this.state, pending: undefined }); this.changed();\n return pending.attempts > 0 && pending.expires > this.clock() ? pending.expires : 0;\n });\n if (expires) void this.serialize(async () => {\n this.withdrawal = { until: expires + DHT_EXPIRY_SKEW_MS, attempts: 0, next: 0 };\n try { await this.publish(true); } catch { /* tried again with a text's backoff (`withdrawal`) */ }\n this.withdrewAt = this.lastPublish;\n this.schedule();\n });\n }\n /**\n * The last envelope was a withdrawal's, inside the publication spacing: the text that takes the floor now goes once\n * the spacing allows (`schedule`), not in an envelope of its own at once. Deleted then, it never went, so it costs\n * no withdrawal: deleting 10 texts queued for an away contact one after the other, each one's withdrawal and the next\n * text's envelope put 10 envelopes on every relay in under 2 s, each replaced a moment later (bug hunt, 2026-11-15).\n */\n private withdrawalWaits(): boolean {\n return this.withdrewAt === this.lastPublish && this.clock() - this.lastPublish < 4_000;\n }\n /** The id of what awaits its receipt on the floor now, if anything does. */\n get pendingId(): string | undefined {\n const now = this.clock(), pending = this.state.pending;\n return pending && pending.expires > now && pending.attempts < MAX_ATTEMPTS ? pending.message[0] : undefined;\n }\n /**\n * This side's capability record has a new revision (WISP 03): an envelope names it now. Otherwise the contact\n * learns of it with the next envelope that goes out anyway, a control one minutes away when nothing is sent,\n * and dials no native transport the record newly offers until then.\n */\n async announce(): Promise<void> {\n await this.serialize(async () => {\n // Every publication spends a relay request: none when the last envelope named this revision already.\n const rev = this.options.capsRev?.();\n if (rev === undefined || rev === this.namedRev) return;\n // An envelope went out a moment ago (a first contact's, as the link's transports are still coming up): this one\n // waits out the publication spacing and names the newest revision then, or none if the chat went live meanwhile\n // (a live session carries the news itself).\n const wait = this.lastPublish + 4_000 - this.clock();\n if (wait > 0) {\n this.announceTimer ??= setTimeout(() => { this.announceTimer = null; if (!this.live) void this.announce(); }, wait);\n return;\n }\n try { await this.publish(true); } catch { /* The next envelope names it. */ }\n });\n }\n /**\n * This side has reactions the contact has not confirmed (`reactions`): the next envelope carries them, and goes\n * as soon as the publication spacing allows.\n */\n async announceReactions(): Promise<void> {\n if (!this.options.reactions?.().length) return;\n this.reactionsDue = true; this.crowdedBy = undefined;\n await this.serialize(async () => { try { await this.publish(); } catch { /* the next envelope carries them */ } });\n if (this.reactionsDue) this.schedule();\n }\n /** A stream receipt for the same stable ID also cancels DHT retransmission. */\n async acknowledge(id: string): Promise<void> {\n await this.serialize(async () => {\n if (this.state.pending?.message[0] === id) await this.persist({ ...this.state, pending: undefined, confirmed: id });\n this.changed();\n });\n }\n private body(sequence: number, issued: number, expires: number, message: Message | null, receipt: string | null, reply?: string, reactions: readonly WireReaction[] = [], edit?: DhtEdit, forwarded?: number, file?: DhtFileElement): Body {\n const rev = this.options.capsRev?.();\n const body: Body = [1, sequence, issued, expires, this.participation.pubKeyZ32, this.mode, message, receipt];\n // Whether it has a revision to name or not, the ninth element holds the place of the tenth: this side uses the pinned mailbox.\n body.push(rev !== undefined && Number.isSafeInteger(rev) && rev >= 0 ? rev : null, this.state.peerPinned ? 2 : 1);\n const taken = this.state.reactionsTaken;\n const offer = message && !edit ? file : undefined;\n const hops = message && !edit ? readForwarded(forwarded) : undefined;\n // As far as the last element that says something; the ones before it hold their places with nothing to say.\n const last = offer ? 16 : hops ? 15 : reactions.length || taken ? 14 : message && edit ? 12 : message && reply ? 11 : 10;\n const tail = [message && reply ? reply : null, message && edit ? edit : null, reactions.map(r => [r.id, r.e, r.n] as DhtReaction), taken ?? null, hops ?? null, offer];\n body.push(...(tail.slice(0, last - 10) as []));\n return body;\n }\n /**\n * The envelope with as many of this side's pending reactions as fit, oldest first: the packet's budget and what a\n * reader reads (`MAX_ENVELOPE_PLAINTEXT`) both bound it. The contact confirms up to the newest it carried.\n */\n private fitted(sequence: number, issued: number, expires: number, message: Message | null, receipt: string | null, reply?: string, edit?: DhtEdit, forwarded?: number, file?: DhtFileElement): { body: Body; records: GhostRecord[]; plaintext?: string; reactions: number } {\n const pending = (this.options.reactions?.() ?? []).slice(0, REACTION_LIMITS.dht);\n for (let count = pending.length; count > 0; count--) {\n const body = this.body(sequence, issued, expires, message, receipt, reply, pending.slice(0, count), edit, forwarded, file);\n try {\n const envelope = this.envelope(body);\n if (utf8Encode(JSON.stringify([body, \"x\".repeat(86)])).length <= MAX_ENVELOPE_PLAINTEXT) return { body, ...envelope, reactions: count };\n } catch { /* one fewer */ }\n }\n const body = this.body(sequence, issued, expires, message, receipt, reply, [], edit, forwarded, file);\n return { body, ...this.envelope(body), reactions: 0 };\n }\n private async publish(force = false): Promise<void> {\n const now = this.clock();\n if (!this.running || (!force && (now - this.lastPublish < 4_000 || now < this.budgetUntil))) return;\n const pending = this.state.pending && this.state.pending.expires > now && this.state.pending.attempts < MAX_ATTEMPTS ? this.state.pending : undefined;\n const receipt = this.state.receipt && this.state.receipt.expires > now && this.state.receipt.attempts < MAX_ATTEMPTS ? this.state.receipt : undefined;\n // A receipt forces an envelope of its own only while the contact still asks for it, and with a text's backoff: the\n // envelope stays in the mailbox until the next one, and every publication spends a request on each relay.\n const receiptDue = !!receipt && !receipt.settled && (receipt.next ?? 0) <= now;\n const reseal = this.resealDue;\n // A withdrawal still to replace on the relays (`withdrawal`) is no keep-alive: it goes with its backoff, as a chat's write.\n const withdrawal = this.withdrawal && this.withdrawal.until > now && this.withdrawal.attempts < MAX_ATTEMPTS ? this.withdrawal : undefined;\n if (!withdrawal) this.withdrawal = undefined;\n const keepAlive = !force && (!pending || pending.next > now) && !receiptDue && !this.reactionsPress && !reseal && !(withdrawal && withdrawal.next <= now);\n // The invite was taken from this side: its mailbox is the joiner's every copy of the invite derives, and a keep-alive\n // there would only cover the envelope of whoever joined first. Nothing goes until the invite turns out not taken, a\n // look-up that pinned the inviter first or not: pinned, the keep-alive went every 4-6 minutes for good (agents#1592).\n if (keepAlive && (this.controlDue > now || this.state.inviteTaken)) return;\n // Dated back (`DHT_ISSUED_BACK_MS`), and a control envelope's lifetime with it: a reader bounds `expires - issued`.\n const expires = pending?.expires ?? now - DHT_ISSUED_BACK_MS + CONTROL_TTL;\n const issued = Math.min(now, Math.max(now - DHT_ISSUED_BACK_MS, expires - (pending ? DHT_MESSAGE_TTL : CONTROL_TTL), (pending?.message[1] ?? 0) - 30_000));\n // In the pinned mailbox once the contact said it reads there; until then where an older app looks.\n // The one that replaces an unsealed envelope goes where that lies.\n const identity = (!reseal && this.state.peerPinned && this.state.peerPinned !== \"can\" && this.pinned()?.identity) || this.identity;\n // Only the keep-alive is due while layer 1 carries the chat: upkeep nobody waits on, a background write (as the\n // link's heartbeat, `LinkSession.publishOnce`), so a profile's live chats never take the requests its groups need.\n // So is it while the contact, pinned, is away (nothing new from it in `PRESENCE_WINDOW`); not an envelope a first\n // contact waits for. As a chat's write, which goes first\n // once refused, the keep-alives of 200 chats whose contacts were away held back every read on one relay, and most\n // of those contacts were not read once in 25 minutes (bug hunt, 2026-11-01).\n const away = !!this.options.credentials.peerKey && now - this.peerNewAt >= PRESENCE_WINDOW;\n // The envelope saying this side left DHT only is signaling (`leavingOut`), never upkeep.\n const options = this.leavingOut ? { signal: true } : keepAlive && (this.live || away) ? { background: true } : undefined;\n // No relay takes it now: refused before it is signed and encrypted, its sequence set aside or a ratchet key taken\n // (`LinkSession.publishOnce`). With 500 contacts away, about 500 envelopes a minute were built for none that went.\n const held = this.options.transport.publishHeld?.(identity.pubKeyZ32, options);\n if (held) { await this.heldBack(held, now, { lastPublish: this.lastPublish, controlDue: this.controlDue }, undefined, undefined); throw held; }\n // Counted before the state is saved and the envelope sealed, as a text's attempt is: one that fails there waits its\n // backoff too, not the next timer turn (each one a read of the mailbox and a view update).\n if (withdrawal) this.withdrawal = { ...withdrawal, attempts: withdrawal.attempts + 1, next: now + backoff(withdrawal.attempts) };\n const fittedEnvelope = this.fitted(this.sequence + 1, issued, expires, pending?.message ?? null, receipt?.id ?? null, pending?.reply, pending?.edit, pending?.forwarded, pending?.file);\n const { body, reactions } = fittedEnvelope;\n const reactionsWereDue = this.reactionsDue;\n // A text that left no room: the reactions go on the next envelope. Once some went, the rest wait for the contact\n // to say those were taken (the engine announces the rest then).\n this.reactionsDue = !reactions && !!this.options.reactions?.().length;\n this.crowdedBy = this.reactionsDue && pending ? pending.message[0] : undefined;\n // Persist the sequence (set aside, a block at a time) and attempt count first. A crash cannot reuse them or\n // reset the retransmission budget/absolute message deadline.\n const sequence = body[1];\n await this.persist({ ...this.state, sequence: sequence > this.state.sequence ? sequence + SEQUENCE_BLOCK - 1 : this.state.sequence,\n pending: pending ? { ...pending, attempts: pending.attempts + 1, next: now + backoff(pending.attempts) } : this.state.pending,\n receipt: receipt ? { ...receipt, attempts: receipt.attempts + 1, next: now + backoff(receipt.attempts) } : this.state.receipt });\n this.sequence = sequence;\n // Ratcheted, the envelope is sealed only now, with the sequence saved: a key is never taken for one that does not go.\n const records = await this.sealed(fittedEnvelope);\n const before = { lastPublish: this.lastPublish, controlDue: this.controlDue };\n // An unused invite of this side's, no longer awaited: nobody reads this mailbox yet, so its keep-alive waits longer.\n // Not a joined chat's: an inviter that comes back reads the joiner's envelope to find it.\n const ownInvite = !this.options.credentials.expectedPeerKey && !this.active && this.unusedInviteAge(now) !== undefined;\n this.lastPublish = now; this.controlDue = now + (ownInvite ? UNUSED_INVITE_UPKEEP_MS : 4 * 60_000);\n traceLink(this.from, \"dht-publish\", { mode: this.mode, seq: body[1], ...(identity !== this.identity && { pinned: true }), ...(records[0]?.label === \"_dr\" && { ratchet: true }) });\n if (pending) this.lastPublished = DhtDelivery.facts(body, records, identity.pubKeyZ32);\n try { await this.options.transport.publish(identity, records, options); }\n catch (error) {\n this.reactionsDue ||= reactionsWereDue;\n // Held back by the budget, it was no attempt: it goes when the budget frees a request.\n if (isDiscoveryBudgetError(error)) { if (withdrawal) this.withdrawal = withdrawal; await this.heldBack(error, now, before, pending, receipt); }\n throw error;\n }\n this.withdrawal = undefined;\n this.namedRev = body[8] ?? undefined;\n if (options?.signal) this.leavingOut = false;\n if (identity === this.identity) this.unsealedOut = !this.options.credentials.peerKey;\n delete this.errors.publish; this.changed();\n }\n /** The contact is pinned and this side's envelope in the invite's mailbox is still unsealed (`unsealedOut`). */\n private get resealDue(): boolean { return this.unsealedOut && !!this.options.credentials.peerKey; }\n /**\n * Reactions due (`reactionsDue`) that force an envelope of their own: not while the text that left them no room\n * (`crowdedBy`) is still retried, or each publication spends one of its attempts 4 s apart instead of at its backoff.\n */\n private get reactionsPress(): boolean {\n const pending = this.state.pending, now = Date.now();\n return this.reactionsDue && !(pending && pending.message[0] === this.crowdedBy && pending.expires > now && pending.attempts < MAX_ATTEMPTS);\n }\n /**\n * The relays' request budget held the envelope back: nothing went out, so it was no attempt (a text keeps its eight),\n * and what it carried (a text, a receipt, a new mode) goes the moment the budget frees a request: the text and the\n * receipt as they were before, and no publication before then (`budgetUntil`) but a forced one.\n */\n private async heldBack(error: Parameters<typeof budgetRetryMs>[0], now: number, before: { lastPublish: number; controlDue: number },\n pending: DhtDeliveryState[\"pending\"], receipt: DhtDeliveryState[\"receipt\"]): Promise<void> {\n const at = now + budgetRetryMs(error, 1_000, BUDGET_HOLD_MAX_MS);\n this.budgetUntil = at;\n this.lastPublish = before.lastPublish; this.controlDue = Math.min(before.controlDue, at);\n traceLink(this.from, \"dht-publish-waits\", { retryInMs: at - now });\n // Held back before it was built, nothing was counted: no save.\n if (pending || receipt) await this.persist({ ...this.state, pending: pending ?? this.state.pending, receipt: receipt ?? this.state.receipt });\n }\n /**\n * One packet from one of the contact's mailboxes, opened and checked the way `receive` takes it: the right address,\n * one sealed record, a well-formed body within its times, signed by the key it names. Null: not an envelope of the\n * contact's (the pin rules are the caller's).\n */\n private open(packet: SignedPacket, box: \"invite\" | \"pinned\", ratchet?: (sealed: Uint8Array) => Uint8Array | null) {\n const address = box === \"pinned\" ? this.pinned()?.peerAddress : this.peerAddress;\n if (!address || packet.pubKeyZ32 !== address || measureRecords(packet.pubKeyZ32, packet.records) > MAX_DNS_PACKET_BYTES) return null;\n const records = packet.records.filter(r => r.label === \"_dm\"), ratcheted = packet.records.filter(r => r.label === \"_dr\");\n if (records.length + ratcheted.length !== 1) return null;\n const hints = packet.records.filter(r => r.label === \"_dmk\"); if (hints.length > 1) return null;\n const sender = hints.length ? tryDecrypt(hints[0].value, this.key) : null;\n if (hints.length && !sender) return null;\n const peer = this.options.credentials.peerKey;\n let plaintext: string | null;\n if (ratcheted.length) {\n // Ratcheted (WISP 4xx): only the pinned contact seals one, to this side. One that does not open in the invite's\n // mailbox is sealed to someone else, as a plain one below; in the pinned mailbox it says the contact pinned this side.\n const closed = box === \"invite\" && sender ? { sealedToAnother: sender } : null;\n if (!ratchet || !peer || sender !== peer) return closed;\n let opened: Uint8Array | null;\n try { opened = ratchet(fromBase64(ratcheted[0].value)); } catch { opened = null; }\n if (!opened) return closed;\n try { plaintext = utf8Decode(opened); } catch { return null; }\n } else {\n // A ratcheted envelope of the contact's opened here: a plain one from it is refused from then on (WISP 4xx § Downgrade).\n if (peer && this.options.ratchet?.box.heard(\"floor\") && (!sender || sender === peer)) { this.traceOnce(\"dht-plain-refused\", records[0].value, { box }); return null; }\n try { plaintext = tryDecrypt(records[0].value, sender ? this.sealedKey(sender) : this.key); } catch { plaintext = null; }\n // Sealed, by its hint, from `sender` to a key other than this side's: nothing to read, but who it names says something.\n if (!plaintext && sender) return { sealedToAnother: sender };\n }\n if (!plaintext || utf8Encode(plaintext).length > MAX_ENVELOPE_PLAINTEXT) return null;\n let envelope: unknown; try { envelope = JSON.parse(plaintext); } catch { return null; }\n if (!Array.isArray(envelope) || envelope.length !== 2 || !Array.isArray(envelope[0])) return null;\n const [body, signature] = envelope as [Body, string];\n const [version, sequence, issued, expires, author, mode, message, receipt, capsRev, pinnedMailbox, replyTo, editOf, reactions, reactionsTaken, forwarded, file] = body;\n const now = Date.now();\n if (body.length < 8 || body.length > 16 || version !== 1 || !Number.isSafeInteger(sequence) || sequence < 1 || !Number.isSafeInteger(issued) ||\n !Number.isSafeInteger(expires) || expires - issued > CONTROL_TTL || issued >= expires ||\n (mode !== \"stream\" && mode !== \"dht\") || typeof author !== \"string\" || typeof signature !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(signature)) return null;\n // Past its expiry by more than two clocks differ (`DHT_EXPIRY_SKEW_MS`).\n const expired = expires + DHT_EXPIRY_SKEW_MS <= now;\n if (sender && sender !== author) return null;\n try {\n if (!verify(fromBase64Url(signature), utf8Encode(JSON.stringify([\"ghostly-dht-envelope\", this.to, this.from, sender ? this.participation.pubKeyZ32 : \"invite\", body])), publicKeyFromZ32(author))) return null;\n } catch { return null; }\n if (expired) {\n // Said once per envelope, and only of one its author signed: it stays in the mailbox.\n if (this.expiredSeen !== sequence) { this.expiredSeen = sequence; traceLink(this.from, \"dht-envelope-expired\", { seq: sequence, lateMs: now - expires }); }\n return null;\n }\n return { body, sender, author, sequence, issued, expires, mode, message, receipt, capsRev, pinnedMailbox, replyTo, editOf, reactions, reactionsTaken, forwarded, file };\n }\n /**\n * The contact's envelope is sealed to another key (`open`): it pinned someone else who used the same invite first, so\n * nothing of this side's will ever be read. Said only while this side is not proven the one it pinned: no envelope\n * sealed to this side read (`peerPinned`), no text confirmed, never live (`wasLive`). The hint is sealed under the\n * invite's key, which any copy of it holds, so past that proof it says nothing of the contact: a passive warning,\n * taken back by the contact's next envelope that opens here, or by a live session.\n */\n private async sealedToAnother(sender: string): Promise<void> {\n const expected = this.options.credentials.peerKey ?? this.options.credentials.expectedPeerKey;\n if (this.state.inviteTaken || !expected || sender !== expected) return;\n if (this.state.peerPinned || this.state.confirmed || this.state.wasLive || this.live) return;\n traceLink(this.from, \"invite-taken\", {});\n // Nothing is awaited from that contact now: the first contact's fast reads end here.\n this.fastUntil = 0;\n await this.persist({ ...this.state, inviteTaken: true });\n this.changed();\n }\n /**\n * One packet from one of the contact's two mailboxes: `invite` (derived from the invite, which anyone holding a copy\n * can write to) or `pinned`. `none`: nothing from the contact in it; `old`: the contact's, already read; `new`: taken.\n */\n private async receive(packet: SignedPacket, box: \"invite\" | \"pinned\"): Promise<\"none\" | \"old\" | \"new\"> {\n const ratcheted = packet.records.find(r => r.label === \"_dr\");\n if (!ratcheted) return this.take(packet, box, this.open(packet, box));\n // The same ratcheted envelope read again: its key is gone, and it was taken (WISP 4xx § The DHT floor).\n const digest = toBase64Url(sha256(utf8Encode(ratcheted.value)).slice(0, 16));\n if (digest === this.state.lastDr) return \"old\";\n const ratchet = this.options.ratchet;\n if (!ratchet) return \"none\";\n // Opened with no lock held, stored, and only then the ratchet's state saved, under the chat's lock, on the state as it\n // is by then (`RatchetBox.commitOpen`): what the content goes to may seal or open a held item, which takes that lock.\n let sealed: Uint8Array | undefined;\n const opened = this.open(packet, box, bytes => { const plain = ratchet.box.peek(\"floor\", bytes); if (plain) sealed = bytes; return plain; });\n // Ratcheted, and not opened here: not for this side, from a session it lost, or before it pinned the contact.\n if (!sealed) this.traceOnce(\"dht-ratchet-closed\", ratcheted.value, { box, pinned: !!this.options.credentials.peerKey });\n // Not opened here, but in the pinned mailbox, whose address only the two participation keys give: the contact pinned\n // this side. A side restored from a backup made before it knew that learns it here, and its next envelope starts a\n // session the contact follows, rather than going plain to a contact that refuses plain.\n if (!sealed && box === \"pinned\" && packet.pubKeyZ32 === this.pinned()?.peerAddress && this.state.peerPinned !== \"seen\") {\n await this.persist({ ...this.state, peerPinned: \"seen\" });\n traceLink(this.from, \"dht-peer-pinned\", { peerPinned: \"seen\", ratchet: true });\n }\n return this.take(packet, box, opened, sealed && { commit: async order => { if (!await ratchet.box.commitOpen(\"floor\", sealed!, order)) throw new Error(\"A ratcheted envelope no longer opens\"); }, digest });\n }\n /** `ratchet`: the envelope was ratcheted; its state is saved once what it carried is stored, with its digest. */\n private async take(packet: SignedPacket, box: \"invite\" | \"pinned\", opened: ReturnType<DhtDelivery[\"open\"]>, ratchet?: { commit(order?: number): Promise<void>; digest: string }): Promise<\"none\" | \"old\" | \"new\"> {\n if (!opened) return \"none\";\n if (\"sealedToAnother\" in opened) { if (opened.sealedToAnother) await this.sealedToAnother(opened.sealedToAnother); return \"none\"; }\n const { body, sender, author, sequence, issued, expires, mode, message, receipt, capsRev, pinnedMailbox, replyTo, editOf, reactions, reactionsTaken, forwarded, file } = opened;\n // Before the pin, the key the invite named: another invite holder's envelope is refused, and not remembered,\n // since whoever holds a copy can write to this mailbox and the inviter's next envelope replaces it.\n if (!this.options.credentials.peerKey && this.options.credentials.expectedPeerKey && this.options.credentials.expectedPeerKey !== author) return \"none\";\n // After it, the same: this mailbox's key comes from the invite, so another key signing here proves only that someone\n // holds a copy of it. Ignored, never a reason to stop the chat; a key change is proven only on a stream (WISP 400).\n if (this.options.credentials.peerKey && this.options.credentials.peerKey !== author) { this.foreignKeySeen(\"dht\"); return \"none\"; }\n // How far the contact is in the pinned mailbox: only an envelope sealed to this side says it (the contact pinned this\n // side, so it can derive the mailbox), and it only goes forward.\n const peerPinned = box === \"pinned\" ? \"seen\" : !sender ? this.state.peerPinned\n : pinnedMailbox === 2 && this.state.peerPinned !== \"seen\" ? \"reads\" : this.state.peerPinned ?? (pinnedMailbox === 1 ? \"can\" : undefined);\n if (sequence <= this.state.peerSequence) {\n if (peerPinned !== this.state.peerPinned && this.options.credentials.peerKey) {\n await this.persist({ ...this.state, peerPinned }); traceLink(this.from, \"dht-peer-pinned\", { peerPinned }); this.changed();\n }\n return \"old\";\n }\n if (message !== null && (!Array.isArray(message) || message.length !== 3 || typeof message[0] !== \"string\" || !ID.test(message[0]) || !Number.isSafeInteger(message[1]) || message[1] <= 0 || message[1] > issued + 30_000 ||\n typeof message[2] !== \"string\" || utf8Encode(message[2]).length > DHT_TEXT_BYTES || expires - issued > DHT_MESSAGE_TTL)) return \"none\";\n if (receipt !== null && (typeof receipt !== \"string\" || !ID.test(receipt))) return \"none\";\n // A joiner pinning its inviter from the envelope the inviter put out before anyone joined: that says nothing of the\n // inviter being there, whose chat may be deleted or its app gone (bug hunt 1014-0136).\n const unanswered = !this.options.credentials.peerKey && !!this.options.credentials.expectedPeerKey && !sender && !this.live;\n this.peerNewAt = Date.now();\n await this.options.pin(author); this.options.credentials.peerKey = author; this.options.credentials.requireSignedSignals = true;\n // Store content before advancing anti-replay state. Retrying after a crash\n // is safe because the durable message table deduplicates the stable ID.\n let nextReceipt = this.state.receipt;\n if (message) {\n // The text this side owes a receipt for was stored already (the receipt is saved only after it): a retransmission\n // that crossed the receipt, or the same envelope moved to the pinned mailbox, is not handed over twice.\n // A reply's id that is not one is dropped, never the text (readers from before ignore the element).\n const reply = typeof replyTo === \"string\" && REPLY_TO.test(replyTo) ? { reply: { i: replyTo } } : {};\n // An edit's element that is not one leaves a text of its own, as an app from before edits reads it.\n const edit = Array.isArray(editOf) && editOf.length === 2 && typeof editOf[0] === \"string\" && ID.test(editOf[0]) && validEditNumber(editOf[1]) ? { edit: { i: editOf[0], e: editOf[1] } } : {};\n // A hop count that is not one, or one on an edit, is dropped: the text reads as written here.\n // Owed for as long as the text had left when its envelope was made, counted on this clock: `expires` is the sender's.\n const hops = edit.edit ? undefined : readForwarded(forwarded);\n // A file's offer (WISP 403 § Files) is a bubble whose bytes follow live. One that does not hold is dropped, and\n // receipted like any text: its name is never shown as a text (its file comes live anyway).\n const offer = file === undefined || file === null ? undefined : edit.edit ? null : readDhtFile(file, message);\n if (nextReceipt?.id !== message[0] && offer !== null) await this.options.message({ id: message[0], timestamp: message[1], text: message[2], ...reply, ...edit, ...(hops && { forwarded: hops }), ...(offer && { file: offer }) }, DhtDelivery.facts(body, packet.records, packet.pubKeyZ32));\n if (nextReceipt?.id !== message[0]) nextReceipt = { id: message[0], expires: Date.now() + Math.min(DHT_MESSAGE_TTL, expires - issued), attempts: 0 };\n // Asked for again (the text sent anew after a lost session): its receipt goes at once again.\n else if (nextReceipt.settled) { const { settled: _settled, next: _next, ...asked } = nextReceipt; nextReceipt = asked; }\n } else if (nextReceipt && !nextReceipt.settled) nextReceipt = { ...nextReceipt, settled: true };\n // The contact's reactions, each checked on its own (what does not hold is skipped, never the envelope), and the\n // highest number taken, which every envelope of this side says back; one carrying only what was taken asks again.\n const theirs = this.options.reaction ? readDhtReactions(reactions) : [];\n for (const reaction of theirs) await this.options.reaction?.(reaction);\n const newest = theirs.reduce((max, r) => Math.max(max, r.n), 0);\n if (theirs.length) { this.reactionsDue = true; this.crowdedBy = undefined; }\n const confirmed = receipt && this.state.pending?.message[0] === receipt ? receipt : this.state.confirmed;\n if (mode !== this.state.peerMode) traceLink(this.from, \"dht-peer-mode\", { peerMode: mode });\n if (peerPinned !== this.state.peerPinned) traceLink(this.from, \"dht-peer-pinned\", { peerPinned });\n // A newer envelope of the contact's that opens here: whatever said the invite was taken was not the contact.\n if (this.state.inviteTaken) traceLink(this.from, \"invite-untaken\", {});\n const { inviteTaken: _taken, ...kept } = this.state;\n // The contact's own sequence orders its sessions (WISP 4xx § Sessions).\n if (ratchet) await ratchet.commit(sequence);\n await this.persist({ ...kept, peerSequence: sequence, peerMode: mode, receipt: nextReceipt, confirmed, ...(peerPinned && { peerPinned }), ...(unanswered && { unanswered: sequence }), ...(ratchet && { lastDr: ratchet.digest }),\n pending: confirmed && this.state.pending?.message[0] === confirmed ? undefined : this.state.pending,\n ...(newest > (this.state.reactionsTaken ?? 0) && { reactionsTaken: newest }) });\n if (confirmed) await this.options.receipt(confirmed);\n if (validReactionNumber(reactionsTaken)) await this.options.reactionsTaken?.(reactionsTaken);\n if (Number.isSafeInteger(capsRev) && (capsRev as number) >= 0) this.options.peerCapsRev?.(capsRev as number);\n this.changed();\n return \"new\";\n }\n /**\n * Reads the contact's mailbox: the pinned one first once the contact said it can use it, the invite's otherwise. The\n * other is read too when the first held nothing from the contact (the contact publishes in the other one still, or a\n * copy of the invite overwrote this one), or when the contact just said it can use the pinned one. Once the contact's\n * envelope was seen in the pinned mailbox, the invite's is not read any more.\n */\n private async read(background: boolean, signal = false): Promise<void> {\n // A contact on DHT only, this side not: its envelope saying it left is what the live link waits on, read like a\n // contact that went away (`PkarrRequestOptions.departed`, `departedRead`).\n const departed = !signal && !background && this.departedRead();\n const pinned = this.pinned(), options = signal ? { signal } : background ? { background } : departed ? { departed } : undefined;\n const before = this.state.peerPinned;\n const boxes: (\"invite\" | \"pinned\")[] = !pinned ? [\"invite\"] : before === \"seen\" ? [\"pinned\"] : before ? [\"pinned\", \"invite\"] : [\"invite\", \"pinned\"];\n let found: SignedPacket | null = null;\n for (const [i, box] of boxes.entries()) {\n if (i > 0 && box === \"pinned\") {\n // The contact just said it can use it: looked in at once. Otherwise a probe, when the invite's mailbox held a\n // packet but nothing from the contact, now and then; never while the invite is taken (that packet is the contact's,\n // sealed to another: had it pinned this side, it would open here).\n if (!this.state.peerPinned && (!found || this.state.inviteTaken || Date.now() - this.pinnedProbeAt < PINNED_PROBE_MS)) return;\n if (!this.state.peerPinned) this.pinnedProbeAt = Date.now();\n }\n const address = box === \"pinned\" ? pinned!.peerAddress : this.peerAddress;\n let packet: SignedPacket | null;\n try { packet = found = await this.options.transport.resolve(address, options); }\n finally { this.readHeld(this.options.transport.readHeldBackFor?.(address)); }\n if (!this.running) return;\n const got = packet ? await this.receive(packet, box) : \"none\";\n if (got !== \"none\" && !(box === \"invite\" && !before && this.state.peerPinned)) return;\n }\n }\n /**\n * A look at this chat from another profile of the device while this one is not running (WISP 04 § Checking other\n * profiles): the mailbox the chat reads first, opened and checked as `receive` does, with nothing saved, pinned or\n * published. It tells only whether the contact's envelope carries a text this side has not taken yet, and that text's\n * id; the words are dropped unread. `reads`: requests spent. Null `text`: nothing new, or nothing of the contact's.\n */\n async peek(options?: PkarrRequestOptions): Promise<{ reads: number; text: string | null }> {\n const expected = this.options.credentials.peerKey ?? this.options.credentials.expectedPeerKey;\n if (!expected) return { reads: 0, text: null };\n const pinned = this.pinned(), before = this.state.peerPinned;\n const boxes: (\"invite\" | \"pinned\")[] = !pinned || !before ? [\"invite\"] : before === \"seen\" ? [\"pinned\"] : [\"pinned\", \"invite\"];\n let reads = 0;\n for (const box of boxes) {\n const packet = await this.options.transport.resolve(box === \"pinned\" ? pinned!.peerAddress : this.peerAddress, options);\n reads++;\n const dr = packet?.records.find(r => r.label === \"_dr\");\n if (dr && toBase64Url(sha256(utf8Encode(dr.value)).slice(0, 16)) === this.state.lastDr) return { reads, text: null };\n const opened = packet && this.open(packet, box, sealed => this.options.ratchet?.box.peek(\"floor\", sealed) ?? null);\n if (!opened || \"sealedToAnother\" in opened || opened.author !== expected) continue;\n const { sequence, message } = opened;\n const fresh = Array.isArray(message) && typeof message[0] === \"string\" && ID.test(message[0]) && sequence > this.state.peerSequence && this.state.receipt?.id !== message[0];\n return { reads, text: fresh ? message[0] : null };\n }\n return { reads, text: null };\n }\n private async tick(): Promise<void> {\n if (!this.running) return;\n // A read asked for during one in flight happens right after it: its answer may predate the reason.\n if (this.ticking) { this.tickAgain = true; return; }\n this.ticking = true; this.tickAgain = false;\n if (this.timer) clearTimeout(this.timer); this.timer = null;\n try { await this.serialize(async () => {\n if (!this.running) return;\n // Only the slow, periodic looks (every 5 minutes while live, every 30 s for a chat in the background) are\n // background requests, served from the relays' background share; a chat on screen, a first contact, DHT\n // only with the contact there, a drop or a text awaiting its receipt reads as signaling. The share also carries held items'\n // pointers, which a busy mailbox must not starve.\n const background = !this.urgent && this.pollMs >= STREAM_POLL_MS;\n const signal = this.signalReads > 0 && !this.leavingRead;\n this.urgent = false; this.leavingRead = false; if (signal) this.signalReads--;\n // A read or a publication the relays' request budget held back is a wait, not an error: it goes when the budget frees.\n // One that started before the network came back failed for want of it (`networkBack`): the read after it says.\n // An inviter's first envelope, before anyone is pinned, goes before the read: the joiner dials only once it read it, and\n // the read (2 s on the DHT for a key nobody wrote yet) can add nothing to it. Every other envelope follows the read,\n // which may pin the contact (the envelope is sealed to it) or take a text (it carries the receipt).\n if (!this.options.credentials.peerKey && !this.options.credentials.expectedPeerKey && !this.state.sequence) await this.publishOnTick();\n const readAt = Date.now();\n this.readHeldUntil = 0;\n try { await this.read(background, signal); if (!this.running) return; delete this.errors.read; }\n catch (error) { if (isDiscoveryBudgetError(error)) this.readHeld(error.retryInMs); else if (readAt >= this.networkBackAt) this.errors.read = `Could not read DHT delivery: ${error instanceof Error ? error.message : String(error)}`; }\n // A signaling read the budget held back asked nothing of the relays: it is not one of the few, and goes again\n // when the budget frees a request (`schedule`). Counted, a read held by a refused write's turn (`WRITE_FIRST_MS` in\n // relay.ts) used them up, and the next ones, plain reads, waited out the minute.\n if (signal && this.readHeldUntil > 0) this.signalReads++;\n // The contact says it left DHT only: nothing waits on its mailbox any more.\n if (this.state.peerMode !== \"dht\") { this.signalReads = 0; this.probeAt = this.probeGap = 0; }\n await this.publishOnTick();\n this.changed();\n });\n } finally { this.ticking = false; }\n if (!this.running) return;\n if (this.tickAgain) { void this.tick(); return; }\n this.schedule();\n }\n /** The budget held a read back for `ms` (`readHeldUntil`); the soonest of the reads of one tick wins. */\n private readHeld(ms: number | undefined): void {\n if (ms === undefined || !Number.isFinite(ms) || ms <= 0) return;\n const at = Date.now() + ms;\n this.readHeldUntil = this.readHeldUntil > Date.now() ? Math.min(this.readHeldUntil, at) : at;\n }\n private async publishOnTick(): Promise<void> {\n const publishAt = Date.now();\n try { await this.publish(); }\n catch (error) { if (!isDiscoveryBudgetError(error) && publishAt >= this.networkBackAt) this.errors.publish = `Could not publish DHT delivery: ${error instanceof Error ? error.message : String(error)}`; }\n }\n /** How long until the next read of the contact's mailbox (WISP 403, poll pace). */\n get pollMs(): number {\n if (this.options.pollMs) return this.options.pollMs;\n const taken = this.takenInviteWait();\n if (taken !== undefined) return taken;\n const now = this.clock();\n // An invite nobody used, no longer awaited: the older it is, the less often its mailbox is read, as far as their count needs.\n const unused = this.running ? this.unusedInviteAge(now) : undefined;\n const readers = countUnusedInvite(this.options.transport, this, unused !== undefined && !this.active && now >= this.fastUntil);\n if (unused !== undefined && !this.active && now >= this.fastUntil) return unusedInviteWait(unused, this.mode === \"dht\" ? DHT_POLL_MS : STREAM_POLL_MS, readers);\n if ((this.mode === \"dht\" && !this.dhtOnlyIdle(now)) || (this.state.peerMode === \"dht\" && now < this.leavingUntil) || now < this.fastUntil) return DHT_POLL_MS;\n if (this.live) return LIVE_POLL_MS;\n // Our text awaits its receipt: the receipt is what the person is looking at.\n if (this.state.pending && this.state.pending.expires > now) return DHT_POLL_MS;\n if (this.active) return ACTIVE_DHT_POLL_MS;\n // A contact that chose DHT only, read where every chat is open (a daemon): its texts come in seconds, not at 30 s.\n // Only while it is there (an envelope of its own in this run, newer than any before: its keep-alive every four minutes\n // or a text, `peerNewAt`). A daemon read 8 such contacts that were gone for good every 10 s each, as plain reads, for as\n // long as it ran: its relays' whole minute, and a contact back on a live method was not read once in 3 minutes (bug\n // hunt, 2026-11-07). Just started, a contact there is read at the background pace until its next envelope.\n const there = now - this.peerNewAt < PRESENCE_WINDOW;\n return this.state.peerMode === \"dht\" && this.options.peerDhtPollMs && there ? Math.min(this.options.peerDhtPollMs, STREAM_POLL_MS) : STREAM_POLL_MS;\n }\n /**\n * The contact is on DHT only and this side is not: a live link waits on the contact's envelope saying it left, and\n * nothing else of the contact's shows before it (no offer is read, no dial taken, while its mailbox says DHT only). Its\n * reads that are not background ones (the chat open, a text awaiting its receipt) then say `departed`: a few may go over\n * the relays' minute (`DEPARTED_READS` in relay.ts, per mailbox, every relay together, 6 at the open chat's 10 s pace).\n * As plain reads, an extension that stayed on Automatic, its minute spent by what it did before, read nothing of its\n * contact for 40 s after the contact left DHT only, and the matrix's chat stayed \"On DHT · retrying live\" (E2E full,\n * 2026-11-07 and 11-08). No more reads than before: those it made anyway, the minute spent, go within the allowance.\n * Not while this side is leaving DHT only itself (`signalReads` left, `leavingRead`): its read at the switch stays a\n * plain one, the rest are signaling, so the few requests past a spent minute stay for the dialling side's read of the\n * answer. As a departed read, the switch's took one, and both sides leaving went live in 34 s, against 10.\n */\n private departedRead(): boolean {\n return this.mode !== \"dht\" && this.state.peerMode === \"dht\" && this.signalReads === 0 && !!this.options.credentials.peerKey;\n }\n /**\n * This side is DHT only, and nothing waits on the contact's mailbox: the contact, pinned, is away (nothing new of its\n * own in `PRESENCE_WINDOW`; it puts a keep-alive every four minutes while there), no text of ours awaits its receipt,\n * and the chat is not on screen. Its mailbox is then read at the background pace, as background reads, not every 4 s:\n * a daemon with 50 such chats looked each contact up on the Mainline DHT every ~3 s, 1,081 lookups a minute for as\n * long as it ran, since its relays' budget held those reads and a held read nobody marked background goes to the DHT.\n * The contact's next envelope (its first on coming back, or a text) is read at the next of those reads, and the\n * 4 s pace is back from there. Just started, a contact there is read so until its next envelope too.\n */\n private dhtOnlyIdle(now: number): boolean {\n if (this.active || !this.options.credentials.peerKey || now - this.peerNewAt < PRESENCE_WINDOW) return false;\n return !(this.state.pending && this.state.pending.expires > now);\n }\n /**\n * How long ago this side's invite was made (or joined), while nobody used it (or its inviter never answered,\n * `unanswered`) and it is no longer awaited (`AWAITING_PEER_MS`).\n */\n private unusedInviteAge(now: number): number | undefined {\n const madeAt = this.options.inviteMadeAt;\n if (madeAt === undefined || ((this.options.credentials.peerKey || this.state.peerSequence) && !this.unanswered)) return undefined;\n const age = now - Math.min(madeAt, this.startedAt);\n return age >= AWAITING_PEER_MS ? age : undefined;\n }\n /**\n * The wait between reads of the mailbox of a joined chat whose invite someone else used first (`inviteTaken`), whether\n * or not its look-up pinned the inviter first (`unanswered`): nothing is awaited from its inviter, so it is read as an\n * unused invite of its age (counted from the join) from the notice on, however few other invites the app holds. One\n * slow read stays, so a chat whose invite turns out not to be taken (`untaken`) still notices. Undefined for any other chat.\n */\n private takenInviteWait(): number | undefined {\n const now = Date.now(), madeAt = this.options.inviteMadeAt;\n if (!this.state.inviteTaken || madeAt === undefined || this.active || now < this.fastUntil) return undefined;\n return unusedInviteWait(now - Math.min(madeAt, this.startedAt), this.mode === \"dht\" ? DHT_POLL_MS : STREAM_POLL_MS, Infinity);\n }\n private schedule(): void {\n if (!this.running || this.ticking) return;\n if (this.timer) clearTimeout(this.timer);\n // A publication the budget held back goes when the budget frees a request, if that comes before the next read.\n const held = this.budgetUntil - this.clock();\n // Reactions to carry, or to say taken, go once the publication spacing allows, not at the next read.\n // So does the envelope sealed to a contact just pinned (`resealDue`), live too, where the next read is minutes away;\n // after a failed one, at the chat's pace, and never before the budget frees a request.\n const due = this.reactionsPress || (this.resealDue && !this.errors.publish) ? Math.max(0, this.lastPublish + 4_000 - Date.now(), held) : Infinity;\n // So does a withdrawal still to replace on the relays (`withdrawal`), at its backoff.\n const withdrawal = this.withdrawal, now = Date.now();\n const retry = withdrawal && withdrawal.until > now && withdrawal.attempts < MAX_ATTEMPTS ? Math.max(0, withdrawal.next - now, this.lastPublish + 4_000 - now, held) : Infinity;\n // So does a text that took the floor just after a withdrawal and has not gone yet (`withdrawalWaits`).\n const pending = this.state.pending;\n const waiting = pending && pending.attempts === 0 && pending.expires > now ? Math.max(0, this.lastPublish + 4_000 - now, held) : Infinity;\n // So does a read it held back, never sooner than a second after.\n const readHeld = this.readHeldUntil > 0 ? Math.max(1_000, this.readHeldUntil - Date.now()) : Infinity;\n this.timer = setTimeout(() => void this.tick(), Math.min(held > 0 ? Math.min(this.pollMs, held) : this.pollMs, due, retry, waiting, readHeld));\n }\n}\nexport const DHT_TEXT_REFUSED = \"Your contact's app does not accept text over the DHT. It is sent when you are live.\";\nexport const DHT_RATCHET_STOPPED = \"Your contact's app no longer reads protected messages over the DHT. It is sent when you are live.\";\nexport const DHT_FILE_REFUSED = \"Your contact's app shows a file only once it comes. It is sent when you are live.\";\nexport const DHT_FILE_TOO_LARGE = \"This file's name is too long to say over the DHT. It is sent when you are live.\";\n\n/**\n * `DhtDelivery.peek` for a chat of a profile that is not running: built from what that profile stored, with every\n * callback a no-op that refuses to save, so the look can change nothing.\n */\nexport function peekDhtMailbox(options: { params: LinkParams; credentials: PairingCredentials; state?: DhtDeliveryState; transport: PkarrTransport; background?: boolean; ratchet?: RatchetState }): Promise<{ reads: number; text: string | null }> {\n const refuse = async () => { throw new Error(\"A peek saves nothing\"); };\n const credentials = { ...options.credentials }, peer = credentials.peerKey;\n // A ratcheted envelope is opened on a copy of the chat's ratchet, and nothing of it kept (`RatchetBox.peek`).\n const box = options.ratchet && peer ? new RatchetBox(() => ({ seed: fromBase64Url(credentials.seedB64), self: identityFromSeedB64(credentials.seedB64).pubKeyZ32, peer,\n rendezvous: [identityFromSeedB64(options.params.seedB64).pubKeyZ32, options.params.peerPubKeyZ32], secret: fromBase64Url(options.params.encKeyB64) }), options.ratchet, refuse) : undefined;\n const delivery = new DhtDelivery({ params: options.params, mode: \"stream\", state: options.state, credentials, transport: options.transport,\n save: refuse, pin: refuse, message: refuse, receipt: refuse, changed: () => {}, ...(box && { ratchet: { box, peerSupports: () => true } }) });\n return delivery.peek(options.background ? { background: true } : undefined);\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { fromBase64Url, toBase64Url } from \"./bytes\";\nimport { LIMITS, type FrameChannel } from \"./frames\";\nimport { sanitizeFileName, sanitizeMime, type FileInfo, type FileSink, type FileTransferEvents } from \"./files\";\nimport { pairedReplyAuthor, readReply, wireReply } from \"./replies\";\nimport { readForwarded } from \"./forwards\";\nimport { parseVideoMeta } from \"./video\";\nimport { parseImageMeta } from \"./image\";\nimport { parseVoiceMeta } from \"./voice\";\n\nconst CHUNK = 16 * 1024;\nconst ID = /^[A-Za-z0-9_-]{8,64}$/;\ninterface Incoming {\n file: FileInfo;\n sink: FileSink | null;\n stored?: string;\n hash: ReturnType<typeof sha256.create>;\n offset: number;\n timer?: ReturnType<typeof setTimeout>;\n}\ninterface Pending { resolve(): void; reject(error: Error): void; frame: object; }\n/** Transfers finished lately, by id, with their final offset: a repeated end is acknowledged again. */\nconst DONE_KEPT = 32;\n\n/** files/2: authenticated text frames work on RTC, Iroh and HyperDHT alike.\n * Stop-and-wait credits bound each sender to one 16 KiB chunk in flight.\n * Final receipt follows digest verification and durable sink.close, never merely send().\n * A live transport switch moves transfers to the new channel (`rebind`): the one frame awaiting its\n * acknowledgement goes again there, and a receiver acknowledges a frame it already applied again. */\nexport class PairedFiles {\n private incoming = new Map<string, Incoming>();\n private outgoing = new Set<string>();\n private pending = new Map<string, Pending>();\n private done = new Map<string, number>();\n private closed = false;\n constructor(private channel: FrameChannel, private events: FileTransferEvents & {\n onStored?(file: FileInfo): Promise<string | undefined>;\n /** files/3 is on for this session: it replaces files/2, so a new file announced here is refused (WISP 501). */\n replaced?(): boolean;\n /** The room this device has left for files, or null when it does not say: a larger file is refused. */\n room?(): Promise<number | null>;\n }) {}\n\n /** A file going either way on this session right now. */\n get busy(): boolean { return this.incoming.size > 0 || this.outgoing.size > 0; }\n\n private sendFrame(frame: object): void {\n if (this.closed) throw new Error(\"Connection lost\");\n this.channel.send(JSON.stringify(frame));\n }\n\n private exchange(id: string, offset: number, phase: string, frame: object): Promise<void> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => finish(new Error(\"File transfer timed out\")), LIMITS.bodyIdleTimeoutMs);\n const key = `${id}:${phase}:${offset}`;\n const finish = (error?: Error) => {\n clearTimeout(timer); this.pending.delete(key);\n if (error) reject(error); else resolve();\n };\n this.pending.set(key, { resolve: () => finish(), reject: finish, frame });\n try { this.sendFrame(frame); } catch (error) { finish(error instanceof Error ? error : new Error(String(error))); }\n });\n }\n\n async send(file: FileInfo, source: AsyncIterable<Uint8Array>): Promise<void> {\n if (this.closed || !ID.test(file.id) || !Number.isSafeInteger(file.size) || file.size < 0 || file.size > LIMITS.maxFileBytes)\n throw new Error(\"Invalid file or connection closed\");\n if (this.outgoing.has(file.id) || this.outgoing.size >= LIMITS.maxIncomingFilesPerPeer) throw new Error(\"File transfer already active\");\n this.outgoing.add(file.id);\n try {\n const { reply, forwarded, ...announced } = file;\n const hops = readForwarded(forwarded);\n await this.exchange(file.id, 0, \"start\", { t: \"pf-start\", ...announced, name: sanitizeFileName(file.name), mime: sanitizeMime(file.mime), voice: parseVoiceMeta(file.voice, sanitizeMime(file.mime)), video: parseVideoMeta(file.video, sanitizeMime(file.mime)), image: parseImageMeta(file.image, sanitizeMime(file.mime)), ...(reply && { r: wireReply(reply) }), ...(hops && { fw: hops }) });\n const hash = sha256.create();\n let offset = 0;\n for await (const part of source) {\n for (let pos = 0; pos < part.length; pos += CHUNK) {\n const chunk = part.subarray(pos, pos + CHUNK);\n if (offset + chunk.length > file.size) throw new Error(\"File changed during transfer\");\n hash.update(chunk);\n await this.exchange(file.id, offset + chunk.length, \"chunk\", { t: \"pf-chunk\", id: file.id, offset, data: toBase64Url(chunk) });\n offset += chunk.length;\n this.events.onProgress?.(file.id, offset, \"out\");\n }\n }\n if (offset !== file.size) throw new Error(\"Incomplete file\");\n await this.exchange(file.id, offset, \"end\", { t: \"pf-end\", id: file.id, offset, digest: toBase64Url(hash.digest()) });\n this.events.onComplete?.(file.id, \"out\");\n } catch (error) {\n try { this.sendFrame({ t: \"pf-cancel\", id: file.id, target: \"receiver\" }); } catch { /* disconnected */ }\n this.events.onFailed?.(file.id, error instanceof Error ? error.message : String(error), \"out\");\n throw error;\n } finally { this.outgoing.delete(file.id); }\n }\n\n /** The session moved to another transport: transfers carry on over `channel`, where what awaits an acknowledgement goes again. */\n rebind(channel: FrameChannel): void {\n if (this.closed) return;\n this.channel = channel;\n for (const pending of this.pending.values()) {\n try { this.sendFrame(pending.frame); } catch (error) { pending.reject(error instanceof Error ? error : new Error(String(error))); }\n }\n }\n\n async handle(frame: Record<string, unknown>): Promise<void> {\n if (this.closed || typeof frame.id !== \"string\" || !ID.test(frame.id)) return;\n const id = frame.id;\n if (frame.t === \"pf-ack\") {\n if (Number.isSafeInteger(frame.offset) && [\"start\", \"chunk\", \"end\"].includes(String(frame.phase)))\n this.pending.get(`${id}:${frame.phase}:${frame.offset}`)?.resolve();\n return;\n }\n if (frame.t === \"pf-cancel\") {\n if (frame.target === \"receiver\") this.fail(id, \"Cancelled by sender\", false);\n if (frame.target === \"sender\") for (const [key, pending] of this.pending)\n if (key.startsWith(`${id}:`)) pending.reject(new Error(\"Peer refused or could not store the file\"));\n return;\n }\n try {\n if (frame.t === \"pf-start\") {\n const active = this.incoming.get(id);\n // Sent again after a transport switch, before any chunk: the same announcement is acknowledged again.\n if (active && active.offset === 0 && frame.size === active.file.size && frame.name === active.file.name) {\n this.sendFrame({ t: \"pf-ack\", id, phase: \"start\", offset: 0 }); return;\n }\n if (active) throw new Error(\"Duplicate active file\");\n if (this.events.replaced?.()) throw new Error(\"files/3 replaces files/2 on this session\");\n if (typeof frame.name !== \"string\" || frame.name.length > 1000 || typeof frame.mime !== \"string\" || frame.mime.length > 130 ||\n typeof frame.size !== \"number\" || !Number.isSafeInteger(frame.size) || frame.size < 0 || frame.size > LIMITS.maxFileBytes ||\n typeof frame.timestamp !== \"number\" || !Number.isSafeInteger(frame.timestamp) || frame.timestamp <= 0 ||\n this.incoming.size >= LIMITS.maxIncomingFilesPerPeer) throw new Error(\"Invalid file announcement\");\n const file: FileInfo = { id, name: sanitizeFileName(frame.name), mime: sanitizeMime(frame.mime), size: frame.size, timestamp: frame.timestamp };\n // A description that does not check out only costs the player: the file itself is fine.\n const voice = parseVoiceMeta(frame.voice, file.mime);\n if (voice) file.voice = voice;\n const video = parseVideoMeta(frame.video, file.mime);\n if (video) file.video = video;\n const image = parseImageMeta(frame.image, file.mime);\n if (image) file.image = image;\n const reply = readReply(frame.r, pairedReplyAuthor);\n if (reply) file.reply = reply;\n const forwarded = readForwarded(frame.fw);\n if (forwarded) file.forwarded = forwarded;\n const stored = await this.events.onStored?.(file);\n if (this.closed) return;\n const room = stored ? null : await this.events.room?.().catch(() => null) ?? null;\n if (this.closed) return;\n if (room !== null && file.size > room) throw new Error(\"No room for this file\");\n const sink = stored ? null : this.events.onIncoming(file);\n if (!stored && (!sink || typeof sink === \"string\")) throw new Error(typeof sink === \"string\" ? sink : \"File refused\");\n const entry: Incoming = { file, sink: sink as FileSink | null, stored, hash: sha256.create(), offset: 0 };\n this.incoming.set(id, entry); this.arm(id, entry);\n this.sendFrame({ t: \"pf-ack\", id, phase: \"start\", offset: 0 });\n return;\n }\n const entry = this.incoming.get(id);\n if (!entry) {\n if (frame.t === \"pf-end\" && this.done.get(id) === frame.offset) this.sendFrame({ t: \"pf-ack\", id, phase: \"end\", offset: frame.offset });\n return;\n }\n // The last chunk again (its acknowledgement was lost in a transport switch): acknowledged again, applied once.\n if (frame.t === \"pf-chunk\" && typeof frame.offset === \"number\" && typeof frame.data === \"string\" && frame.offset < entry.offset &&\n frame.offset + fromBase64Url(frame.data).length === entry.offset) {\n this.sendFrame({ t: \"pf-ack\", id, phase: \"chunk\", offset: entry.offset }); return;\n }\n if (frame.offset !== entry.offset) throw new Error(\"Invalid file offset\");\n if (frame.t === \"pf-chunk\") {\n if (typeof frame.data !== \"string\" || frame.data.length > Math.ceil(CHUNK * 4 / 3) || !/^[A-Za-z0-9_-]+$/.test(frame.data)) throw new Error(\"Invalid chunk\");\n const bytes = fromBase64Url(frame.data);\n if (!bytes.length || bytes.length > CHUNK || entry.offset + bytes.length > entry.file.size) throw new Error(\"Invalid chunk size\");\n entry.hash.update(bytes);\n await entry.sink?.write(bytes);\n if (this.incoming.get(id) !== entry) return;\n entry.offset += bytes.length;\n this.arm(id, entry);\n this.events.onProgress?.(id, entry.offset, \"in\");\n this.sendFrame({ t: \"pf-ack\", id, phase: \"chunk\", offset: entry.offset });\n } else if (frame.t === \"pf-end\") {\n const digest = toBase64Url(entry.hash.digest());\n if (entry.offset !== entry.file.size || frame.digest !== digest || (entry.stored && entry.stored !== digest)) throw new Error(\"File integrity check failed\");\n await entry.sink?.close(digest);\n if (this.incoming.get(id) !== entry) return;\n clearTimeout(entry.timer); this.incoming.delete(id);\n this.done.set(id, entry.offset);\n if (this.done.size > DONE_KEPT) this.done.delete(this.done.keys().next().value!);\n if (!entry.stored) this.events.onComplete?.(id, \"in\");\n this.sendFrame({ t: \"pf-ack\", id, phase: \"end\", offset: entry.offset });\n }\n } catch (error) { this.fail(id, error instanceof Error ? error.message : String(error), true); }\n }\n\n private arm(id: string, entry: Incoming): void {\n clearTimeout(entry.timer);\n entry.timer = setTimeout(() => this.fail(id, \"File transfer stalled\", true), LIMITS.bodyIdleTimeoutMs);\n }\n private fail(id: string, reason: string, notify: boolean): void {\n const entry = this.incoming.get(id);\n if (entry) {\n clearTimeout(entry.timer); this.incoming.delete(id); entry.sink?.abort();\n if (!entry.stored) this.events.onFailed?.(id, reason, \"in\");\n }\n if (notify) try { this.sendFrame({ t: \"pf-cancel\", id, target: \"sender\" }); } catch { /* disconnected */ }\n }\n closeAll(): void {\n this.closed = true;\n for (const id of this.incoming.keys()) this.fail(id, \"Connection lost\", false);\n for (const pending of this.pending.values()) pending.reject(new Error(\"Connection lost\"));\n }\n}\n","import { RateWindow } from \"./pairedEdits\";\nimport { checkedDescriptors, rankTransports, relayedTransports, transportOrder, TRANSPORTS, type PairedTransport, type TransportDescriptors } from \"./pairedTransports\";\n\nexport interface TransportPolicy {\n revision: number;\n intent: number;\n preferred: PairedTransport;\n fallback: boolean;\n available: PairedTransport[];\n descriptors: TransportDescriptors;\n}\nexport interface SwitchPlan {\n id: string;\n local: TransportPolicy;\n remote: TransportPolicy;\n choices: PairedTransport[];\n /**\n * Nobody chose: the session is on a relayed transport and a direct one ranks first, and both sides said they move\n * (`upgrade`). Quiet: no transport shown as wanted, no row when it does not connect, and tried once.\n */\n upgrade?: boolean;\n}\n/**\n * The contact's policies read per window. A choice, a retry or a session's start each say one, so a handful a minute;\n * every one read may plan a move this side dials. Past that only the newest waits, read once the window has room.\n */\nexport const POLICY_RECEIVE_LIMIT = 10, POLICY_RECEIVE_WINDOW_MS = 60_000;\nexport const allowedTransports = (policy: TransportPolicy) => transportOrder(policy.available, policy.preferred, policy.fallback);\n/** The first ranked transport that is not relayed. */\nconst directFirst = (ranked: readonly PairedTransport[], relayed: readonly string[]) => ranked.find(t => !relayed.includes(t));\n\nfunction parsePolicy(raw: unknown): TransportPolicy | null {\n if (!raw || typeof raw !== \"object\") return null;\n const p = raw as TransportPolicy;\n if (!Number.isSafeInteger(p.revision) || p.revision < 0 || !Number.isSafeInteger(p.intent) || p.intent < 0 ||\n !TRANSPORTS.includes(p.preferred) || typeof p.fallback !== \"boolean\" || !Array.isArray(p.available) ||\n p.available.length > 3 || new Set(p.available).size !== p.available.length || p.available.some(t => !TRANSPORTS.includes(t)) ||\n !p.descriptors || typeof p.descriptors !== \"object\" || JSON.stringify(p.descriptors).length > 4096) return null;\n return { revision: p.revision, intent: p.intent, preferred: p.preferred, fallback: p.fallback, available: [...p.available],\n descriptors: checkedDescriptors(p.descriptors) };\n}\n\n/** Runs only inside a participation-authenticated channel. Both roles may propose;\n * the lower rendezvous key coordinates a revision-checked plan, never both dials.\n * The existing channel stays alive while a replacement proves its own binding. */\nexport class TransportSwitch {\n private context = \"\";\n private revision = 0;\n private intent = 0;\n private remote: TransportPolicy | null = null;\n /** The contact's policy as it last said it, kept across sessions: where the next reconnect dials first. */\n private lastRemote: TransportPolicy | null = null;\n private actual?: PairedTransport;\n private plan: SwitchPlan | null = null;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private settled = \"\";\n private failed = \"\";\n private preparing = false;\n /** The coordinator's dial for the pending plan has started (`dialing`): from then on a newer choice waits for it. */\n private dialStarted = false;\n /**\n * The contact's `paired-policy` says `replaces`: its app reads a `paired-switch-keep` for a plan a newer choice\n * replaced as that (`supersede`). An app before 1.1.5 reads it as its target missed and says the chat was kept on its\n * transport; 1.1.5 reads it right but does not say so.\n */\n private remoteReplaces = false;\n /** This side chose while no session was open: the next one begins with it as a choice. */\n private apart = false;\n private readonly policiesRead = new RateWindow(POLICY_RECEIVE_LIMIT, POLICY_RECEIVE_WINDOW_MS);\n /** The session on which the contact's policy, the one read already, was said again and read for free (`handle`). */\n private repeatRead = \"\";\n private policyHeld: { frame: Record<string, unknown>; timer: ReturnType<typeof setTimeout> } | null = null;\n constructor(private readonly options: {\n key: string; peerKey: string;\n policy(): Omit<TransportPolicy, \"revision\" | \"intent\">;\n send(frame: object): void;\n peer(policy: TransportPolicy): void;\n state(error?: string, target?: PairedTransport): void;\n prepare(plan: SwitchPlan, dial: boolean): void;\n cancel(): void;\n /** A plan's target could not be reached and the session stayed on the current transport (fallback allowed it). */\n kept?(target: PairedTransport, reason?: string): void;\n /**\n * A plan's target could not be reached, and nothing kept the chat on another transport: the chat waits for it\n * (WISP 100, \"A chosen transport not reached yet\") rather than failing, and is told why here, not as an error.\n * `reason` is known on the side that dialled. Without this callback, the failure is an error state, as before.\n */\n unreached?(target: PairedTransport, reason?: string): void;\n /** Both sides move a session off a relayed transport to a direct one ranked first, nobody having chose (`upgrade/1`). */\n upgrade?(): boolean;\n timeoutMs?: number;\n }) {}\n\n get peerPolicy(): TransportPolicy | null { return this.remote; }\n /**\n * The transport a standing explicit choice names (the higher intent; the lower key on a tie), from this side's\n * policy and the contact's last one, when both can use it. None when neither side chose: the rank sum decides.\n * Both sides get the same answer, so whichever redials after a drop lands where the agreement would move it.\n */\n get chosenTarget(): PairedTransport | undefined {\n const local = this.local(), remote = this.lastRemote;\n if (!remote) return undefined;\n const winner = this.winner(local, remote);\n if (winner.intent === 0) return undefined;\n return rankTransports(allowedTransports(local), allowedTransports(remote)).includes(winner.preferred) ? winner.preferred : undefined;\n }\n private winner(local: TransportPolicy, remote: TransportPolicy): TransportPolicy {\n return local.intent > remote.intent || (local.intent === remote.intent && this.options.key < this.options.peerKey) ? local : remote;\n }\n get pending(): SwitchPlan | null { return this.plan; }\n /**\n * Where the policies put the chat while a session is open, and whose choice that is: the agreed target, or, when\n * the two sides' transports do not overlap, the winning side's preferred. `by` is absent when nobody chose (a\n * policy alone, such as Fallback off, names it). Both sides get the same answer.\n */\n wanted(): { transport: PairedTransport; by?: \"you\" | \"contact\" } | undefined {\n if (!this.context || !this.remote) return undefined;\n const local = this.local(), remote = this.remote, winner = this.winner(local, remote);\n // A move off a relay (`upgrade`) is quiet: the transport the session is on is not waiting for another.\n const transport = (this.isUpgrade(local, remote) ? this.actual : undefined) ?? this.choices(local, remote)[0] ?? winner.preferred;\n return { transport, ...(winner.intent > 0 ? { by: winner === local ? \"you\" as const : \"contact\" as const } : {}) };\n }\n private local(): TransportPolicy { return { ...this.options.policy(), revision: this.revision, intent: this.intent }; }\n private signature(local: TransportPolicy, remote: TransportPolicy): string {\n return this.options.key < this.options.peerKey ? `${local.revision}:${remote.revision}` : `${remote.revision}:${local.revision}`;\n }\n private send(frame: object): void { if (this.context) this.options.send({ ...frame, context: this.context }); }\n /** Older apps read the policy's own fields only, and drop `replaces`. */\n private announce(): void { this.send({ t: \"paired-policy\", policy: this.local(), replaces: true }); }\n\n /**\n * A session is ready. `migrated`: it is the one a plan dialled, so that plan is done, even on a fallback choice.\n * Otherwise it is a fresh session (a reconnect after a drop): a plan still pending from the old one did not happen,\n * and what the old one kept or gave up on does not bind this one. Both sides agree again from their policies, so\n * the chat ends on the same transport whichever side dialled.\n * A plan that landed on a fallback choice (its target did not connect, a later choice did) is a target not reached,\n * as when the current transport is kept: its owner waits for it and tries it again (WISP 100).\n */\n begin(context: string, actual: PairedTransport, migrated = false): void {\n const landed = migrated ? this.plan : null;\n this.settled = landed ? this.signature(landed.local, landed.remote) : \"\";\n // A fresh session may be the contact's app started again, which counts its revisions from 0: its policy is heard\n // anew (it announces it on this session). One kept from the old session made every newer policy look older, and\n // no change ever moved the chat after a contact's crash and resume (`attachReplacement` stops nothing here).\n if (!migrated) { this.failed = \"\"; this.remote = null; this.remoteReplaces = false; }\n // A choice made while apart is a choice now: above the contact's last intent, as one made on a session would be.\n if (this.apart) { this.intent = Math.max(this.intent, this.lastRemote?.intent ?? 0) + 1; this.apart = false; }\n this.clearPlan();\n this.context = context; this.actual = actual;\n this.options.state(); this.announce();\n if (landed && landed.choices[0] !== actual) this.options.kept?.(landed.choices[0]);\n }\n /** `automatic`: no choice of this side's any more; the contact's explicit one wins, and without one the\n * current transport is kept while it is allowed. */\n changed(userIntent: boolean | \"automatic\" = true): void {\n this.revision++;\n if (userIntent === \"automatic\") { this.intent = 0; this.apart = false; }\n else if (userIntent) this.intent = Math.max(this.intent, this.remote?.intent ?? 0) + 1;\n this.failed = \"\";\n this.announce(); this.supersede(); this.reconcile();\n }\n /**\n * This side's user chose the transport its policy now names. `again`: the one it named already. Choosing again\n * what this side's standing choice names raises no intent: it would move nothing, and a raised intent could beat\n * a newer choice of the contact's still on its way (the tie goes to the lower key). It still counts as a retry.\n * Choosing again while the contact's choice stands is an override, and raises it.\n */\n chose(again = false): void { this.changed(!(again && this.standing)); }\n /**\n * This side's user chose with no session open (WISP 100, \"A choice made while not live\"). Nothing to announce it on:\n * the next session begins with it as a choice, so the chat moves there if that session opened elsewhere.\n */\n choseApart(): void { this.revision++; this.apart = true; this.failed = \"\"; }\n /** This side's explicit choice is the one that stands (its intent is the higher, or wins the tie). */\n get standing(): boolean {\n if (this.intent === 0) return false;\n const local = this.local();\n return !this.remote || this.winner(local, this.remote) === local;\n }\n keep(reason?: string): void {\n const target = this.plan?.choices[0];\n if (this.plan) this.settled = this.signature(this.plan.local, this.plan.remote);\n if (target && target !== this.actual && !this.plan?.upgrade) this.options.kept?.(target, reason);\n this.send({ t: \"paired-switch-keep\", id: this.plan?.id });\n this.clearPlan(); this.options.state(); this.reconcile();\n }\n retry(): void { this.failed = \"\"; this.announce(); this.reconcile(); }\n /**\n * Tries the target again after it did not connect (WISP 100: retried, never given up), also when a fallback kept\n * the chat on another transport. The coordinator plans again. The other side cannot: its policy goes out again under\n * a new revision, which the coordinator reconciles afresh, whatever it had given up on.\n */\n again(): void {\n if (!this.context || !this.remote || this.plan) return;\n this.failed = this.settled = \"\";\n if (this.options.key > this.options.peerKey) { this.revision++; this.announce(); }\n this.reconcile();\n }\n stop(): void {\n if (this.policyHeld) clearTimeout(this.policyHeld.timer);\n this.policyHeld = null; this.clearPlan(); this.context = \"\"; this.remote = null; this.remoteReplaces = false;\n }\n private clearPlan(): void {\n if (this.timer) clearTimeout(this.timer);\n this.timer = null; this.plan = null; this.preparing = false; this.dialStarted = false;\n }\n /** The coordinator starts dialling the pending plan (a move back to WebRTC first waits for the old session to retire). */\n dialing(plan: SwitchPlan): void { if (this.plan === plan) this.dialStarted = true; }\n /**\n * A newer choice (this side's, or the contact's policy) while a plan both sides agreed has not started its dial: a\n * move back to WebRTC waits for the WebRTC session it left to retire (`SWITCH_RETIRE_MS`), and nothing has been tried\n * yet. The coordinator drops that plan, so the chat does not move there only to move again; the other side is told\n * with `paired-switch-keep`, and whatever the newer policies call for is planned next. A plan already dialling goes\n * on: a choice made then is planned once it ended (`replanIfMoved`). So does a plan the contact's app would take\n * that keep for a target missed (its policy did not say `replaces`): the newer choice is planned once it landed.\n */\n private supersede(): void {\n const plan = this.plan;\n if (!plan || !this.preparing || this.dialStarted || !this.context || !this.remote || this.options.key > this.options.peerKey || !this.remoteReplaces) return;\n if (this.choices(this.local(), this.remote)[0] === plan.choices[0]) return;\n this.send({ t: \"paired-switch-keep\", id: plan.id });\n this.clearPlan(); this.options.cancel(); this.options.state();\n }\n fail(error: string): void {\n const target = this.plan?.choices[0], upgrade = !!this.plan?.upgrade;\n if (this.plan) this.failed = this.signature(this.plan.local, this.plan.remote);\n this.send({ t: \"paired-switch-failed\", id: this.plan?.id });\n this.clearPlan(); this.options.cancel();\n // A move off a relay that did not connect: the chat stays where it is, as it would have without it.\n if (upgrade) this.options.state(); else this.unreached(target, error, error);\n this.replanIfMoved();\n }\n /**\n * A choice made while a move was dialling could not cut in (WISP 100): once that move failed, it is planned at once.\n * Policies that are still the failed plan's are not planned again here; the owner's retry pace does that.\n */\n private replanIfMoved(): void {\n if (this.context && this.remote && this.failed && this.signature(this.local(), this.remote) !== this.failed) this.reconcile();\n }\n /** Waiting for `target`, not failed, where the owner says why; an error state for an owner that does not. */\n private unreached(target: PairedTransport | undefined, error: string, reason?: string): void {\n if (target && this.options.unreached) { this.options.unreached(target, reason); this.options.state(); }\n else this.options.state(error);\n }\n private choices(local: TransportPolicy, remote: TransportPolicy): PairedTransport[] {\n const relayed = relayedTransports(local.descriptors, remote.descriptors);\n const ranked = rankTransports(allowedTransports(local), allowedTransports(remote), relayed);\n if (!ranked.length) return [];\n const winner = this.winner(local, remote);\n // Nobody chose: the current transport stays, a relayed one too (no probing while live, WISP 100); the next\n // dial ranks direct paths first again. Unless both sides move off a relay (`upgrade`): then a direct transport\n // ranked first is where the chat goes, once (a plan that does not connect is not made again for these policies).\n const upgrade = this.upgrading(winner, ranked, relayed);\n const target = upgrade ? directFirst(ranked, relayed)! : winner.intent === 0 && this.actual && ranked.includes(this.actual) ? this.actual\n : ranked.includes(winner.preferred) ? winner.preferred : ranked[0];\n return [target, ...(local.fallback && remote.fallback ? ranked.filter(t => t !== target) : [])];\n }\n /**\n * Nobody chose, the session is on a relayed transport, a direct one is ranked, and both sides move (`upgrade/1`). The\n * first direct one, not the first ranked: Iroh through its relay ranks first so that a chat comes back over it at once\n * (WISP 100, revision 2026-11-08), and the session then moves to the direct path, which carries files many times faster.\n */\n private upgrading(winner: TransportPolicy, ranked: PairedTransport[], relayed: readonly string[]): boolean {\n const direct = directFirst(ranked, relayed);\n return winner.intent === 0 && !!this.actual && relayed.includes(this.actual) && ranked.includes(this.actual)\n && !!direct && direct !== this.actual && !!this.options.upgrade?.();\n }\n private isUpgrade(local: TransportPolicy, remote: TransportPolicy): boolean {\n const relayed = relayedTransports(local.descriptors, remote.descriptors);\n return this.upgrading(this.winner(local, remote), rankTransports(allowedTransports(local), allowedTransports(remote), relayed), relayed);\n }\n /**\n * Something `upgrade` depends on changed (what the contact's app offers on this session, said once it is ready): plan\n * again. The session's first agreement, made before that, settled on the relay it is on; a move off it is not that.\n */\n reconsider(): void {\n if (this.context && this.remote && !this.plan && this.isUpgrade(this.local(), this.remote) && this.settled === this.signature(this.local(), this.remote)) this.settled = \"\";\n this.reconcile();\n }\n private install(plan: SwitchPlan): void {\n this.clearPlan(); this.plan = plan;\n this.options.state(undefined, plan.upgrade ? undefined : plan.choices[0]);\n this.timer = setTimeout(() => this.fail(\"Transport change timed out. Your previous connection is kept when available; retry or choose another transport.\"), this.options.timeoutMs ?? 30_000);\n }\n private reconcile(): void {\n if (!this.context || !this.remote || this.plan) return;\n const local = this.local(), remote = this.remote;\n const choices = this.choices(local, remote);\n if (!choices.length) {\n this.clearPlan();\n // A transport one side does not run (yet) is waited for, and its owner says why; only choices that exclude\n // each other (both limited to different transports) are an error.\n const wanted = this.winner(local, remote).preferred;\n const missing = !local.available.includes(wanted) || !remote.available.includes(wanted);\n this.options.state(missing && this.options.unreached ? undefined\n : \"Transport preferences do not overlap. Enable fallback or choose the same supported transport on both sides.\");\n return;\n }\n const signature = this.signature(local, remote);\n if (choices[0] === this.actual || (signature === this.settled && this.actual && choices.includes(this.actual))) {\n this.settled = signature; this.clearPlan(); this.options.state(); return;\n }\n if (signature === this.failed) return;\n const upgrade = this.isUpgrade(local, remote);\n this.options.state(undefined, upgrade ? undefined : choices[0]);\n if (this.options.key > this.options.peerKey) {\n if (!this.timer) this.timer = setTimeout(() => {\n this.failed = signature; this.clearPlan();\n if (upgrade) { this.options.state(); return; }\n this.unreached(choices[0], \"Your contact did not acknowledge the transport change. Retry when both peers are connected.\", \"Your contact did not answer\");\n }, this.options.timeoutMs ?? 30_000);\n return;\n }\n const plan = { id: `${signature}:${choices[0]}`, local, remote, choices, ...(upgrade && { upgrade }) };\n this.install(plan);\n this.send({ t: \"paired-switch-plan\", id: plan.id, revisions: [local.revision, remote.revision], target: choices[0] });\n }\n handle(frame: Record<string, unknown>): boolean {\n if (![\"paired-policy\", \"paired-switch-plan\", \"paired-switch-ready\", \"paired-switch-go\", \"paired-switch-keep\", \"paired-switch-failed\"].includes(String(frame.t))) return false;\n if (!this.context || frame.context !== this.context) return true;\n if (frame.t === \"paired-policy\") {\n const policy = parsePolicy(frame.policy);\n if (!policy || (this.remote && (policy.revision < this.remote.revision ||\n (policy.revision === this.remote.revision && JSON.stringify(policy) !== JSON.stringify(this.remote))))) return true;\n // The policy read already, said again as a moved session begins (`begin`): once per session, it spends none of\n // the window. A move spent two of it, and the sixth in a minute waited 37-51 s for its room.\n const repeat = !!this.remote && policy.revision === this.remote.revision && this.repeatRead !== this.context;\n if (repeat) this.repeatRead = this.context;\n else if (!this.policiesRead.take()) {\n if (this.policyHeld) this.policyHeld.frame = frame;\n else this.policyHeld = { frame, timer: setTimeout(() => {\n const held = this.policyHeld; this.policyHeld = null;\n if (held) this.handle(held.frame);\n }, this.policiesRead.wait()) };\n return true;\n }\n const changed = !this.remote || policy.revision !== this.remote.revision;\n this.remote = this.lastRemote = policy; this.remoteReplaces = frame.replaces === true; this.options.peer(policy);\n if (changed && this.plan && !this.preparing) this.clearPlan();\n else if (changed) this.supersede();\n this.reconcile(); return true;\n }\n if (frame.t === \"paired-switch-plan\") {\n if (this.options.key < this.options.peerKey || !this.remote) return true;\n const local = this.local(), remote = this.remote, choices = this.choices(local, remote);\n if (!Array.isArray(frame.revisions) || frame.revisions[0] !== remote.revision || frame.revisions[1] !== local.revision ||\n choices[0] !== frame.target || frame.id !== `${this.signature(local, remote)}:${choices[0]}`) { this.announce(); return true; }\n if (!this.plan || this.plan.id !== frame.id) this.install({ id: String(frame.id), local, remote, choices, ...(this.isUpgrade(local, remote) && { upgrade: true }) });\n // Permission is installed before the ACK; a native channel may arrive before\n // the subsequent GO frame on the old channel. Its fresh proof is still mandatory.\n this.options.prepare(this.plan!, false);\n this.send({ t: \"paired-switch-ready\", id: frame.id }); return true;\n }\n if (!this.plan || frame.id !== this.plan.id) return true;\n if (frame.t === \"paired-switch-failed\") {\n const target = this.plan.choices[0], upgrade = !!this.plan.upgrade;\n this.failed = this.signature(this.plan.local, this.plan.remote);\n this.clearPlan(); this.options.cancel();\n if (upgrade) this.options.state();\n else this.unreached(target, \"The transport change failed. Retry or choose another transport.\");\n this.replanIfMoved(); return true;\n }\n if (frame.t === \"paired-switch-keep\") {\n // The coordinator dropped a plan a newer choice replaced before anything was dialled (`supersede`): not a target\n // missed, nothing to say. The newer policies are planned next.\n if (this.preparing && this.remote && this.choices(this.local(), this.remote)[0] !== this.plan.choices[0]) {\n this.clearPlan(); this.options.state(); this.reconcile(); return true;\n }\n if (this.actual && this.plan.choices.includes(this.actual)) {\n if (this.plan.choices[0] !== this.actual && !this.plan.upgrade) this.options.kept?.(this.plan.choices[0]);\n this.settled = this.signature(this.plan.local, this.plan.remote);\n this.clearPlan(); this.options.state(); this.reconcile();\n }\n return true;\n }\n if (frame.t === \"paired-switch-ready\" && this.options.key < this.options.peerKey && !this.preparing) {\n if (!this.remote || this.signature(this.local(), this.remote) !== this.signature(this.plan.local, this.plan.remote)) {\n this.clearPlan(); this.announce(); this.reconcile(); return true;\n }\n this.preparing = true;\n this.send({ t: \"paired-switch-go\", id: frame.id });\n this.options.prepare(this.plan, true);\n } else if (frame.t === \"paired-switch-go\" && this.options.key > this.options.peerKey) this.preparing = true;\n return true;\n }\n}\n","/** The retired experimental Ring identity authorization (a modified Pubky Ring signed one peer challenge per\n * conversation). NOT a Pubky homeserver grant; the official Ring never supported it, and nothing makes it any more:\n * Pubky identities are the `pubky` identity provider now (WISP 302, pubkyProofs.ts). What is left verifies\n * evidence a contact already accepted, so old records are not orphaned.\n */\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { base64urlnopad } from '@scure/base';\nimport { fromZ32, toZ32, utf8Encode, utf8Decode } from './bytes';\nexport const RING_LIFETIME = 600;\nconst enc = base64urlnopad.encode, dec = base64urlnopad.decode;\n/** No bytes for text that is not base64url: the checks then refuse it with their own message. */\nconst decOrEmpty = (s: string) => { try { return dec(s); } catch { return new Uint8Array(0); } };\nconst hash = (s: string) => enc(sha256(utf8Encode(s)));\nconst header = enc(utf8Encode(JSON.stringify({alg:'EdDSA',typ:'ghostly-pubky-identity-delegation/1'})));\nexport interface RingEvidence { id: string; scheme: 'pubky-ring/1'; authorization: string; signature: string }\nexport interface RingClaims { iss: string; cnf: string; aud: 'ghostly-peer-proof/1'; challenge: string; iat: number; exp: number }\nexport function ringClaims(statement: string, issuer: string, delegate: string, issuedAt: number, expiresAt: number): RingClaims {\n return {iss:issuer,cnf:delegate,aud:'ghostly-peer-proof/1',challenge:hash(statement),iat:issuedAt,exp:expiresAt};\n}\nexport function ringAuthorization(claims: RingClaims, seed: Uint8Array): string {\n if(toZ32(ed25519.getPublicKey(seed))!==claims.iss) throw new Error('Ring identity mismatch');\n const input=header+'.'+enc(utf8Encode(JSON.stringify(claims)));\n return input+'.'+enc(ed25519.sign(utf8Encode(input),seed));\n}\nexport function verifyRingAuthorization(authorization: string, statement: string, issuer: string, issuedAt: number, expiresAt: number): RingClaims {\n if(typeof authorization!=='string'||authorization.length>2400)throw new Error('Invalid Ring authorization');\n const [h,p,s,...extra]=authorization.split('.');\n if(extra.length||h!==header||!p||!s)throw new Error('Unsupported Ring authorization');\n let claims: RingClaims;\n try{claims=JSON.parse(utf8Decode(dec(p))) as RingClaims;}catch{throw new Error('Unsupported Ring authorization');}\n const sig=decOrEmpty(s);\n if(typeof claims?.cnf!=='string'||!validRingKey(claims.cnf)||expiresAt!==issuedAt+RING_LIFETIME||\n p!==enc(utf8Encode(JSON.stringify(ringClaims(statement,issuer,claims.cnf,issuedAt,expiresAt))))||\n !validRingKey(issuer)||sig.length!==64||enc(sig)!==s||\n !ed25519.verify(sig,utf8Encode(h+'.'+p),fromZ32(issuer),{zip215:false}))throw new Error('Ring did not authorize this exact conversation');\n return claims;\n}\nexport function validRingKey(key: string): boolean {\n try{return /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/.test(key)&&toZ32(fromZ32(key))===key;}catch{return false;}\n}\nconst possession = (authorization: string, statement: string) => utf8Encode(JSON.stringify(['ghostly-pubky-possession',1,hash(authorization),statement]));\nfunction evidenceId(authorization: string, signature: string): string {\n return Array.from(sha256(utf8Encode(JSON.stringify(['pubky-ring/1',authorization,signature]))),b=>b.toString(16).padStart(2,'0')).join('');\n}\nexport function ringEvidence(authorization: string, statement: string, delegatedSeed: Uint8Array): RingEvidence {\n const signature=enc(ed25519.sign(possession(authorization,statement),delegatedSeed));\n return {id:evidenceId(authorization,signature),scheme:'pubky-ring/1',authorization,signature};\n}\nexport function verifyRingEvidence(e: RingEvidence, statement: string, issuer: string, issuedAt: number, expiresAt: number): void {\n if(!e||e.scheme!=='pubky-ring/1'||typeof e.signature!=='string'||e.signature.length!==86)throw new Error('Invalid Ring proof');\n const claims=verifyRingAuthorization(e.authorization,statement,issuer,issuedAt,expiresAt);\n const sig=decOrEmpty(e.signature);\n if(enc(sig)!==e.signature||e.id!==evidenceId(e.authorization,e.signature)||!ed25519.verify(sig,possession(e.authorization,statement),fromZ32(claims.cnf),{zip215:false}))throw new Error('Invalid delegated proof of possession');\n}\n","// eslint-disable-next-line @typescript-eslint/triple-slash-reference -- Share ambient types with importing workspaces without a runtime import.\n/// <reference path=\"./keet-identity-key.d.ts\" />\nimport b4a from 'b4a';\nimport { RING_LIFETIME, verifyRingEvidence, type RingEvidence } from './pubkyRing';\nimport { verify } from './identity';\nimport { schnorr } from '@noble/curves/secp256k1.js';\nimport { fromBase64Url, fromZ32, toZ32, randomBytes, toBase64Url, utf8Encode } from './bytes';\n\nexport type ProofAdapter = 'nostr' | 'pubky-import' | 'keet-import' | 'pubky-ring' | 'pubky-storage';\nexport const PROOF_ADAPTERS: ProofAdapter[] = ['nostr', 'pubky-import', 'keet-import', 'pubky-storage'];\nexport const proofCapability = (adapter: ProofAdapter) => `proof-${adapter}/1`;\nexport const isProofAdapter = (value: unknown): value is ProofAdapter => PROOF_ADAPTERS.includes(value as ProofAdapter);\nexport interface ProofScope { subject: string; audience: string; context: string; session: string }\nexport interface ProofChallenge extends ProofScope {\n adapter: ProofAdapter; externalKey: string; nonce: string; issuedAt: number; expiresAt: number;\n}\nexport interface NostrProofEvent { id: string; pubkey: string; created_at: number; kind: number; tags: string[][]; content: string; sig: string }\nexport interface ImportedProof { id: string; scheme: 'pubky-import/1' | 'keet-import/1'; signature: string }\nexport interface StorageProof { scheme: 'pubky-storage/1'; id: string; folder: string }\nexport type StorageProofReader = (key: string, path: string) => Promise<string>;\nexport type ProofEvidence = NostrProofEvent | ImportedProof | RingEvidence | StorageProof;\nexport const STORAGE_LIFETIME = 600;\nexport const STORAGE_ROOT = '/pub/ghostly.app/proofs/';\nexport async function storageProof(c: ProofChallenge, folder: string): Promise<StorageProof> {\n if (c.adapter !== 'pubky-storage' || !/^[a-f0-9]{64}$/.test(folder)) throw new Error('Invalid storage proof');\n return { scheme: 'pubky-storage/1', folder, id: await proofHash(JSON.stringify(['pubky-storage/1', folder, proofStatement(c)])) };\n}\nexport function storageProofPath(e: StorageProof): `/pub/${string}` { return `${STORAGE_ROOT}${e.folder}/${e.id}.json`; }\nexport function storageProofBody(c: ProofChallenge, e: StorageProof): string {\n // No participants, conversation identifier, key, or chat content is published.\n return JSON.stringify({ version: 1, commitment: e.id, expiresAt: c.expiresAt });\n}\nexport interface ProofRecord { challenge: ProofChallenge; event: ProofEvidence; verifiedAt: number; status: 'pending' | 'accepted' | 'withdrawal-pending' | 'withdrawn' }\nexport interface ProofLedger { incoming: ProofChallenge[]; outgoing: ProofChallenge[]; local: ProofRecord[]; remote: ProofRecord[] }\nexport const emptyProofLedger = (): ProofLedger => ({ incoming: [], outgoing: [], local: [], remote: [] });\nexport interface ProofStorage {\n read(): ProofLedger;\n /** Atomic, durable read-transform-write, preserving other conversation fields. */\n update(change: (ledger: ProofLedger) => ProofLedger): Promise<void>;\n}\nexport const PROOF_CAPABILITY = 'proof-nostr/1';\nconst WINDOW = 300;\nconst LIFETIME = 86400;\nconst hex = /^[a-f0-9]{64}$/;\nconst unhex = (value: string) => Uint8Array.from(value.match(/../g)!, x => parseInt(x, 16));\nconst key = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\nconst nonce = /^[A-Za-z0-9_-]{43}$/;\nconst nowSeconds = () => Math.floor(Date.now() / 1000);\nexport async function proofHash(text: string): Promise<string> {\n return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new Uint8Array(utf8Encode(text)))), b => b.toString(16).padStart(2, '0')).join('');\n}\nexport function proofStatement(c: ProofChallenge): string {\n return JSON.stringify(['ghostly-peer-proof', 1, c.adapter === 'pubky-storage' ? 'authorized-storage-control' : c.adapter === 'pubky-ring' ? 'delegated-conversation-proof' : 'control-of-external-key', c.adapter, c.externalKey,\n c.subject, c.audience, c.context, c.session, c.nonce, c.issuedAt, c.expiresAt]);\n}\nexport function nostrProofTemplate(c: ProofChallenge) {\n return { kind: 30078, created_at: c.issuedAt,\n tags: [['d', `ghostly-peer-proof/1:${c.context}`], ['expiration', String(c.expiresAt)]], content: proofStatement(c) };\n}\nfunction assertChallenge(c: ProofChallenge, scope: ProofScope, now: number) {\n if (!c || !isProofAdapter(c.adapter) || !validExternalKey(c.adapter, c.externalKey) || !key.test(c.subject) || !key.test(c.audience) ||\n !hex.test(c.context) || !hex.test(c.session) || !nonce.test(c.nonce) || c.subject === c.audience ||\n c.subject !== scope.subject || c.audience !== scope.audience || c.context !== scope.context || c.session !== scope.session ||\n !Number.isSafeInteger(c.issuedAt) || !Number.isSafeInteger(c.expiresAt) || c.expiresAt !== c.issuedAt + (c.adapter === 'pubky-storage' ? STORAGE_LIFETIME : c.adapter === 'pubky-ring' ? RING_LIFETIME : LIFETIME) ||\n c.issuedAt > now + 30 || c.issuedAt < now - WINDOW) throw new Error('Proof challenge expired or belongs to another connection');\n}\nexport async function verifyNostrProof(event: NostrProofEvent, c: ProofChallenge): Promise<void> {\n const expected = nostrProofTemplate(c);\n if (!event || event.pubkey !== c.externalKey || event.kind !== expected.kind || event.created_at !== expected.created_at ||\n event.content !== expected.content || JSON.stringify(event.tags) !== JSON.stringify(expected.tags) ||\n typeof event.id !== 'string' || !hex.test(event.id) || typeof event.sig !== 'string' || !/^[a-f0-9]{128}$/.test(event.sig))\n throw new Error('Signer did not sign the exact Ghostly proof');\n const id = await proofHash(JSON.stringify([0, event.pubkey, event.created_at, event.kind, event.tags, event.content]));\n if (event.id !== id || !schnorr.verify(unhex(event.sig), unhex(id), unhex(event.pubkey))) throw new Error('Invalid Nostr signature');\n}\nexport function validExternalKey(adapter: ProofAdapter, value: string): boolean {\n if (typeof value !== 'string') return false;\n if (adapter !== 'pubky-import' && adapter !== 'pubky-ring' && adapter !== 'pubky-storage') return hex.test(value);\n try { return key.test(value) && toZ32(fromZ32(value)) === value; } catch { return false; }\n}\nexport async function importedProof(c: ProofChallenge, signature: Uint8Array): Promise<ImportedProof> {\n if (c.adapter === 'nostr' || c.adapter === 'pubky-ring' || c.adapter === 'pubky-storage') throw new Error('Wrong proof adapter');\n const scheme = `${c.adapter}/1` as ImportedProof['scheme'];\n const encoded = toBase64Url(signature);\n return { scheme, signature: encoded, id: await proofHash(JSON.stringify([scheme, proofStatement(c), encoded])) };\n}\nexport async function verifyPeerProof(event: ProofEvidence, c: ProofChallenge, readStorage?: StorageProofReader): Promise<void> {\n if (c.adapter === 'nostr') return verifyNostrProof(event as NostrProofEvent, c);\n if (c.adapter === 'pubky-ring') return verifyRingEvidence(event as RingEvidence, proofStatement(c), c.externalKey, c.issuedAt, c.expiresAt);\n if (c.adapter === 'pubky-storage') {\n const e = event as StorageProof;\n if (!e || e.scheme !== 'pubky-storage/1' || !hex.test(e.id) || typeof e.folder !== 'string' ||\n !hex.test(e.folder) || Object.keys(e).sort().join(',') !== 'folder,id,scheme' ||\n (await storageProof(c, e.folder)).id !== e.id || !readStorage) throw new Error('Invalid storage proof');\n if (await readStorage(c.externalKey, storageProofPath(e)) !== storageProofBody(c, e)) throw new Error('Homeserver proof does not match this challenge');\n return;\n }\n const e = event as ImportedProof;\n if (!e || e.scheme !== `${c.adapter}/1` || typeof e.signature !== 'string' || !/^[A-Za-z0-9_-]{1,160}$/.test(e.signature) ||\n typeof e.id !== 'string' || !hex.test(e.id) || !validExternalKey(c.adapter,c.externalKey)) throw new Error('Invalid imported-key proof');\n const sig = fromBase64Url(e.signature);\n if (toBase64Url(sig) !== e.signature || (await importedProof(c,sig)).id !== e.id) throw new Error('Invalid proof encoding or digest');\n const data = utf8Encode(proofStatement(c));\n if (c.adapter === 'pubky-import') {\n if (sig.length !== 64 || !verify(sig,data,fromZ32(c.externalKey))) throw new Error('Invalid Pubky signature');\n } else if (c.adapter === 'keet-import') {\n // Pinned SDK v1 root-only DataAttestation: uint version, uint64 epoch,\n // fixed32 identity, empty chain, data flag, fixed64 signature. Enforce this\n // bounded canonical shape before the SDK's generic array decoder runs.\n if (sig.length !== 107 || sig[0] !== 1 || sig[41] !== 0 || sig[42] !== 1) throw new Error('Unsupported Keet attestation');\n const { default: IdentityKey } = await import('keet-identity-key');\n if (!IdentityKey.verify(b4a.from(sig), b4a.from(data), { expectedIdentity: b4a.from(unhex(c.externalKey)) }))\n throw new Error('Invalid Keet attestation');\n } else throw new Error('Unsupported proof adapter');\n}\nfunction replace(records: ProofRecord[], record: ProofRecord): ProofRecord[] {\n return [...records.filter(r => r.challenge.adapter !== record.challenge.adapter), record];\n}\n\n/** Optional application protocol. All calls require an authenticated, pinned paired channel.\n * A bad external proof never replaces participation authentication or disconnects ordinary chat. */\nexport class PeerProofs {\n private waiting = new Map<string, { adapter: ProofAdapter; externalKey: string; resolve: (c: ProofChallenge) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>();\n constructor(private options: { scope(): ProofScope; send(frame: object): void; storage: ProofStorage; supports?(adapter: ProofAdapter): boolean; now?: () => number; readStorage?: StorageProofReader; onError?(error: string): void }) {}\n private now() { return (this.options.now ?? nowSeconds)(); }\n private scope(incoming = false): ProofScope {\n const s = this.options.scope();\n return incoming ? { ...s, subject: s.audience, audience: s.subject } : s;\n }\n async prepare(externalKey: string, adapter: ProofAdapter = 'nostr'): Promise<ProofChallenge> {\n this.scope();\n if (!isProofAdapter(adapter) || !validExternalKey(adapter, externalKey) || this.options.supports?.(adapter) === false) throw new Error('Proof adapter unavailable or invalid public key');\n if (this.waiting.size) throw new Error('A proof request is already pending');\n const id = toBase64Url(randomBytes(32));\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => { this.waiting.delete(id); reject(new Error('Peer did not provide a challenge. Try again.')); }, 15_000);\n this.waiting.set(id, { adapter, externalKey, resolve, reject, timer });\n try { this.options.send({ t: 'proof-request', id, adapter, externalKey }); }\n catch (e) { clearTimeout(timer); this.waiting.delete(id); reject(e); }\n });\n }\n async submit(c: ProofChallenge, event: ProofEvidence): Promise<void> {\n assertChallenge(c, this.scope(), this.now());\n if (this.options.supports?.(c.adapter) === false) throw new Error('Peer does not support this proof');\n await verifyPeerProof(event, c, this.options.readStorage);\n await this.options.storage.update(l => {\n assertChallenge(c, this.scope(), this.now());\n if (!l.outgoing.some(x => proofStatement(x) === proofStatement(c))) throw new Error('Unknown or used proof challenge');\n return { ...l, outgoing: l.outgoing.filter(x => x.nonce !== c.nonce),\n local: replace(l.local, { challenge: c, event, verifiedAt: this.now(), status: 'pending' }) };\n });\n this.options.send({ t: 'proof-present', challenge: c, event });\n }\n async withdraw(adapter: ProofAdapter = 'nostr'): Promise<void> {\n this.scope();\n const record = this.options.storage.read().local.find(r => r.challenge.adapter === adapter);\n if (!record) return;\n await this.options.storage.update(l => ({ ...l, local: l.local.map(r => r.event.id === record.event.id ? { ...r, status: 'withdrawal-pending' } : r) }));\n this.resendWithdrawals();\n }\n resendWithdrawals(): void {\n const scope = this.scope();\n for (const record of this.options.storage.read().local) {\n if (record.status === 'withdrawal-pending' && record.challenge.subject === scope.subject && record.challenge.audience === scope.audience && record.challenge.context === scope.context)\n this.options.send({ t: 'proof-withdraw', id: record.event.id });\n }\n }\n async receive(frame: Record<string, unknown>): Promise<void> {\n try {\n if (JSON.stringify(frame).length > 8192) throw new Error('Proof too large');\n const scope = this.scope();\n const now = this.now();\n if (frame.t === 'proof-request') {\n if (!isProofAdapter(frame.adapter) || this.options.supports?.(frame.adapter) === false || typeof frame.id !== 'string' || !nonce.test(frame.id) || typeof frame.externalKey !== 'string' || !validExternalKey(frame.adapter, frame.externalKey)) return;\n const c: ProofChallenge = { ...this.scope(true), adapter: frame.adapter, externalKey: frame.externalKey,\n nonce: toBase64Url(randomBytes(32)), issuedAt: now, expiresAt: now + (frame.adapter === 'pubky-storage' ? STORAGE_LIFETIME : frame.adapter === 'pubky-ring' ? RING_LIFETIME : LIFETIME) };\n await this.options.storage.update(l => {\n const incoming = l.incoming.filter(x => x.issuedAt >= now - WINDOW);\n if (incoming.length >= 8) throw new Error('Too many proof challenges');\n return { ...l, incoming: [...incoming, c] };\n });\n this.options.send({ t: 'proof-challenge', id: frame.id, challenge: c });\n } else if (frame.t === 'proof-challenge') {\n const pending = typeof frame.id === 'string' ? this.waiting.get(frame.id) : undefined;\n if (!pending) return;\n const c = frame.challenge as ProofChallenge;\n assertChallenge(c, scope, now);\n if (c.adapter !== pending.adapter || c.externalKey !== pending.externalKey) throw new Error(\"Peer changed the requested external key\");\n await this.options.storage.update(l => ({ ...l, outgoing: [c] }));\n clearTimeout(pending.timer); this.waiting.delete(frame.id as string); pending.resolve(c);\n } else if (frame.t === 'proof-present') {\n const c = frame.challenge as ProofChallenge, event = frame.event as ProofEvidence;\n assertChallenge(c, this.scope(true), now);\n if (this.options.supports?.(c.adapter) === false) throw new Error(\"Unsupported peer proof\");\n if (!this.options.storage.read().incoming.some(x => proofStatement(x) === proofStatement(c))) throw new Error('Unknown or reused proof challenge');\n await verifyPeerProof(event, c, this.options.readStorage);\n await this.options.storage.update(l => {\n assertChallenge(c, this.scope(true), this.now());\n // Consuming and recording are one transaction. An unknown nonce is always rejected,\n // including after restart, reconnect, or expiry of the bounded pending ledger.\n if (!l.incoming.some(x => proofStatement(x) === proofStatement(c))) throw new Error('Unknown or reused proof challenge');\n return { ...l, incoming: l.incoming.filter(x => x.nonce !== c.nonce),\n remote: replace(l.remote, { challenge: c, event, verifiedAt: now, status: 'accepted' }) };\n });\n this.options.send({ t: 'proof-accepted', id: event.id });\n } else if (frame.t === 'proof-accepted') {\n await this.options.storage.update(l => ({ ...l, local: l.local.map(r => r.event.id === frame.id &&\n r.challenge.subject === scope.subject && r.challenge.audience === scope.audience && r.challenge.context === scope.context && r.status === 'pending'\n ? { ...r, status: 'accepted' } : r) }));\n } else if (frame.t === 'proof-withdrawn') {\n await this.options.storage.update(l => ({ ...l, local: l.local.map(r => r.event.id === frame.id && r.status === 'withdrawal-pending' ? { ...r, status: 'withdrawn' } : r) }));\n } else if (frame.t === 'proof-withdraw') {\n if (typeof frame.id !== 'string' || !hex.test(frame.id)) return;\n await this.options.storage.update(l => ({ ...l, remote: l.remote.map(r => r.event.id === frame.id ? { ...r, status: 'withdrawn' } : r) }));\n this.options.send({ t: 'proof-withdrawn', id: frame.id });\n }\n } catch (e) { this.options.onError?.(e instanceof Error ? e.message : 'Invalid peer proof'); }\n }\n stop(): void {\n for (const p of this.waiting.values()) { clearTimeout(p.timer); p.reject(new Error('Connection closed')); }\n this.waiting.clear();\n }\n}\n","import { ed25519, x25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { fromBase64Url, isZ32Key, toBase64Url, utf8Encode } from \"./bytes\";\nimport { encrypt, tryDecrypt } from \"./crypto\";\nimport { identityFromSeed, identityFromSeedB64, publicKeyFromZ32, sign, verify, type Identity } from \"./identity\";\nimport type { LinkParams } from \"./invite\";\nimport type { PairingCredentials } from \"./pairedSession\";\nimport { RELAY_URL, RELAY_WITH_SECRETS, relayUrl, type TransportDescriptors } from \"./pairedTransports\";\nimport { measureRecords, MAX_DNS_PACKET_BYTES, type GhostRecord, type SignedPacket } from \"./pkarr\";\nimport { sanitizeNick } from \"./text\";\nimport { budgetRetryMs, isDiscoveryBudgetError, type PkarrRequestOptions, type PkarrTransport } from \"./transport\";\n\n/**\n * The layer-0 capability record of a chat (WISP 03, revision 0.2): what each side accepts on the DHT\n * (`dht-text/1`, `hold/1`), what its layer 1 would carry, the minimum to dial its native transports\n * without a WebRTC session first, and the name it shares. One Pkarr key per direction, derived from the\n * invite secret like the DHT mailboxes, so its size never competes with a text.\n *\n * Sealed with the invitation-derived key until the contact is pinned, and with a key only the two\n * participation keys derive afterwards, so a copied invite stops reading it. Always signed by the\n * author's participation key over both rendezvous keys.\n */\nexport const DHT_TEXT_CAPABILITY = \"dht-text/1\" as const;\nexport const CAPS_LABEL = \"_caps\";\nexport const CAPS_LIMITS = {\n versions: 8,\n transports: 8,\n capabilities: 32,\n extensions: 32,\n /** One identifier, capability or extension. */\n itemChars: 48,\n nameBytes: 64,\n} as const;\n/**\n * How far before its own clock an author dates a record (`issued`). No reader orders records by that time, `rev` does,\n * and this one refuses none for it. Apps up to 1.0.2 refuse a record dated more than a minute past their clock: one\n * dated by a clock two minutes ahead was never read by them, with nothing on screen, and the chat could not dial its\n * contact's native transports before a session. Dated back, a record from a clock up to about eleven minutes ahead is\n * taken by them too.\n */\nexport const CAPS_ISSUED_BACK_MS = 10 * 60_000;\n/** Published again this often while the chat exists, so it does not age out of the DHT. */\nexport const CAPS_REFRESH_MS = 60 * 60_000;\n/** Reads of the contact's record closer together than this are merged into one. */\nconst CAPS_READ_SPACING_MS = 15_000;\n/**\n * An envelope named a revision of the contact's record and the read found an older one, or none: read again this long\n * after each read, while still behind. A DHT read directly (Desktop, CLI, relay reads off) hands back the copy it\n * already knows and looks the key up behind it, and a lookup that started before the publication landed finds the old\n * one; a relay may serve an old copy for a while too. The envelope names each revision once, so one read was the last\n * until the next envelope, minutes away, and the chat stayed on the DHT with no descriptors to dial.\n *\n * The first ones come soon: a contact's record that lists a native transport with no descriptor is the \"Peer native\n * address unavailable\" a dial ends with, and its revision with the descriptors is usually out a second or two after the\n * first (its endpoints were starting). Read 5 s, then 20 s after, two Desktops DHT direct with Iroh's relay out of reach\n * went live 11 to 28 s after their chats opened (2026-10-07). One read more than before, three in the first 7 s.\n */\nconst CAPS_READ_RETRY_MS = [1_000, 2_000, 4_000, 15_000, 60_000] as const;\nconst NATIVE = [\"iroh/1\", \"hyperdht/1\"] as const;\n/** The native transports a record says how to dial. */\nconst described = (content: CapsContent) => NATIVE.filter(t => !!content.descriptors[t]);\n/**\n * Changes closer together than this go out as one publication, the last: every publication spends one of the\n * relays' requests per relay, a budget the chat's signaling needs more.\n */\nexport const CAPS_PUBLISH_SPACING_MS = 30_000;\n\n/**\n * Per native transport, the minimum to dial it: no network address, ever. Keys travel as base64url (32\n * bytes, 43 characters) to leave the packet room for capabilities.\n */\nexport interface CapsDescriptors {\n \"iroh/1\"?: { id: string; relay?: string };\n /** `relay`: a browser's HyperDHT is reached through a relay server, which it names (a public service, not its address). */\n \"hyperdht/1\"?: { publicKey: string; relay?: string };\n}\nexport interface CapsContent {\n versions: number[];\n /** Layer-1 transports this runtime has, in local preference order. Never the DHT. */\n transports: string[];\n capabilities: string[];\n extensions: string[];\n descriptors: CapsDescriptors;\n /** The name this profile shares with contacts; empty when it shares none. */\n name: string;\n /**\n * The layer-1 transport chosen for this chat in its Connection menu, absent on Automatic (WISP 100, \"A choice made\n * while not live\"). It reaches a contact that has no session to hear a switch intent on. A trailing element: apps\n * from before it ignore it.\n */\n choice?: string;\n}\nexport interface CapsRecord extends CapsContent {\n rev: number;\n issued: number;\n /** The participation key that signed it. */\n author: string;\n}\ntype Body = [version: 1, rev: number, issued: number, author: string, versions: number[], transports: string[], capabilities: string[],\n extensions: string[], descriptors: CapsDescriptors, name: string, choice?: string];\n\nexport type CapsRefusal = \"address\" | \"size\" | \"sealed\" | \"format\" | \"signature\" | \"author\" | \"rev\";\n/** Why a record was not used. A refused record leaves the last good one in force. */\nexport class CapsRefusedError extends Error {\n constructor(readonly reason: CapsRefusal, message: string) { super(message); }\n}\n\nconst IDENT = /^[a-z0-9][a-z0-9._-]*\\/[0-9]+$/;\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst KEY = /^[A-Za-z0-9_-]{43}$/;\nconst hexToKey = (hex: string) => toBase64Url(Uint8Array.from(hex.match(/../g)!, b => parseInt(b, 16)));\nconst keyToHex = (key: string) => Array.from(fromBase64Url(key), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n/**\n * The part of the native descriptors a capability record may carry: the Iroh endpoint id (and the relay\n * it is reachable through, a public service rather than an address of this device), the HyperDHT key.\n */\nexport function capsDescriptors(descriptors: TransportDescriptors | undefined): CapsDescriptors {\n const out: CapsDescriptors = {};\n const iroh = descriptors?.[\"iroh/1\"] as { id?: unknown; relay?: unknown } | undefined;\n if (iroh && typeof iroh.id === \"string\" && HEX64.test(iroh.id))\n out[\"iroh/1\"] = { id: hexToKey(iroh.id), ...(relayUrl(iroh.relay) ? { relay: iroh.relay } : {}) };\n const hyper = descriptors?.[\"hyperdht/1\"] as { publicKey?: unknown; relay?: unknown } | undefined;\n if (hyper && typeof hyper.publicKey === \"string\" && HEX64.test(hyper.publicKey))\n out[\"hyperdht/1\"] = { publicKey: hexToKey(hyper.publicKey), ...(relayUrl(hyper.relay) ? { relay: hyper.relay } : {}) };\n return out;\n}\n\n/**\n * A record's descriptors as the transport adapters dial them. With no address in the record, an Iroh path is\n * relayed; a HyperDHT that names a relay (a browser's) is too: both rank after direct paths and before the DHT\n * floor (WISP 100, \"Relayed\"), and a first contact can dial them before WebRTC has failed.\n */\nexport function dialDescriptors(descriptors: CapsDescriptors): TransportDescriptors {\n const out: TransportDescriptors = {};\n const iroh = descriptors[\"iroh/1\"], hyper = descriptors[\"hyperdht/1\"];\n if (iroh) out[\"iroh/1\"] = { id: keyToHex(iroh.id), relay: iroh.relay ?? null, addresses: [], relayed: true };\n if (hyper) out[\"hyperdht/1\"] = { publicKey: keyToHex(hyper.publicKey), ...(hyper.relay ? { relay: hyper.relay, relayed: true } : {}) };\n return out;\n}\n\nconst list = (value: unknown, max: number, item: (v: unknown) => boolean): boolean =>\n Array.isArray(value) && value.length <= max && value.every(item);\nconst ident = (v: unknown) => typeof v === \"string\" && v.length <= CAPS_LIMITS.itemChars && IDENT.test(v);\n\nfunction parseDescriptors(value: unknown): CapsDescriptors | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n // Descriptors of transports this reader does not know are skipped, not a reason to refuse the record.\n const raw = value as Record<string, { id?: unknown; relay?: unknown; publicKey?: unknown } | undefined>;\n const out: CapsDescriptors = {};\n const iroh = raw[\"iroh/1\"], hyper = raw[\"hyperdht/1\"];\n // A relay with a login, a query or a fragment (an older app's HyperDHT relay, as set): its descriptor is not kept,\n // and the rest of the record still is.\n const withSecrets = (relay: unknown) => typeof relay === \"string\" && RELAY_WITH_SECRETS.test(relay);\n if (iroh !== undefined) {\n if (!iroh || typeof iroh.id !== \"string\" || !KEY.test(iroh.id) || (iroh.relay !== undefined && (typeof iroh.relay !== \"string\" || !RELAY_URL.test(iroh.relay)))) return null;\n if (!withSecrets(iroh.relay)) out[\"iroh/1\"] = { id: iroh.id, ...(iroh.relay !== undefined ? { relay: iroh.relay as string } : {}) };\n }\n if (hyper !== undefined) {\n if (!hyper || typeof hyper.publicKey !== \"string\" || !KEY.test(hyper.publicKey) || (hyper.relay !== undefined && (typeof hyper.relay !== \"string\" || !RELAY_URL.test(hyper.relay)))) return null;\n if (!withSecrets(hyper.relay)) out[\"hyperdht/1\"] = { publicKey: hyper.publicKey, ...(hyper.relay !== undefined ? { relay: hyper.relay as string } : {}) };\n }\n return out;\n}\n\n/**\n * A group link's transports in its own packet (`_tr`, WISP 902 § Transports): a group's edge or entry session has no\n * capability record, so an app with no WebRTC (the Linux Desktop) says there which layer-1 transports it runs and how to\n * dial its native ones, and a member's app that has WebRTC answers in kind. The same minimum a record carries: keys and\n * relays, never an address. Sealed with the link key like every other label of the packet.\n */\nexport interface PacketTransports {\n transports: PairedTransportName[];\n descriptors: CapsDescriptors;\n}\ntype PairedTransportName = \"iroh/1\" | \"hyperdht/1\" | \"webrtc/1\";\nconst PACKET_TRANSPORTS: readonly string[] = [\"iroh/1\", \"hyperdht/1\", \"webrtc/1\"];\n\n/** The `_tr` value: `{\"t\": transports, \"d\": descriptors}`, versionless and additive (an unknown field is ignored). */\nexport function encodePacketTransports(transports: readonly string[], descriptors: TransportDescriptors | undefined): string {\n return JSON.stringify({ t: transports.filter(t => PACKET_TRANSPORTS.includes(t)), d: capsDescriptors(descriptors) });\n}\n\n/** A `_tr` value read from a packet; null when it is not one (a reader drops it, as a record it cannot read). */\nexport function parsePacketTransports(json: string | null): PacketTransports | null {\n if (!json || json.length > 1_000) return null;\n try {\n const value = JSON.parse(json) as { t?: unknown; d?: unknown };\n if (!value || typeof value !== \"object\" || !Array.isArray(value.t) || value.t.length > CAPS_LIMITS.transports) return null;\n const transports = value.t.filter((t): t is PairedTransportName => typeof t === \"string\" && PACKET_TRANSPORTS.includes(t));\n const descriptors = parseDescriptors(value.d ?? {});\n if (!descriptors) return null;\n return { transports: [...new Set(transports)], descriptors };\n } catch { return null; }\n}\n\n/** Keys of the capability record of one link: my record's key and seals, the contact's address. */\nexport class CapsKeys {\n readonly from: string;\n readonly to: string;\n readonly me: string;\n /** Publishes my record. */\n readonly identity: Identity;\n /** Where the contact publishes its record. */\n readonly peerAddress: string;\n private readonly seed: Uint8Array;\n private readonly inviteKey: Uint8Array;\n\n constructor(params: LinkParams, participationSeedB64: string) {\n this.from = identityFromSeedB64(params.seedB64).pubKeyZ32;\n this.to = params.peerPubKeyZ32;\n const mine = identityFromSeedB64(participationSeedB64);\n this.seed = mine.seed;\n this.me = mine.pubKeyZ32;\n const secret = fromBase64Url(params.encKeyB64);\n const context = JSON.stringify([\"ghostly-caps/1\", [this.from, this.to].sort()]);\n const derive = (label: string) => hkdf(sha256, secret, utf8Encode(context), utf8Encode(label), 32);\n this.identity = identityFromSeed(derive(`caps:${this.from}`));\n this.peerAddress = identityFromSeed(derive(`caps:${this.to}`)).pubKeyZ32;\n this.inviteKey = derive(\"envelope\");\n }\n\n /** The key sealed for each pinned contact: one X25519 per contact and link, not one per seal and open (agents#1087). */\n private readonly pinned = new Map<string, Uint8Array>();\n\n private pinnedKey(peer: string): Uint8Array {\n let key = this.pinned.get(peer);\n if (!key) {\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peer)));\n key = hkdf(sha256, shared, this.inviteKey, utf8Encode(\"ghostly-caps-participation/1\"), 32);\n // A link pins one contact; a few more (a re-pin, a device change) stay bounded.\n if (this.pinned.size >= 4) this.pinned.delete(this.pinned.keys().next().value!);\n this.pinned.set(peer, key);\n }\n return key;\n }\n private signable(from: string, to: string, body: unknown[]): Uint8Array { return utf8Encode(JSON.stringify([\"ghostly-caps\", from, to, body])); }\n\n /**\n * My record as Pkarr records, sealed for the pinned contact (or with the invite key before the pin).\n * Past 1,000 bytes the name goes first, then the extensions; capabilities and transports are never cut.\n */\n seal(content: CapsContent, rev: number, peerKey?: string, now = Date.now()): { records: GhostRecord[]; dropped: (\"name\" | \"extensions\")[] } {\n const dropped: (\"name\" | \"extensions\")[] = [];\n let name = content.name, extensions = content.extensions;\n for (;;) {\n const body: Body = [1, rev, now - CAPS_ISSUED_BACK_MS, this.me, content.versions, content.transports, content.capabilities, extensions, content.descriptors, name,\n ...(content.choice ? [content.choice] : [])] as Body;\n const signature = toBase64Url(sign(this.signable(this.from, this.to, body), this.seed));\n const records = [{ label: CAPS_LABEL, value: encrypt(JSON.stringify([body, signature]), peerKey ? this.pinnedKey(peerKey) : this.inviteKey), ttl: 3600 }];\n if (measureRecords(this.identity.pubKeyZ32, records) <= MAX_DNS_PACKET_BYTES) return { records, dropped };\n if (name) { name = \"\"; dropped.push(\"name\"); continue; }\n if (extensions.length) { extensions = []; dropped.push(\"extensions\"); continue; }\n throw new CapsRefusedError(\"size\", \"The capability record does not fit a DHT packet even without its name and extensions.\");\n }\n }\n\n /**\n * The contact's record, checked: its address, its seal, a well-formed body, a signature by the pinned\n * participation key (before the pin, by `expected` when a first contact named one) and not older than `minRev`.\n *\n * Its `issued` is the author's word on its own clock and refuses nothing. A record is the author's alone (signed by\n * its participation key, bound to both rendezvous keys), and an older one cannot take a newer one's place because of\n * `rev`, which the reader keeps. Refusing a record dated over a minute ahead added nothing to that, and cost every\n * contact whose clock runs a couple of minutes fast its record.\n */\n open(packet: SignedPacket, options: { pinned?: string; expected?: string; minRev?: number } = {}): CapsRecord {\n if (packet.pubKeyZ32 !== this.peerAddress) throw new CapsRefusedError(\"address\", \"Not this contact's capability record.\");\n if (measureRecords(packet.pubKeyZ32, packet.records) > MAX_DNS_PACKET_BYTES) throw new CapsRefusedError(\"size\", \"Capability record over the DHT packet budget.\");\n const sealed = packet.records.filter(r => r.label === CAPS_LABEL);\n if (sealed.length !== 1) throw new CapsRefusedError(\"format\", \"No single capability record.\");\n const plaintext = (options.pinned ? tryDecrypt(sealed[0].value, this.pinnedKey(options.pinned)) : null) ?? tryDecrypt(sealed[0].value, this.inviteKey);\n if (!plaintext) throw new CapsRefusedError(\"sealed\", \"The capability record cannot be opened with this chat's keys.\");\n let envelope: unknown;\n try { envelope = JSON.parse(plaintext); } catch { throw new CapsRefusedError(\"format\", \"Malformed capability record.\"); }\n if (!Array.isArray(envelope) || envelope.length !== 2 || !Array.isArray(envelope[0]) || typeof envelope[1] !== \"string\" || !SIG.test(envelope[1]))\n throw new CapsRefusedError(\"format\", \"Malformed capability record.\");\n const body = envelope[0] as unknown[], signature = envelope[1];\n // Trailing elements a later revision may add are carried by the signature and otherwise ignored.\n if (body.length < 10 || body.length > 16) throw new CapsRefusedError(\"format\", \"Malformed capability record.\");\n const [version, rev, issued, author, versions, transports, capabilities, extensions, rawDescriptors, name, choice] = body;\n const descriptors = parseDescriptors(rawDescriptors);\n if (version !== 1 || !Number.isSafeInteger(rev) || (rev as number) < 0 || !Number.isSafeInteger(issued) || (issued as number) <= 0 ||\n !isZ32Key(author) ||\n !list(versions, CAPS_LIMITS.versions, v => Number.isSafeInteger(v) && (v as number) > 0) ||\n !list(transports, CAPS_LIMITS.transports, ident) || (transports as string[]).includes(\"dht/1\") ||\n !list(capabilities, CAPS_LIMITS.capabilities, ident) || !list(extensions, CAPS_LIMITS.extensions, ident) ||\n !descriptors || typeof name !== \"string\" || utf8Encode(name).length > CAPS_LIMITS.nameBytes ||\n (choice !== undefined && (!ident(choice) || choice === \"dht/1\")))\n throw new CapsRefusedError(\"format\", \"Malformed capability record.\");\n const signer = options.pinned ?? options.expected;\n if (signer && author !== signer) throw new CapsRefusedError(\"author\", \"The capability record is signed by another participation key than this contact's.\");\n try {\n if (!verify(fromBase64Url(signature), this.signable(this.to, this.from, body), publicKeyFromZ32(author)))\n throw new CapsRefusedError(\"signature\", \"The capability record's signature does not verify.\");\n } catch (error) {\n if (error instanceof CapsRefusedError) throw error;\n throw new CapsRefusedError(\"signature\", \"The capability record's signature does not verify.\");\n }\n if (options.minRev !== undefined && (rev as number) < options.minRev) throw new CapsRefusedError(\"rev\", \"An older capability record than one already seen.\");\n // The name is the contact's text, shown as it is: cleaned as a nickname from any other source, empty when nothing\n // visible is left.\n return { rev: rev as number, issued: issued as number, author, versions: versions as number[], transports: transports as string[],\n capabilities: capabilities as string[], extensions: extensions as string[], descriptors, name: sanitizeNick(name) ?? \"\", ...(choice !== undefined ? { choice: choice as string } : {}) };\n }\n}\n\nexport interface CapsState {\n /** My record's revision: increases with every change of its content. */\n rev: number;\n /**\n * A digest of the content of revision `rev`, and when it was last published, and whether sealed for the pinned\n * contact. No `publishedAt`: that revision is not known to be out (a publication failed, or was cut short), and goes\n * out at the next look.\n */\n digest?: string;\n publishedAt?: number;\n sealedFor?: string;\n /** The contact's last good record. */\n peer?: CapsRecord;\n}\nexport const emptyCapsState = (): CapsState => ({ rev: 0 });\n\nconst digestOf = (content: CapsContent) => toBase64Url(sha256(utf8Encode(JSON.stringify(content)))).slice(0, 22);\n\n/**\n * Publishes this side's record (at first start, at every change, hourly) and reads the contact's (at\n * pairing, when an envelope names a newer revision, when the chat drops to the DHT). Publications go one\n * at a time, and reads one at a time beside them (a read never waits for a put); reads close together are merged.\n */\nexport class CapsExchange {\n private state: CapsState;\n private readonly keys: CapsKeys;\n /** Publications, one at a time; reads of the contact's record (another key) have their own, so neither waits for the other. */\n private chain: Promise<unknown> = Promise.resolve();\n private readChain: Promise<unknown> = Promise.resolve();\n private saveChain: Promise<unknown> = Promise.resolve();\n private timer: ReturnType<typeof setTimeout> | null = null;\n private running = false;\n private lastRead = 0;\n private readTimer: ReturnType<typeof setTimeout> | null = null;\n private readBackground = false;\n /** The newest revision of the contact's record an envelope named, and the reads made again since for it. */\n private named = -1;\n private retries = 0;\n /** A revision named since the last new record read started the read-again chain: the next ones named are only background reads. */\n private chased = false;\n private retryTimer: ReturnType<typeof setTimeout> | null = null;\n /** What the last publication of this run carried. */\n private lastOut?: CapsContent;\n private dropped: (\"name\" | \"extensions\")[] = [];\n\n constructor(private readonly options: {\n params: LinkParams;\n credentials: PairingCredentials;\n transport: PkarrTransport;\n local(): CapsContent;\n state?: CapsState;\n save(state: CapsState): Promise<void>;\n /** The contact's record changed (a newer revision was read). */\n changed?(record: CapsRecord): void;\n /** A new revision of this side's record went out: the contact learns of it from an envelope that names it. */\n published?(rev: number): void;\n /** A record was refused; `author` is a security signal (another key signed under this chat's address). */\n refused?(error: CapsRefusedError): void;\n }) {\n this.state = structuredClone(options.state ?? emptyCapsState());\n this.keys = new CapsKeys(options.params, options.credentials.seedB64);\n }\n\n get rev(): number { return this.state.rev; }\n get peer(): CapsRecord | undefined { return this.state.peer; }\n /** What had to be left out to fit the packet at the last publication. */\n get droppedFields(): readonly (\"name\" | \"extensions\")[] { return this.dropped; }\n get address(): string { return this.keys.identity.pubKeyZ32; }\n\n private serialize<T>(run: () => Promise<T>, chain: \"chain\" | \"readChain\" | \"saveChain\" = \"chain\"): Promise<T> {\n const next = this[chain].then(run); this[chain] = next.catch(() => {}); return next;\n }\n /** Saves are one at a time, each over the state as it is then: a read and a publication change different fields. */\n private persist(patch: Partial<CapsState>): Promise<void> {\n return this.serialize(async () => { const next = { ...this.state, ...patch }; await this.options.save(structuredClone(next)); this.state = next; }, \"saveChain\");\n }\n\n start(): void {\n if (this.running || this.ended) return;\n this.running = true;\n void this.update().catch(() => {});\n // Paired, and the contact's record never read: once. After that, a newer revision named in an envelope,\n // a drop or a new pin is what reads it again, not every start. One named before a late start is read now.\n if (this.options.credentials.peerKey && (!this.state.peer || this.named > this.state.peer.rev)) this.refresh(true);\n }\n /** Stopped for good: a start still waiting (the engine starts it once the chat's endpoints are up) does nothing. */\n private ended = false;\n async stop(): Promise<void> {\n this.ended = true;\n this.running = false;\n if (this.timer) clearTimeout(this.timer);\n if (this.readTimer) clearTimeout(this.readTimer);\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.timer = this.readTimer = this.retryTimer = null;\n await Promise.all([this.chain, this.readChain]);\n await this.saveChain;\n }\n\n /**\n * Publishes when the content changed, when the contact was pinned since the last publication (the\n * record is sealed anew for it), or when the last one is an hour old. Otherwise nothing goes out.\n */\n update(): Promise<void> {\n return this.serialize(async () => {\n if (!this.running) return;\n const content = this.options.local(), digest = digestOf(content), now = Date.now();\n const peerKey = this.options.credentials.peerKey;\n const changed = digest !== this.state.digest;\n // A revision saved but not known to be out (its publication failed): it goes now, as it is.\n const unpublished = this.state.digest !== undefined && !this.state.publishedAt;\n const due = changed || peerKey !== this.state.sealedFor || !this.state.publishedAt || now - this.state.publishedAt >= CAPS_REFRESH_MS;\n // A change right after a publication waits for the spacing; a new pin does not (the contact reads it next).\n // Nor does a native transport that can be dialled now and could not at the last one (its endpoint came up after the\n // record went out): the contact waits for it to go live. Once per transport and run, so the budget barely notices.\n const dialable = !!this.lastOut && described(content).some(t => !described(this.lastOut!).includes(t));\n const soon = changed && !dialable && peerKey === this.state.sealedFor && !!this.state.publishedAt && now - this.state.publishedAt < CAPS_PUBLISH_SPACING_MS;\n if (due && soon) { this.schedule(this.state.publishedAt! + CAPS_PUBLISH_SPACING_MS - now); return; }\n if (due) {\n const options = changed || unpublished ? undefined : { background: true };\n // No relay takes it now: refused before it is sealed and saved (`LinkSession.publishOnce`). With 500 contacts\n // away, about 380 records a minute were sealed, and their rows saved, for none that went.\n const held = this.options.transport.publishHeld?.(this.keys.identity.pubKeyZ32, options);\n if (held) { this.schedule(budgetRetryMs(held, 1_000, 60_000)); throw held; }\n const rev = changed ? this.state.rev + 1 : this.state.rev;\n const { records, dropped } = this.keys.seal(content, rev, peerKey, now);\n this.dropped = dropped;\n // The revision is saved before it is published, so a crash never reuses it for other content; until it is\n // out, it has no `publishedAt`, so a publication that fails (or a crash) does not lose it until the hourly one.\n // Saved already as it is (a publication that failed before): not again.\n const saved = rev === this.state.rev && digest === this.state.digest && peerKey === this.state.sealedFor && this.state.publishedAt === undefined;\n if (!saved) await this.persist({ rev, digest, sealedFor: peerKey, publishedAt: undefined });\n try { await this.options.transport.publish(this.keys.identity, records, options); }\n catch (error) {\n // Held back by the relays' request budget: again when the budget frees a request; any other failure, in a minute.\n this.schedule(isDiscoveryBudgetError(error) ? budgetRetryMs(error, 1_000, 60_000) : 60_000);\n throw error;\n }\n await this.persist({ publishedAt: now });\n this.lastOut = content;\n if (changed || unpublished) this.options.published?.(rev);\n // This side can dial it now: a contact's record that listed it with no descriptor is worth a few reads again.\n if (dialable) { this.retries = 0; this.readAgainIfBehind(); }\n }\n this.schedule();\n });\n }\n private schedule(inMs?: number): void {\n if (this.timer) clearTimeout(this.timer);\n if (!this.running) return;\n const age = Date.now() - (this.state.publishedAt ?? 0);\n // A failed publication already scheduled its retry.\n this.timer = setTimeout(() => void this.update().catch(() => {}), inMs ?? Math.max(60_000, CAPS_REFRESH_MS - age));\n }\n\n /**\n * An envelope named this revision of the contact's record: read it when it is newer than the one known. The number is\n * the contact's word, not a record: read at the spacing. The first one named since the last new record read is read as\n * the chat's own (not background) and starts the read-again chain over: a chat waits on it (a transport chosen, a\n * descriptor), and while a link signals the relays hand a held background read the old copy. Any other is background\n * upkeep until a new record is read. An envelope every 4 s naming a higher one each time made 45 reads a minute.\n */\n peerRev(rev: number): void {\n if (!Number.isSafeInteger(rev) || rev <= (this.state.peer?.rev ?? -1)) return;\n const chase = rev > this.named && !this.chased;\n if (rev > this.named) this.named = rev;\n if (chase) { this.chased = true; this.retries = 0; }\n this.refresh(false, !chase);\n }\n\n /**\n * Reads the contact's record now (or right after the last read, when that was a moment ago). `background`: upkeep,\n * on the background share of the relays' budget; a read asked for meanwhile that is not makes it one that is not.\n */\n refresh(force = false, background = false): void {\n if (!this.running) return;\n if (this.readTimer) { this.readBackground &&= background; return; }\n this.readBackground = background;\n const wait = force ? 0 : Math.max(0, this.lastRead + CAPS_READ_SPACING_MS - Date.now());\n const run = () => { this.readTimer = null; void this.read(this.readBackground ? { background: true } : undefined).catch(() => {}); };\n if (!wait) { this.readTimer = setTimeout(run, 0); return; }\n this.readTimer = setTimeout(run, wait);\n }\n\n /** Reads and checks the contact's record; the last good one stays when this one is refused. */\n read(options?: PkarrRequestOptions): Promise<CapsRecord | undefined> {\n const read = this.serialize(async () => {\n if (!this.running) return this.state.peer;\n this.lastRead = Date.now();\n const packet = await this.options.transport.resolve(this.keys.peerAddress, options);\n if (!packet || !this.running) return this.state.peer;\n let record: CapsRecord;\n try {\n record = this.keys.open(packet, { pinned: this.options.credentials.peerKey, minRev: this.state.peer?.rev });\n } catch (error) {\n if (error instanceof CapsRefusedError && error.reason !== \"rev\") this.options.refused?.(error);\n return this.state.peer;\n }\n if (this.state.peer && record.rev === this.state.peer.rev && record.author === this.state.peer.author) return this.state.peer;\n await this.persist({ peer: record });\n // A new revision: what it still lacks (a transport without its descriptor) is worth a few reads again.\n this.retries = 0; this.chased = false;\n this.options.changed?.(record);\n return record;\n }, \"readChain\");\n return read.finally(() => this.readAgainIfBehind());\n }\n\n /**\n * Read again in a moment, a few times at most, while the record known is short of what the contact has: of the\n * revision an envelope named, or of a descriptor for a native transport it lists (its endpoint was still starting)\n * that this side runs too. Its next revision, with the descriptor, is named only once, by an envelope that may\n * come before the record is out; without it neither side could dial the other. Started over only by a new record read,\n * the first revision named after one, or this side's own endpoint coming up: the chat's reads, not background ones.\n */\n private readAgainIfBehind(): void {\n if (this.retryTimer) clearTimeout(this.retryTimer);\n this.retryTimer = null;\n if (!this.running || this.retries >= CAPS_READ_RETRY_MS.length) return;\n const peer = this.state.peer;\n const behind = this.named > (peer?.rev ?? -1);\n const starting = !!peer && described(this.options.local()).some(t => peer.transports.includes(t) && !peer.descriptors[t]);\n if (!behind && !starting) return;\n this.retryTimer = setTimeout(() => { this.retryTimer = null; void this.read().catch(() => {}); }, CAPS_READ_RETRY_MS[this.retries++]);\n }\n}\n","import { fromBase64Url, toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { identityFromSeedB64, publicKeyFromZ32, sign, verify } from \"./identity\";\nimport { parseRtcSignal } from \"./signal\";\nimport type { Signer } from \"./signer\";\n\nconst transcript = (signal: string, from: string, to: string) =>\n utf8Encode(JSON.stringify([\"ghostly-paired-signal\", 1, from, to, JSON.parse(signal)]));\n\n/** Sign the existing compact signal, including its timestamp and DTLS binding.\n * Extra fields remain readable by first-increment clients during migration. */\nexport function signPairedSignal(signal: string, seed: string, from: string, to: string): string {\n const parsed = parseRtcSignal(signal);\n if (!parsed) throw new Error(\"Invalid outgoing signal\");\n const canonical = JSON.stringify(parsed);\n const identity = identityFromSeedB64(seed);\n return JSON.stringify({ ...parsed, auth: { key: identity.pubKeyZ32,\n sig: toBase64Url(sign(transcript(canonical, from, to), identity.seed)) } });\n}\n\n/** Invalid input never reaches DataLink's timestamp/glare/SDP state machine. */\nexport function verifyPairedSignal(signal: string, from: string, to: string,\n peerKey?: string, required = false): string | null {\n try {\n if (signal.length > 4096) return null;\n const raw = JSON.parse(signal);\n const parsed = parseRtcSignal(signal);\n if (!parsed) return null;\n if (!raw.auth) return required ? null : JSON.stringify(parsed);\n const { key, sig } = raw.auth;\n if (typeof key !== \"string\" || typeof sig !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(sig) ||\n (peerKey && key !== peerKey)) return null;\n const canonical = JSON.stringify(parsed);\n return verify(fromBase64Url(sig), transcript(canonical, from, to), publicKeyFromZ32(key)) ? canonical : null;\n } catch { return null; }\n}\n\n\n/** Keep at least one candidate. Drop duplicate candidate types first; if still\n * necessary prefer relay/server-reflexive reachability over another host route.\n * Every resulting set is signed afresh, never truncated after authentication. */\nexport function fitSignedPairedSignal(signal: string, seed: string, from: string, to: string,\n fits: (signed: string) => boolean): string {\n const parsed = parseRtcSignal(signal);\n if (!parsed) throw new Error(\"Invalid outgoing signal\");\n for (;;) {\n const signed = signPairedSignal(JSON.stringify(parsed), seed, from, to);\n if (fits(signed)) return signed;\n if (parsed.c.length <= 1) throw new Error(\"Signed connection details exceed the discovery packet budget\");\n parsed.c.splice(candidateToDrop(parsed.c), 1);\n }\n}\n\n/** The candidate a signal that does not fit loses next. */\nfunction candidateToDrop(candidates: string[]): number {\n let remove = -1;\n for (const type of [\"h\", \"s\", \"r\"]) {\n const indexes = candidates.map((c, i) => c.startsWith(`${type},`) ? i : -1).filter(i => i >= 0);\n if (indexes.length > 1) { remove = indexes[indexes.length - 1]; break; }\n }\n if (remove < 0) remove = candidates.findIndex(c => c.startsWith(\"h,\"));\n if (remove < 0) remove = candidates.findIndex(c => c.startsWith(\"s,\"));\n return remove < 0 ? candidates.length - 1 : remove;\n}\n\n/**\n * `signPairedSignal` through a signer (a device link's: the app may hold no seed for a device signing key, WISP 06).\n * The same frame and the same transcript; only who signs differs.\n */\nexport async function signPairedSignalWith(signal: string, signer: Signer, from: string, to: string): Promise<string> {\n const parsed = parseRtcSignal(signal);\n if (!parsed) throw new Error(\"Invalid outgoing signal\");\n const canonical = JSON.stringify(parsed);\n return JSON.stringify({ ...parsed, auth: { key: toZ32(signer.publicKey),\n sig: toBase64Url(await signer.sign(transcript(canonical, from, to))) } });\n}\n\n/** `fitSignedPairedSignal` through a signer: the same candidates are dropped in the same order. */\nexport async function fitSignedPairedSignalWith(signal: string, signer: Signer, from: string, to: string,\n fits: (signed: string) => boolean): Promise<string> {\n const parsed = parseRtcSignal(signal);\n if (!parsed) throw new Error(\"Invalid outgoing signal\");\n for (;;) {\n const signed = await signPairedSignalWith(JSON.stringify(parsed), signer, from, to);\n if (fits(signed)) return signed;\n if (parsed.c.length <= 1) throw new Error(\"Signed connection details exceed the discovery packet budget\");\n parsed.c.splice(candidateToDrop(parsed.c), 1);\n }\n}\n","import { PROOF_ADAPTERS, proofCapability, type ProofAdapter } from \"./peerProofs\";\nimport { IDENTITY_PROOF_CAPABILITY } from \"./identityProofs\";\nimport { HOLD_CAPABILITY } from \"./storeForward\";\nimport { fromBase64Url, isZ32Key, randomBytes, toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { identityFromSeedB64, publicKeyFromZ32, sign, verify } from \"./identity\";\nimport type { FrameChannel } from \"./frames\";\nimport { rankTransports, type PairedTransport, type NativeBinding } from \"./pairedTransports\";\nimport type { Signer } from \"./signer\";\n\n/** Experimental, opt-in profile. Ed25519 authenticates a transcript bound to WebRTC DTLS.\n * This is not a new cipher/key exchange, nor an audited WISP Final profile. */\nexport const PAIRED_PROFILE = \"paired-chat/1\" as const;\nexport interface PairingState {\n transport?: PairedTransport;\n preferred?: PairedTransport;\n status: \"connecting\" | \"negotiating\" | \"confirm\" | \"waiting\" | \"ready\" | \"error\";\n code?: string;\n error?: string;\n peerKey?: string;\n verified?: boolean;\n peerNeedsConfirmation?: boolean;\n keyMismatch?: boolean;\n transitionTarget?: PairedTransport;\n transitionError?: string;\n}\nexport interface PairingCredentials {\n /** This side's participation seed. Not read when `signer` is given (a device link passes an empty one). */\n seedB64: string;\n /**\n * Signs in place of the seed (WISP 06 § Terms): a device link's participation key is the device signing key, which\n * the app may hold no seed for. The session then names `signer.publicKey` as its key and signs its transcript\n * through it. Absent, as in every chat and group: the seed signs, exactly as before.\n */\n signer?: Signer;\n peerKey?: string;\n requireSignedSignals?: boolean;\n verifiedPeerKey?: string;\n /**\n * The key the invite named (a `ghostly1` code carries the inviter's): before\n * anything is pinned, an answer signed by any other key is a security rejection.\n */\n expectedPeerKey?: string;\n}\ninterface Offer {\n t: \"pair-offer\";\n versions: number[];\n transports: string[];\n capabilities: string[];\n /** Absent in apps that do not send it; see `OFFER_EXTENSIONS`. */\n extensions?: string[];\n key: string;\n nonce: string;\n}\nexport interface PairedSessionOptions {\n credentials: PairingCredentials;\n rendezvousKeys: [string, string];\n /** SHA-256 certificate fingerprints extracted from this exact RTCPeerConnection. */\n fingerprints?: [string, string];\n binding?: NativeBinding;\n transports?: PairedTransport[];\n allowFallback?: boolean;\n proofSupport?: boolean;\n /** Identity proofs (WISP 300): `identity-proof/1`. */\n identitySupport?: boolean;\n filesSupport?: boolean;\n paymentsSupport?: boolean;\n /** Ecash straight in the chat. Absent means allowed, as before ways of paying could be chosen per chat. */\n cashuPaymentsSupport?: boolean;\n /** Lightning invoices in the chat. Absent means allowed. */\n lightningPaymentsSupport?: boolean;\n arkPaymentsSupport?: boolean;\n usdtPaymentsSupport?: boolean;\n barkPaymentsSupport?: boolean;\n transportSwitchSupport?: boolean;\n /** Store-and-forward for an away contact (`hold/1`): this device accepts held items and may hold some. */\n holdSupport?: boolean;\n /** TOFU admission is distinct from an optional human comparison. */\n trustOnFirstUse?: boolean;\n /**\n * How long the peer has to authenticate before the session fails: three minutes by default, room for a person to\n * compare codes. A connection that holds a place no person waits on (one dialled in on a pinned chat) gets less.\n */\n authTimeoutMs?: number;\n verifyPeer?: (key: string) => Promise<void>;\n /** Atomic durable compare-and-set. Resolving means the key is pinned on disk. */\n pinPeer: (key: string, signedSignals?: boolean) => Promise<void>;\n onState: (state: PairingState) => void;\n onReady: () => void;\n onApplication: (data: string | Uint8Array) => void | Promise<void>;\n onFailure: () => void;\n}\n\n/** The ways of paying a chat can allow one by one. */\n/**\n * `bitcoin` (on-chain), `fedimint` and `spark` are never offered in the handshake: a full offer is already at the 16\n * capabilities apps before 0.5 accept. Both sides allow them only through the `paired-payments` list of the open\n * session.\n */\nexport type PaymentMethodName = \"cashu\" | \"lightning\" | \"arkade\" | \"usdt\" | \"bark\" | \"bitcoin\" | \"fedimint\" | \"spark\";\n\n/**\n * What this app does that grants nothing, said outside `capabilities`: apps before 0.5 accept at most 16\n * of those, and a full offer is already there. The field is not in the transcript (an app that does not\n * know it could not sign it), so nothing that needs authenticating may go here; the DTLS binding of the\n * transcript still ties it to this connection. `ping/1`: this app answers `paired-ping`, from the open.\n */\nconst OFFER_EXTENSIONS = [\"ping/1\"];\n\nconst MAX_HANDSHAKE_BYTES = 4096;\n/** One frame from the peer, at most (UTF-16 units for text, bytes for binary): a bigger one breaks the protocol. */\nexport const SESSION_FRAME_MAX = 60 * 1024;\n/**\n * Frames received and not handled yet, at most: their count and their size together. Frames are handled one at a time,\n * each awaited (a group frame is decrypted, checked and stored before the next), and the peer sends at the network's\n * pace. A member back in a group answers a sync with a burst: a commit per epoch, its kept messages, the ones it hands\n * on, edits, reactions. With a bound of 64 frames a phone handling them a few milliseconds each failed its session\n * mid catch-up (\"Session receive limit exceeded\" then, \"Session receive queue full\" now, 2026-10-07). The size bound keeps the old worst case in memory\n * (64 frames of 60 KiB); the count only bounds a flood of tiny frames.\n */\nexport const SESSION_RECEIVE_PENDING = { frames: 1024, bytes: 64 * SESSION_FRAME_MAX } as const;\nconst NONCE = /^[A-Za-z0-9_-]{43}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst FINGERPRINT = /^[a-f0-9]{64}$/;\nconst isList = (v: unknown, maximum = 8): v is string[] => Array.isArray(v) && v.length > 0 && v.length <= maximum &&\n v.every(x => typeof x === \"string\" && /^[a-z0-9/-]{1,40}$/.test(x)) && new Set(v).size === v.length;\n\nfunction parseOffer(v: Record<string, unknown>): Offer | null {\n if (!Array.isArray(v.versions) || v.versions.length === 0 || v.versions.length > 8 ||\n !v.versions.every(n => Number.isSafeInteger(n) && n > 0) || new Set(v.versions).size !== v.versions.length ||\n !isList(v.transports) || !isList(v.capabilities, 32) || !isZ32Key(v.key) ||\n typeof v.nonce !== \"string\" || !NONCE.test(v.nonce)) return null;\n // Optional and new: one this app cannot read counts as none said, rather than failing the offer.\n const extensions = isList(v.extensions, 32) ? v.extensions : undefined;\n return { t: \"pair-offer\", versions: v.versions, transports: v.transports, capabilities: v.capabilities, ...(extensions && { extensions }), key: v.key, nonce: v.nonce };\n}\nconst offerTuple = (o: Offer) => [o.key, o.nonce, o.versions, o.transports, o.capabilities];\n\nexport class PairedSession {\n state: PairingState = { status: \"negotiating\" };\n /** The peer said nothing more within `authTimeoutMs`: the connection carried nothing, which proves nothing about the peer. */\n authTimedOut = false;\n /**\n * The peer sent faster than this side handles, past `SESSION_RECEIVE_PENDING`: the session ends, which is no proof\n * of anything wrong with the peer (a burst of catch-up on a slow device), so the chat dials again.\n */\n overloaded = false;\n /** The seed's identity; null when a signer signs. */\n private readonly identity;\n private readonly signer?: Signer;\n private readonly offer: Offer;\n private readonly transport: PairedTransport;\n private preferred?: PairedTransport;\n private peer: Offer | null = null;\n private transcript: Uint8Array | null = null;\n private digest = \"\";\n private proofReceived = false;\n private localReady = false;\n private peerReady = false;\n private stopped = false;\n private confirming = false;\n private admission: Promise<void> | null = null;\n private pending = 0;\n private pendingBytes = 0;\n private queue = Promise.resolve();\n private timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(private channel: FrameChannel, private options: PairedSessionOptions) {\n this.signer = options.credentials.signer;\n this.identity = this.signer ? null : identityFromSeedB64(options.credentials.seedB64);\n this.transport = options.binding?.transport ?? \"webrtc/1\";\n this.offer = { t: \"pair-offer\", versions: [1], transports: options.transports ?? [this.transport], capabilities: [\"chat/1\", \"signed-signal/1\", ...(options.trustOnFirstUse ? [\"tofu/1\"] : []), ...(options.filesSupport ? [\"files/2\"] : []), ...(options.paymentsSupport && (options.cashuPaymentsSupport !== false || options.lightningPaymentsSupport !== false) ? [\"payments/1\"] : []), ...(options.paymentsSupport && options.cashuPaymentsSupport !== false ? [\"payments-cashu/1\"] : []), ...(options.paymentsSupport && options.lightningPaymentsSupport !== false ? [\"payments-lightning/1\"] : []), ...(options.arkPaymentsSupport && options.paymentsSupport ? [\"payments-arkade/1\"] : []), ...(options.usdtPaymentsSupport && options.paymentsSupport ? [\"payments-usdt/1\"] : []), ...(options.barkPaymentsSupport && options.paymentsSupport ? [\"payments-bark/1\"] : []), ...(options.transportSwitchSupport ? [\"transport-switch/1\"] : []), ...(options.holdSupport ? [HOLD_CAPABILITY] : []), ...(options.proofSupport ? PROOF_ADAPTERS.map(proofCapability) : []), ...(options.identitySupport ? [IDENTITY_PROOF_CAPABILITY] : []), ...(options.allowFallback ? [\"transport-fallback/1\"] : [])],\n extensions: OFFER_EXTENSIONS, key: this.identity ? this.identity.pubKeyZ32 : toZ32(this.signer!.publicKey), nonce: toBase64Url(randomBytes(32)) };\n }\n\n supports(capability: \"files/2\" | \"payments/1\" | \"payments-arkade/1\" | \"payments-usdt/1\" | \"payments-bark/1\" | typeof HOLD_CAPABILITY): boolean { return this.state.status === \"ready\" && this.offer.capabilities.includes(capability) && !!this.peer?.capabilities.includes(capability); }\n /**\n * Both sides allow this way of paying. A peer that offers payments/1 without naming Cashu or\n * Lightning predates choosing them per chat, and allows both.\n */\n allowsPayment(method: PaymentMethodName): boolean {\n return this.state.status === \"ready\" && this.offer.capabilities.includes(`payments-${method}/1`) && this.peerAllowsPayment(method);\n }\n /** The peer's offer alone allows this way of paying. */\n peerAllowsPayment(method: PaymentMethodName): boolean {\n if (this.state.status !== \"ready\" || !this.peer) return false;\n const theirs = this.peer.capabilities, capability = `payments-${method}/1`;\n if (method === \"arkade\" || method === \"usdt\" || method === \"bark\" || method === \"bitcoin\" || method === \"fedimint\" || method === \"spark\") return theirs.includes(capability);\n const other = method === \"cashu\" ? \"payments-lightning/1\" : \"payments-cashu/1\";\n return theirs.includes(\"payments/1\") && (theirs.includes(capability) || !theirs.includes(other));\n }\n get peerTransportSwitchSupport(): boolean { return !!this.peer?.capabilities.includes(\"transport-switch/1\"); }\n /** The peer's offer alone carries `hold/1`: it accepts held items from us, whatever we offered. */\n get peerHoldSupport(): boolean { return !!this.peer?.capabilities.includes(HOLD_CAPABILITY); }\n\n get proofSession(): string { return this.digest; }\n get peerProofAdapters(): ProofAdapter[] { return PROOF_ADAPTERS.filter(a => this.offer.capabilities.includes(proofCapability(a)) && this.peer?.capabilities.includes(proofCapability(a))); }\n get peerProofSupport(): boolean { return this.peerProofAdapters.length > 0; }\n /** Both offers carry `identity-proof/1`. */\n get identitySupport(): boolean { return this.state.status === \"ready\" && this.offer.capabilities.includes(IDENTITY_PROOF_CAPABILITY) && !!this.peer?.capabilities.includes(IDENTITY_PROOF_CAPABILITY); }\n get peerTransports(): readonly string[] { return this.peer?.transports ?? []; }\n /** The peer said in its offer that it answers pings, so its silence from the open means it stopped. */\n get peerAnswersPings(): boolean { return !!this.peer?.extensions?.includes(\"ping/1\"); }\n get peerAllowsFallback(): boolean { return this.peer?.capabilities.includes(\"transport-fallback/1\") ?? false; }\n /** Frames received from the peer and not handled yet (the one being handled included). */\n get waiting(): number { return this.pending; }\n\n start(): void {\n const binding = this.options.binding;\n const validBinding = binding\n ? (binding.transport === \"hyperdht/1\" ? /^[a-f0-9]{128}$/.test(binding.context) : FINGERPRINT.test(binding.context)) && binding.identities.length === 2 && binding.identities.every(k => FINGERPRINT.test(k)) && binding.identities[0] !== binding.identities[1]\n : this.options.fingerprints?.length === 2 && this.options.fingerprints.every(f => FINGERPRINT.test(f));\n if (!validBinding || !this.offer.transports.includes(this.transport) ||\n this.options.rendezvousKeys.some(k => !isZ32Key(k))) return this.fail(\"Invalid connection binding or unavailable transport\");\n this.channel.onMessage = data => {\n if (this.stopped) return;\n const size = data.length;\n // Two limits, two texts: a frame over the maximum is the peer breaking the protocol (a refused session), too much\n // waiting is a flood or a slow side (a dropped one, dialled again). The app tells them apart by these words.\n if (size > SESSION_FRAME_MAX) return this.fail(\"Session frame too large\");\n if (++this.pending > SESSION_RECEIVE_PENDING.frames || (this.pendingBytes += size) > SESSION_RECEIVE_PENDING.bytes) {\n this.overloaded = true;\n return this.fail(\"Session receive queue full\");\n }\n this.queue = this.queue.then(async () => {\n if (this.stopped) return;\n if (typeof data === \"string\" && data.startsWith('{\"t\":\"pair-')) {\n if (data.length > MAX_HANDSHAKE_BYTES) return this.fail(\"Negotiation message too large\");\n await this.receive(data);\n } else if (this.state.status === \"ready\") await this.options.onApplication(data);\n }).catch(() => this.fail(\"Invalid session negotiation\"))\n .finally(() => { this.pending--; this.pendingBytes -= size; });\n };\n this.timer = setTimeout(() => { this.authTimedOut = true; this.fail(\"The peer did not finish authentication. Reconnect to try again.\"); }, this.options.authTimeoutMs ?? 180_000);\n this.update({ status: \"negotiating\" });\n this.send(this.offer);\n }\n\n private send(frame: object): void {\n if (!this.stopped) this.channel.send(JSON.stringify(frame));\n }\n\n private async receive(text: string): Promise<void> {\n if (this.stopped) return;\n const raw = JSON.parse(text) as Record<string, unknown>;\n if (raw.t === \"pair-offer\") {\n const peer = parseOffer(raw);\n if (!peer || peer.key === this.offer.key) return this.fail(\"Invalid participation key or offer\");\n if (this.peer) {\n if (JSON.stringify(peer) !== JSON.stringify(this.peer)) this.fail(\"The peer changed its negotiation offer\");\n return;\n }\n if (!peer.versions.includes(1) || !peer.transports.includes(this.transport) || !peer.capabilities.includes(\"chat/1\"))\n return this.fail(\"No compatible paired chat profile\");\n const pinned = this.options.credentials.peerKey ?? this.options.credentials.expectedPeerKey;\n if (pinned && pinned !== peer.key)\n return this.fail(\"Saved contact key mismatch. This invite is already paired with another participation key. Check with your contact and use a new invitation if the change was intended.\", true);\n const ranked = rankTransports(this.offer.transports, peer.transports);\n if (!ranked.length) return this.fail(\"No common available transport\");\n this.preferred = ranked[0];\n if (this.transport !== this.preferred && !(this.options.allowFallback && peer.capabilities.includes(\"transport-fallback/1\")))\n return this.fail(\"This transport would violate the negotiated fallback policy\");\n this.peer = peer;\n // Fixed arrays define the canonical transcript; unknown offer fields grant nothing.\n const offers = [this.offer, peer].sort((a,b) => a.key < b.key ? -1 : 1).map(offerTuple);\n this.transcript = utf8Encode(JSON.stringify([\"ghostly-paired-chat\", 1,\n [...this.options.rendezvousKeys].sort(), this.options.binding\n ? [this.transport, [...this.options.binding.identities].sort(), this.options.binding.context]\n : [...this.options.fingerprints!].sort(), offers,\n [1, this.transport, \"chat/1\", \"no-dht-payload\"]]));\n const hash = await crypto.subtle.digest(\"SHA-256\", new Uint8Array(this.transcript));\n if (this.stopped) return;\n this.digest = Array.from(new Uint8Array(hash), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n if (this.identity) this.send({ t: \"pair-proof\", sig: toBase64Url(sign(this.transcript, this.identity.seed)) });\n else {\n // A signer may sign outside this page's code (WebCrypto): the frames behind this one wait in the queue.\n const sig = toBase64Url(await this.signer!.sign(this.transcript));\n if (this.stopped) return;\n this.send({ t: \"pair-proof\", sig });\n }\n } else if (raw.t === \"pair-proof\") {\n if (!this.peer || !this.transcript || typeof raw.sig !== \"string\" || !SIG.test(raw.sig) ||\n !verify(fromBase64Url(raw.sig), this.transcript, publicKeyFromZ32(this.peer.key)))\n return this.fail(\"The peer could not authenticate this connection\");\n if (this.proofReceived) return;\n this.proofReceived = true;\n if (this.options.credentials.peerKey || this.options.trustOnFirstUse) await this.admit();\n else this.update({ status: \"confirm\", code: this.code(), peerKey: this.peer.key });\n } else if (raw.t === \"pair-ready\") {\n if (!this.proofReceived || raw.context !== this.digest) return this.fail(\"Invalid session confirmation\");\n this.peerReady = true;\n this.maybeReady();\n } else this.fail(\"Unsupported session message\");\n }\n\n private code(): string { return this.digest.slice(0, 24).match(/.{4}/g)!.join(\" \"); }\n\n /** A user's explicit comparison. Never called by automatic admission/reconnection. */\n async confirm(expectedCode: string): Promise<void> {\n if (this.stopped || !this.proofReceived || !this.peer) throw new Error(\"No authenticated peer to verify\");\n if (expectedCode !== this.code()) throw new Error(\"The connection changed. Compare the current code again.\");\n if (this.confirming) return;\n this.confirming = true;\n const peerKey = this.peer.key;\n try {\n await this.admit();\n // Admission reports its own failure and stops the session; a stop is also\n // what a deliberate disconnect looks like. Neither is a verification, and\n // neither is news worth raising at whoever asked for one.\n if (this.stopped) return;\n if (!this.localReady) throw new Error(\"The connection closed. Compare again after reconnecting.\");\n await this.options.verifyPeer?.(peerKey);\n this.options.credentials.verifiedPeerKey = peerKey;\n if (!this.stopped) this.update({ ...this.state, verified: true });\n } finally { this.confirming = false; }\n }\n\n /** Save the authenticated key before enabling any application capability. */\n private admit(): Promise<void> {\n if (this.admission) return this.admission;\n this.admission = this.admitOnce();\n return this.admission;\n }\n\n private async admitOnce(): Promise<void> {\n if (this.stopped || !this.proofReceived || !this.peer || this.localReady) return;\n const peerKey = this.peer.key;\n try {\n const signedSignals = this.peer.capabilities.includes(\"signed-signal/1\");\n if (this.options.credentials.requireSignedSignals && !signedSignals) throw new Error(\"This peer needs a version supporting signed signaling\");\n await this.options.pinPeer(peerKey, signedSignals);\n this.options.credentials.requireSignedSignals ||= signedSignals;\n if (this.stopped) return;\n this.options.credentials.peerKey = peerKey;\n this.localReady = true;\n this.update({ status: \"waiting\", code: this.code(), peerKey,\n peerNeedsConfirmation: !this.peer.capabilities.includes(\"tofu/1\") });\n // This means authenticated, durably pinned and ready, not independently verified.\n this.send({ t: \"pair-ready\", context: this.digest });\n this.maybeReady();\n } catch {\n this.fail(\"Could not durably save this peer. No messages were enabled.\");\n }\n }\n\n private maybeReady(): void {\n if (this.stopped || !this.localReady || !this.peerReady || this.state.status === \"ready\") return;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n this.update({ status: \"ready\", code: this.code(), peerKey: this.peer!.key });\n this.options.onReady();\n }\n\n private update(state: PairingState): void { this.state = { ...state, verified: !!state.peerKey && this.options.credentials.verifiedPeerKey === state.peerKey, transport: this.transport, preferred: this.preferred }; this.options.onState(this.state); }\n private fail(error: string, keyMismatch = false): void {\n if (this.stopped) return;\n this.update({ status: \"error\", error, keyMismatch });\n this.stop();\n this.options.onFailure();\n }\n stop(): void {\n this.stopped = true;\n if (this.timer) clearTimeout(this.timer);\n this.timer = null;\n }\n}\n","import { fromBase64Url, toBase64Url } from \"./bytes\";\nimport { CHUNK_KIND, decodeChunk, decodeControl, type FrameChannel } from \"./frames\";\nimport { HttpClient, HttpHost, type HostedHttpService, type LocalFetch } from \"./http\";\n\n/**\n * What the session hears of the bodies going on its channel: each chunk written, with its frame's length, and each wait\n * for room. An app's data in the chat keeps its own share above them, as beside a file (WISP 1200 § In a chat).\n */\nexport interface PairedHttpBodies {\n wrote(bytes: number): void;\n waiting(drained: Promise<void>): Promise<void>;\n}\n\n/**\n * Shared services over a paired session: the same HTTP frames as the older data link, carried as\n * `ph` application frames on the authenticated channel. Binary chunks travel base64url-encoded,\n * since paired application data is text. The frames carry no `id`, so an older app drops them.\n */\nexport class PairedHttp {\n readonly client: HttpClient;\n readonly host: HttpHost;\n\n constructor(channel: FrameChannel, getService: (id: string) => HostedHttpService | undefined, localFetch: LocalFetch, bodies?: PairedHttpBodies) {\n const tunnel: FrameChannel = {\n send: (data) => {\n if (typeof data === \"string\") return channel.send(JSON.stringify({ t: \"ph\", c: data }));\n // Only a body's chunks are binary.\n const frame = JSON.stringify({ t: \"ph\", b: toBase64Url(data) });\n channel.send(frame);\n bodies?.wrote(frame.length);\n },\n get bufferedAmount() { return channel.bufferedAmount; },\n // Only a body waits for room.\n drained: () => bodies ? bodies.waiting(channel.drained()) : channel.drained(),\n // Its frames are counted on the session's channel, base64url and all, so a body keeps under that channel's budget.\n get sendBudget() { return channel.sendBudget; },\n // The paired channel belongs to the session; closing is the session's business.\n close: () => {},\n onMessage: null,\n onClose: null,\n };\n this.client = new HttpClient(tunnel);\n this.host = new HttpHost(tunnel, getService, localFetch);\n }\n\n /** One `ph` frame from the peer. Anything that is not HTTP traffic is ignored. */\n handle(frame: Record<string, unknown>): void {\n if (typeof frame.b === \"string\") {\n let bytes: Uint8Array;\n try { bytes = fromBase64Url(frame.b); } catch { return; }\n const chunk = decodeChunk(bytes);\n if (chunk?.kind === CHUNK_KIND.requestBody) this.host.handleChunk(chunk);\n else if (chunk?.kind === CHUNK_KIND.responseBody) this.client.handleChunk(chunk);\n return;\n }\n if (typeof frame.c !== \"string\") return;\n const control = decodeControl(frame.c);\n if (control?.t === \"req\") this.host.handleRequest(control);\n else if (control?.t === \"res\") this.client.handleResponse(control);\n else if (control?.t === \"rst\" && control.d === \"q\") this.host.handleReset(control);\n else if (control?.t === \"rst\" && control.d === \"s\") this.client.handleReset(control);\n }\n\n close(): void {\n this.host.closeAll();\n this.client.close();\n }\n}\n","/**\n * Capabilities a paired session announces once it is ready (WISP 03, 401): what this app does on this\n * session beyond what the handshake offer carries. Apps before 0.5 accept at most 16 entries in the offer's\n * `capabilities`, and a full offer is already there, so these travel in one frame on the authenticated\n * session instead, the way `paired-payments` and `paired-groups` do:\n *\n * {\"t\":\"paired-capabilities\",\"c\":[\"calls/1\",\"services/1\",\"files/3\",\"typing/1\",\"react/1\",\"edit/1\"]}\n *\n * Each side sends it on every ready session, and again whenever what it offers changes. Something is on\n * only while both sides list it; a peer that never sends the frame (an older app) offers nothing here.\n * The frame carries no message id, so older apps drop it.\n */\n\nimport type { DeviceCapability } from \"./deviceLink\";\n\n/** Voice and video calls: `paired-call` signals on this session, media on a WebRTC connection of its own (WISP 601). */\nexport const CALLS_CAPABILITY = \"calls/1\";\n/** Shared local web apps: `paired-services` and `ph` HTTP frames on this session (WISP 701). */\nexport const SERVICES_CAPABILITY = \"services/1\";\n\n/**\n * Files of any size (WISP 501 rev 0.3): offered and accepted, many chunks in flight, resumed from the last\n * confirmed byte, checked by digest (`pf-offer` … frames, `chatFiles.ts`). Without it, files/2 and 100 MiB.\n */\nexport const FILES_CAPABILITY = \"files/3\";\n\n/**\n * A file's bytes as binary messages (WISP 501 § files/4): beside `files/3`, on a session whose channel carries binary\n * messages, a chunk travels as it is (`encodeFileData`, `chatFiles.ts`) and not as base64url text in a `pf-data` frame.\n */\nexport const FILES_BINARY_CAPABILITY = \"files/4\";\n\n/** The typing indicator: `paired-typing` frames on this session, 1:1 chats only (WISP 401 § Typing, `pairedTyping.ts`). */\nexport const TYPING_CAPABILITY = \"typing/1\";\n\n/**\n * Presence and a set status: `paired-status` frames on this session, 1:1 chats only (WISP 401 § Presence and status,\n * `pairedStatus.ts`).\n */\nexport const STATUS_CAPABILITY = \"status/1\";\n\n/** Reactions to messages: `paired-reaction` frames on this session, 1:1 chats only (WISP 401 § Reactions, `reactions.ts`). */\nexport const REACTIONS_CAPABILITY = \"react/1\";\n\n/** Editing sent texts: `paired-edit` frames on this session, 1:1 chats only (WISP 401 § Edits, `pairedEdits.ts`). */\nexport const EDIT_CAPABILITY = \"edit/1\";\n\n/** Wake-up push: `paired-wake` frames on this session, 1:1 chats only (WISP 401 § Wake-up push, `pairedWake.ts`). */\nexport const WAKE_SESSION_CAPABILITY = \"wake/1\";\n\n/** A pinned message: `paired-pin` frames on this session, 1:1 chats only (WISP 401 § Pinned message, `pins.ts`). */\nexport const PIN_CAPABILITY = \"pin/1\";\n\n/**\n * Status cards: this app shows a message's card (`sc`) and takes a card message's edits past the text's 100, which an\n * older app would drop (WISP 405 · Status Cards, `statusCards.ts`). A card itself needs nothing: older apps show its text.\n */\nexport const STATUS_CARD_CAPABILITY = \"status-card/1\";\n\n/**\n * Message buttons: this app shows a message's buttons (a card of kind `buttons`) and presses them with a reply naming\n * the button (WISP 406 · Message Buttons). Nothing is gated on it: an older app shows the text and sends replies, and\n * a press reads as an ordinary reply there. It tells a bot whether its contact can press at all.\n */\nexport const BUTTONS_CAPABILITY = \"buttons/1\";\n\n/**\n * A session live on a relayed transport while a direct one ranks first, with nobody's choice behind it, moves to the\n * direct one once, in place, its signaling on the session (WISP 100 § Back to a quiet contact): what a chat that came\n * back over a relay at once (rather than wait for an offer's answer) needs to end where a direct path would have put\n * it. Both sides must say it: the switch is planned by one and checked by the other. Also in the capability record\n * (WISP 03), so an app back after an absence knows before any session whether a relay can carry it there at once.\n */\nexport const UPGRADE_CAPABILITY = \"upgrade/1\";\n\n/**\n * Mini-apps in a 1:1 chat: `paired-app` frames on this session, live only (WISP 1200 § In a chat: `apps/1`,\n * `pairedApps.ts`). Offered only while the apps feature is on.\n */\nexport const APPS_CAPABILITY = \"apps/1\";\n\n/**\n * The read lane of mini-apps (WISP 1200 § A read lane to the contact, `pairedAppRanges.ts`): the contact's app reads a\n * file this side's app serves, in ranges, outside `apps/1`. Offered beside `apps/1` only.\n */\nexport const APP_RANGES_CAPABILITY = \"app-ranges/1\";\n\n/**\n * What only a device link offers (WISP 06, `deviceLink.ts`): the frames between a person's own devices. They are in\n * the type so a device link can announce them, and not in `KNOWN_SESSION_CAPABILITIES`: no chat knows them.\n */\nexport type SessionCapability = DeviceCapability | typeof CALLS_CAPABILITY | typeof SERVICES_CAPABILITY | typeof FILES_CAPABILITY | typeof FILES_BINARY_CAPABILITY | typeof TYPING_CAPABILITY | typeof STATUS_CAPABILITY | typeof REACTIONS_CAPABILITY | typeof EDIT_CAPABILITY | typeof WAKE_SESSION_CAPABILITY | typeof PIN_CAPABILITY | typeof STATUS_CARD_CAPABILITY | typeof BUTTONS_CAPABILITY | typeof UPGRADE_CAPABILITY | typeof APPS_CAPABILITY | typeof APP_RANGES_CAPABILITY;\n\n/** Every capability this app knows on a session: what `receive` reports changes of. */\nexport const KNOWN_SESSION_CAPABILITIES: readonly SessionCapability[] = [CALLS_CAPABILITY, SERVICES_CAPABILITY, FILES_CAPABILITY, FILES_BINARY_CAPABILITY, TYPING_CAPABILITY, STATUS_CAPABILITY, REACTIONS_CAPABILITY, EDIT_CAPABILITY, WAKE_SESSION_CAPABILITY, PIN_CAPABILITY, STATUS_CARD_CAPABILITY, BUTTONS_CAPABILITY, UPGRADE_CAPABILITY, APPS_CAPABILITY, APP_RANGES_CAPABILITY];\n\nexport const SESSION_CAPABILITIES_FRAME = \"paired-capabilities\";\n\nconst MAX_ENTRIES = 32;\nconst IDENTIFIER = /^[a-z0-9/-]{1,40}$/;\n\n/** The frame that says what this side offers. */\nexport function sessionCapabilitiesFrame(offered: readonly SessionCapability[]): { t: typeof SESSION_CAPABILITIES_FRAME; c: string[] } {\n return { t: SESSION_CAPABILITIES_FRAME, c: [...new Set(offered)] };\n}\n\n/**\n * The capabilities a `paired-capabilities` frame lists, or null when it is malformed (then it says nothing,\n * and what the peer said before stands). Identifiers this app does not know are kept: they grant nothing,\n * since only what both sides list is on.\n */\nexport function parseSessionCapabilities(frame: Record<string, unknown>): Set<string> | null {\n const list = frame.c;\n if (!Array.isArray(list) || list.length > MAX_ENTRIES) return null;\n if (!list.every((entry): entry is string => typeof entry === \"string\" && IDENTIFIER.test(entry))) return null;\n return new Set(list);\n}\n\n/** What both sides of one session offer. Reset when the session goes. */\nexport class SessionCapabilities {\n private peer: Set<string> | null = null;\n\n constructor(private readonly offered: () => readonly SessionCapability[]) {}\n\n /** The frame to send now: on every ready session, and after what this side offers changed. */\n announcement() { return sessionCapabilitiesFrame(this.offered()); }\n\n /** This side offers it (whatever the peer says). */\n offers(capability: SessionCapability): boolean { return this.offered().includes(capability); }\n\n /** The peer listed it on this session. False until the peer says anything. */\n peerOffers(capability: SessionCapability): boolean { return !!this.peer?.has(capability); }\n\n /** The peer has said what it offers on this session. */\n get peerAnnounced(): boolean { return this.peer !== null; }\n\n /** Both sides offer it on this session. */\n agreed(capability: SessionCapability): boolean { return this.offers(capability) && this.peerOffers(capability); }\n\n /**\n * A `paired-capabilities` frame from the peer. Returns the capabilities whose agreement changed, or null\n * when the frame was malformed and ignored.\n */\n receive(frame: Record<string, unknown>, known: readonly SessionCapability[] = KNOWN_SESSION_CAPABILITIES): SessionCapability[] | null {\n const parsed = parseSessionCapabilities(frame);\n if (!parsed) return null;\n const before = known.map(capability => this.agreed(capability));\n this.peer = parsed;\n return known.filter((capability, index) => this.agreed(capability) !== before[index]);\n }\n\n /** The session ended: nothing is agreed until the next one says so. */\n reset(): void { this.peer = null; }\n}\n","import { hmac } from \"@noble/hashes/hmac.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { isAppRef } from \"./appStatements\";\nimport { concatBytes, toBase64Url, utf8Encode } from \"./bytes\";\n\n/**\n * Mini-apps talking in a 1:1 chat (WISP 1200 § In a chat: `apps/1`): the same app on both sides sends JSON to the\n * other over the live session, in one frame with three forms.\n *\n * {\"t\":\"paired-app\",\"a\":\"<chat app id>\",\"o\":\"open\",\"v\":\"1.2.0\"}\n * {\"t\":\"paired-app\",\"a\":\"<chat app id>\",\"o\":\"close\"}\n * {\"t\":\"paired-app\",\"a\":\"<chat app id>\",\"d\":<JSON value>}\n *\n * It needs `apps/1` in `paired-capabilities` on both sides. Live only: never on the DHT, never held, never queued for\n * later; while the session is not live a send fails with `offline`. An `open` goes when the person opens the app in\n * the chat, again on an update, and again on every session that comes back while the app is open. The receiver\n * enforces the limits (the sender's client may be the attacker): at most `APP_DATA_MAX_BYTES` of data, at most\n * `APP_RATE_LIMIT` frames a second per app, data only for an app open on both sides, at most `APP_PEER_OPEN_MAX`\n * apps the peer has open, and nothing unless both sides offer `apps/1`.\n *\n * The chat app id names one app in one chat: the first 16 bytes of HMAC-SHA-256 keyed by the two pinned participation\n * keys over the app reference `<publisher key in z-base32>/<name>`. One app's id differs in each chat, so ids cannot\n * be matched across a person's chats; it travels only inside the encrypted session.\n */\n\nexport const APP_FRAME = \"paired-app\";\n\n/** The largest `d`, as compact UTF-8 JSON. The session's 60 KiB cap on any frame still holds above it. */\nexport const APP_DATA_MAX_BYTES = 32 * 1024;\n/** Frames a receiver takes per app per `APP_RATE_WINDOW_MS`; the rest are dropped unread. */\nexport const APP_RATE_LIMIT = 50;\nexport const APP_RATE_WINDOW_MS = 1_000;\n/** Data frames a sender sends per app per window: under the receiver's limit, so an `open` or `close` always fits. */\nexport const APP_SEND_LIMIT = APP_RATE_LIMIT - 2;\n/** Distinct apps the peer may have open on one session, held ones counted; an `open` for one more is dropped. */\nexport const APP_PEER_OPEN_MAX = 16;\n/** The longest version an `open` carries. */\nexport const APP_VERSION_MAX = 64;\n/**\n * How long the peer's open apps are held when its session ends or is replaced (a transport switch, a resume, a\n * re-dial), before they are taken as closed. A new session within it says `open` again for each: the app hears that\n * open (and catches up), never a `close` in between. Past it, each still held is closed with `offline`.\n */\nexport const APP_RESUME_GRACE_MS = 10_000;\n\n/** Why a send did not go. */\nexport type AppSendError =\n /** This side has not opened the app in this chat. */\n | \"not-open\"\n /** The value is over `APP_DATA_MAX_BYTES` as JSON (or is not JSON). */\n | \"too-large\"\n /** The session is not live. Nothing is kept to send later. */\n | \"offline\"\n /** The peer has not opened the app on this session, or its app does not offer `apps/1`. */\n | \"peer-closed\"\n /** Over `APP_SEND_LIMIT` data frames in the window for this app. */\n | \"too-fast\";\n\nexport type AppFrame =\n | { t: typeof APP_FRAME; a: string; o: \"open\"; v: string }\n | { t: typeof APP_FRAME; a: string; o: \"close\" }\n | { t: typeof APP_FRAME; a: string; d: unknown };\n\n/**\n * What the peer said about one app, as the engine passes it on. `close` with `offline` is not a frame: the session\n * ended (or `apps/1` stopped being agreed) while the peer had the app open.\n */\nexport type AppFrameEvent =\n | { app: string; o: \"open\"; v: string }\n | { app: string; o: \"close\"; offline?: true }\n | { app: string; d: unknown };\n\nconst DOMAIN = \"ghostly-apps/1\";\nconst APP_ID = /^[A-Za-z0-9_-]{22}$/;\n/** Semantic versioning 2.0.0, as a manifest's `version` is. */\nconst SEMVER = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/** A chat app id as it is on the wire: 22 base64url characters (16 bytes, no padding). */\nexport function isChatAppId(value: unknown): value is string {\n return typeof value === \"string\" && APP_ID.test(value);\n}\n\n/** A version an `open` may carry: semantic versioning, at most `APP_VERSION_MAX` characters. */\nexport function isAppVersion(value: unknown): value is string {\n return typeof value === \"string\" && value.length <= APP_VERSION_MAX && SEMVER.test(value);\n}\n\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return a[i] - b[i];\n return a.length - b.length;\n}\n\n/**\n * The chat app id of `ref` in the chat between these two participation keys (raw, 32 bytes each, in either order):\n * HMAC-SHA-256 keyed by SHA-256(`ghostly-apps/1`, 0x00, the lower key, the higher key), over the UTF-8 reference;\n * its first 16 bytes, base64url without padding.\n */\nexport function chatAppId(keyA: Uint8Array, keyB: Uint8Array, ref: string): string {\n if (keyA.length !== 32 || keyB.length !== 32) throw new Error(\"A participation key is 32 bytes\");\n if (!isAppRef(ref)) throw new Error(\"Not an app reference\");\n const [low, high] = compareBytes(keyA, keyB) <= 0 ? [keyA, keyB] : [keyB, keyA];\n const key = sha256(concatBytes(utf8Encode(DOMAIN), new Uint8Array([0]), low, high));\n return toBase64Url(hmac(sha256, key, utf8Encode(ref)).slice(0, 16));\n}\n\n/** The size of a value as compact UTF-8 JSON; Infinity when it is not JSON (undefined, a function, a cycle, a BigInt). */\nexport function appDataBytes(value: unknown): number {\n let json: string | undefined;\n try { json = JSON.stringify(value); } catch { return Infinity; }\n return json === undefined ? Infinity : utf8Encode(json).length;\n}\n\nexport function appOpenFrame(app: string, version: string): AppFrame {\n if (!isChatAppId(app) || !isAppVersion(version)) throw new Error(\"Not an app open\");\n return { t: APP_FRAME, a: app, o: \"open\", v: version };\n}\n\nexport function appCloseFrame(app: string): AppFrame {\n if (!isChatAppId(app)) throw new Error(\"Not an app close\");\n return { t: APP_FRAME, a: app, o: \"close\" };\n}\n\nexport function appDataFrame(app: string, data: unknown): AppFrame {\n if (!isChatAppId(app) || appDataBytes(data) > APP_DATA_MAX_BYTES) throw new Error(\"Not app data\");\n return { t: APP_FRAME, a: app, d: data };\n}\n\n/** Why a reader refuses a `paired-app` frame (the vectors' `refusal`). */\nexport type AppFrameRefusal = \"not-app\" | \"bad-a\" | \"o-and-d\" | \"no-o-or-d\" | \"too-large\" | \"unknown-o\" | \"bad-v\";\n\n/**\n * A `paired-app` frame as the peer sent it, or why a reader must refuse it: no valid `a` (22 base64url characters),\n * both or neither of `o` and `d`, an unknown `o`, an `open` without a valid `v`, or a `d` over `APP_DATA_MAX_BYTES`.\n * Other keys are ignored, so a later version can add some.\n */\nexport function readAppFrame(frame: Record<string, unknown>): { ok: true; frame: AppFrame } | { ok: false; refusal: AppFrameRefusal } {\n const refuse = (refusal: AppFrameRefusal) => ({ ok: false as const, refusal });\n if (frame?.t !== APP_FRAME) return refuse(\"not-app\");\n if (!isChatAppId(frame.a)) return refuse(\"bad-a\");\n const own = (key: string) => Object.prototype.hasOwnProperty.call(frame, key);\n const hasO = own(\"o\"), hasD = own(\"d\");\n if (hasO && hasD) return refuse(\"o-and-d\");\n if (!hasO && !hasD) return refuse(\"no-o-or-d\");\n if (hasD) return appDataBytes(frame.d) <= APP_DATA_MAX_BYTES ? { ok: true, frame: { t: APP_FRAME, a: frame.a, d: frame.d } } : refuse(\"too-large\");\n if (frame.o === \"close\") return { ok: true, frame: { t: APP_FRAME, a: frame.a, o: \"close\" } };\n if (frame.o !== \"open\") return refuse(\"unknown-o\");\n return isAppVersion(frame.v) ? { ok: true, frame: { t: APP_FRAME, a: frame.a, o: \"open\", v: frame.v } } : refuse(\"bad-v\");\n}\n\n/** A `paired-app` frame as the peer sent it, or null when a reader must refuse it (`readAppFrame` says why). */\nexport function parseAppFrame(frame: Record<string, unknown>): AppFrame | null {\n const read = readAppFrame(frame);\n return read.ok ? read.frame : null;\n}\n\n/** Frames per app in a sliding window, for at most `max` apps at once. */\nclass RateWindows {\n private readonly windows = new Map<string, number[]>();\n\n constructor(private readonly limit: number, private readonly max: number) {}\n\n /** Counts one frame for `app` at `now`; false when it is over the limit (not counted then). */\n take(app: string, now: number): boolean {\n let window = this.windows.get(app);\n if (!window) {\n if (this.windows.size >= this.max) this.prune(now);\n if (this.windows.size >= this.max) return false;\n window = [];\n this.windows.set(app, window);\n }\n while (window.length && now - window[0] >= APP_RATE_WINDOW_MS) window.shift();\n if (window.length >= this.limit) return false;\n window.push(now);\n return true;\n }\n\n private prune(now: number): void {\n for (const [app, window] of this.windows) if (!window.length || now - window[window.length - 1] >= APP_RATE_WINDOW_MS) this.windows.delete(app);\n }\n}\n\n/**\n * The apps of one chat on its live sessions. `open` (this side's apps, by chat app id, with their versions) lasts\n * across sessions, so each new one says `open` again; what the peer has open lasts one session.\n */\nexport class AppSessions {\n private readonly peer = new Map<string, string>();\n /**\n * What the peer had open on a session that ended, until it says so again: each with its version and the time its\n * grace ends, counted from the suspension that took it from the peer.\n */\n private readonly held = new Map<string, { version: string; until: number }>();\n private received = new RateWindows(APP_RATE_LIMIT, 4 * APP_PEER_OPEN_MAX);\n private sent = new RateWindows(APP_SEND_LIMIT, 4 * APP_PEER_OPEN_MAX);\n\n constructor(readonly open: Map<string, string> = new Map(), private readonly now: () => number = Date.now) {}\n\n /** The peer has this app open on this session, at this version. */\n peerVersion(app: string): string | undefined { return this.peer.get(app); }\n\n /** The apps the peer has open on this session. */\n get peerOpen(): ReadonlyMap<string, string> { return this.peer; }\n\n /**\n * A `paired-app` frame from the peer, on a session where both sides offer `apps/1`. Counted before it is read; the\n * event to pass on, or null when it was dropped (malformed, over the rate, a data frame for an app not open on both\n * sides, an `open` past `APP_PEER_OPEN_MAX`, a `close` of an app the peer did not have open).\n */\n receive(frame: Record<string, unknown>): AppFrameEvent | null {\n if (!isChatAppId(frame?.a) || !this.received.take(frame.a, this.now())) return null;\n const parsed = parseAppFrame(frame);\n if (!parsed) return null;\n const app = parsed.a;\n if (\"d\" in parsed) return this.open.has(app) && this.peer.has(app) ? { app, d: parsed.d } : null;\n if (parsed.o === \"close\") return this.peer.delete(app) || this.held.delete(app) ? { app, o: \"close\" } : null;\n // A held app the peer says open again moves back without growing what it has; each new one counts the held too,\n // or every quick re-dial would take another 16.\n if (!this.peer.has(app) && !this.held.has(app) && this.peer.size + this.held.size >= APP_PEER_OPEN_MAX) return null;\n this.held.delete(app);\n this.peer.set(app, parsed.v);\n return { app, o: \"open\", v: parsed.v };\n }\n\n /** Whether a data frame for `app` may go now, the session being live with `apps/1` agreed; counted when it may. */\n canSend(app: string, data: unknown): AppSendError | null {\n if (!this.open.has(app)) return \"not-open\";\n if (appDataBytes(data) > APP_DATA_MAX_BYTES) return \"too-large\";\n if (!this.peer.has(app)) return \"peer-closed\";\n return this.sent.take(app, this.now()) ? null : \"too-fast\";\n }\n\n /**\n * The session ended, or `apps/1` is no longer agreed: what the peer had open is gone, and each such app hears a\n * `close` with `offline`. This side's open apps stay, and say `open` again on the next session. The rate windows\n * stay too: they are the contact's per app, or turning `apps/1` off and on would give each app a new 50.\n */\n sessionEnded(): AppFrameEvent[] {\n const closed = [...new Set([...this.held.keys(), ...this.peer.keys()])].map((app): AppFrameEvent => ({ app, o: \"close\", offline: true }));\n this.peer.clear();\n this.held.clear();\n return closed;\n }\n\n /**\n * The session ended or was replaced, and another may follow at once: what the peer had open is held, not closed (no\n * event now). Nothing is sent to a held app; an `open` on the next session takes it back, a `close` closes it, and\n * `heldExpired` closes the rest once `graceMs` has passed since the suspension that held each. The rate windows stay,\n * as in `sessionEnded`.\n */\n sessionSuspended(graceMs = APP_RESUME_GRACE_MS): void {\n const until = this.now() + graceMs;\n for (const [app, version] of this.peer) this.held.set(app, { version, until });\n this.peer.clear();\n }\n\n /** Whether any of the peer's apps is held, waiting for its next session. */\n get holding(): boolean { return this.held.size > 0; }\n\n /** When the next held app's grace ends; undefined when none is held. */\n get heldUntil(): number | undefined {\n let first: number | undefined;\n for (const { until } of this.held.values()) if (first === undefined || until < first) first = until;\n return first;\n }\n\n /** Each app held whose grace is over is closed, with `offline`; the ones held later keep theirs. */\n heldExpired(): AppFrameEvent[] {\n const now = this.now(), closed: AppFrameEvent[] = [];\n for (const [app, { until }] of this.held) if (until <= now) { this.held.delete(app); closed.push({ app, o: \"close\", offline: true }); }\n return closed;\n }\n}\n","import { concatBytes, fromBase64Url, randomBytes, toBase64Url } from \"./bytes\";\nimport { isChatAppId } from \"./pairedApps\";\n\n/**\n * The read lane of mini-apps in a 1:1 chat (WISP 1200 § A read lane to the contact: `app-ranges/1`): the contact's app\n * reads, in ranges, a file this side's app serves, over the chat's session but not through `apps/1`.\n *\n * {\"t\":\"ar-get\",\"a\":\"<chat app id>\",\"s\":\"<serve id>\",\"r\":7,\"o\":0,\"n\":1048576}\n * {\"t\":\"ar-data\",\"a\":\"<chat app id>\",\"r\":7,\"o\":0,\"d\":\"<base64url>\"}\n * {\"t\":\"ar-end\",\"a\":\"<chat app id>\",\"r\":7,\"z\":734003200}\n * {\"t\":\"ar-err\",\"a\":\"<chat app id>\",\"r\":7,\"e\":\"not-served\"}\n * {\"t\":\"ar-cancel\",\"a\":\"<chat app id>\",\"r\":7}\n *\n * The asker sends `ar-get` (request `r`, a number of its own, for `n` bytes at offset `o` of serve `s`) and may send\n * `ar-cancel`; the server answers with the bytes in chunks of at most `APP_RANGE_LIMITS.chunkBytes`, then `ar-end`\n * once every byte asked was sent (fewer at the end of the file), with `z` the served file's size, or `ar-err` instead of\n * any. A read of one byte at 0 is how the asker learns the size. Where `files/4` is on,\n * a chunk is a binary message of kind `APP_RANGE_DATA_KIND` (`encodeAppRangeData`) in place of `ar-data`. It needs\n * `app-ranges/1` in `paired-capabilities` on both sides. A reader ignores keys it does not know, so a later version\n * can add some.\n */\n\nexport const APP_RANGE_FRAMES = new Set([\"ar-get\", \"ar-data\", \"ar-end\", \"ar-err\", \"ar-cancel\"]);\n\nexport const APP_RANGE_LIMITS = {\n /** One `ar-get`, at most: as one `remote.read` of the app. */\n requestBytes: 1024 * 1024,\n /** One chunk, `ar-data` or binary: as a chat file's. */\n chunkBytes: 16 * 1024,\n /** The largest request number: it is 4 bytes in a binary chunk. */\n maxRequest: 0xffff_ffff,\n /** Requests a server takes in flight per app; one more is answered `busy`. An asker keeps the rest waiting. */\n inFlight: 4,\n /**\n * The bytes a server takes asks for in one second, its apps together: one more is answered `busy`. Counted as they\n * are asked, so a cancelled one counts as the read it started. Twice the asking app's own budget (16 MiB a second).\n */\n bytesPerSecond: 32 * 1024 * 1024,\n /**\n * The least one ask counts in `bytesPerSecond`, however few bytes it asked or the file held from its offset: each is\n * a read on this device, so a contact gets at most 512 a second.\n */\n askFloorBytes: 64 * 1024,\n} as const;\n\n/**\n * What an `ar-err` says. `not-served`: no serve of that id (never given, or ended); `changed` and\n * `gone`: the file under it, as `files.read` says them; `busy`: past the requests the server takes in flight. A\n * later version may add one: an asker reads a code it does not know as a failure.\n */\nexport const APP_RANGE_ERRORS = [\"not-served\", \"changed\", \"gone\", \"busy\"] as const;\nexport type AppRangeError = typeof APP_RANGE_ERRORS[number];\n\nexport type AppRangeFrame =\n | { t: \"ar-get\"; a: string; s: string; r: number; o: number; n: number }\n | { t: \"ar-data\"; a: string; r: number; o: number; d: string }\n | { t: \"ar-end\"; a: string; r: number; z: number }\n | { t: \"ar-err\"; a: string; r: number; e: string }\n | { t: \"ar-cancel\"; a: string; r: number };\n\n/** Why a reader refuses an `ar-*` frame (the vectors' `refusal`). */\nexport type AppRangeRefusal = \"not-ranges\" | \"bad-a\" | \"bad-s\" | \"bad-r\" | \"bad-o\" | \"bad-n\" | \"bad-d\" | \"bad-e\" | \"bad-z\";\n\n/** A serve id as it is on the wire: 22 base64url characters (16 random bytes, no padding), as a chat app id. */\nexport const isServeId = isChatAppId;\n\nconst isRequest = (value: unknown): value is number => typeof value === \"number\" && Number.isInteger(value) && value >= 0 && value <= APP_RANGE_LIMITS.maxRequest;\nconst isOffset = (value: unknown): value is number => typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\nconst ERROR_CODE = /^[a-z][a-z-]{0,31}$/;\nconst BASE64URL = /^[A-Za-z0-9_-]*$/;\n\n/** The bytes of `d`, or null when it is not 1 to `chunkBytes` bytes of canonical base64url without padding. */\nexport function appRangeChunk(d: unknown): Uint8Array | null {\n if (typeof d !== \"string\" || !d.length || d.length % 4 === 1 || d.length > Math.ceil(APP_RANGE_LIMITS.chunkBytes * 4 / 3) || !BASE64URL.test(d)) return null;\n let bytes: Uint8Array;\n try { bytes = fromBase64Url(d); } catch { return null; }\n return bytes.length && bytes.length <= APP_RANGE_LIMITS.chunkBytes && toBase64Url(bytes) === d ? bytes : null;\n}\n\nexport function appRangeGetFrame(app: string, serve: string, request: number, offset: number, length: number): AppRangeFrame {\n const frame = { t: \"ar-get\" as const, a: app, s: serve, r: request, o: offset, n: length };\n if (!readAppRangeFrame(frame).ok) throw new Error(\"Not an app range request\");\n return frame;\n}\n\nexport function appRangeDataFrame(app: string, request: number, offset: number, data: Uint8Array): AppRangeFrame {\n const frame = { t: \"ar-data\" as const, a: app, r: request, o: offset, d: toBase64Url(data) };\n if (!readAppRangeFrame(frame).ok) throw new Error(\"Not app range data\");\n return frame;\n}\n\nexport function appRangeEndFrame(app: string, request: number, size: number): AppRangeFrame {\n if (!isChatAppId(app) || !isRequest(request) || !isOffset(size)) throw new Error(\"Not an app range end\");\n return { t: \"ar-end\", a: app, r: request, z: size };\n}\n\nexport function appRangeErrorFrame(app: string, request: number, error: AppRangeError): AppRangeFrame {\n if (!isChatAppId(app) || !isRequest(request) || !APP_RANGE_ERRORS.includes(error)) throw new Error(\"Not an app range error\");\n return { t: \"ar-err\", a: app, r: request, e: error };\n}\n\nexport function appRangeCancelFrame(app: string, request: number): AppRangeFrame {\n if (!isChatAppId(app) || !isRequest(request)) throw new Error(\"Not an app range cancel\");\n return { t: \"ar-cancel\", a: app, r: request };\n}\n\n/**\n * An `ar-*` frame as the peer sent it, or why a reader must refuse it: an unknown `t`, no valid `a`, an `ar-get`\n * without a valid `s`, a request number that is not 0 to 2^32 - 1, an offset that is not a safe whole number at or\n * above 0, an `n` that is not 1 to `requestBytes` (or runs past 2^53 - 1), a `d` that is not 1 to `chunkBytes` bytes of\n * canonical base64url, an `e` that is not a code (lower case letters and `-`, at most 32), an `ar-end` whose `z` is not\n * a size (a safe whole number at or above 0). Other keys are ignored.\n */\nexport function readAppRangeFrame(frame: Record<string, unknown>): { ok: true; frame: AppRangeFrame } | { ok: false; refusal: AppRangeRefusal } {\n const refuse = (refusal: AppRangeRefusal) => ({ ok: false as const, refusal });\n const t = frame?.t;\n if (typeof t !== \"string\" || !APP_RANGE_FRAMES.has(t)) return refuse(\"not-ranges\");\n if (!isChatAppId(frame.a)) return refuse(\"bad-a\");\n const a = frame.a;\n if (t === \"ar-get\" && !isServeId(frame.s)) return refuse(\"bad-s\");\n if (!isRequest(frame.r)) return refuse(\"bad-r\");\n const r = frame.r;\n switch (t) {\n case \"ar-get\": {\n if (!isOffset(frame.o)) return refuse(\"bad-o\");\n const n = frame.n;\n if (typeof n !== \"number\" || !Number.isInteger(n) || n < 1 || n > APP_RANGE_LIMITS.requestBytes || !Number.isSafeInteger(frame.o + n)) return refuse(\"bad-n\");\n return { ok: true, frame: { t, a, s: frame.s as string, r, o: frame.o, n } };\n }\n case \"ar-data\": {\n if (!isOffset(frame.o)) return refuse(\"bad-o\");\n if (!appRangeChunk(frame.d)) return refuse(\"bad-d\");\n return { ok: true, frame: { t, a, r, o: frame.o, d: frame.d as string } };\n }\n case \"ar-err\":\n return typeof frame.e === \"string\" && ERROR_CODE.test(frame.e) ? { ok: true, frame: { t, a, r, e: frame.e } } : refuse(\"bad-e\");\n case \"ar-end\":\n return isOffset(frame.z) ? { ok: true, frame: { t, a, r, z: frame.z } } : refuse(\"bad-z\");\n default:\n return { ok: true, frame: { t: \"ar-cancel\", a, r } };\n }\n}\n\n/** An `ar-*` frame as the peer sent it, or null when a reader must refuse it (`readAppRangeFrame` says why). */\nexport function parseAppRangeFrame(frame: Record<string, unknown>): AppRangeFrame | null {\n const read = readAppRangeFrame(frame);\n return read.ok ? read.frame : null;\n}\n\n/**\n * `app-ranges/1` beside `files/4` (WISP 100 § Text and binary messages): a chunk as one binary message of the session,\n * in place of the base64url text of an `ar-data` frame:\n *\n * kind 0x05 (1) | chat app id (16) | request (4, big endian) | offset (8, big endian) | data (1 to `chunkBytes`)\n */\nexport const APP_RANGE_DATA_KIND = 0x05;\nconst HEAD = 1 + 16 + 4 + 8;\n\n/** The binary message for the bytes of request `request` of app `app` at `offset`. Throws on what no receiver would take. */\nexport function encodeAppRangeData(app: string, request: number, offset: number, data: Uint8Array): Uint8Array {\n if (!isChatAppId(app) || !isRequest(request) || !isOffset(offset) || !data.length || data.length > APP_RANGE_LIMITS.chunkBytes) throw new Error(\"Invalid app range data\");\n const id = fromBase64Url(app);\n if (id.length !== 16) throw new Error(\"Invalid app range data\");\n const out = new Uint8Array(HEAD + data.length);\n out[0] = APP_RANGE_DATA_KIND;\n out.set(id, 1);\n const view = new DataView(out.buffer);\n view.setUint32(17, request);\n view.setUint32(21, Math.floor(offset / 2 ** 32));\n view.setUint32(25, offset % 2 ** 32);\n out.set(data, HEAD);\n return out;\n}\n\n/** What a binary message from the contact says, or null when it is not well-formed app range data. `data` is a view of `message`. */\nexport function decodeAppRangeData(message: Uint8Array): { a: string; r: number; o: number; data: Uint8Array } | null {\n if (message.length <= HEAD || message[0] !== APP_RANGE_DATA_KIND || message.length - HEAD > APP_RANGE_LIMITS.chunkBytes) return null;\n const view = new DataView(message.buffer, message.byteOffset, message.byteLength);\n const high = view.getUint32(21);\n // Past 2^53 - 1 an offset is no longer a whole number here.\n if (high > 0x1fffff) return null;\n return { a: toBase64Url(message.slice(1, 17)), r: view.getUint32(17), o: high * 2 ** 32 + view.getUint32(25), data: message.subarray(HEAD) };\n}\n\n/** Why a read of the contact's file failed, as the app hears it (a broker code). */\nexport type AppRangeReadError = \"not-served\" | \"changed\" | \"gone\" | \"busy\" | \"offline\" | \"peer-closed\" | \"failed\";\n\n/** A request of the contact's to answer: read `length` bytes of `file` at `offset`, send them, then `finish`. */\nexport interface AppRangeTask {\n readonly app: string;\n readonly request: number;\n /** The serve id it came under: the page that served it answers it. */\n readonly serve: string;\n /** What this side's app served, as it named it (a linked file's id). */\n readonly file: string;\n readonly offset: number;\n readonly length: number;\n /**\n * False once the asker cancelled, the app closed or the session ended: send nothing more for it. It still holds its\n * place among the app's `inFlight` until it is settled (`finish`, `fail` or `release`), unless this side's app closed.\n */\n readonly live: boolean;\n}\n\ninterface Serving { app: string; request: number; serve: string; file: string; offset: number; length: number; live: boolean; charge?: Taken }\n/** An ask counted in `bytesPerSecond`: when, how many bytes, and whether it aged out of the second. */\ninterface Taken { at: number; bytes: number; out?: true }\n\ninterface Asking {\n app: string;\n serve: string;\n offset: number;\n length: number;\n request?: number;\n chunks: Uint8Array[];\n got: number;\n resolve(read: { bytes: Uint8Array; size: number }): void;\n reject(error: Error): void;\n}\n\nconst slot = (app: string, request: number) => `${app}:${request}`;\n\n/**\n * The read lane of one chat, both ways (WISP 1200 § A read lane to the contact). As the side that serves it keeps the\n * serve ids it gave out and answers the contact's `ar-get` for those only, at most\n * `APP_RANGE_LIMITS.inFlight` per app and `bytesPerSecond` asked in all (`busy` past either); the bytes themselves\n * are read and sent by the session, which calls `finish` or `fail` for each task. As the side that asks it sends at\n * most `inFlight` requests per app, keeps\n * the rest waiting, and puts each answer back together, in order, from the offset asked. Requests last one session\n * (`suspend` ends them); serves last until the app closes on either side (`closeApp`) or the session ends for good\n * (`reset`, which ends both). A task still being read counts until it is settled.\n */\nexport class AppRanges {\n private readonly serves = new Map<string, { app: string; file: string }>();\n /** The same serves by app, then file: an app may serve 100,000 files, and walking `serves` for each was O(n²). */\n private readonly servesByApp = new Map<string, Map<string, string>>();\n private readonly serving = new Map<string, Serving>();\n /**\n * Tasks cancelled, unserved, or stopped by the contact's close or a session's end, that this side is still reading or\n * sending: each counts in its app's `inFlight` until settled, across sessions.\n */\n private readonly draining = new Set<Serving>();\n private readonly asking = new Map<string, Asking>();\n private readonly waiting = new Map<string, Asking[]>();\n /**\n * The size each serve of the contact said (its last `ar-end`), by app and serve id: an ask past it is cut to it. The\n * server counts the bytes asked against its 32 MiB a second; an app reading small files with remote.read's 1 MiB\n * length was refused `busy` from the 33rd read in a second, having moved about 1 MiB (agents#1766).\n */\n private readonly sizes = new Map<string, number>();\n private nextRequest = 0;\n /** The asks taken in the last second (when, how many bytes) and their sum: what `bytesPerSecond` counts. Kept across sessions. */\n private readonly taken: Taken[] = [];\n private takenBytes = 0;\n\n constructor(private readonly send: (frame: AppRangeFrame) => void, private readonly newServeId = () => toBase64Url(randomBytes(16)), private readonly now = Date.now) {}\n\n /**\n * Lets the contact's `app` read `file` until the app closes: the serve id to tell it. A file the app serves already\n * answers the id it has, so an app that serves again on each play holds one serve per file, not one per call.\n */\n serve(app: string, file: string): string {\n if (!isChatAppId(app)) throw new Error(\"Not a chat app id\");\n const files = this.servesByApp.get(app) ?? new Map<string, string>();\n const served = files.get(file);\n if (served !== undefined) return served;\n let id = this.newServeId();\n while (this.serves.has(id)) id = this.newServeId();\n this.serves.set(id, { app, file });\n files.set(file, id);\n this.servesByApp.set(app, files);\n return id;\n }\n\n /** Ends one serve: requests under it still being sent stop. False when it was not served. */\n unserve(serveId: string): boolean {\n const serve = this.serves.get(serveId);\n if (!serve) return false;\n this.serves.delete(serveId);\n const files = this.servesByApp.get(serve.app)!;\n files.delete(serve.file);\n if (!files.size) this.servesByApp.delete(serve.app);\n for (const task of this.serving.values()) if (task.serve === serveId) this.drop(task, true);\n return true;\n }\n\n /** The serve ids `app` has given out and not ended (what the panel's \"Sharing with\" line shows). */\n servesOf(app: string): string[] {\n return [...this.servesByApp.get(app)?.values() ?? []];\n }\n\n /** An `ar-get` from the contact: the task to read and send, or null when it was refused (the refusal is sent) or dropped. */\n receiveGet(frame: Extract<AppRangeFrame, { t: \"ar-get\" }>): AppRangeTask | null {\n const { a: app, r: request } = frame;\n // A request number still in flight is the asker's own mistake: answering it would end the first one.\n if (this.serving.has(slot(app, request))) return null;\n const serve = this.serves.get(frame.s);\n if (!serve || serve.app !== app) { this.send(appRangeErrorFrame(app, request, \"not-served\")); return null; }\n // A request cancelled but not yet settled still counts: a cancel stops the bytes, not the read under them.\n const inFlight = [...this.serving.values(), ...this.draining].filter(task => task.app === app).length;\n if (inFlight >= APP_RANGE_LIMITS.inFlight) { this.send(appRangeErrorFrame(app, request, \"busy\")); return null; }\n // Each ask is a read on this device, cancelled or not: past the bytes a second, nothing more is read.\n const at = this.now();\n while (this.taken.length && this.taken[0]!.at <= at - 1000) { const old = this.taken.shift()!; old.out = true; this.takenBytes -= old.bytes; }\n const bytes = Math.max(frame.n, APP_RANGE_LIMITS.askFloorBytes);\n if (this.takenBytes + bytes > APP_RANGE_LIMITS.bytesPerSecond) { this.send(appRangeErrorFrame(app, request, \"busy\")); return null; }\n const charge: Taken = { at, bytes };\n this.taken.push(charge);\n this.takenBytes += bytes;\n const task: Serving = { app, request, serve: frame.s, file: serve.file, offset: frame.o, length: frame.n, live: true, charge };\n this.serving.set(slot(app, request), task);\n return task;\n }\n\n /** An `ar-cancel` from the contact: that request sends nothing more, and its number frees; its place frees once it is settled. */\n receiveCancel(frame: Extract<AppRangeFrame, { t: \"ar-cancel\" }>): void {\n const task = this.serving.get(slot(frame.a, frame.r));\n if (task) this.drop(task, true);\n }\n\n /** Every byte of `task` was sent: `ar-end` goes with the file's size, unless the task was dropped meanwhile. */\n finish(task: AppRangeTask, size: number): void {\n if (!this.take(task)) return;\n // Read and sent whole: it counts what the file held from its offset, not the length asked. An app reading small\n // files at remote.read's 1 MiB was refused `busy` from the 33rd read in a second, having moved ~1 MiB (agents#1766).\n // A cancelled ask is never finished, and keeps counting the read it started. Never under `askFloorBytes`.\n const charge = (task as Serving).charge, sent = Math.max(APP_RANGE_LIMITS.askFloorBytes, Math.min(task.length, size - task.offset));\n if (charge && !charge.out && charge.bytes > sent) { this.takenBytes -= charge.bytes - sent; charge.bytes = sent; }\n this.send(appRangeEndFrame(task.app, task.request, size));\n }\n\n /** The file under `task` could not be read: `ar-err` goes in place of the rest, unless the task was dropped meanwhile. */\n fail(task: AppRangeTask, error: \"changed\" | \"gone\"): void {\n if (this.take(task)) this.send(appRangeErrorFrame(task.app, task.request, error));\n }\n\n /** The session stopped working on `task` without an answer (it is no longer live, or the channel went): its place frees, nothing is sent. */\n release(task: AppRangeTask): void {\n this.take(task);\n }\n\n /**\n * Whether `task` still holds a place: serving, or no longer live and draining until it is settled. False once it was\n * settled, or this side's app closed, which frees its place: an answer to it sends and frees nothing.\n */\n holds(task: AppRangeTask): boolean {\n return this.draining.has(task as Serving) || this.serving.get(slot(task.app, task.request)) === task;\n }\n\n /** Reads `length` bytes at `offset` of what the contact's `app` serves as `serve`: the bytes (fewer at the end) and the file's size. */\n read(app: string, serve: string, offset: number, length: number): Promise<{ bytes: Uint8Array; size: number }> {\n appRangeGetFrame(app, serve, 0, offset, length);\n const size = this.sizes.get(`${app} ${serve}`);\n if (size !== undefined && size > offset) length = Math.min(length, size - offset);\n return new Promise((resolve, reject) => {\n const ask: Asking = { app, serve, offset, length, chunks: [], got: 0, resolve, reject };\n const queue = this.waiting.get(app) ?? [];\n queue.push(ask);\n this.waiting.set(app, queue);\n this.pump(app);\n });\n }\n\n /** Bytes of a request of ours, from `ar-data` or a binary chunk. Out of order or past what was asked fails the request. */\n receiveData(app: string, request: number, offset: number, data: Uint8Array): void {\n const ask = this.asking.get(slot(app, request));\n if (!ask) return;\n if (offset !== ask.offset + ask.got || ask.got + data.length > ask.length) {\n this.send(appRangeCancelFrame(app, request));\n return this.settle(ask, \"failed\");\n }\n ask.chunks.push(data.slice());\n ask.got += data.length;\n }\n\n /** The contact's `ar-end` or `ar-err` for a request of ours. */\n receiveAnswer(frame: Extract<AppRangeFrame, { t: \"ar-end\" | \"ar-err\" }>): void {\n const ask = this.asking.get(slot(frame.a, frame.r));\n if (!ask) return;\n // `busy`: the server's limits, a wait (the app hears too-fast), not a failure.\n if (frame.t === \"ar-err\") return this.settle(ask, ([\"not-served\", \"changed\", \"gone\", \"busy\"] as const).find(code => code === frame.e) ?? \"failed\");\n // Fewer bytes than asked only at the end of the file, and none past it.\n if (ask.got !== Math.max(0, Math.min(ask.length, frame.z - ask.offset))) return this.settle(ask, \"failed\");\n this.settle(ask);\n this.sizes.set(`${ask.app} ${ask.serve}`, frame.z);\n ask.resolve({ bytes: concatBytes(...ask.chunks), size: frame.z });\n }\n\n /**\n * `app` closed on either side: its serves end, what it was sending stops and what it asked fails with `error`. A task\n * this side is still reading keeps its place until it is settled, as a cancelled one does, so a contact that closes\n * and opens its app again meets `busy`; only `stopped` (this side's app closed: nothing reads for it any more) frees\n * them now.\n */\n closeApp(app: string, error: AppRangeReadError = \"peer-closed\", stopped = false): void {\n for (const id of this.servesByApp.get(app)?.values() ?? []) this.serves.delete(id);\n this.servesByApp.delete(app);\n for (const key of [...this.sizes.keys()]) if (key.startsWith(`${app} `)) this.sizes.delete(key);\n this.endRequests(app, error, stopped);\n }\n\n /** The session ended: no serve id lasts into the next, and every request fails with `offline`. Tasks still being read keep their places into the next. */\n reset(): void {\n this.sizes.clear();\n for (const app of [...this.servesByApp.keys()]) this.closeApp(app, \"offline\");\n this.suspend();\n }\n\n /**\n * The session changed (a resume, a re-dial, a transport switch) and the apps are held across it: every request fails\n * with `offline`, and the serve ids stay, for the next session, until the app closes on either side.\n */\n suspend(): void {\n const apps = new Set([...this.serving.values(), ...this.draining].map(task => task.app).concat([...this.waiting.keys()], [...this.asking.values()].map(ask => ask.app)));\n for (const app of apps) this.endRequests(app, \"offline\");\n }\n\n /**\n * What `app` was sending stops and what it asked fails with `error`. A task this side is still reading keeps its place\n * until it is settled; only `stopped` (this side's app closed) frees them now.\n */\n private endRequests(app: string, error: AppRangeReadError, stopped = false): void {\n for (const task of this.serving.values()) if (task.app === app) this.drop(task, !stopped);\n if (stopped) for (const task of this.draining) if (task.app === app) this.draining.delete(task);\n for (const ask of this.waiting.get(app) ?? []) ask.reject(new Error(error));\n this.waiting.delete(app);\n for (const ask of this.asking.values()) if (ask.app === app) this.settle(ask, error);\n }\n\n /** Stops `task` and frees its request number; `draining` keeps it counted until it is settled. */\n private drop(task: Serving, draining = false): void {\n task.live = false;\n this.serving.delete(slot(task.app, task.request));\n if (draining) this.draining.add(task);\n }\n\n /** Frees `task`'s place; false when it was no longer live (nothing to send for it). */\n private take(task: AppRangeTask): boolean {\n if (this.draining.delete(task as Serving)) return false;\n const held = this.serving.get(slot(task.app, task.request));\n if (held !== task || !held.live) return false;\n this.drop(held);\n return true;\n }\n\n /** Ends `ask` (failing it with `error` when given) and sends the next one waiting for its app. */\n private settle(ask: Asking, error?: AppRangeReadError): void {\n if (ask.request === undefined || this.asking.get(slot(ask.app, ask.request)) !== ask) return;\n this.asking.delete(slot(ask.app, ask.request));\n if (error) ask.reject(new Error(error));\n this.pump(ask.app);\n }\n\n private pump(app: string): void {\n const queue = this.waiting.get(app);\n let inFlight = [...this.asking.values()].filter(ask => ask.app === app).length;\n while (queue?.length && inFlight < APP_RANGE_LIMITS.inFlight) {\n const ask = queue.shift()!;\n let request = this.nextRequest;\n while (this.asking.has(slot(app, request))) request = request === APP_RANGE_LIMITS.maxRequest ? 0 : request + 1;\n this.nextRequest = request === APP_RANGE_LIMITS.maxRequest ? 0 : request + 1;\n ask.request = request;\n this.asking.set(slot(app, request), ask);\n inFlight++;\n this.send(appRangeGetFrame(app, ask.serve, request, ask.offset, ask.length));\n }\n if (queue && !queue.length) this.waiting.delete(app);\n }\n}\n","import { p256 } from \"@noble/curves/nist.js\";\nimport { gcm } from \"@noble/ciphers/aes.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { concatBytes, fromBase64Url, randomBytes, toBase64Url, utf8Encode } from \"./bytes\";\n\n/*\n * Web Push, the sending side, with no server: what a Ghostly app needs to wake a contact's closed web app\n * through the contact's own push subscription (WISP 401 § Wake-up push). Two standards:\n * - VAPID (RFC 8292): the request carries a short JWT signed with the key pair the subscription was made\n * with, so the push service accepts it. The contact shares that key pair's private half with its paired\n * contacts, so each of them can sign; nothing else can be done with it.\n * - Message encryption (RFC 8291, `aes128gcm`, RFC 8188): the body is encrypted to the subscription's\n * P-256 key and auth secret. The push service (Google, Apple, Mozilla) sees only ciphertext, and only\n * the browser that subscribed can read it.\n */\n\n/** A VAPID key pair: the public key as an uncompressed P-256 point, the private one as its 32-byte scalar. */\nexport interface VapidKeys {\n publicKey: string;\n privateKey: string;\n}\n\n/** What a browser's `PushSubscription` gives: where to post, and the keys to encrypt to. */\nexport interface PushTarget {\n endpoint: string;\n /** The subscription's P-256 public key, uncompressed, base64url (`getKey(\"p256dh\")`). */\n p256dh: string;\n /** Its 16-byte auth secret, base64url (`getKey(\"auth\")`). */\n auth: string;\n}\n\n/** An HTTP request, ready for `fetch` or a relay. */\nexport interface PushRequest {\n url: string;\n headers: Record<string, string>;\n body: Uint8Array;\n}\n\nexport class WebPushError extends Error {}\n\nconst RECORD_SIZE = 4096;\n/**\n * Every wake-up's record is padded to this many bytes (its plaintext, the delimiter and zeros, RFC 8188), so the push\n * service and a relay see one body length for a message, a call and a device handoff. 128 holds the longest of them\n * with the longest token a contact may give (64 characters).\n */\nexport const PUSH_PAD_BYTES = 128;\n/** Push services refuse a token valid for more than 24 hours; 12 leaves room for skewed clocks. */\nconst TOKEN_SECONDS = 12 * 60 * 60;\n\nexport function generateVapidKeys(): VapidKeys {\n const secret = p256.utils.randomSecretKey();\n return { publicKey: toBase64Url(p256.getPublicKey(secret, false)), privateKey: toBase64Url(secret) };\n}\n\nfunction point(value: string, what: string): Uint8Array {\n let bytes: Uint8Array;\n try { bytes = fromBase64Url(value); } catch { throw new WebPushError(`${what} is not base64url`); }\n if (bytes.length !== 65 || bytes[0] !== 4) throw new WebPushError(`${what} is not an uncompressed P-256 key`);\n try { p256.Point.fromBytes(bytes); } catch { throw new WebPushError(`${what} is not a point on P-256`); }\n return bytes;\n}\n\n/** Whether a VAPID key pair is well formed and its halves belong together. */\nexport function vapidKeysMatch(keys: VapidKeys): boolean {\n try {\n const secret = fromBase64Url(keys.privateKey);\n return secret.length === 32 && toBase64Url(p256.getPublicKey(secret, false)) === toBase64Url(point(keys.publicKey, \"The VAPID key\"));\n } catch {\n return false;\n }\n}\n\n/**\n * The push services a browser subscribes with: Google (Chrome, Edge on Android, Brave, Opera), Apple (Safari), Mozilla\n * (Firefox), Microsoft (Edge on Windows). The same list as the push relay's (infra/services/push-relay/relay.mjs).\n */\nexport const PUSH_SERVICE_HOSTS: readonly RegExp[] = [/^fcm\\.googleapis\\.com$/, /(^|\\.)push\\.apple\\.com$/, /(^|\\.)push\\.services\\.mozilla\\.com$/, /(^|\\.)notify\\.windows\\.com$/];\n\n/**\n * Only https, on one of the push services' host names and their default port, without credentials. The endpoint came\n * from a contact: it must not turn this app into a way to post to the contact's choice of address, local or not.\n */\nexport function checkPushEndpoint(endpoint: string): URL {\n let url: URL;\n try { url = new URL(endpoint); } catch { throw new WebPushError(\"The push endpoint is not a URL\"); }\n if (url.protocol !== \"https:\") throw new WebPushError(\"The push endpoint is not https\");\n if (url.username || url.password) throw new WebPushError(\"The push endpoint carries credentials\");\n if (url.port) throw new WebPushError(\"The push endpoint names a port\");\n const host = url.hostname.toLowerCase();\n if (!PUSH_SERVICE_HOSTS.some(pattern => pattern.test(host))) throw new WebPushError(\"The push endpoint is not a push service\");\n if (endpoint.length > 2048) throw new WebPushError(\"The push endpoint is too long\");\n return url;\n}\n\n/** `Authorization: vapid t=<JWT>, k=<public key>` for a request to `endpoint` (RFC 8292). */\nexport function vapidAuthorization(endpoint: string, keys: VapidKeys, subject: string, now = Date.now()): string {\n const audience = checkPushEndpoint(endpoint).origin;\n const encode = (value: object) => toBase64Url(utf8Encode(JSON.stringify(value)));\n const unsigned = `${encode({ typ: \"JWT\", alg: \"ES256\" })}.${encode({ aud: audience, exp: Math.floor(now / 1000) + TOKEN_SECONDS, sub: subject })}`;\n const signature = p256.sign(utf8Encode(unsigned), fromBase64Url(keys.privateKey));\n return `vapid t=${unsigned}.${toBase64Url(signature)}, k=${keys.publicKey}`;\n}\n\n/**\n * `plaintext` encrypted for a subscription (RFC 8291 with RFC 8188 `aes128gcm`, one record). `padTo`: the record's\n * plaintext is padded with zeros after the delimiter to this many bytes (a longer one goes as it is). `secret` and\n * `salt` fix the sender's ephemeral key and salt, for the RFC's test vector only.\n */\nexport function encryptPushPayload(plaintext: Uint8Array, target: Pick<PushTarget, \"p256dh\" | \"auth\">, options: { padTo?: number; secret?: Uint8Array; salt?: Uint8Array } = {}): Uint8Array {\n const receiver = point(target.p256dh, \"The subscription key\");\n let auth: Uint8Array;\n try { auth = fromBase64Url(target.auth); } catch { throw new WebPushError(\"The auth secret is not base64url\"); }\n if (auth.length !== 16) throw new WebPushError(\"The auth secret is not 16 bytes\");\n if (plaintext.length > RECORD_SIZE - 17 - 86) throw new WebPushError(\"The payload is too long for one record\");\n\n const secret = options.secret ?? p256.utils.randomSecretKey();\n const salt = options.salt ?? randomBytes(16);\n const senderPublic = p256.getPublicKey(secret, false);\n const shared = p256.getSharedSecret(secret, receiver).subarray(1);\n\n const keyInfo = concatBytes(utf8Encode(\"WebPush: info\\0\"), receiver, senderPublic);\n const ikm = hkdf(sha256, shared, auth, keyInfo, 32);\n const cek = hkdf(sha256, ikm, salt, utf8Encode(\"Content-Encoding: aes128gcm\\0\"), 16);\n const nonce = hkdf(sha256, ikm, salt, utf8Encode(\"Content-Encoding: nonce\\0\"), 12);\n // The last (and only) record: the plaintext, the delimiter 0x02, then zeros up to `padTo`.\n const record = new Uint8Array(Math.max(plaintext.length + 1, Math.min(options.padTo ?? 0, RECORD_SIZE - 17 - 86)));\n record.set(plaintext);\n record[plaintext.length] = 2;\n const ciphertext = gcm(cek, nonce).encrypt(record);\n\n const header = new Uint8Array(16 + 4 + 1 + senderPublic.length);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE);\n header[20] = senderPublic.length;\n header.set(senderPublic, 21);\n return concatBytes(header, ciphertext);\n}\n\n/**\n * The receiving side of `encryptPushPayload`, which a browser does for its service worker. Here for tests and\n * for a push service stand-in; the app itself never decrypts a push.\n */\nexport function decryptPushPayload(body: Uint8Array, receiverSecret: Uint8Array, authSecret: Uint8Array): Uint8Array {\n if (body.length < 21) throw new WebPushError(\"Too short\");\n const salt = body.subarray(0, 16);\n const idLength = body[20];\n const senderPublic = body.subarray(21, 21 + idLength);\n const receiverPublic = p256.getPublicKey(receiverSecret, false);\n const shared = p256.getSharedSecret(receiverSecret, senderPublic).subarray(1);\n const keyInfo = concatBytes(utf8Encode(\"WebPush: info\\0\"), receiverPublic, senderPublic);\n const ikm = hkdf(sha256, shared, authSecret, keyInfo, 32);\n const cek = hkdf(sha256, ikm, salt, utf8Encode(\"Content-Encoding: aes128gcm\\0\"), 16);\n const nonce = hkdf(sha256, ikm, salt, utf8Encode(\"Content-Encoding: nonce\\0\"), 12);\n const padded = gcm(cek, nonce).decrypt(body.subarray(21 + idLength));\n let end = padded.length - 1;\n while (end >= 0 && padded[end] === 0) end--;\n if (end < 0 || padded[end] !== 2) throw new WebPushError(\"No last-record delimiter\");\n return padded.subarray(0, end);\n}\n\n/**\n * The whole request that wakes a subscription: POST, encrypted body, VAPID authorization, a short time to live\n * (a wake-up an hour late is no use) and high urgency (a phone on battery saver still gets it). The body is padded to\n * `PUSH_PAD_BYTES`, so its length does not tell one kind of wake-up from another.\n */\nexport function pushRequest(target: PushTarget, keys: VapidKeys, payload: Uint8Array, options: { subject: string; ttlSeconds?: number; now?: number }): PushRequest {\n checkPushEndpoint(target.endpoint);\n const body = encryptPushPayload(payload, target, { padTo: PUSH_PAD_BYTES });\n return {\n url: target.endpoint,\n headers: {\n Authorization: vapidAuthorization(target.endpoint, keys, options.subject, options.now),\n \"Content-Encoding\": \"aes128gcm\",\n \"Content-Type\": \"application/octet-stream\",\n TTL: String(options.ttlSeconds ?? 60 * 60),\n Urgency: \"high\",\n },\n body,\n };\n}\n","import { toBase64Url, utf8Encode, randomBytes } from \"./bytes\";\nimport { checkPushEndpoint, pushRequest, vapidKeysMatch, type PushRequest, type PushTarget, type VapidKeys } from \"./webPush\";\n\n/**\n * Wake-up push (WISP 401 § Wake-up push): a contact whose web app is closed can be woken by this app, with no\n * server of Ghostly's. The contact's app subscribes to its browser's push service and shares, with each paired\n * contact and only on the live session, where to post and how:\n *\n * {\"t\":\"paired-wake\",\"w\":{\"e\":\"https://fcm.googleapis.com/fcm/send/…\",\"p\":\"<p256dh>\",\"a\":\"<auth>\",\n * \"vp\":\"<VAPID public>\",\"vk\":\"<VAPID private>\",\"k\":\"<token>\"}}\n * {\"t\":\"paired-wake\",\"w\":null} (stopped: forget what I shared)\n *\n * When a message to that contact cannot go live (the contact's app is closed), this app posts an encrypted push\n * of a few bytes to the endpoint: `{\"wake\":1,\"k\":\"<token>\"}`. It says nothing about the message: the contact's\n * app shows \"New message\", opens on a tap, connects and fetches the message itself. The token is the contact's\n * own name for this chat, different for every contact, so its app knows which chat (and whether it is muted)\n * without the push service learning anything: every wake-up is padded to one size (`PUSH_PAD_BYTES`), so it sees that\n * a push happened, and when; only the time to live and a call's repeats set a call, an online notice or a device\n * handoff apart (an online notice has a handoff's time to live).\n *\n * It needs `wake/1` in `paired-capabilities` on both sides. The VAPID key pair belongs to that one subscription,\n * so sharing its private half lets a contact post to that subscription and nothing else. Rotating it (a new\n * subscription, new tokens) is how the contact's app revokes everyone it no longer shares with.\n */\n\nexport { WAKE_SESSION_CAPABILITY as WAKE_CAPABILITY } from \"./pairedCapabilities\";\nexport const WAKE_FRAME = \"paired-wake\";\n\n/** At most one wake-up per contact in this long. A burst of messages is one push. */\nexport const WAKE_INTERVAL_MS = 5 * 60_000;\n/**\n * A wake-up that did not reach the push service (no network, the push relay did not forward it, the push service\n * answered 429 or 5xx) is not the contact's wake-up: the next one may go this long after it, not 5 minutes. Never a\n * retry of that one; only a pause, so a relay that is refusing is not asked again on every message.\n */\nexport const WAKE_RETRY_MS = 30_000;\n/** A wake-up that has not reached the phone within this is no use: the push service may drop it. */\nexport const WAKE_TTL_SECONDS = 60 * 60;\n/** The VAPID subject push services ask for: who to contact about abuse. The project, never a person. */\nexport const WAKE_SUBJECT = \"https://ghostly.tools\";\n\n/**\n * What a contact shares: its push subscription, the key pair it was made with, and its token for this chat. `online`:\n * it wants an online notice when this side comes online while its app is closed (`o: 1`, revision 2026-10-27).\n */\nexport interface WakeTarget extends PushTarget {\n vapid: VapidKeys;\n token: string;\n online?: true;\n}\n\nexport type WakeFrame = {\n t: typeof WAKE_FRAME;\n w: { e: string; p: string; a: string; vp: string; vk: string; k: string; o?: 1 } | null;\n};\n\n/** A fresh per-contact token: 16 random bytes, base64url. */\nexport function newWakeToken(): string {\n return toBase64Url(randomBytes(16));\n}\n\nexport function wakeFrame(target: WakeTarget | null): WakeFrame {\n return {\n t: WAKE_FRAME,\n w: target && { e: target.endpoint, p: target.p256dh, a: target.auth, vp: target.vapid.publicKey, vk: target.vapid.privateKey, k: target.token, ...(target.online && { o: 1 as const }) },\n };\n}\n\nconst TOKEN = /^[A-Za-z0-9_-]{16,64}$/;\nconst B64URL = /^[A-Za-z0-9_-]{1,200}$/;\n\n/**\n * What a `paired-wake` frame says: the contact's target, null when it stopped sharing, or undefined when the frame\n * is malformed (then it says nothing, and what the contact said before stands). The endpoint must be an https\n * push service on a public host name, and the key pair must be a pair.\n */\nexport function parseWakeFrame(frame: Record<string, unknown>): WakeTarget | null | undefined {\n if (frame.w === null) return null;\n const w = frame.w as Record<string, unknown> | undefined;\n if (!w || typeof w !== \"object\") return undefined;\n const { e, p, a, vp, vk, k, o } = w;\n if (typeof e !== \"string\" || ![p, a, vp, vk].every((v) => typeof v === \"string\" && B64URL.test(v)) || typeof k !== \"string\" || !TOKEN.test(k)) return undefined;\n try { checkPushEndpoint(e); } catch { return undefined; }\n const target: WakeTarget = { endpoint: e, p256dh: p as string, auth: a as string, vapid: { publicKey: vp as string, privateKey: vk as string }, token: k, ...(o === 1 && { online: true as const }) };\n if (!vapidKeysMatch(target.vapid)) return undefined;\n return target;\n}\n\n/**\n * What a wake-up is for: a message waits, or a call does (the caller rings until the contact's app is live, then\n * calls), or this side just came online (revision 2026-10-27; only to a contact that asked, `online`). The receiving\n * app picks its own words for each; the push says nothing more.\n */\nexport type WakeKind = \"message\" | \"call\" | \"online\";\n\n/** At most one online notice per contact in this long, whatever the message wake-ups do. Kept across restarts. */\nexport const WAKE_ONLINE_INTERVAL_MS = 30 * 60_000;\n/** An online notice the phone gets later than this is stale: worse than none. */\nexport const WAKE_ONLINE_TTL_SECONDS = 5 * 60;\n/** How long after this side comes online it waits for the chat to go live before it says so: a live contact needs no push. */\nexport const WAKE_ONLINE_DELAY_MS = 30_000;\n/**\n * Most online notices that go out in `WAKE_ONLINE_BATCH_MS`; the rest wait for the next one. A page posts its wake-ups\n * through a push relay, which takes 30 a minute from one address: all at once, a profile with 30 contacts that asked\n * spent the whole minute, and a call or message wake-up right after was refused.\n */\nexport const WAKE_ONLINE_BATCH = 10;\nexport const WAKE_ONLINE_BATCH_MS = 60_000;\n\n/** At most one call wake-up per contact in this long: a caller who tries again at once is not a new push. */\nexport const WAKE_CALL_INTERVAL_MS = 30_000;\n/** How long a caller waits for the woken contact's app to come live before giving up. */\nexport const WAKE_CALL_WAIT_MS = 60_000;\n/** A call wake-up is useless once the caller stopped waiting: the push service may drop it after this. */\nexport const WAKE_CALL_TTL_SECONDS = 60;\n\n/** The wake-up's plaintext: the contact's token for this chat, and whether it is for a call or an online notice. Nothing else. */\nexport function wakePayload(token: string, kind: WakeKind = \"message\"): Uint8Array {\n return utf8Encode(JSON.stringify({ wake: 1, k: token, ...(kind === \"call\" && { c: 1 }), ...(kind === \"online\" && { o: 1 }) }));\n}\n\n/**\n * A wake-up as the receiving service worker reads it: the token and its kind; null for anything else. `device`: one of\n * the person's own devices asks this one to open for a handoff (WISP 06 § Push and the phone, `{\"wake\":1,\"k\":…,\"d\":1}`).\n * The flag alone proves nothing: the worker believes it only for a token it gave one of its own devices.\n */\nexport function readWake(text: string | null | undefined): { token: string; kind: WakeKind | \"device\" } | null {\n if (!text || text.length > 200) return null;\n try {\n const value = JSON.parse(text) as { wake?: unknown; k?: unknown; c?: unknown; d?: unknown; o?: unknown };\n if (value?.wake !== 1 || typeof value.k !== \"string\" || !TOKEN.test(value.k)) return null;\n return { token: value.k, kind: value.d === 1 ? \"device\" : value.c === 1 ? \"call\" : value.o === 1 ? \"online\" : \"message\" };\n } catch {\n return null;\n }\n}\n\n/** A device wake-up is useless once the device that asked stopped waiting for its handoff. */\nexport const DEVICE_WAKE_TTL_SECONDS = 5 * 60;\n\n/**\n * The request that wakes another of the person's devices for a handoff (WISP 06 § Push and the phone): sent as a\n * wake-up to a contact is, with body `{\"wake\":1,\"k\":\"<token>\",\"d\":1}`, where the token is the one that device gave this\n * one on their device link. Throws `WebPushError` when the target cannot be used.\n */\nexport function deviceWakeRequest(target: WakeTarget, now = Date.now()): PushRequest {\n return pushRequest(target, target.vapid, utf8Encode(JSON.stringify({ wake: 1, k: target.token, d: 1 })), {\n subject: WAKE_SUBJECT, ttlSeconds: DEVICE_WAKE_TTL_SECONDS, now,\n });\n}\n\n/** The token a wake-up carries; null for anything else. */\nexport function readWakePayload(text: string | null | undefined): string | null {\n return readWake(text)?.token ?? null;\n}\n\n/** The request that wakes the contact. Throws `WebPushError` when the target cannot be used. */\nexport function wakeRequest(target: WakeTarget, now = Date.now(), kind: WakeKind = \"message\"): PushRequest {\n return pushRequest(target, target.vapid, wakePayload(target.token, kind), {\n subject: WAKE_SUBJECT, ttlSeconds: kind === \"call\" ? WAKE_CALL_TTL_SECONDS : kind === \"online\" ? WAKE_ONLINE_TTL_SECONDS : WAKE_TTL_SECONDS, now,\n });\n}\n\n/** One wake-up per contact per `WAKE_INTERVAL_MS`. Kept in memory: a restart may send one more, never a flood. */\nexport class WakeLimiter {\n private readonly last = new Map<string, number>();\n constructor(private readonly interval = WAKE_INTERVAL_MS) {}\n /** Whether a wake-up to `contact` may go now; if so, it counts as sent. */\n take(contact: string, now = Date.now()): boolean {\n const before = this.last.get(contact);\n if (before !== undefined && now - before < this.interval) return false;\n this.last.set(contact, now);\n return true;\n }\n /**\n * The wake-up taken at `takenAt` did not reach the push service: it does not count, and the next may go\n * `retryMs` from now. Nothing changes when another was taken since, or the count started over.\n */\n missed(contact: string, takenAt: number, retryMs = WAKE_RETRY_MS, now = Date.now()): void {\n if (this.last.get(contact) !== takenAt) return;\n this.last.set(contact, now - this.interval + Math.min(retryMs, this.interval));\n }\n /** The contact answered (it is live again): the next time it is away, it may be woken at once. */\n reset(contact: string): void {\n this.last.delete(contact);\n }\n}\n\n/**\n * What a push relay is asked (Settings → Network → Push relay): a browser page may not post to a push service\n * itself (the services answer without CORS), so it can hand the finished request to a relay the person chose,\n * which posts it as it is. The relay learns what the push service learns, plus this device's address.\n *\n * POST <relay> {\"endpoint\":\"https://…\",\"headers\":{\"Authorization\":\"vapid …\",…},\"body\":\"<base64url>\"}\n */\nexport function relayRequest(request: PushRequest): { endpoint: string; headers: Record<string, string>; body: string } {\n return { endpoint: request.url, headers: request.headers, body: toBase64Url(request.body) };\n}\n\n","import { REPLY_ID } from \"./replies\";\nimport { nextReactionNumber, validReactionNumber } from \"./reactions\";\n\n/**\n * A pinned message (WISP 400 § Pinned message): one per chat, shown in a bar at the top. Whoever pins says which\n * message (the id both sides know it by, as a reply names it) and a number: the clock in milliseconds, past the pin\n * it replaces. An empty id unpins. The highest number wins, whatever order the frames arrive in, so the last pin wins\n * on every side and a late frame changes nothing. A number further ahead of the receiver's clock than\n * `PIN_CLOCK_SKEW_MS` is refused: clocks drift, but a number past that is the sender's choice, and one near the\n * largest safe integer would leave nobody a higher number to pin or unpin with.\n *\n * A 1:1 chat says it on the live session once both sides list `pin/1` in `paired-capabilities`, and the contact\n * confirms the number it took:\n *\n * {\"t\":\"paired-pin\",\"id\":\"<message id>\",\"n\":1790000000000}\n * {\"t\":\"paired-pinned\",\"n\":1790000000000}\n *\n * A private group signs it and passes it over the edges (`group-pin`); a community seals it to the group as an\n * application frame (`pin`). Older apps drop all of these: a `t` they do not know.\n */\n\nexport const PIN_FRAME = \"paired-pin\";\nexport const PINNED_FRAME = \"paired-pinned\";\n/** A pin in a private group, signed by the member who pinned, passed on by every member that takes it. */\nexport const GROUP_PIN_FRAME = \"group-pin\";\n/** A pin in a community, as an application frame sealed to the group. */\nexport const COMMUNITY_PIN_FRAME = \"pin\";\n\n/**\n * How far ahead of this device's clock a pin's number may be. What a session and a call allow a contact's clock\n * (`RTC_SIGNAL_FUTURE_MS`, `CALL_SIGNAL_FUTURE_MS`): a contact whose clock runs seven minutes ahead pairs, chats and\n * calls, and its pins were dropped, each said again every 30 seconds and never taken.\n */\nexport const PIN_CLOCK_SKEW_MS = 10 * 60_000;\n\nexport const PIN_LIMITS = {\n /** Pin frames a receiver takes per window on one chat; the rest are dropped unconfirmed and come again. */\n receive: 10,\n windowMs: 10_000,\n /** A pin said on the live session and not confirmed is said again after this long. */\n resendMs: 30_000,\n} as const;\n\n/** A pin as it goes on the wire: the message's id (\"\" unpins) and the pinner's number. */\nexport interface WirePin { id: string; n: number }\n\n/**\n * Who may pin in a group. The one place the rule lives (WISP 400 § Pinned message): in a private group any member,\n * in a community only its admin.\n */\nexport function mayPin(kind: \"mesh\" | \"community\", member: string, admin: string | undefined): boolean {\n return kind === \"mesh\" || member === admin;\n}\n\n/**\n * Whether a pin's number holds at `now`: a positive safe integer no further ahead of the clock than\n * `PIN_CLOCK_SKEW_MS`. A kept pin whose number does not hold (taken before receivers checked it) counts as none.\n */\nexport function pinNumberHolds(n: unknown, now = Date.now()): n is number {\n return validReactionNumber(n) && n <= now + PIN_CLOCK_SKEW_MS;\n}\n\n/**\n * The number for a new pin: the clock, or one past the pin shown now, whichever is higher. Past a shown pin whose\n * number does not hold, the clock: a receiver would refuse one past it.\n */\nexport function nextPinNumber(current = 0, now = Date.now()): number {\n if (current && !pinNumberHolds(current, now)) return Math.max(1, Math.floor(now));\n return Math.min(nextReactionNumber(current, now), Number.MAX_SAFE_INTEGER);\n}\n\n/**\n * Whether `pin` replaces the chat's pin now: a higher number wins; two pins with the same number (two sides at the\n * same millisecond) are settled by the id, so every side ends on the same one. A shown pin whose number does not hold\n * is replaced by any pin.\n */\nexport function pinIsNewer(current: WirePin | undefined, pin: WirePin, now = Date.now()): boolean {\n return !current || !pinNumberHolds(current.n, now) || pin.n > current.n || (pin.n === current.n && pin.id > current.id);\n}\n\n/**\n * A pin as a receiver takes it at `now`, or null: an id of a chat's shape or \"\" (unpinned), and a number that holds\n * (`pinNumberHolds`). One refused is not confirmed: its sender says it again, and it is taken once the clocks agree.\n */\nexport function readPin(raw: unknown, now = Date.now()): WirePin | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const { id, n } = raw as Record<string, unknown>;\n if (typeof id !== \"string\" || (id !== \"\" && !REPLY_ID.test(id)) || !pinNumberHolds(n, now)) return null;\n return { id, n };\n}\n\nexport function pinFrame(pin: WirePin): string {\n return JSON.stringify({ t: PIN_FRAME, id: pin.id, n: pin.n });\n}\n\nexport function pinnedFrame(n: number): string {\n return JSON.stringify({ t: PINNED_FRAME, n });\n}\n\n/** The pin a `paired-pin` frame says, or null when it is malformed. */\nexport function parsePinFrame(frame: Record<string, unknown>): WirePin | null {\n return frame?.t === PIN_FRAME ? readPin(frame) : null;\n}\n\n/** The number a `paired-pinned` frame confirms, or null when it is malformed. */\nexport function parsePinnedFrame(frame: Record<string, unknown>): number | null {\n return frame?.t === PINNED_FRAME && validReactionNumber(frame.n) ? frame.n : null;\n}\n","import { sanitizeDisplayText } from \"./text\";\n\n/**\n * The typing indicator of a 1:1 chat (WISP 401 § Typing): \"your contact is writing\", said on the live session only.\n *\n * {\"t\":\"paired-typing\",\"s\":\"start\"} {\"t\":\"paired-typing\",\"s\":\"stop\"}\n * {\"t\":\"paired-typing\",\"s\":\"start\",\"kind\":\"recording\"}\n * {\"t\":\"paired-typing\",\"s\":\"start\",\"kind\":\"thinking\",\"status\":\"Transcribing your audio…\"}\n *\n * It needs `typing/1` in `paired-capabilities` on both sides. It is presence, not a message: never sent on the\n * DHT, never stored, never counted as unread, no message id (older apps drop it). While the person keeps typing,\n * `start` is said again at most every `TYPING_REFRESH_MS`; the receiver shows it until `stop`, a message from that\n * contact, the end of the session, or `TYPING_TIMEOUT_MS` without a new `start` (so a dropped link never leaves it on).\n * A start standing when a session ends (a transport switch, a reconnect) is said again once the next one agreed\n * `typing/1`, if the person's last word is still that recent.\n *\n * A `start` may say what the contact is doing (`kind`: typing, recording a voice note, thinking) and, for bots, a\n * short `status` line. Both are optional: an app that knows neither shows \"typing…\", and so does a kind it does not\n * know. A `start` with a new kind or status goes at once, not at the next refresh.\n */\n\nexport const TYPING_FRAME = \"paired-typing\";\n\n/** How often a `start` is said again while the person keeps typing. */\nexport const TYPING_REFRESH_MS = 3_000;\n/** How long a `start` holds on the receiving side without another. Twice the refresh, so one lost frame is no gap. */\nexport const TYPING_TIMEOUT_MS = 6_000;\n/** At most this many typing frames count per `TYPING_RATE_WINDOW_MS`; the rest are dropped unread. */\nexport const TYPING_RATE_LIMIT = 8;\nexport const TYPING_RATE_WINDOW_MS = 10_000;\n/**\n * The sender keeps under the reader's limit: a `start` goes only while fewer than this many frames went in the\n * window, so the `stop` that follows it always has room (and a clock skew between the two sides has one frame more).\n */\nexport const TYPING_SEND_LIMIT = TYPING_RATE_LIMIT - 2;\n\n/** What the contact is doing: writing, recording a voice note, or working on an answer (a bot). */\nexport const TYPING_KINDS = [\"typing\", \"recording\", \"thinking\"] as const;\nexport type TypingKind = (typeof TYPING_KINDS)[number];\n/** Longest status line kept, in characters (code points). */\nexport const TYPING_STATUS_MAX = 40;\n\n/** A `start`'s word: the kind, and a bot's status line when it gave one. */\nexport interface TypingActivity { kind: TypingKind; status?: string }\n\nexport type TypingState = \"start\" | \"stop\";\n\n// A type, not an interface: it is read back as a plain frame record.\nexport type TypingFrame = { t: typeof TYPING_FRAME; s: TypingState; kind?: Exclude<TypingKind, \"typing\">; status?: string };\n\n/** A scheme (`https://`, `nostr:npub…`, `javascript:`), `www.`, or a tag: a status that holds one is not shown. */\nconst LINK_OR_MARKUP = /[a-z][a-z0-9+.-]*:\\/\\/|\\bwww\\.|\\b(?:mailto|javascript|data|nostr|lightning|bitcoin|ghostly|magnet|tel|sms|file):|<\\/?[a-z!]/i;\n\n/**\n * A status line as it may be shown: one line (line breaks and runs of spaces become one space), no invisible or\n * direction-changing characters, at most `TYPING_STATUS_MAX` characters. Undefined when nothing is left, or when it\n * holds a link or markup (it is plain text, never a way to put a link on the contact's screen).\n */\nexport function sanitizeTypingStatus(value: unknown): string | undefined {\n return plainStatusLine(value, TYPING_STATUS_MAX);\n}\n\n/** A contact's line of plain text by the typing status's rules, at most `max` characters (a set status uses it too). */\nexport function plainStatusLine(value: unknown, max: number): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const oneLine = value.slice(0, 4 * max).replace(/\\s+/g, \" \");\n const clean = sanitizeDisplayText(oneLine, max);\n if (!clean || LINK_OR_MARKUP.test(clean)) return undefined;\n return clean;\n}\n\n/** A kind as it arrived: anything this app does not know reads as plain typing. */\nexport function typingKindOf(value: unknown): TypingKind {\n return typeof value === \"string\" && (TYPING_KINDS as readonly string[]).includes(value) ? value as TypingKind : \"typing\";\n}\n\n/** The activity as it goes on the wire and is shown: kind checked, status sanitized. */\nexport function typingActivity(kind?: unknown, status?: unknown): TypingActivity {\n const clean = sanitizeTypingStatus(status);\n return { kind: typingKindOf(kind), ...(clean ? { status: clean } : {}) };\n}\n\nexport function typingFrame(state: TypingState, activity?: TypingActivity): TypingFrame {\n const frame: TypingFrame = { t: TYPING_FRAME, s: state };\n if (state !== \"start\" || !activity) return frame;\n if (activity.kind !== \"typing\") frame.kind = activity.kind;\n const status = sanitizeTypingStatus(activity.status);\n if (status) frame.status = status;\n return frame;\n}\n\n/** The state a `paired-typing` frame says, or null when it is malformed (then it says nothing). */\nexport function parseTypingFrame(frame: Record<string, unknown>): TypingState | null {\n if (frame?.t !== TYPING_FRAME) return null;\n return frame.s === \"start\" || frame.s === \"stop\" ? frame.s : null;\n}\n\n/** What a `start` says the contact is doing: `typing` when it says nothing (an older app) or a kind unknown here. */\nexport function parseTypingActivity(frame: Record<string, unknown>): TypingActivity {\n return typingActivity(frame?.kind, frame?.status);\n}\n\nconst sameActivity = (a: TypingActivity | null, b: TypingActivity | null) => a?.kind === b?.kind && a?.status === b?.status;\n\n/**\n * This side's word: when to say `start` again, and whether a `stop` is owed. One per chat; what was said is per session\n * (`reset`), what the person is doing is not: a new session (a transport switch, a reconnect) says a standing start\n * again (`resume`), since the contact's reader cleared it when the old session ended.\n *\n * The rate window is not per session: the reader's is per chat too (it is not cleared when a session ends), so a\n * window that started afresh on each session could put a start past the reader's limit just after a switch.\n */\nexport class TypingSender {\n private startedAt = 0;\n private standing: TypingActivity | null = null;\n private recent: number[] = [];\n /** What the person is doing, and when it last said so: kept across sessions, until it stops. */\n private wanted: { activity: TypingActivity; at: number } | null = null;\n\n constructor(private readonly now: () => number = Date.now) {}\n\n /**\n * The person typed (or records, or thinks): the frame to send now, or null when a `start` with the same word went\n * out less than a refresh ago, or the window is full (the next call tries again).\n */\n typing(activity: TypingActivity = { kind: \"typing\" }): TypingFrame | null {\n const now = this.now();\n const word = typingActivity(activity.kind, activity.status);\n this.wanted = { activity: word, at: now };\n return this.say(word, now);\n }\n\n /**\n * The person typed while nothing can be said (no session, or `typing/1` not agreed on it yet): kept, so the start\n * goes once a session can carry it (`resume`).\n */\n want(activity: TypingActivity = { kind: \"typing\" }): void {\n this.wanted = { activity: typingActivity(activity.kind, activity.status), at: this.now() };\n }\n\n /**\n * A new session agreed `typing/1`: the `start` to say on it when the person was still at it, its last word less than\n * `TYPING_TIMEOUT_MS` ago (as long as the contact would still have shown it). Null otherwise, when a start already\n * went on this session, or when the window is full (the person's next keystroke says it).\n */\n resume(): TypingFrame | null {\n const wanted = this.wanted, now = this.now();\n if (!wanted || this.startedAt || now - wanted.at >= TYPING_TIMEOUT_MS) return null;\n return this.say(wanted.activity, now);\n }\n\n private say(word: TypingActivity, now: number): TypingFrame | null {\n if (this.startedAt && now - this.startedAt < TYPING_REFRESH_MS && sameActivity(this.standing, word)) return null;\n this.recent = this.recent.filter(at => now - at < TYPING_RATE_WINDOW_MS);\n if (this.recent.length >= TYPING_SEND_LIMIT) return null;\n this.recent.push(now);\n this.startedAt = now;\n this.standing = word;\n return typingFrame(\"start\", word);\n }\n\n /**\n * The person stopped (cleared the text, sent it, left the chat): a `stop`, only when a `start` is standing on this\n * session. Nothing is said again on the next one either way.\n */\n stopped(): TypingFrame | null {\n this.wanted = null;\n if (!this.startedAt) return null;\n this.recent.push(this.now());\n this.startedAt = 0;\n this.standing = null;\n return typingFrame(\"stop\");\n }\n\n /** A `start` is standing on this session. */\n get active(): boolean { return this.startedAt !== 0; }\n\n /** The session ended: nothing is standing on the next one until `resume` (or the next keystroke) says it. */\n reset(): void { this.startedAt = 0; this.standing = null; }\n}\n\n/**\n * The contact's word, with its timeout and a rate limit. `onChange` hears every change, and only changes: typing on\n * or off, and a new kind or status while it is on.\n */\nexport class TypingReceiver {\n private activity: TypingActivity | null = null;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private recent: number[] = [];\n\n constructor(private readonly onChange: (typing: boolean, activity: TypingActivity | null) => void, private readonly now: () => number = Date.now) {}\n\n /** The contact is typing now. */\n get peerTyping(): boolean { return this.activity !== null; }\n /** What the contact is doing now, or null. */\n get peerActivity(): TypingActivity | null { return this.activity; }\n\n /**\n * A `paired-typing` frame from the contact. False when it was dropped: malformed, or over the rate limit (a\n * contact flooding frames gets its word held where it was until the window lets it speak again).\n */\n receive(frame: Record<string, unknown>): boolean {\n const now = this.now();\n this.recent = this.recent.filter(at => now - at < TYPING_RATE_WINDOW_MS);\n if (this.recent.length >= TYPING_RATE_LIMIT) return false;\n this.recent.push(now);\n const state = parseTypingFrame(frame);\n if (!state) return false;\n if (state === \"stop\") { this.clear(); return true; }\n if (this.timer) clearTimeout(this.timer);\n this.timer = setTimeout(() => { this.timer = null; this.set(null); }, TYPING_TIMEOUT_MS);\n this.set(parseTypingActivity(frame));\n return true;\n }\n\n /** A message from the contact arrived, or the session ended: it is not typing any more. */\n clear(): void {\n if (this.timer) { clearTimeout(this.timer); this.timer = null; }\n this.set(null);\n }\n\n private set(activity: TypingActivity | null): void {\n if (sameActivity(activity, this.activity)) return;\n this.activity = activity;\n this.onChange(activity !== null, activity);\n }\n}\n","import { plainStatusLine } from \"./pairedTyping\";\nimport { reactionEmoji } from \"./reactions\";\n\n/**\n * Presence and a set status in a 1:1 chat (WISP 401 § Presence and status): whether the person is there, and a status\n * they set (Slack-like), said to the contact on the live session only.\n *\n * {\"t\":\"paired-status\",\"p\":\"active\"}\n * {\"t\":\"paired-status\",\"p\":\"idle\",\"s\":{\"a\":\"busy\",\"e\":\"🍕\",\"m\":\"At lunch\",\"u\":1762603600000}}\n * {\"t\":\"paired-status\"}\n *\n * It needs `status/1` in `paired-capabilities` on both sides. Each frame is the whole state and replaces the one before.\n * Like typing, it is presence, not a message: no message id (older apps drop it), never stored, held or put on the DHT.\n * `p` is absent when the person does not share when they are online; `s` is absent when they set no status.\n */\n\nexport const STATUS_FRAME = \"paired-status\";\n\n/** What a person can say they are: `dnd` is Do not disturb. */\nexport const STATUS_AVAILABILITIES = [\"available\", \"busy\", \"away\", \"dnd\"] as const;\nexport type StatusAvailability = (typeof STATUS_AVAILABILITIES)[number];\n/** Whether the person uses the app now (`active`) or not for a while (`idle`). */\nexport const PRESENCES = [\"active\", \"idle\"] as const;\nexport type Presence = (typeof PRESENCES)[number];\n\n/** Longest status text kept, in characters (code points). */\nexport const STATUS_TEXT_MAX = 60;\n/** No input in the app for this long: the person is idle. */\nexport const STATUS_IDLE_AFTER_MS = 600_000;\n/** The sender says at most one frame per this; a change in between goes when it ends, the latest state only. */\nexport const STATUS_SEND_INTERVAL_MS = 5_000;\n/** The reader drops frames past this many per window: room above the sender's 12 a minute. */\nexport const STATUS_RATE_LIMIT = 15;\nexport const STATUS_RATE_WINDOW_MS = 60_000;\n\n/** A status a person set. Every field is optional; `until` is when it ends (Unix milliseconds). */\nexport interface PersonStatus { availability?: StatusAvailability; emoji?: string; text?: string; until?: number }\n/** What one side says of itself: presence only when it shares it, a status only when it set one. */\nexport interface StatusState { presence?: Presence; status?: PersonStatus }\n\n// Types, not interfaces: they are read back as plain frame records.\nexport type WireStatus = { a?: StatusAvailability; e?: string; m?: string; u?: number };\nexport type StatusFrame = { t: typeof STATUS_FRAME; p?: Presence; s?: WireStatus };\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst validUntil = (value: unknown): value is number => typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\nconst availabilityOf = (value: unknown): StatusAvailability =>\n (STATUS_AVAILABILITIES as readonly unknown[]).includes(value) ? value as StatusAvailability : \"available\";\nconst presenceOf = (value: unknown): Presence => (PRESENCES as readonly unknown[]).includes(value) ? value as Presence : \"active\";\n\n/** A status text as it may be shown: one line, no invisible characters, no link or markup, at most 60 characters. */\nexport function sanitizeStatusText(value: unknown): string | undefined {\n return plainStatusLine(value, STATUS_TEXT_MAX);\n}\n\n/** A status with each field checked; undefined when nothing is left of it. An unknown availability reads as available. */\nexport function personStatus(raw: { availability?: unknown; emoji?: unknown; text?: unknown; until?: unknown } | undefined): PersonStatus | undefined {\n if (!isObject(raw)) return undefined;\n const status: PersonStatus = {};\n if (raw.availability !== undefined) status.availability = availabilityOf(raw.availability);\n const emoji = reactionEmoji(raw.emoji);\n if (emoji) status.emoji = emoji;\n const text = sanitizeStatusText(raw.text);\n if (text) status.text = text;\n if (validUntil(raw.until)) status.until = raw.until;\n return Object.keys(status).length ? status : undefined;\n}\n\n/** The status while it lasts: undefined once its `until` is past by this clock. */\nexport function liveStatus(status: PersonStatus | undefined, now = Date.now()): PersonStatus | undefined {\n return status && (status.until === undefined || status.until > now) ? status : undefined;\n}\n\n/** A state with its fields checked. */\nexport function statusState(raw: StatusState): StatusState {\n const state: StatusState = {};\n if (raw.presence !== undefined) state.presence = presenceOf(raw.presence);\n const status = personStatus(raw.status);\n if (status) state.status = status;\n return state;\n}\n\nexport function statusFrame(state: StatusState): StatusFrame {\n const frame: StatusFrame = { t: STATUS_FRAME };\n const clean = statusState(state);\n if (clean.presence) frame.p = clean.presence;\n const status = clean.status;\n if (status) {\n const wire: WireStatus = {};\n if (status.availability) wire.a = status.availability;\n if (status.emoji) wire.e = status.emoji;\n if (status.text) wire.m = status.text;\n if (status.until !== undefined) wire.u = status.until;\n frame.s = wire;\n }\n return frame;\n}\n\n/**\n * The state a `paired-status` frame says, or null when it is malformed (then the reader keeps what it had): `s` not an\n * object, or `p` or `s.a` present and not a string. A field that does not hold (an emoji that is not one, a text with a\n * link, a bad `u`) is left out, not the frame.\n */\nexport function parseStatusFrame(frame: Record<string, unknown>): StatusState | null {\n if (frame?.t !== STATUS_FRAME) return null;\n if (frame.p !== undefined && typeof frame.p !== \"string\") return null;\n if (frame.s !== undefined && !isObject(frame.s)) return null;\n const s = frame.s as Record<string, unknown> | undefined;\n if (s?.a !== undefined && typeof s.a !== \"string\") return null;\n return statusState({\n ...(frame.p !== undefined ? { presence: frame.p as Presence } : {}),\n ...(s ? { status: { availability: s.a, emoji: s.e, text: s.m, until: s.u } as PersonStatus } : {}),\n });\n}\n\nconst sameStatus = (a?: PersonStatus, b?: PersonStatus) =>\n a?.availability === b?.availability && a?.emoji === b?.emoji && a?.text === b?.text && a?.until === b?.until;\n/** Two states say the same. */\nexport const sameStatusState = (a: StatusState, b: StatusState) => a.presence === b.presence && sameStatus(a.status, b.status);\n\n/**\n * This side's word: what it says, and when. One per chat. A new session owes the whole state (`reset`); a change owes\n * it again. Frames go at most one per `STATUS_SEND_INTERVAL_MS`, across sessions, so the reader's window always has room.\n */\nexport class StatusSender {\n private state: StatusState = {};\n private owed = true;\n private sentAt = -Infinity;\n\n constructor(private readonly now: () => number = () => Date.now()) {}\n\n /** What this side says now. */\n get current(): StatusState { return this.state; }\n\n /** This side's presence or status changed: owed again when it says something new. */\n set(state: StatusState): void {\n const clean = statusState(state);\n if (sameStatusState(clean, this.state)) return;\n this.state = clean;\n this.owed = true;\n }\n\n /**\n * On a session that agreed `status/1`: the frame to send now; or how long to wait before asking again (the interval\n * has not passed); or null when nothing is owed.\n */\n take(): { frame: StatusFrame } | { wait: number } | null {\n if (!this.owed) return null;\n const now = this.now(), wait = this.sentAt + STATUS_SEND_INTERVAL_MS - now;\n // A clock set back does not hold the frame: `now` before the last send says it at once.\n if (wait > 0 && now >= this.sentAt) return { wait };\n this.owed = false;\n this.sentAt = now;\n return { frame: statusFrame(this.state) };\n }\n\n /** The session ended: the next one is owed the whole state. */\n reset(): void { this.owed = true; }\n}\n\n/**\n * The contact's word, with a rate limit. Presence ends with the session (`endSession`); the status stays until a new\n * frame replaces it or its `until` passes (read through `peer`). `onChange` hears changes only.\n */\nexport class StatusReceiver {\n private state: StatusState = {};\n private recent: number[] = [];\n\n constructor(private readonly onChange: (state: StatusState) => void, private readonly now: () => number = () => Date.now()) {}\n\n /** What the contact says now, a status past its `until` left out. */\n get peer(): StatusState {\n const status = liveStatus(this.state.status, this.now());\n return { ...(this.state.presence ? { presence: this.state.presence } : {}), ...(status ? { status } : {}) };\n }\n\n /** A `paired-status` frame from the contact. False when it was dropped: malformed, or over the rate limit. */\n receive(frame: Record<string, unknown>): boolean {\n const now = this.now();\n this.recent = this.recent.filter(at => at <= now && now - at < STATUS_RATE_WINDOW_MS);\n if (this.recent.length >= STATUS_RATE_LIMIT) return false;\n this.recent.push(now);\n const state = parseStatusFrame(frame);\n if (!state) return false;\n this.set(state);\n return true;\n }\n\n /** The session ended: the contact is not online any more; its status stands. */\n endSession(): void {\n if (this.state.presence) this.set(this.state.status ? { status: this.state.status } : {});\n }\n\n private set(state: StatusState): void {\n if (sameStatusState(state, this.state)) return;\n this.state = state;\n this.onChange(this.peer);\n }\n}\n","import { fromBase64Url, toBase64Url } from \"./bytes\";\nimport { formatFileSize, sanitizeFileName, sanitizeMime, type FileInfo } from \"./files\";\nimport { pairedReplyAuthor, readReply, wireReply } from \"./replies\";\nimport { readForwarded } from \"./forwards\";\nimport { isChatAppId } from \"./pairedApps\";\nimport { parseVideoMeta } from \"./video\";\nimport { parseImageMeta } from \"./image\";\nimport { parseVoiceMeta } from \"./voice\";\n\n/**\n * files/3 (WISP 501, revision 0.3): files of any size in a chat, offered before they are sent, sent with\n * many chunks in flight, resumed from the last confirmed byte after a drop, a transport switch or a\n * restart, and checked against the sender's SHA-256 once stored.\n *\n * One `ChatFiles` per chat lives as long as the app does, across sessions: `attach` when a session that\n * agreed `files/3` is open, `detach` when it goes. Records (`FileTransferRecord`) are the state that\n * survives a restart; the host keeps them and hands them back with `restore`.\n *\n * Frames (authenticated JSON on the paired session):\n *\n * sender → receiver pf-offer {id,name,mime,size,ts,voice?,video?,image?,r?,fw?,app?,paused?} pf-data {id,offset,data}\n * pf-sum {id,size,digest} pf-abort {id}\n * receiver → sender pf-accept {id,offset} pf-wait {id,why} pf-got {id,offset} pf-done {id}\n * pf-refuse {id,why,room?}\n * both pf-room {max}\n *\n * The offer is repeated on every session until the transfer ends, so every answer is idempotent: the\n * receiver says where it stands (accept from an offset, wait, done, refuse) and the sender goes on from\n * there. Nothing but the offset a receiver confirms moves a sender forward. A receiver may say `pf-accept`\n * again at any time (nothing arrived for a while, or its person asked again): the sender goes on from that offset.\n * What a sender sends again that way is bounded (`FILE_LIMITS.resendBytes`, and the host's `resend`): past it the\n * sender ends the transfer.\n */\n\nexport const FILE_LIMITS = {\n /** Bytes in one `pf-data` frame: a frame stays far below the 60 KiB a session carries. */\n chunkBytes: 16 * 1024,\n /** Bytes a sender has sent and not seen confirmed, at most: throughput is this per round trip. */\n windowBytes: 1024 * 1024,\n /**\n * Bytes all of a chat's files have sent and not seen confirmed, together, at most. Three files' windows at once were 3 MiB, and\n * as base64 text past what a session's receive queue holds (`SESSION_RECEIVE_PENDING`, 3.75 MiB).\n */\n chatWindowBytes: 2 * 1024 * 1024,\n /**\n * What a chat's files have in flight is sized by the path (`ChatFiles.paced`), down to this. A fixed 1 MiB on a 5 Mbit/s\n * uplink queued 1.8 s ahead of every text, ring and hang-up of the sender's in that chat, and of its voice in a call.\n */\n minWindowBytes: 64 * 1024,\n /** How much longer than the shortest round trip seen a confirm may take, by the queue the files keep on the path. */\n queueMs: 50,\n /**\n * On a long path, the queue a confirm may show is this share of the shortest round trip, when that is more than `queueMs`.\n * A relay's round trip wavers by more than 50 ms on its own: read as the files' queue, it held their window at its\n * floor, 64 KiB per round trip (about 0.1 MiB/s at 600 ms), however fast the path.\n */\n queueOfBase: 0.5,\n /**\n * A shortest round trip no confirm has come close to for this long is measured again, with the queue drained\n * (`ChatFiles.paced`). A path that got longer mid-session (another route, a relay) read as a queue for good before, and\n * held the window at its floor: 0.5 MiB/s where the same path from the start gave 8 MiB/s.\n */\n baseProbeMs: 10_000,\n /**\n * The window is sized by rate as well as by delay (`FilePace.tried`): a window up to this much larger is tried, and\n * kept when it made no queue. On a path whose round trip wavers on its own (a radio's scheduling: 5G, Wi-Fi), the\n * delay rule reads the waver as the files' queue and held the window at its floor, 0.25 MiB/s on a 50 Mbit/s link,\n * where a larger window carried ten times as much with no longer round trip.\n */\n trialGain: 2,\n /**\n * A tried window is kept when its round trip grew by less than this share of the queue it would make on a full link\n * (what it adds, at the rate the path carried). A full link's grows by all of it; a path that only wavers, by none.\n */\n trialPaid: 0.5,\n /**\n * What a trial may add, as queue on a full link at the rate the path carries: a chunk at least, or no trial. A 1 Mbit/s\n * uplink never tries (a chunk is 131 ms there), so its texts keep the delay rule's queue.\n */\n trialQueueMs: 100,\n /**\n * Trials go only where the round trip wavers: its confirms' round trips within a round trip spread by this much\n * (their standard deviation). A full link's own queue keeps them close (493-523 ms behind a relay on 5 Mbit/s); a\n * radio's scheduling spreads them (150-450 ms on 5G). So a slow uplink's texts never wait behind a trial.\n */\n waverMs: 25,\n /** Round trips between two trials that were not kept, at first (it doubles with each, up to 8 times). */\n trialEvery: 4,\n /** A round trip whose rate counts lasts until this many windows were confirmed: one is a coin flip on a wavering path. */\n trialWindows: 4,\n /** A receiver asks its person before taking a file larger than this. */\n askAboveBytes: 25 * 1024 * 1024,\n /** Files taken without asking, per contact, while stored. Past it, every file is asked about. */\n autoAcceptBytesPerPeer: 500 * 1024 * 1024,\n /** Offers from one contact waiting for an answer here. */\n maxWaitingOffers: 16,\n /**\n * Files from one contact not finished here, whatever their state (asked about, taken and waiting their turn, paused,\n * arriving). Only bytes were counted before: offers of 0 bytes were each taken, and 2,500 of them were 2,500\n * messages and records waiting for good.\n */\n maxUnfinishedIncoming: 256,\n /** Files one contact sends at once; accepted ones beyond wait their turn. */\n maxActiveIncoming: 3,\n /** An offer nobody answered ends after this long. */\n offerTtlMs: 7 * 24 * 60 * 60 * 1000,\n /**\n * No answer while something is outstanding: the sender offers again, which puts both sides back in step. Nothing\n * arriving for a file under way: the receiver says again where it stands.\n */\n idleMs: 30_000,\n /**\n * A transfer that has not moved for this long (or not since the app started) offers its person \"Send again\" or\n * \"Ask again\". Longer than `idleMs`, so what happens on its own has its turn first.\n */\n stallMs: 60_000,\n /** A receiver makes what it stored durable, and records the point to resume from, this often. */\n checkpointBytes: 8 * 1024 * 1024,\n /**\n * A receiver confirms at least this often while writing, and the file's last bytes at once. Its writes are buffered\n * and done at once, so confirming whenever they were all done too was confirming nearly every chunk: 6,400 confirms for\n * 100 MiB, each a native call and a progress update on both sides. A host that batches them (`batchConfirms`) does not.\n */\n ackEveryBytes: 128 * 1024,\n /**\n * Batched (`ChatFilesHost.batchConfirms`), bytes stored and not confirmed are confirmed this long after the first of\n * them was stored, at most. What a sender has in flight may be no more than `ackEveryBytes` (a window at its floor, one\n * chunk while the path is measured), and bytes waiting here for a confirm are bytes it cannot send: on a slow or\n * wavering path a confirm comes about every this long, as fast as the window needs. A round trip it measures is up to\n * this much longer, well inside the queue it allows (`queueMs`).\n */\n ackWaitMs: 10,\n /** A sender reads its file this much at a time. */\n readBytes: 1024 * 1024,\n /** The session refused a data frame (its send budget was full): the sender looks again after this long. */\n sendRetryMs: 250,\n /**\n * What a sender sends of one file beyond its size (parts sent again after a drop, a restart of the receiver, or a\n * `pf-accept` from an earlier offset): twice the file's size and this much. Past it the sender ends the transfer (WISP 501 § Resume).\n */\n resendBytes: 256 * 1024 * 1024,\n} as const;\n\nconst ID = /^[A-Za-z0-9_-]{8,64}$/;\nconst DIGEST = /^[A-Za-z0-9_-]{43}$/;\nconst DATA = /^[A-Za-z0-9_-]+$/;\n\nexport const FILE_FRAMES = new Set([\"pf-offer\", \"pf-accept\", \"pf-wait\", \"pf-data\", \"pf-got\", \"pf-sum\", \"pf-done\", \"pf-refuse\", \"pf-abort\", \"pf-room\"]);\n\nexport type TransferState =\n /** Out: waiting for a session to offer it on. In: accepted, waiting for its turn or for the sender. */\n | \"queued\"\n /** Out: offered on this session, no answer yet. */\n | \"offered\"\n /** Out: the receiver's person has not decided (or it waits its turn there, `waitingFor: \"busy\"`). In: this person has not decided. */\n | \"asking\"\n | \"active\"\n | \"paused\"\n /** Every byte confirmed; the receiver is checking the digest. */\n | \"verifying\"\n | \"done\"\n | \"failed\"\n | \"declined\"\n | \"cancelled\";\n\nexport interface FileTransferRecord {\n /** The sender's id, on the wire. */\n id: string;\n direction: \"in\" | \"out\";\n file: FileInfo;\n state: TransferState;\n /** Out: bytes the receiver confirmed. In: bytes stored durably, where a restart resumes. */\n confirmed: number;\n /** SHA-256 of the file, base64url: the sender's own, or the one it announced. */\n digest?: string;\n pausedBy?: \"me\" | \"peer\";\n /** Out, `asking`: why the receiver waits. */\n waitingFor?: \"consent\" | \"busy\";\n error?: string;\n /** When the transfer began (the offer), for its time to live. */\n since: number;\n /** In: the person accepted it (not taken on its own). */\n consented?: boolean;\n /**\n * In, `cancelled`: the sender stopped it (`pf-abort`), not this person. Offered again (the sender could not read its\n * file and sends it again), it is taken again from the start.\n */\n abortedBySender?: boolean;\n /**\n * In: taken, by the person or within the app's limits. An offer that expired unanswered never was, so offered again\n * it is refused, never taken without asking. Out: the receiver took it (`pf-accept`), so the offer's week no longer\n * ends it (`sweep`): a file paused or cut off for more than a week failed \"Not delivered in time\" when it went on,\n * and its part there was deleted.\n */\n agreed?: boolean;\n}\n\nconst FINAL: ReadonlySet<TransferState> = new Set([\"done\", \"failed\", \"declined\", \"cancelled\"]);\nexport const transferEnded = (record: FileTransferRecord): boolean => FINAL.has(record.state);\n\n/**\n * Whether a file sent from here arrived whole (the receiver confirmed every byte, and may be checking it): too late\n * for its person to cancel. The receiver's check comes before a `pf-abort` behind it, so it would keep the file while\n * the sender said it was cancelled. Not once the receiver asks about it again (`asking`), nor paused here.\n */\nexport function sentWhole(record: FileTransferRecord): boolean {\n if (record.direction !== \"out\" || transferEnded(record)) return false;\n return record.state === \"verifying\" || (record.file.size > 0 && record.confirmed === record.file.size && record.state !== \"asking\" && record.state !== \"paused\");\n}\n\n/**\n * Whether an unfinished transfer is stuck, so its person is offered to push it: \"Send again\" (sending) or \"Ask again\"\n * (receiving). `movedAt` is when its bytes last moved, `restored` that it has not moved since the app started. What\n * waits for a person (an answer, a pause) is not stuck, and a failed one has its own \"Retry\".\n */\nexport function transferStalled(record: FileTransferRecord, movedAt: number, restored: boolean, now: number): boolean {\n if (transferEnded(record) || record.state === \"asking\" || record.state === \"paused\") return false;\n if (record.direction === \"in\" && record.state === \"verifying\") return false;\n return restored || now - movedAt >= FILE_LIMITS.stallMs;\n}\n\n/** A file being sent, read in ranges. */\nexport interface OutgoingSource {\n read(offset: number, length: number): Promise<Uint8Array>;\n /** SHA-256 of the whole file, base64url. */\n digest(): Promise<string>;\n}\n\n/** Where a file being received is written, in order, from `offset`. */\nexport interface IncomingTarget {\n /** Bytes already stored when it was opened: where this transfer resumes. */\n readonly offset: number;\n append(bytes: Uint8Array): Promise<void>;\n /** What was appended is durable. */\n flush(): Promise<void>;\n /** Checks what was stored against the sender's digest, and keeps the file when it matches. */\n verify(digest: string): Promise<boolean>;\n /** Removes what was stored. */\n discard(): Promise<void>;\n}\n\nexport type OfferDecision = \"accept\" | \"ask\" | { refuse: RefuseReason; room?: number };\nexport type RefuseReason = \"declined\" | \"no-room\" | \"too-many\" | \"damaged\" | \"cancelled\" | \"expired\" | \"invalid\";\n\nexport interface ChatFilesHost {\n /** Sends a frame on the open session; false when there is none. */\n send(frame: Record<string, unknown>): boolean;\n /**\n * Sends a file's bytes at `offset` in the form the open session agreed (WISP 501 § files/4): a binary message, or\n * the `pf-data` frame; false when there is no session or it has no room. A host without it gets `pf-data` through `send`.\n */\n sendData?(id: string, offset: number, data: Uint8Array): boolean;\n /**\n * A new offer from the contact: take it, ask the person, or refuse it. `again`: a file taken here without asking\n * that ended (failed, or stopped by the sender) and is offered again; it counts against the same limits as a new one.\n */\n decide(file: FileInfo, again?: boolean): Promise<OfferDecision>;\n openTarget(record: FileTransferRecord): Promise<IncomingTarget>;\n openSource(record: FileTransferRecord): Promise<OutgoingSource>;\n /**\n * Something changed: keep it and show it. `transferred` is what moved so far (confirmed by the receiver when\n * sending, stored when receiving); `progress` says only that moved, so keeping it can wait.\n */\n changed(record: FileTransferRecord, transferred: number, progress: boolean): void;\n /**\n * Resolves once what `changed` was given so far is kept, so a restart finds it. A receiver says a file is done\n * (`pf-done`) only then: said before, a restart found it unfinished while its sender had it done, and asking for it\n * again got no answer. Absent: `changed` keeps it at once.\n */\n kept?(): Promise<void>;\n /** Bytes a file may still take here, or null when the platform does not say. */\n room?(): Promise<number | null>;\n /**\n * Resolves once the session can take another data frame without crowding out everything else on it (nothing when it\n * can now: a large file does not make a promise per frame). Channels with a\n * small send budget (native, iroh) refuse frames past it; sending into a full one again at once spun a loop of\n * promises that never let the budget drain, and froze the app.\n */\n writable?(): Promise<void> | undefined;\n /**\n * Asked before each data frame once a transfer has sent more than its file's size (`sent` is every byte of data sent\n * for it so far, parts sent again included): false ends the transfer. A host with a budget for what it sends says so here.\n */\n resend?(record: FileTransferRecord, sent: number): boolean;\n now?(): number;\n /**\n * Receiving, a confirm goes every `FILE_LIMITS.ackEveryBytes` stored, or `FILE_LIMITS.ackWaitMs` after the first\n * bytes it would confirm, not whenever the writes are all done (nearly every chunk). Not for a group's edges: on a\n * shared uplink an edge's window goes down to a chunk (`FileUplink.floor`), far less than a confirm's worth.\n */\n batchConfirms?: boolean;\n /**\n * The uplink this chat's files share with others that leave the device by it (`FileUplink`): a group's edges, each\n * a `ChatFiles` of its own, serving one file to several members at once. Absent: the uplink is this chat's alone.\n */\n uplink?: FileUplink;\n}\n\n/** What a `FileUplink` asks of the `ChatFiles` that share it. */\ninterface UplinkMember {\n /** Its files are sending: bytes in flight, or held for the window. */\n sending(): boolean;\n /** The shortest round trip its files saw on its own session. */\n baseRtt(): number;\n}\n\n/**\n * The uplink several chats' files leave the device by. Each chat paces its files by its own path (`FilePace`), down to\n * a floor of `FILE_LIMITS.minWindowBytes`; on one uplink, that floor is shared out among the chats sending at once.\n * Each with a floor of its own, a member serving a file to three members on a 1 Mbit/s uplink kept 192 KiB in flight,\n * and everything else it sent (texts, a ring, a call's voice) waited 1-2 s behind them, up to 5.8 s (agents#1569). A\n * chat whose receiver barely confirms holds only its share, never the others' bytes. Each chat also reads the queue\n * against the lowest round trip of the uplink's chats, not its own alone (`lowestBase`).\n */\nexport class FileUplink {\n private readonly members = new Set<UplinkMember>();\n\n join(member: UplinkMember): void { this.members.add(member); }\n leave(member: UplinkMember): void { this.members.delete(member); }\n\n /**\n * The floor of one chat's window: its share of `minWindowBytes` among the chats sending, in whole chunks, a chunk at\n * least (a window sends chunks while what is in flight is under it: 21 KiB would let two go).\n */\n floor(): number {\n let sending = 0;\n for (const member of this.members) if (member.sending()) sending++;\n const share = FILE_LIMITS.minWindowBytes / Math.max(1, sending);\n return Math.max(FILE_LIMITS.chunkBytes, Math.floor(share / FILE_LIMITS.chunkBytes) * FILE_LIMITS.chunkBytes);\n }\n\n /**\n * The shortest round trip any chat on the uplink saw: its path with the least queue. Each chat's own counts the\n * others' queue on the shared uplink as its path (428-637 ms read on a 1-10 ms path), and so never sees one.\n */\n lowestBase(): number {\n let lowest = Infinity;\n for (const member of this.members) lowest = Math.min(lowest, member.baseRtt());\n return lowest;\n }\n}\n\n/** How much one chat's files may have in flight on its session, sized by the path (delay-based, as LEDBAT: `paced`). */\nclass FilePace {\n /** Bytes the files may have in flight together: sized by the path, from the confirms (`paced`). */\n window: number = FILE_LIMITS.minWindowBytes;\n /** The shortest round trip of a chunk to its confirm: the path without a queue. */\n private baseRtt = Infinity;\n /** When a confirm last came close to `baseRtt`, or a probe measured it. */\n private baseAt = 0;\n /** The path's own round trip is being measured: one chunk in flight from `since`, until one sent then is confirmed. */\n private probe?: { since: number; window: number };\n /** A confirm has sized the window on this path. */\n private sized = false;\n /** Bytes of the chat's files confirmed on this session so far. */\n delivered = 0;\n /**\n * The round trip under way (`tried`): from `start` until a chunk sent since is confirmed, and `trialWindows` windows\n * were. `delivered` then, the round trips of its confirms added up, and whether little was in flight meanwhile\n * (`limited`: it says nothing of the window).\n */\n private round?: { start: number; delivered: number; rtts: number; squares: number; count: number; limited: boolean };\n /** The last round trip's: what the path carried, bytes per ms, its confirms' mean round trip and their spread. */\n private last = { rate: 0, rtt: 0, spread: 0 };\n /** A window a trial showed the path takes with no queue: the delay rule does not shrink the window below it. */\n private held = 0;\n /** A larger window being tried, `from` the one before: it shows in its second round trip (the first confirms what went before). */\n private trial?: { from: number; window: number; before: { rate: number; rtt: number; spread: number }; rounds: number };\n /** Round trips until the next trial, and between two trials while they are not kept (doubles with each, up to a limit). */\n private wait: number = FILE_LIMITS.trialEvery;\n private spacing: number = FILE_LIMITS.trialEvery;\n\n /** Another path (a session of its own opened): what was learnt of the old one goes. */\n reset(): void {\n this.window = FILE_LIMITS.minWindowBytes;\n this.baseRtt = Infinity;\n this.baseAt = 0;\n this.probe = undefined;\n this.sized = false;\n this.last = { rate: 0, rtt: 0, spread: 0 };\n this.held = 0;\n this.round = this.trial = undefined;\n this.wait = this.spacing = FILE_LIMITS.trialEvery;\n }\n\n /** The shortest round trip seen on this path. */\n get base(): number { return this.baseRtt; }\n\n /**\n * What may be in flight now: one chunk while the path's own round trip is measured, else the window; before any\n * confirm sized it, no more than `floor` (the chat's share of an uplink it shares: three edges starting at once each\n * sent their whole 64 KiB, 1.5 s of queue at 1 Mbit/s).\n */\n limit(floor: number): number { return this.probe ? FILE_LIMITS.chunkBytes : this.sized ? this.window : Math.min(this.window, floor); }\n\n /**\n * A confirm came for a chunk sent at `sentAt` with `flight` bytes in flight then: the window becomes what keeps the path\n * busy with no more than `FILE_LIMITS.queueMs` of queue on it, or half its round trip on a long path\n * (`FILE_LIMITS.queueOfBase`) (delay-based, as LEDBAT). Throughput is about\n * flight / rtt, so flight × (base + queueMs) / rtt: it grows while confirms come about as fast as they can, and shrinks\n * when they slow down because the files queue on a slow uplink, ahead of everything else the sender says there.\n * The base is measured again once no confirm has come close to it for `FILE_LIMITS.baseProbeMs`: with one chunk in\n * flight, so the queue drains first and a slow link's own queue never passes for a longer path. `floor`: the least\n * the window is, `minWindowBytes` or the chat's share of an uplink it shares (`FileUplink.floor`). A round trip that\n * wavers on its own reads as queue here: the window is sized by rate as well (`tried`).\n */\n paced(sentAt: number, flight: number, now: number, floor: number = FILE_LIMITS.minWindowBytes, lowest = Infinity): void {\n const rtt = Math.max(1, now - sentAt);\n this.sized = true;\n if (this.probe) {\n // Sent before the probe: it waited behind the queue the probe lets drain.\n if (sentAt < this.probe.since) return;\n this.baseRtt = rtt;\n this.baseAt = now;\n this.window = this.probe.window;\n this.probe = undefined;\n return;\n }\n if (rtt - this.baseRtt < FILE_LIMITS.queueMs / 2) this.baseAt = now;\n this.baseRtt = Math.min(this.baseRtt, rtt);\n if (now - this.baseAt > FILE_LIMITS.baseProbeMs) {\n // One chunk in flight carries nothing to compare: the round trips start again after it, and a trial waits for the\n // queue it drained to fill again (that spreads the round trips as a waver does).\n this.probe = { since: now, window: this.window };\n this.round = this.trial = undefined;\n this.wait = Math.max(this.wait, FILE_LIMITS.trialEvery);\n return;\n }\n // No queue to speak of yet: twice as much per round trip at least, as a long fast path needs many to fill. On a\n // shared uplink, the queue is read against the lowest round trip any of its chats saw.\n const base = Math.min(this.baseRtt, lowest);\n const queueMs = Math.max(FILE_LIMITS.queueMs, base * FILE_LIMITS.queueOfBase);\n const fits = Math.max((flight * (base + queueMs)) / rtt, rtt - base < queueMs / 2 ? 2 * flight : 0);\n // Little was in flight (a file starting or ending): that says nothing about a larger window being too large.\n const limited = flight < this.window / 2;\n const delayed = limited ? Math.max(this.window, fits) : fits;\n this.tried(sentAt, rtt, now, limited);\n this.window = Math.min(FILE_LIMITS.chatWindowBytes, Math.max(floor, Math.round(this.trial?.window ?? Math.max(delayed, this.held))));\n }\n\n /**\n * Sizes the window by rate: what the delay rule holds back may be a waver of the path, not a queue. After\n * `trialEvery` round trips a larger window is tried. On a full link the bytes it adds wait in its queue, and the\n * round trip grows by them at the rate the path carries; where the path only wavers, the round trip stays and the\n * larger window carries more. So a trial whose round trip grew by less than `trialPaid` of that queue is kept\n * (`held`) and a larger one tried at once; else what was kept goes down a step, and the next trial waits twice as\n * long. A trial adds `trialQueueMs` of queue at most, meanwhile, and goes only where the round trip wavers (`waverMs`).\n */\n private tried(sentAt: number, rtt: number, now: number, limited: boolean): void {\n const round = this.round;\n if (round) {\n round.rtts += rtt;\n round.squares += rtt * rtt;\n round.count++;\n if (limited) round.limited = true;\n }\n // A trial's first round trip only confirms what went before it: it lasts no longer than that.\n const windows = this.trial?.rounds === 0 ? 0 : FILE_LIMITS.trialWindows;\n if (round && (sentAt < round.start || this.delivered - round.delivered < windows * this.window)) return;\n this.round = { start: now, delivered: this.delivered, rtts: 0, squares: 0, count: 0, limited: false };\n if (!round) return;\n if (round.limited) { this.trial = undefined; return; }\n const trial = this.trial;\n if (trial && ++trial.rounds < 2) return;\n const mean = round.rtts / round.count;\n const last = { rate: (this.delivered - round.delivered) / Math.max(1, now - round.start), rtt: mean, spread: Math.sqrt(Math.max(0, round.squares / round.count - mean * mean)) };\n if (trial) {\n const queued = (trial.window - trial.from) / trial.before.rate;\n const paid = last.rtt - trial.before.rtt < queued * FILE_LIMITS.trialPaid;\n this.held = paid ? trial.window : Math.min(this.held, trial.from) * (trial.from / trial.window);\n this.spacing = paid ? FILE_LIMITS.trialEvery : Math.min(FILE_LIMITS.trialEvery * 8, this.spacing * 2);\n this.wait = paid ? 0 : this.spacing;\n this.trial = undefined;\n }\n this.last = last;\n if (this.wait > 0) { this.wait--; return; }\n if (last.spread < FILE_LIMITS.waverMs) return;\n // Larger than the window it was measured with. On a full link what it adds is queue at that rate, ahead of the\n // sender's texts: `trialQueueMs` of it at most, and a chunk at least (windows go by chunks), or no trial.\n const step = Math.min(this.window * (FILE_LIMITS.trialGain - 1), last.rate * FILE_LIMITS.trialQueueMs);\n const window = Math.round(this.window + step);\n if (step >= FILE_LIMITS.chunkBytes && window <= FILE_LIMITS.chatWindowBytes) this.trial = { from: this.window, window, before: last, rounds: 0 };\n }\n}\n\ninterface Outgoing {\n source?: Promise<OutgoingSource>;\n next: number;\n /** Bytes of data sent for it since the app started (or since its person sent it again), parts sent again included. */\n sent: number;\n /** Bumped whenever sending stops or restarts: a read that finishes late sends nothing. */\n generation: number;\n /**\n * The generation a pump runs for. A pump still waiting on a session that went (a send that never drains) belongs to\n * an older generation, and does not keep the next session's pump from starting.\n */\n pumping?: number;\n /** The file read ahead (a MiB), while it sends: one paused or cut off holds none (32 paused held 32 MiB). */\n block?: { start: number; bytes: Uint8Array };\n timer?: ReturnType<typeof setTimeout>;\n /** A pump that paused on a refused frame starts again. */\n wake?: ReturnType<typeof setTimeout>;\n /** Chunks sent and not confirmed yet, in order: where each ended, when it went, and the chat's bytes in flight then. */\n sends: { end: number; at: number; flight: number; generation: number }[];\n}\n\ninterface Incoming {\n target?: Promise<IncomingTarget>;\n /** Nothing arrived for a while: the receiver says again where it stands. */\n timer?: ReturnType<typeof setTimeout>;\n /** When data last came (the timer is not moved for every chunk). */\n heardAt?: number;\n /** What was stored and is not confirmed yet is confirmed when it fires (`FILE_LIMITS.ackWaitMs`). */\n ackTimer?: ReturnType<typeof setTimeout>;\n /** Bytes taken in order (some may still be on their way to storage). */\n written: number;\n stored: number;\n acked: number;\n checkpointed: number;\n gapAt?: number;\n writing: Promise<void>;\n verifying?: boolean;\n /** Where it is written is being opened, before it is accepted: it holds one of the turns already. */\n starting?: boolean;\n /** What was stored is being removed: nothing more is written. */\n dropped?: boolean;\n}\n\ninterface Entry {\n record: FileTransferRecord;\n out?: Outgoing;\n in?: Incoming;\n}\n\nconst key = (direction: \"in\" | \"out\", id: string) => `${direction}:${id}`;\nconst isInt = (value: unknown, max = Number.MAX_SAFE_INTEGER): value is number => typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 && value <= max;\n\n/**\n * files/4 (WISP 501 § files/4): a chunk as one binary message of the session, in place of the base64url text of a\n * `pf-data` frame, which is a third more than the bytes it carries:\n *\n * kind 0x04 (1) | id length (1) | id (ASCII) | offset (8, big endian) | data (1 to `FILE_LIMITS.chunkBytes`)\n */\nexport const FILE_DATA_KIND = 0x04;\nconst FILE_DATA_OFFSET_BYTES = 8;\n\n/** The binary message for the bytes of file `id` at `offset`. Throws on what no receiver would take. */\nexport function encodeFileData(id: string, offset: number, data: Uint8Array): Uint8Array {\n if (!ID.test(id) || !isInt(offset) || !data.length || data.length > FILE_LIMITS.chunkBytes) throw new Error(\"Invalid file data\");\n const head = 2 + id.length;\n const out = new Uint8Array(head + FILE_DATA_OFFSET_BYTES + data.length);\n out[0] = FILE_DATA_KIND;\n out[1] = id.length;\n for (let i = 0; i < id.length; i++) out[2 + i] = id.charCodeAt(i);\n const view = new DataView(out.buffer);\n view.setUint32(head, Math.floor(offset / 2 ** 32));\n view.setUint32(head + 4, offset % 2 ** 32);\n out.set(data, head + FILE_DATA_OFFSET_BYTES);\n return out;\n}\n\n/** What a binary message from the contact says, or null when it is not a well-formed file data message. `data` is a view of `message`. */\nexport function decodeFileData(message: Uint8Array): { id: string; offset: number; data: Uint8Array } | null {\n if (message.length < 2 || message[0] !== FILE_DATA_KIND) return null;\n const head = 2 + message[1], body = head + FILE_DATA_OFFSET_BYTES;\n if (message.length <= body || message.length - body > FILE_LIMITS.chunkBytes) return null;\n const id = String.fromCharCode(...message.subarray(2, head));\n if (!ID.test(id)) return null;\n const view = new DataView(message.buffer, message.byteOffset, message.byteLength);\n const high = view.getUint32(head);\n // Past 2^53 - 1 an offset is no longer a whole number here.\n if (high > 0x1fffff) return null;\n return { id, offset: high * 2 ** 32 + view.getUint32(head + 4), data: message.subarray(body) };\n}\n\n/**\n * Why a received file could not be stored, as its record says it. A storage with no room left is told by the error's\n * name, `QuotaExceededError` (IndexedDB's, the OPFS worker's, the CLI's), never by its words: each storage words it\n * its own way, and Chromium's own has no message at all. The app reads that name as \"no room here\" (errorText.ts).\n */\nfunction storeFailure(error: unknown): string {\n const message = (error instanceof Error ? error.message : String(error)).trim();\n const quota = (error as { name?: unknown } | null)?.name === \"QuotaExceededError\" && !message.startsWith(\"QuotaExceededError\");\n return `Could not store the file: ${quota ? `QuotaExceededError${message ? `: ${message}` : \"\"}` : message}`;\n}\n\n/** What a refusal means to the sender's person. */\nexport function refusalText(why: string, room?: number): { state: TransferState; error: string } {\n switch (why) {\n case \"declined\": return { state: \"declined\", error: \"Declined by your contact\" };\n case \"cancelled\": return { state: \"cancelled\", error: \"Cancelled by your contact\" };\n case \"no-room\": return { state: \"failed\", error: room !== undefined ? `Not enough space on your contact's device (${formatFileSize(room)} free)` : \"Not enough space on your contact's device\" };\n case \"too-many\": return { state: \"failed\", error: \"Your contact has too many files waiting. Try again later.\" };\n case \"damaged\": return { state: \"failed\", error: \"The file arrived damaged and was deleted. Send it again.\" };\n case \"expired\": return { state: \"failed\", error: \"Not accepted in time\" };\n default: return { state: \"failed\", error: \"Your contact could not take this file\" };\n }\n}\n\nexport class ChatFiles {\n private readonly entries = new Map<string, Entry>();\n /** Files sending that may have bytes not confirmed yet: what `inFlight` adds up (the rest are left out as it goes). */\n private readonly moving = new Set<Entry>();\n /** Files that stopped sending for the chat's window alone: they go on once another's bytes are confirmed. */\n private readonly held = new Set<Entry>();\n /**\n * The entries not ended (`track`): what is still to come or under way is read from these, not from every file the\n * chat ever had, which it keeps for good. An offer read all of them, in every chat, at 100,000 files about 10 ms each.\n */\n private readonly unended = new Set<Entry>();\n /**\n * Files this side cancelled while no session carried the cancel (`pf-abort`), said on the next one. The session also\n * goes for a moment when a move swaps it (its capabilities are agreed again): unsaid, the receiver showed the file\n * moving, its bytes kept, until its idle nudge asked 30 s later.\n */\n private readonly unsaid = new Set<string>();\n private attached = false;\n private peerRoomValue: number | null = null;\n /** What the chat's files may have in flight, sized by the path. */\n private readonly pace = new FilePace();\n /**\n * What the chat's files had in flight just before the last confirm. A receiver confirms many chunks at once\n * (`ackEveryBytes`), and the chunks sent for them go with that much in flight, the window: counted one by one, the\n * first went with the window less a confirm, and read as a path carrying that little, it shrank the window and ended\n * every trial of a larger one (a fifth of the rate on a wavering path). Confirmed chunk by chunk, it is what each sends with.\n */\n private refill = 0;\n\n constructor(private readonly host: ChatFilesHost) {}\n\n /** The floor of this chat's window: all of `minWindowBytes`, or its share of an uplink it shares (`FileUplink`). */\n private floor(): number { return this.host.uplink?.floor() ?? FILE_LIMITS.minWindowBytes; }\n\n /** Its files are sending: bytes in flight, or held for the window (`FileUplink`). */\n sending(): boolean { return this.attached && (this.inFlight() > 0 || this.held.size > 0); }\n\n /** The shortest round trip this chat's files saw on its session (`FileUplink.lowestBase`). */\n baseRtt(): number { return this.pace.base; }\n\n private now(): number { return this.host.now?.() ?? Date.now(); }\n\n /** Records kept from before a restart. Nothing is sent until `attach`. */\n restore(records: FileTransferRecord[]): void {\n for (const record of records) {\n const entry: Entry = { record: { ...record } };\n if (record.direction === \"out\") entry.out = { next: record.confirmed, sent: 0, generation: 0, sends: [] };\n else entry.in = { written: record.confirmed, stored: record.confirmed, acked: record.confirmed, checkpointed: record.confirmed, writing: Promise.resolve() };\n const replaced = this.entries.get(key(record.direction, record.id));\n if (replaced) this.unended.delete(replaced);\n this.entries.set(key(record.direction, record.id), entry);\n this.track(entry);\n }\n }\n\n get live(): boolean { return this.attached; }\n /** What the contact said it can take, on this session. */\n get peerRoom(): number | null { return this.attached ? this.peerRoomValue : null; }\n\n records(): FileTransferRecord[] { return [...this.entries.values()].map((e) => ({ ...e.record })); }\n /** Bytes still to come of the files taken here, not ended (one still asked about is not taken yet). */\n stillToCome(): number {\n let due = 0;\n for (const { record } of this.unended) if (record.direction === \"in\" && record.state !== \"asking\" && !transferEnded(record)) due += Math.max(0, record.file.size - record.confirmed);\n return due;\n }\n /** A transfer under way: offered, moving, or being checked. */\n underWay(): boolean {\n for (const { record } of this.unended) if (record.state === \"offered\" || record.state === \"active\" || record.state === \"verifying\") return true;\n return false;\n }\n /** Bytes of the files received here that were taken without asking and are kept (or on their way). */\n takenUnasked(): number {\n let taken = 0;\n for (const { record } of this.entries.values()) {\n if (record.direction === \"in\" && !record.consented && record.state !== \"asking\" && record.state !== \"failed\" && record.state !== \"declined\" && record.state !== \"cancelled\") taken += record.file.size;\n }\n return taken;\n }\n get(direction: \"in\" | \"out\", id: string): FileTransferRecord | undefined {\n const record = this.entries.get(key(direction, id))?.record;\n return record && { ...record };\n }\n /** Bytes moved so far: confirmed by the receiver (sending), stored (receiving). */\n transferred(direction: \"in\" | \"out\", id: string): number {\n const entry = this.entries.get(key(direction, id));\n return entry ? this.moved(entry) : 0;\n }\n /** Bytes of data sent for a file so far, parts sent again included: what sending it cost, whatever the receiver confirmed. */\n sent(id: string): number {\n return this.entries.get(key(\"out\", id))?.out?.sent ?? 0;\n }\n private moved(entry: Entry): number {\n return entry.in && !transferEnded(entry.record) ? Math.max(entry.in.stored, entry.record.confirmed) : entry.record.confirmed;\n }\n\n private changed(entry: Entry, progress = false): void {\n this.track(entry);\n this.host.changed({ ...entry.record }, this.moved(entry), progress);\n }\n\n /**\n * Keeps `unended` to the entries of this chat not ended. Each change of a record's state is reported (`changed`),\n * so that is where a file that ended leaves it, and one taken or sent again comes back.\n */\n private track(entry: Entry): void {\n if (!transferEnded(entry.record) && this.entries.get(key(entry.record.direction, entry.record.id)) === entry) this.unended.add(entry);\n else this.unended.delete(entry);\n }\n\n private send(frame: Record<string, unknown>): boolean {\n return this.attached && this.host.send(frame);\n }\n\n private sendData(id: string, offset: number, data: Uint8Array): boolean {\n if (!this.host.sendData) return this.send({ t: \"pf-data\", id, offset, data: toBase64Url(data) });\n return this.attached && this.host.sendData(id, offset, data);\n }\n\n /** A session that agreed files/3 is open: say what fits here, then offer again what is not finished. */\n attach(): void {\n this.attached = true;\n this.peerRoomValue = null;\n // Another session may be another path.\n this.pace.reset();\n this.refill = 0;\n this.host.uplink?.join(this);\n void this.sayRoom();\n for (const id of this.unsaid) if (this.send({ t: \"pf-abort\", id })) this.unsaid.delete(id);\n this.sweep();\n for (const entry of this.entries.values()) {\n if (transferEnded(entry.record)) continue;\n if (entry.record.direction === \"out\") this.announce(entry);\n else if (entry.record.state === \"queued\") this.startIncoming(entry);\n // The sender offers again on its own; one that does not (an older app, one stuck) is asked.\n else if (entry.record.state === \"active\") this.armNudge(entry);\n // Paused there: a sender that cancelled it meanwhile no longer offers it, and asked, ends it (`pf-abort`). One\n // that still has it paused answers with its paused offer, and nothing moves.\n else if (entry.record.state === \"paused\" && entry.record.pausedBy === \"peer\") this.send({ t: \"pf-accept\", id: entry.record.id, offset: entry.in!.written });\n // Still asked about here: a sender that cancelled, deleted or let it expire meanwhile no longer offers it, and asked,\n // ends it (`pf-abort`), so Accept is not shown for a file that will never come. One that still offers it waits.\n else if (entry.record.state === \"asking\") this.send({ t: \"pf-wait\", id: entry.record.id, why: \"consent\" });\n }\n }\n\n /** The session went: nothing moves until the next one. What was received is made durable. */\n detach(): void {\n if (!this.attached) return;\n this.attached = false;\n this.peerRoomValue = null;\n this.moving.clear(); this.held.clear();\n this.host.uplink?.leave(this);\n for (const entry of this.entries.values()) {\n if (entry.out) { entry.out.generation++; clearTimeout(entry.out.timer); clearTimeout(entry.out.wake); entry.out.next = entry.record.confirmed; entry.out.block = undefined; }\n if (entry.in) { clearTimeout(entry.in.timer); clearTimeout(entry.in.ackTimer); entry.in.ackTimer = undefined; }\n if (entry.in && !transferEnded(entry.record)) void this.checkpoint(entry);\n }\n }\n\n /**\n * Offers ended by their time to live. The host calls it now and then; `attach` does too. A file taken here and waiting\n * its turn ends too once nothing of it arrived in that time: its sender never sent it. Offered again, it is taken\n * again (`retakeAgreed`).\n */\n sweep(): void {\n const now = this.now();\n for (const entry of this.entries.values()) {\n const { record } = entry;\n if (![\"queued\", \"offered\", \"asking\"].includes(record.state) || record.since + FILE_LIMITS.offerTtlMs > now) continue;\n // Taken there: what it waits for now is the receiver's to end (its own week to arrive, `pf-refuse`).\n if (record.direction === \"out\" && record.agreed) continue;\n if (record.direction === \"in\" && record.state === \"queued\" && (entry.in?.starting || this.moved(entry) > 0)) continue;\n this.end(entry, \"failed\", record.direction === \"in\" ? \"The offer expired\" : record.state === \"queued\" ? \"Not delivered in time\" : \"Not accepted in time\");\n // Ended here, it ends there too: the receiver's week began when the offer arrived, later, and it still showed Accept.\n this.send(record.direction === \"in\" ? { t: \"pf-refuse\", id: record.id, why: \"expired\" } : { t: \"pf-abort\", id: record.id });\n }\n }\n\n private async sayRoom(): Promise<void> {\n const room = await this.host.room?.().catch(() => null);\n if (typeof room === \"number\" && Number.isSafeInteger(room)) this.send({ t: \"pf-room\", max: room });\n }\n\n // ─── Sending ────────────────────────────────────────────────────────────\n\n /** A new file to send: offered now if a session is open, or on the next one. */\n offer(file: FileInfo, digest?: string): FileTransferRecord {\n if (!ID.test(file.id) || !isInt(file.size)) throw new Error(\"Invalid file\");\n if (this.entries.has(key(\"out\", file.id))) throw new Error(\"File transfer already active\");\n const entry: Entry = {\n record: { id: file.id, direction: \"out\", file, state: \"queued\", confirmed: 0, since: this.now(), ...(digest && { digest }) },\n out: { next: 0, sent: 0, generation: 0, sends: [] },\n };\n this.entries.set(key(\"out\", file.id), entry);\n this.changed(entry);\n if (this.attached) this.announce(entry);\n return { ...entry.record };\n }\n\n private offerFrame(record: FileTransferRecord, paused: boolean): Record<string, unknown> {\n const { file } = record;\n return { t: \"pf-offer\", id: file.id, name: file.name, mime: file.mime, size: file.size, ts: file.timestamp, ...(file.voice && { voice: file.voice }), ...(file.video && { video: file.video }), ...(file.image && { image: file.image }), ...(file.reply && { r: wireReply(file.reply) }), ...(readForwarded(file.forwarded) && { fw: file.forwarded }), ...(isChatAppId(file.app) && { app: file.app }), ...(paused && { paused: true }) };\n }\n\n private announce(entry: Entry): void {\n const { record } = entry, out = entry.out!;\n out.generation++;\n out.next = record.confirmed;\n const paused = record.state === \"paused\" && record.pausedBy === \"me\";\n if (!this.send(this.offerFrame(record, paused))) return;\n // Every byte was confirmed: it stays so (`sentWhole`), the receiver answers with its check (`pf-done`) or its offset.\n // As `offered`, an empty file was one nobody had answered yet, and its Cancel left it cancelled here, kept there.\n if (!paused && record.state !== \"offered\" && record.state !== \"verifying\") { record.state = \"offered\"; record.pausedBy = undefined; this.changed(entry); }\n this.armStall(entry);\n }\n\n private armStall(entry: Entry): void {\n const out = entry.out!;\n clearTimeout(out.timer);\n if (!this.attached || transferEnded(entry.record) || entry.record.state === \"paused\" || entry.record.state === \"asking\") return;\n out.timer = setTimeout(() => {\n // Nothing came back: what is on its way was lost (a switch, a drop not seen yet). Offering again resyncs.\n if (this.attached && !transferEnded(entry.record) && entry.record.state !== \"paused\" && entry.record.state !== \"asking\") this.announce(entry);\n }, FILE_LIMITS.idleMs);\n }\n\n private source(entry: Entry): Promise<OutgoingSource> {\n const out = entry.out!;\n out.source ??= this.host.openSource(entry.record);\n out.source.catch(() => { out.source = undefined; });\n return out.source;\n }\n\n private async chunkAt(entry: Entry, offset: number, generation: number): Promise<Uint8Array> {\n const out = entry.out!, size = entry.record.file.size;\n const length = Math.min(FILE_LIMITS.chunkBytes, size - offset);\n let block = out.block;\n if (!block || offset < block.start || offset + length > block.start + block.bytes.length) {\n const bytes = await (await this.source(entry)).read(offset, Math.min(FILE_LIMITS.readBytes, size - offset));\n if (!bytes.length) throw new Error(\"The file is shorter than it says\");\n block = { start: offset, bytes };\n // Kept only while it still sends: a read that ends after a pause would hold its MiB until the file ended.\n if (generation === out.generation) out.block = block;\n }\n const at = offset - block.start;\n return block.bytes.subarray(at, at + length);\n }\n\n /** Whether this file's own window lets it send more. */\n private fileMayPump(entry: Entry): boolean {\n const { record } = entry, out = entry.out!;\n return this.attached && record.state === \"active\" && out.next < record.file.size && out.next - record.confirmed < FILE_LIMITS.windowBytes;\n }\n\n private shouldPump(entry: Entry): boolean {\n return this.fileMayPump(entry) && this.inFlight() < this.pace.limit(this.floor());\n }\n\n /** Bytes this chat's files sent and have not seen confirmed. */\n private inFlight(): number {\n let bytes = 0;\n for (const entry of this.moving) {\n const out = entry.out, { record } = entry;\n if (!out || record.state !== \"active\" || out.next <= record.confirmed) { this.moving.delete(entry); continue; }\n bytes += out.next - record.confirmed;\n }\n return bytes;\n }\n\n /** Bytes were confirmed, or a file stopped sending: the files the chat's window held go on, before the one that freed it. */\n private wakeHeld(): void {\n for (const entry of [...this.held]) { this.held.delete(entry); void this.pump(entry); }\n }\n\n /**\n * Whether the next `length` bytes go. Within the file's size they always do; past it the receiver is having parts\n * sent again, which nothing it says bounds, so this side does.\n */\n private mayResend(entry: Entry, length: number): boolean {\n const { record } = entry, size = record.file.size, sent = entry.out!.sent + length;\n if (sent <= size) return true;\n return sent - size <= 2 * size + FILE_LIMITS.resendBytes && this.host.resend?.({ ...record }, sent) !== false;\n }\n\n private async pump(entry: Entry): Promise<void> {\n const out = entry.out!;\n if (out.pumping === out.generation) return;\n const generation = out.pumping = out.generation;\n clearTimeout(out.wake);\n let refused = false;\n try {\n while (this.shouldPump(entry) && generation === out.generation) {\n const offset = out.next;\n const chunk = await this.chunkAt(entry, offset, generation);\n const room = this.host.writable?.();\n if (room) await room;\n if (generation !== out.generation || !this.shouldPump(entry) || out.next !== offset) break;\n if (!this.mayResend(entry, chunk.length)) {\n this.send({ t: \"pf-abort\", id: entry.record.id });\n this.end(entry, \"failed\", \"Your contact asked for the same part of this file too many times\");\n break;\n }\n if (!this.sendData(entry.record.id, offset, chunk)) { refused = true; break; }\n out.next = offset + chunk.length;\n out.sent += chunk.length;\n this.moving.add(entry);\n if (out.sends[out.sends.length - 1]?.generation !== generation) out.sends.length = 0;\n out.sends.push({ end: out.next, at: this.now(), flight: Math.max(this.inFlight(), Math.min(this.refill, this.pace.limit(this.floor()))), generation });\n }\n } catch (error) {\n if (generation === out.generation) {\n this.send({ t: \"pf-abort\", id: entry.record.id });\n this.end(entry, \"failed\", `Could not read the file: ${error instanceof Error ? error.message : String(error)}`);\n }\n } finally {\n if (out.pumping === generation) out.pumping = undefined;\n if (generation === out.generation && this.shouldPump(entry)) {\n // A refused frame is tried again later, never at once: at once, nothing else would run until it went.\n if (refused) out.wake = setTimeout(() => void this.pump(entry), FILE_LIMITS.sendRetryMs);\n else void this.pump(entry);\n } else if (generation === out.generation && this.fileMayPump(entry)) this.held.add(entry);\n }\n }\n\n private async sendSum(entry: Entry): Promise<void> {\n const { record } = entry;\n if (record.state !== \"verifying\") { record.state = \"verifying\"; this.changed(entry); }\n try {\n record.digest ??= await (await this.source(entry)).digest();\n } catch (error) {\n this.send({ t: \"pf-abort\", id: record.id });\n this.end(entry, \"failed\", `Could not read the file: ${error instanceof Error ? error.message : String(error)}`);\n return;\n }\n if (record.state !== \"verifying\") return;\n this.send({ t: \"pf-sum\", id: record.id, size: record.file.size, digest: record.digest });\n this.armStall(entry);\n }\n\n // ─── Receiving ──────────────────────────────────────────────────────────\n\n private waitingOffers(): number {\n return [...this.entries.values()].filter((e) => e.record.direction === \"in\" && e.record.state === \"asking\").length;\n }\n\n private unfinishedIncoming(): number {\n return [...this.entries.values()].filter((e) => e.record.direction === \"in\" && !transferEnded(e.record)).length;\n }\n\n private activeIncoming(except: Entry): number {\n return [...this.entries.values()].filter((e) => e !== except && e.record.direction === \"in\" && (e.record.state === \"active\" || e.record.state === \"verifying\" || e.in?.starting)).length;\n }\n\n /**\n * Removes what this side stored of an incoming file that ends here. Through its target, opened now if need be: after\n * a restart a transfer has none until bytes arrive again, and one cancelled before that kept its part on the disk.\n * After the write under way, and with the ones queued behind it stopped: a write landing after the removal would\n * store a part of the file again.\n */\n private discardStored(entry: Entry): Promise<void> {\n const incoming = entry.in;\n if (!incoming) return Promise.resolve();\n incoming.dropped = true;\n return incoming.writing.then(() => this.target(entry)).then((t) => t.discard()).catch(() => {});\n }\n\n private target(entry: Entry): Promise<IncomingTarget> {\n const incoming = entry.in!;\n if (!incoming.target) {\n incoming.target = this.host.openTarget(entry.record).then((target) => {\n incoming.written = incoming.stored = incoming.acked = incoming.checkpointed = target.offset;\n return target;\n });\n incoming.target.catch(() => { incoming.target = undefined; });\n }\n return incoming.target;\n }\n\n /**\n * An accepted file goes when a session is open and fewer than three others arrive at once. One whose target is still\n * being opened counts among the three: counted only once active, every file offered or queued meanwhile went too, and\n * the windows of ten files and more at once overflowed the session's receive queue.\n */\n private startIncoming(entry: Entry): void {\n if (!this.attached || transferEnded(entry.record) || entry.record.state === \"asking\" || (entry.record.state === \"paused\" && entry.record.pausedBy === \"me\")) return;\n const incoming = entry.in!;\n if (incoming.starting) return;\n if (this.activeIncoming(entry) >= FILE_LIMITS.maxActiveIncoming) {\n if (entry.record.state !== \"queued\") { entry.record.state = \"queued\"; this.changed(entry); }\n this.send({ t: \"pf-wait\", id: entry.record.id, why: \"busy\" });\n return;\n }\n incoming.starting = true;\n void this.target(entry).then(() => {\n incoming.starting = false;\n // Ended, paused or cut off while it opened: its turn goes to the next one.\n if (transferEnded(entry.record) || !this.attached || (entry.record.state === \"paused\" && entry.record.pausedBy === \"me\")) { this.startNext(); return; }\n entry.record.state = \"active\";\n entry.record.pausedBy = undefined;\n entry.in!.gapAt = undefined;\n this.changed(entry);\n this.send({ t: \"pf-accept\", id: entry.record.id, offset: entry.in!.written });\n entry.in!.heardAt = this.now();\n this.armNudge(entry);\n }, (error) => {\n incoming.starting = false;\n this.end(entry, \"failed\", storeFailure(error));\n this.send({ t: \"pf-refuse\", id: entry.record.id, why: \"no-room\" });\n this.startNext();\n });\n }\n\n /**\n * The next file waiting its turn, once one ends. The others were told they wait when they were queued: told again at\n * each end, n files at once made about n²/2 frames, and their sender stored its record for each.\n */\n private startNext(): void {\n for (const entry of this.entries.values()) {\n if (entry.record.direction !== \"in\" || entry.record.state !== \"queued\" || entry.in!.starting) continue;\n if (this.activeIncoming(entry) >= FILE_LIMITS.maxActiveIncoming) return;\n this.startIncoming(entry);\n }\n }\n\n private async onOffer(frame: Record<string, unknown>): Promise<void> {\n const id = frame.id as string;\n if (typeof frame.name !== \"string\" || frame.name.length > 1000 || typeof frame.mime !== \"string\" || frame.mime.length > 130 ||\n !isInt(frame.size) || !isInt(frame.ts) || frame.ts === 0) { this.send({ t: \"pf-refuse\", id, why: \"invalid\" }); return; }\n const file: FileInfo = { id, name: sanitizeFileName(frame.name), mime: sanitizeMime(frame.mime), size: frame.size, timestamp: frame.ts };\n const voice = parseVoiceMeta(frame.voice, file.mime);\n if (voice) file.voice = voice;\n const video = parseVideoMeta(frame.video, file.mime);\n if (video) file.video = video;\n const image = parseImageMeta(frame.image, file.mime);\n if (image) file.image = image;\n const reply = readReply(frame.r, pairedReplyAuthor);\n if (reply) file.reply = reply;\n const forwarded = readForwarded(frame.fw);\n if (forwarded) file.forwarded = forwarded;\n // Sent ahead by a mini-app: kept with the file, which is still taken as any file; a malformed one is dropped.\n if (isChatAppId(frame.app)) file.app = frame.app;\n const paused = frame.paused === true;\n const existing = this.entries.get(key(\"in\", id));\n if (existing) {\n const { record } = existing;\n if (record.file.size !== file.size || record.file.name !== file.name) { this.send({ t: \"pf-refuse\", id, why: \"invalid\" }); return; }\n switch (record.state) {\n case \"done\": this.sayDone(id); return;\n case \"declined\": this.send({ t: \"pf-refuse\", id, why: \"declined\" }); return;\n case \"cancelled\":\n // Cancelled here stays cancelled; stopped by the sender (it could not read its file), it is taken again.\n if (!record.abortedBySender || (!record.agreed && !record.consented)) { this.send({ t: \"pf-refuse\", id, why: \"cancelled\" }); return; }\n if (!(await this.retakeAgreed(existing))) return;\n break;\n case \"failed\":\n // Expired here before anyone answered: nothing was agreed, and offered again it would skip the question.\n if (!record.agreed && !record.consented) { this.send({ t: \"pf-refuse\", id, why: \"expired\" }); return; }\n // Sent again after it failed here (damaged, not stored): taken again from the start, as it was agreed.\n if (!(await this.retakeAgreed(existing))) return;\n break;\n case \"asking\": this.send({ t: \"pf-wait\", id, why: \"consent\" }); return;\n // Being checked (a new session's offer, while the old one's still waits on it): the check answers, `pf-done` or\n // `pf-refuse`. Taken up again, it read as arriving at 100% for the rest of the check, with Pause and Ask again.\n // One that was being checked when the app stopped is taken up again: its check starts over.\n case \"verifying\": if (existing.in?.verifying) return; break;\n }\n if (record.state === \"paused\" && record.pausedBy === \"me\") { this.send({ t: \"pf-wait\", id, why: \"paused\" }); return; }\n if (paused) {\n if (record.state !== \"paused\") { record.state = \"paused\"; record.pausedBy = \"peer\"; this.changed(existing); void this.checkpoint(existing); }\n return;\n }\n if (record.state === \"paused\") { record.state = \"queued\"; record.pausedBy = undefined; this.changed(existing); }\n this.startIncoming(existing);\n return;\n }\n if (this.waitingOffers() >= FILE_LIMITS.maxWaitingOffers || this.unfinishedIncoming() >= FILE_LIMITS.maxUnfinishedIncoming) {\n this.send({ t: \"pf-refuse\", id, why: \"too-many\" }); return;\n }\n let decision: OfferDecision;\n try { decision = await this.host.decide(file); } catch { decision = { refuse: \"invalid\" }; }\n if (this.entries.has(key(\"in\", id))) return;\n if (typeof decision === \"object\") { this.send({ t: \"pf-refuse\", id, why: decision.refuse, ...(decision.room !== undefined && { room: decision.room }) }); return; }\n const entry: Entry = {\n record: { id, direction: \"in\", file, state: decision === \"ask\" ? \"asking\" : paused ? \"paused\" : \"queued\", confirmed: 0, since: this.now(),\n ...(decision !== \"ask\" && { agreed: true }), ...(paused && decision !== \"ask\" && { pausedBy: \"peer\" as const }) },\n in: { written: 0, stored: 0, acked: 0, checkpointed: 0, writing: Promise.resolve() },\n };\n this.entries.set(key(\"in\", id), entry);\n this.changed(entry);\n if (decision === \"ask\") this.send({ t: \"pf-wait\", id, why: \"consent\" });\n else if (!paused) this.startIncoming(entry);\n }\n\n /**\n * An agreed file that ended here, offered again. One the person consented to is taken again from the start; one taken\n * without asking is decided again, as a new offer would be (the contact's limit for files taken without asking, and\n * the room here): taken again, asked about, or refused. True when it is taken again.\n */\n private async retakeAgreed(entry: Entry): Promise<boolean> {\n const { record } = entry;\n if (this.unfinishedIncoming() >= FILE_LIMITS.maxUnfinishedIncoming) { this.send({ t: \"pf-refuse\", id: record.id, why: \"too-many\" }); return false; }\n if (!record.consented) {\n let decision: OfferDecision;\n try { decision = await this.host.decide(record.file, true); } catch { decision = { refuse: \"invalid\" }; }\n if (typeof decision === \"object\") { this.send({ t: \"pf-refuse\", id: record.id, why: decision.refuse, ...(decision.room !== undefined && { room: decision.room }) }); return false; }\n if (decision === \"ask\") {\n if (this.waitingOffers() >= FILE_LIMITS.maxWaitingOffers) { this.send({ t: \"pf-refuse\", id: record.id, why: \"too-many\" }); return false; }\n await this.retake(entry);\n record.state = \"asking\";\n record.agreed = undefined;\n this.changed(entry);\n this.send({ t: \"pf-wait\", id: record.id, why: \"consent\" });\n return false;\n }\n }\n await this.retake(entry);\n return true;\n }\n\n /** An agreed file that ended here, offered again: taken again from the start. */\n private async retake(entry: Entry): Promise<void> {\n await entry.in?.target?.then((t) => t.discard()).catch(() => {});\n clearTimeout(entry.in?.ackTimer);\n entry.in = { written: 0, stored: 0, acked: 0, checkpointed: 0, writing: Promise.resolve() };\n Object.assign(entry.record, { state: \"queued\", confirmed: 0, error: undefined, digest: undefined, abortedBySender: undefined, since: this.now() });\n this.changed(entry);\n }\n\n private onData(entry: Entry, frame: Record<string, unknown>): void {\n const { record } = entry, incoming = entry.in!;\n if (record.state !== \"active\" || !incoming.target) return;\n incoming.heardAt = this.now();\n const { offset, data } = frame;\n // The bytes themselves when they came as a binary message (files/4), base64url text in a `pf-data` frame.\n const binary = data instanceof Uint8Array;\n if (!isInt(offset) || !(binary || typeof data === \"string\") || !data.length) return;\n if (!binary && (data.length > Math.ceil(FILE_LIMITS.chunkBytes * 4 / 3) || !DATA.test(data))) return;\n if (offset < incoming.written) {\n // Sent again (a resync): already taken. Said again only once everything is stored.\n if (incoming.stored === incoming.written) this.send({ t: \"pf-got\", id: record.id, offset: incoming.stored });\n return;\n }\n if (offset > incoming.written) {\n // Something before this was lost: once per gap, the sender is told where to go on from.\n if (incoming.gapAt !== incoming.written) { incoming.gapAt = incoming.written; this.send({ t: \"pf-accept\", id: record.id, offset: incoming.written }); }\n return;\n }\n const bytes = binary ? data : fromBase64Url(data);\n if (!bytes.length || bytes.length > FILE_LIMITS.chunkBytes || offset + bytes.length > record.file.size) return;\n incoming.written += bytes.length;\n const target = incoming.target;\n incoming.writing = incoming.writing.then(async () => {\n if (transferEnded(record) || incoming.dropped) return;\n await (await target).append(bytes);\n incoming.stored = offset + bytes.length;\n const due = incoming.stored - incoming.acked >= FILE_LIMITS.ackEveryBytes || incoming.stored === record.file.size;\n if (due || (!this.host.batchConfirms && incoming.stored === incoming.written)) this.confirm(entry);\n else if (this.host.batchConfirms) incoming.ackTimer ??= setTimeout(() => this.confirm(entry), FILE_LIMITS.ackWaitMs);\n // Inside the chain of writes: waiting for the chain here would wait for itself.\n if (incoming.stored - incoming.checkpointed >= FILE_LIMITS.checkpointBytes) await this.checkpointNow(entry);\n }).catch((error) => {\n if (transferEnded(record)) return;\n this.end(entry, \"failed\", storeFailure(error));\n void target.then((t) => t.discard()).catch(() => {});\n this.send({ t: \"pf-refuse\", id: record.id, why: \"no-room\" });\n this.startNext();\n });\n }\n\n /** `pf-got` for what is stored and not confirmed yet. */\n private confirm(entry: Entry): void {\n const { record } = entry, incoming = entry.in!;\n clearTimeout(incoming.ackTimer);\n incoming.ackTimer = undefined;\n if (transferEnded(record) || incoming.stored <= incoming.acked) return;\n incoming.acked = incoming.stored;\n this.send({ t: \"pf-got\", id: record.id, offset: incoming.stored });\n this.changed(entry, true);\n }\n\n /** What was stored is durable, and a restart resumes from there. */\n private async checkpoint(entry: Entry): Promise<void> {\n if (!entry.in?.target) return;\n await entry.in.writing;\n await this.checkpointNow(entry);\n }\n\n private async checkpointNow(entry: Entry): Promise<void> {\n const incoming = entry.in!;\n if (!incoming.target) return;\n const stored = incoming.stored;\n if (stored === incoming.checkpointed && entry.record.confirmed === stored) return;\n try { await (await incoming.target).flush(); } catch { return; }\n incoming.checkpointed = Math.max(incoming.checkpointed, stored);\n // Kept at once (not as progress): a restart resumes from here.\n if (!transferEnded(entry.record)) { entry.record.confirmed = incoming.checkpointed; this.changed(entry); }\n }\n\n /** Nothing arrives for a file under way: after a quiet spell the receiver says again where it stands. */\n private armNudge(entry: Entry, delay: number = FILE_LIMITS.idleMs): void {\n const incoming = entry.in!;\n clearTimeout(incoming.timer);\n if (!this.attached || entry.record.state !== \"active\") return;\n incoming.heardAt ??= this.now();\n incoming.timer = setTimeout(() => {\n const quiet = this.now() - (incoming.heardAt ?? 0);\n if (quiet < FILE_LIMITS.idleMs) this.armNudge(entry, FILE_LIMITS.idleMs - quiet);\n else void this.askAgain(entry);\n }, delay);\n }\n\n /** `pf-accept` from what is taken here: the sender goes on from there (it ignores it for a transfer that ended). */\n private async askAgain(entry: Entry): Promise<void> {\n const { record } = entry, incoming = entry.in!;\n // Kept from before a restart, not opened yet: opening it says where it stands.\n if (!incoming.target) { this.startIncoming(entry); return; }\n await incoming.writing;\n if (!this.attached || record.state !== \"active\" || incoming.verifying) return;\n incoming.gapAt = undefined;\n this.send({ t: \"pf-accept\", id: record.id, offset: incoming.written });\n incoming.heardAt = this.now();\n this.armNudge(entry);\n }\n\n private async onSum(entry: Entry, frame: Record<string, unknown>): Promise<void> {\n const { record } = entry, incoming = entry.in!;\n if (record.state === \"done\") { this.sayDone(record.id); return; }\n if (record.state !== \"active\" || incoming.verifying || !incoming.target) return;\n if (frame.size !== record.file.size || typeof frame.digest !== \"string\" || !DIGEST.test(frame.digest)) return;\n const digest = frame.digest;\n // Set before the writes are waited for: the check runs beside the session's frames (`handle`), and a second `pf-sum`\n // meanwhile is not a second check.\n incoming.verifying = true;\n await incoming.writing;\n // Taken again meanwhile (the sender stopped it, then offered it again): this check is the old transfer's.\n if (entry.in !== incoming) return;\n if (transferEnded(record) || record.state !== \"active\" || incoming.stored < record.file.size) {\n incoming.verifying = false;\n if (!transferEnded(record) && record.state === \"active\") this.send({ t: \"pf-accept\", id: record.id, offset: incoming.stored });\n return;\n }\n record.state = \"verifying\";\n this.changed(entry);\n let ok: boolean;\n try { const target = await incoming.target; await target.flush(); ok = await target.verify(digest); } catch { ok = false; }\n incoming.verifying = false;\n // The check runs beside the session's frames: the sender's abort and a new offer may have taken the file up again\n // from the start. Its answer was the old bytes', and ended the new transfer done with what had come of it.\n if (transferEnded(record) || entry.in !== incoming) return;\n if (ok) {\n record.digest = digest;\n record.confirmed = record.file.size;\n this.end(entry, \"done\");\n this.sayDone(record.id);\n } else {\n await incoming.target.then((t) => t.discard()).catch(() => {});\n this.end(entry, \"failed\", \"The file arrived damaged and was deleted. Ask for it again.\");\n this.send({ t: \"pf-refuse\", id: record.id, why: \"damaged\" });\n }\n this.startNext();\n }\n\n /**\n * `pf-done` once the host kept the file's done record (`kept`). Not kept (the app gone first), the sender still\n * waits, offers it again on the next session, and the receiver answers from what it kept.\n */\n private sayDone(id: string): void {\n const kept = this.host.kept?.().catch(() => {});\n if (!kept) { this.send({ t: \"pf-done\", id }); return; }\n void kept.then(() => this.send({ t: \"pf-done\", id }));\n }\n\n // ─── Frames ─────────────────────────────────────────────────────────────\n\n /** A frame from the contact (one of `FILE_FRAMES`). Returns quickly: writing goes on in the background. */\n async handle(frame: Record<string, unknown>): Promise<void> {\n if (!this.attached) return;\n if (frame.t === \"pf-room\") { if (isInt(frame.max)) this.peerRoomValue = frame.max; return; }\n if (typeof frame.id !== \"string\" || !ID.test(frame.id)) return;\n const id = frame.id;\n if (frame.t === \"pf-offer\") return this.onOffer(frame);\n const incoming = this.entries.get(key(\"in\", id)), outgoing = this.entries.get(key(\"out\", id));\n if (frame.t === \"pf-data\") { if (incoming) this.onData(incoming, frame); return; }\n // Not waited for: the check reads the whole file again (a 4 GiB one about 20 s at 200 MiB/s), and the session's\n // frames come in one queue. Waited for, every text, pong and other file of the chat waited behind it, and a check\n // longer than the contact's three pings (45 s) had the session dropped as dead.\n if (frame.t === \"pf-sum\") { if (incoming) void this.onSum(incoming, frame); return; }\n if (frame.t === \"pf-abort\") {\n if (incoming && !transferEnded(incoming.record)) {\n await this.discardStored(incoming);\n incoming.record.abortedBySender = true;\n this.end(incoming, \"cancelled\", \"Cancelled by the sender\");\n this.startNext();\n }\n return;\n }\n if (!outgoing || transferEnded(outgoing.record)) {\n // Asked about a file this side does not send any more (deleted with its message, expired or failed while the\n // receiver was away): it hears so, and ends it. Unanswered, it stayed under way there for good, its bytes kept.\n const asked = frame.t === \"pf-accept\" || frame.t === \"pf-wait\";\n if (outgoing?.record.state === \"cancelled\" ? frame.t !== \"pf-refuse\" : asked && outgoing?.record.state !== \"done\") this.send({ t: \"pf-abort\", id });\n return;\n }\n const { record } = outgoing, out = outgoing.out!;\n switch (frame.t) {\n case \"pf-accept\": {\n if (!isInt(frame.offset, record.file.size)) return;\n // Paused here before the person there answered: it stays so, and their side hears it is paused.\n if (record.state === \"paused\" && record.pausedBy === \"me\") { this.send(this.offerFrame(record, true)); return; }\n out.generation++;\n record.confirmed = frame.offset;\n out.next = frame.offset;\n this.refill = 0;\n record.state = \"active\";\n record.agreed = true;\n record.pausedBy = record.waitingFor = undefined;\n this.changed(outgoing);\n this.wakeHeld();\n if (record.confirmed === record.file.size) void this.sendSum(outgoing);\n else { this.armStall(outgoing); void this.pump(outgoing); }\n return;\n }\n case \"pf-wait\": {\n // The answer to the paused offer said while the person there still decides: the pause here holds.\n if (record.state === \"paused\" && record.pausedBy === \"me\") return;\n // Told again what it already waits for (an older receiver says so each time a file there ends): nothing changes.\n if (frame.why === \"paused\" ? record.state === \"paused\" && record.pausedBy === \"peer\"\n : record.state === \"asking\" && record.waitingFor === (frame.why === \"busy\" ? \"busy\" : \"consent\")) return;\n out.generation++;\n out.next = record.confirmed;\n out.block = undefined;\n clearTimeout(out.timer);\n if (frame.why === \"paused\") { record.state = \"paused\"; record.pausedBy = \"peer\"; }\n else {\n record.state = \"asking\";\n record.waitingFor = frame.why === \"busy\" ? \"busy\" : \"consent\";\n // Asked about again there (taken again after it ended): unanswered, it ends with the offer's week again.\n if (record.waitingFor === \"consent\") record.agreed = undefined;\n }\n this.changed(outgoing);\n this.wakeHeld();\n return;\n }\n case \"pf-got\": {\n if (!isInt(frame.offset) || frame.offset <= record.confirmed || frame.offset > out.next) return;\n this.refill = this.inFlight();\n this.pace.delivered += frame.offset - record.confirmed;\n record.confirmed = frame.offset;\n // The last chunk this confirms says how long the path took (one sent before a resync says nothing).\n let sample: Outgoing[\"sends\"][number] | undefined;\n while (out.sends.length && out.sends[0].end <= frame.offset) sample = out.sends.shift();\n if (sample?.generation === out.generation) this.pace.paced(sample.at, sample.flight, this.now(), this.floor(), this.host.uplink?.lowestBase());\n this.changed(outgoing, true);\n this.wakeHeld();\n if (record.confirmed === record.file.size) void this.sendSum(outgoing);\n else { this.armStall(outgoing); void this.pump(outgoing); }\n return;\n }\n case \"pf-done\": {\n // Checked out there. Said again to the offer of a new session too, after which this side is no longer verifying,\n // and to one sent again from the start (Send again on a file that failed here once the contact had it whole):\n // ignored, the file was offered every 30 s for good, a done one there never anything else.\n if (record.state !== \"verifying\" && record.state !== \"offered\" && record.confirmed !== record.file.size) return;\n record.confirmed = record.file.size;\n this.end(outgoing, \"done\");\n return;\n }\n case \"pf-refuse\": {\n const { state, error } = refusalText(String(frame.why), isInt(frame.room) ? frame.room : undefined);\n this.end(outgoing, state, error);\n return;\n }\n }\n }\n\n private end(entry: Entry, state: TransferState, error?: string): void {\n const { record } = entry;\n record.state = state;\n record.error = error;\n record.pausedBy = record.waitingFor = undefined;\n if (entry.out) {\n entry.out.generation++; clearTimeout(entry.out.timer); clearTimeout(entry.out.wake); entry.out.block = undefined; entry.out.source = undefined; entry.out.sends.length = 0;\n this.moving.delete(entry); this.held.delete(entry);\n }\n if (entry.in) {\n const incoming = entry.in;\n clearTimeout(incoming.timer);\n clearTimeout(incoming.ackTimer);\n incoming.ackTimer = undefined;\n // Its writer goes once the writes under way are done (a host's holds a 256 KiB buffer): every file received kept\n // one until the app quit. One taken again opens a new target.\n void incoming.writing.finally(() => { if (transferEnded(record)) incoming.target = undefined; });\n }\n this.changed(entry);\n if (entry.out) this.wakeHeld();\n }\n\n // ─── What the person does ───────────────────────────────────────────────\n\n private entry(direction: \"in\" | \"out\", id: string): Entry {\n const entry = this.entries.get(key(direction, id));\n if (!entry) throw new Error(\"No such file transfer\");\n return entry;\n }\n\n /** Takes an offered file. */\n accept(id: string): void {\n const entry = this.entry(\"in\", id);\n if (entry.record.state !== \"asking\") return;\n entry.record.state = \"queued\";\n entry.record.consented = entry.record.agreed = true;\n // Its time to live, now to arrive, starts with the answer: one accepted late does not end at once (`sweep`).\n entry.record.since = this.now();\n this.changed(entry);\n this.startIncoming(entry);\n }\n\n decline(id: string): void {\n const entry = this.entry(\"in\", id);\n if (transferEnded(entry.record)) return;\n void this.discardStored(entry);\n this.end(entry, \"declined\", \"You declined it\");\n this.send({ t: \"pf-refuse\", id, why: \"declined\" });\n this.startNext();\n }\n\n /**\n * An offer taken here whose record or message the host could not store: refused, so its sender does not count it\n * delivered and keeps its Retry, and forgotten, so that retry is a new offer here. Nothing of it is reported changed\n * (there is nothing to write it to); what was stored of it is removed.\n */\n refuse(id: string, why: RefuseReason): void {\n const entry = this.entries.get(key(\"in\", id));\n if (!entry || transferEnded(entry.record)) return;\n this.entries.delete(key(\"in\", id));\n this.unended.delete(entry);\n const incoming = entry.in!;\n entry.record.state = \"failed\";\n clearTimeout(incoming.timer);\n clearTimeout(incoming.ackTimer);\n incoming.dropped = true;\n void incoming.writing.then(() => incoming.target?.then((t) => t.discard())).catch(() => {});\n this.send({ t: \"pf-refuse\", id, why });\n this.startNext();\n }\n\n pause(direction: \"in\" | \"out\", id: string): void {\n const entry = this.entry(direction, id), { record } = entry;\n if (transferEnded(record) || record.state === \"verifying\" || (record.state === \"paused\" && record.pausedBy === \"me\")) return;\n if (direction === \"in\" && record.state === \"asking\") return;\n // Arrived whole (offered again after a restart or a switch while it was checked there): paused, it could be cancelled.\n if (sentWhole(record)) return;\n record.state = \"paused\";\n record.pausedBy = \"me\";\n if (entry.out) { entry.out.generation++; entry.out.next = record.confirmed; entry.out.block = undefined; clearTimeout(entry.out.timer); this.send(this.offerFrame(record, true)); }\n else { this.send({ t: \"pf-wait\", id, why: \"paused\" }); void this.checkpoint(entry); this.startNext(); }\n this.changed(entry);\n if (entry.out) this.wakeHeld();\n }\n\n resume(direction: \"in\" | \"out\", id: string): void {\n const entry = this.entry(direction, id), { record } = entry;\n if (record.state !== \"paused\" || record.pausedBy !== \"me\") return;\n record.pausedBy = undefined;\n record.state = \"queued\";\n if (direction === \"in\") record.since = this.now();\n this.changed(entry);\n if (direction === \"out\") { if (this.attached) this.announce(entry); }\n else this.startIncoming(entry);\n }\n\n cancel(direction: \"in\" | \"out\", id: string): void {\n const entry = this.entry(direction, id);\n if (transferEnded(entry.record)) return;\n if (direction === \"out\") {\n if (!this.send({ t: \"pf-abort\", id })) this.unsaid.add(id);\n this.end(entry, \"cancelled\", \"You cancelled it\");\n } else {\n void this.discardStored(entry);\n this.end(entry, \"cancelled\", \"You cancelled it\");\n this.send({ t: \"pf-refuse\", id, why: \"cancelled\" });\n this.startNext();\n }\n }\n\n /** A sent file that failed, offered again from the start under its id. */\n retry(id: string): void {\n const entry = this.entry(\"out\", id), { record } = entry;\n if (record.state !== \"failed\") return;\n // The digest is taken again from the source: the one sent last time may be what was wrong.\n Object.assign(record, { state: \"queued\", confirmed: 0, error: undefined, digest: undefined, agreed: undefined, since: this.now() });\n clearTimeout(entry.out!.timer); clearTimeout(entry.out!.wake);\n entry.out = { next: 0, sent: 0, generation: entry.out!.generation + 1, sends: [] };\n this.changed(entry);\n if (this.attached) this.announce(entry);\n }\n\n /**\n * \"Send again\": a sent file that failed, or stopped moving, is offered again now (or on the next session). The\n * receiver answers from what it holds, so it goes on from there, never twice in the chat: same id, same message.\n * True when it went now.\n */\n resend(id: string): boolean {\n const entry = this.entry(\"out\", id), { record } = entry;\n if (record.state === \"failed\") { this.retry(id); return this.attached; }\n if (transferEnded(record)) return false;\n if (record.state === \"paused\" && record.pausedBy === \"me\") { this.resume(\"out\", id); return this.attached; }\n if (!this.attached) return false;\n this.announce(entry);\n return true;\n }\n\n /**\n * \"Ask again\": a file that stopped arriving is asked for again from where it stands here. No new frame: a receiver's\n * `pf-accept` already moves any files/3 sender to its offset.\n * True when it went now.\n */\n request(id: string): boolean {\n const entry = this.entry(\"in\", id), { record } = entry;\n if (transferEnded(record) || record.state === \"asking\" || record.state === \"verifying\") return false;\n if (record.state === \"paused\") {\n if (record.pausedBy !== \"me\") return false;\n this.resume(\"in\", id);\n return this.attached;\n }\n if (!this.attached) return false;\n if (record.state === \"queued\") this.startIncoming(entry);\n else void this.askAgain(entry);\n return true;\n }\n\n /** Forgets a transfer (its message was deleted): an unfinished one is cancelled on both sides first. */\n forget(direction: \"in\" | \"out\", id: string): void {\n const entry = this.entries.get(key(direction, id));\n if (!entry) return;\n if (!transferEnded(entry.record)) this.cancel(direction, id);\n this.entries.delete(key(direction, id));\n this.unended.delete(entry);\n }\n}\n","import { CALL_SIGNAL_MAX_AGE_MS, heardCallSignal, parseCallSignal } from \"./callSignal\";\n\n/**\n * Call signaling on a paired session (`calls/1`, WISP 601): the same compact signals a compatibility chat\n * keeps in its `_call` record, carried as one frame each on the authenticated session instead:\n *\n * {\"t\":\"paired-call\",\"s\":\"<signal>\"}\n *\n * The media is not on this session: it runs on a WebRTC connection of its own, whose DTLS fingerprint the\n * offer and answer carry, so whatever carries the chat (WebRTC, Iroh, HyperDHT) the media is bound to the\n * contact this session authenticated. Nothing about a call is ever published on the DHT.\n */\nexport const PAIRED_CALL_FRAME = \"paired-call\";\n\n/** A compact offer with the eight candidates `parseCallSignal` accepts stays well under this. */\nexport const MAX_PAIRED_CALL_SIGNAL = 8192;\n\n/**\n * A receiver takes at most this many `paired-call` frames from a contact per `CALL_RATE_WINDOW_MS`, counted before they\n * are read; the rest are dropped. A person's busiest minute is under half of it, 68 frames: three calls placed, each\n * started over 4 times on a newer offer (`MAX_RESTARTS`) and hung up; two calls whose path was lost twice, restarted\n * every 8 s for 30 s each time (`ICE_RESTART_RETRY_MS`, `RECONNECT_TIMEOUT_MS`); the camera and the screen turned on\n * and off five times each; and the latest signal said again on ten new sessions. Only an app that loops its signals\n * reaches it.\n */\nexport const CALL_RECEIVE_LIMIT = 150;\nexport const CALL_RATE_WINDOW_MS = 60_000;\n\nexport interface PairedCallFrame { t: typeof PAIRED_CALL_FRAME; s: string }\n\n/**\n * The signal a `paired-call` frame carries, or null when it is not a well-formed one. It came on a live session, now:\n * that is when it was heard (`heardCallSignal`), whatever time its sender's clock gave it.\n */\nexport function parsePairedCallFrame(frame: Record<string, unknown>, now = Date.now()): string | null {\n const signal = frame.s;\n if (typeof signal !== \"string\" || signal.length > MAX_PAIRED_CALL_SIGNAL) return null;\n const heard = heardCallSignal(signal, now);\n return parseCallSignal(heard, now) ? heard : null;\n}\n\nfunction signalKind(signal: string): unknown {\n try { return (JSON.parse(signal) as { t?: unknown }).t; } catch { return undefined; }\n}\n\n/**\n * This side's latest call signal. What could not go (the session dropped between two frames) goes on the\n * next session while it is still fresh, as the `_call` record of a compatibility chat is read on the next\n * poll; clearing it (after a hang-up, or a call that never started) means there is nothing left to say.\n */\nexport class PairedCalls {\n private latest: { signal: string; at: number } | null = null;\n /** When this side last said anything about a call, a clear included. */\n private saidAt = 0;\n /** The contact's latest signal on a session: its kind, when it came, and the time its sender gave it. */\n private peer: { kind: unknown; at: number; ts: number } | null = null;\n\n constructor(private readonly now: () => number = Date.now) {}\n\n /** A new signal to send (null clears it). Returns the frame to send now, if any. */\n set(signal: string | null): PairedCallFrame | null {\n this.saidAt = this.now();\n if (signal === null) { this.latest = null; return null; }\n if (signal.length > MAX_PAIRED_CALL_SIGNAL) throw new Error(\"Call signal too large\");\n this.latest = { signal, at: this.saidAt };\n return { t: PAIRED_CALL_FRAME, s: signal };\n }\n\n /**\n * A signal the contact sent (one `parsePairedCallFrame` took). False when it is not newer than the last one heard\n * from the contact on this chat: the contact's app sends its latest signal again on each new session while it is\n * fresh (`pending`), and one already heard is not news. Handed on again, an answer to an earlier call that names no\n * offer (an app up to 1.0.2) was taken for the call placed since, whose connection it does not fit.\n */\n heard(signal: string): boolean {\n let ts = NaN;\n try { ts = Number((JSON.parse(signal) as { ts?: unknown }).ts); } catch { /* not a signal the parser took */ }\n if (!Number.isFinite(ts) || (this.peer && ts <= this.peer.ts)) return false;\n this.peer = { kind: signalKind(signal), at: this.now(), ts };\n return true;\n }\n\n /**\n * Whether a call is on, as the latest signal of either side says: an answer or a picture change, or an offer still\n * fresh enough to ring. A hang-up, a clear, or an offer nobody answered in time ends it. Read by kind, as `hangUp` is:\n * the media runs on a connection of its own, so an hour-long call shows nothing else on the session.\n */\n get on(): boolean {\n const own = { kind: this.latest ? signalKind(this.latest.signal) : \"h\", at: this.saidAt };\n const last = this.peer && this.peer.at > own.at ? this.peer : own;\n // A restart offer (`r`) is only sent on a call that is on.\n if (last.kind === \"a\" || last.kind === \"v\" || last.kind === \"r\") return true;\n return last.kind === \"o\" && this.now() - last.at <= CALL_SIGNAL_MAX_AGE_MS;\n }\n\n /**\n * This app is going away: a call it placed or answered is hung up, as its person would (its latest signal an\n * offer, an answer, or a picture change, which only a call on sends). `declineRinging` (the app quits: the Desktop app\n * or a CLI daemon) also declines the contact's call still ringing here, so the caller stops ringing for nobody; a web\n * page that goes (a reload looks the same as a close) leaves it ringing, so the reopened page rings again. Returns\n * the hang-up to send before the goodbye, or null when no call is on. Our own call is read by its kind, not its age:\n * a call outlasts its offer's freshness.\n */\n hangUp(options: { declineRinging?: boolean } = {}): PairedCallFrame | null {\n const said = this.said();\n const ours = said.t === \"o\" || said.t === \"a\" || said.t === \"v\" || said.t === \"r\";\n const peer = this.peer;\n const ringing = options.declineRinging === true && peer?.kind === \"o\" && peer.at > this.saidAt && this.now() - peer.at <= CALL_SIGNAL_MAX_AGE_MS ? peer : null;\n if (!ours && !ringing) return null;\n const ts = Math.max(this.now(), typeof said.ts === \"number\" ? said.ts + 1 : 0, ringing ? ringing.ts + 1 : 0);\n return this.set(JSON.stringify({ t: \"h\", ts }));\n }\n\n /**\n * The hang-up of a call this side placed or answered, for the transport to send should the app go without a word\n * (`FrameChannel.parting`: a logout ends the Desktop's page with the app), or null when no call of ours is on. Nothing\n * is said or changed here. Its time is just after this side's latest signal, so it stays the same until that changes;\n * a hang-up the page itself says on its way out too (`hangUp`) is no older, and finds the call over already.\n */\n parting(): PairedCallFrame | null {\n const said = this.said();\n const ours = said.t === \"o\" || said.t === \"a\" || said.t === \"v\" || said.t === \"r\";\n if (!ours || typeof said.ts !== \"number\") return null;\n return { t: PAIRED_CALL_FRAME, s: JSON.stringify({ t: \"h\", ts: said.ts + 1 }) };\n }\n\n private said(): { t?: unknown; ts?: unknown } {\n if (this.latest) try { return JSON.parse(this.latest.signal); } catch { /* no signal of ours */ }\n return {};\n }\n\n /** On a new session that carries calls: the latest signal again, if it is still fresh enough to act on. */\n pending(): PairedCallFrame | null {\n if (!this.latest) return null;\n if (this.now() - this.latest.at > CALL_SIGNAL_MAX_AGE_MS) { this.latest = null; return null; }\n return { t: PAIRED_CALL_FRAME, s: this.latest.signal };\n }\n}\n","import { xchacha20poly1305 } from \"@noble/ciphers/chacha.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { concatBytes, fromBase64Url, randomBytes, toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { identityFromSeed, publicKeyFromZ32, type Identity } from \"./identity\";\nimport type { GhostRecord } from \"./pkarr\";\n\n/**\n * Where the members of a `group-community/1` group find each other (WISP 903 · Group Community §\n * Topology): a **beacon** listing the current hubs, and a **lobby** per hub where a member asks\n * that hub for an edge. Both are Pkarr records under identities every member derives from the\n * group's rendezvous secret, sealed with a key from the same secret: relays see a key and an\n * opaque value. Several members write the same record, so a writer reads, merges and publishes.\n */\nexport const COMMUNITY_TOPOLOGY = {\n /** Hubs listed in the beacon, at most. */\n maxHubs: 8,\n /** Hubs wanted before a member settles for being a member. */\n minHubs: 2,\n /** Members one hub keeps edges with. */\n hubCapacity: 48,\n /** Hubs a member connects to: one; if it goes, the member asks another and a sync fills the gap. */\n hubsPerMember: 1,\n /** A hub republishes its beacon entry this often… */\n beaconEveryMs: 30_000,\n /** …and an entry older than this is stale. */\n beaconFreshMs: 90_000,\n /** Lobby entries: at most this many, fresh this long. */\n lobbyEntries: 6,\n lobbyFreshMs: 2 * 60_000,\n} as const;\n\nconst NONCE_LENGTH = 24;\nconst BEACON_LABEL = \"_hubs\";\nconst HEAD_LABEL = \"_head\";\nconst LOBBY_LABEL = \"_lobby\";\nconst info = (label: string) => utf8Encode(`ghostly-group-community/1 ${label}`);\n\n/** A hub as the beacon lists it: when it last said so (`ts`), since when it is a hub, and how many members it holds. */\nexport interface Hub { key: string; ts: number; load: number; since?: number }\nexport interface LobbyEntry { key: string; ts: number }\n\nfunction material(rv: Uint8Array, salt: Uint8Array, label: string): Uint8Array {\n return hkdf(sha256, rv, salt, info(label), 32);\n}\n\n/** The beacon's Pkarr identity and sealing key, for a group. */\nexport function beaconKeys(rvB64: string, groupId: string): { identity: Identity; key: Uint8Array; aad: Uint8Array } {\n const rv = fromBase64Url(rvB64), salt = utf8Encode(groupId);\n return { identity: identityFromSeed(material(rv, salt, \"beacon seed\")), key: material(rv, salt, \"beacon key\"), aad: utf8Encode(`beacon/${groupId}`) };\n}\n\n/** A hub's lobby: its Pkarr identity and sealing key. */\nexport function lobbyKeys(rvB64: string, groupId: string, hubKey: string): { identity: Identity; key: Uint8Array; aad: Uint8Array } {\n const rv = fromBase64Url(rvB64), salt = concatBytes(utf8Encode(groupId), publicKeyFromZ32(hubKey));\n return { identity: identityFromSeed(material(rv, salt, \"lobby seed\")), key: material(rv, salt, \"lobby key\"), aad: utf8Encode(`lobby/${groupId}/${hubKey}`) };\n}\n\nfunction seal(label: string, keys: { key: Uint8Array; aad: Uint8Array }, body: Uint8Array): GhostRecord[] {\n const nonce = randomBytes(NONCE_LENGTH);\n return [{ label, value: toBase64Url(concatBytes(nonce, xchacha20poly1305(keys.key, nonce, keys.aad).encrypt(body))) }];\n}\nfunction open(label: string, keys: { key: Uint8Array; aad: Uint8Array }, records: GhostRecord[]): Uint8Array | null {\n const value = records.find(r => r.label === label)?.value;\n if (!value || value.length > 900) return null;\n try {\n const bytes = fromBase64Url(value);\n return xchacha20poly1305(keys.key, bytes.slice(0, NONCE_LENGTH), keys.aad).decrypt(bytes.slice(NONCE_LENGTH));\n } catch { return null; }\n}\n\n/** 32-byte key, 4-byte time in seconds, then (beacon) one byte of load and 4 bytes of since (seconds). */\nfunction pack(entries: { key: string; ts: number; load?: number; since?: number }[], withLoad: boolean): Uint8Array {\n const size = 36 + (withLoad ? 5 : 0), out = new Uint8Array(entries.length * size), view = new DataView(out.buffer);\n entries.forEach((entry, i) => {\n out.set(publicKeyFromZ32(entry.key), i * size);\n view.setUint32(i * size + 32, Math.floor(entry.ts / 1000));\n if (withLoad) {\n out[i * size + 36] = Math.max(0, Math.min(255, entry.load ?? 0));\n view.setUint32(i * size + 37, Math.floor((entry.since ?? entry.ts) / 1000));\n }\n });\n return out;\n}\nfunction unpack(bytes: Uint8Array, withLoad: boolean, max: number): Hub[] {\n const size = 36 + (withLoad ? 5 : 0);\n if (bytes.length % size !== 0) return [];\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), out: Hub[] = [];\n for (let i = 0; i < bytes.length / size && out.length < max; i++) {\n try {\n const key = toZ32(bytes.slice(i * size, i * size + 32));\n publicKeyFromZ32(key);\n const ts = view.getUint32(i * size + 32) * 1000;\n out.push(withLoad ? { key, ts, load: bytes[i * size + 36], since: view.getUint32(i * size + 37) * 1000 } : { key, ts, load: 0 });\n } catch { /* not a key: skipped */ }\n }\n return out;\n}\n\n/**\n * The hubs that take turns at the door (WISP 903 § Admission): those that said so lately and have\n * been hubs for a minute, so that every hub, having read the beacon at least once since, agrees on\n * the same set. Only when there is none (a group's first minute), the one that has been a hub longest. And when none said so lately, a hub asking (`me`)\n * that sees no other fresh hub in the beacon is the door alone, listed or not: its own entry may not have reached the\n * relays yet (a new group's first hub, whose write the relays' budget holds back), and there is nobody to agree with.\n *\n * A hub that says since when it is one (`mine.since`) counts itself among those of the first minute, listed or not, so\n * the first hub whose entry is held back still reads itself as the door beside a newer hub's entry. And one that became\n * a hub less than a minute ago, reading no other hub but knowing of one (`mine.known`: the member who let it in, whose\n * entry may be the one held back), is not the door alone: that hub still is.\n */\nexport function doorHubs(hubs: Hub[], now = Date.now(), me?: string, mine?: { since: number; known: readonly string[] }): string[] {\n const lately = hubs.filter(h => now - h.ts < COMMUNITY_TOPOLOGY.beaconEveryMs * 1.5);\n const settled = lately.filter(h => now - (h.since ?? h.ts) >= 60_000);\n // None settled (a group's first minute): the hub that has been one longest, alone, and the lowest key between two of\n // the same second. A hub alone in the beacon reads it only when it republishes, so for half a minute it does not know\n // of a member that just became a hub; that member, counting both of them at the door with the lower key, answered\n // the same knock as the first hub did: two hubs on one entry session, where at best one of them looks 90 s for nobody.\n const since = (h: Hub) => Math.floor((h.since ?? h.ts) / 1000);\n const self = mine && me !== undefined && !lately.some(h => h.key === me) ? [{ key: me, ts: now, load: 0, since: mine.since }] : [];\n const first = [...lately, ...self].sort((a, b) => since(a) - since(b) || (a.key < b.key ? -1 : 1)).slice(0, 1);\n const door = (settled.length ? settled : first).map(h => h.key);\n if (me === undefined) return door;\n const alone = !freshHubs(hubs, now).some(h => h.key !== me);\n if (alone && mine && now - mine.since < 60_000 && mine.known.some(key => key !== me) && door.every(key => key === me)) return [];\n if (door.length || !alone) return door;\n return [me];\n}\n\n/**\n * The newest message frame a hub holds (WISP 903 · Group Community § Head): who sent it, in which epoch (number and\n * first 16 hex of its commit hash), its sequence and time. Hubs publish it beside the hub list, so a member's other\n * profile on the same device can tell something new was said without being online (WISP 04 § Checking other profiles).\n */\nexport interface CommunityHead { s: string; e: number; h: string; n: number; ts: number }\nconst HEAD_BYTES = 32 + 4 + 8 + 4 + 4;\n/** The head is sealed with the beacon's key under its own associated data: it cannot be passed off as a hub list. */\nconst headKeys = (keys: { key: Uint8Array; aad: Uint8Array }) => ({ key: keys.key, aad: concatBytes(keys.aad, utf8Encode(\"/head\")) });\nfunction packHead(head: CommunityHead): Uint8Array {\n const out = new Uint8Array(HEAD_BYTES), view = new DataView(out.buffer);\n out.set(publicKeyFromZ32(head.s), 0);\n view.setUint32(32, head.e);\n for (let i = 0; i < 8; i++) out[36 + i] = parseInt(head.h.slice(i * 2, i * 2 + 2), 16);\n view.setUint32(44, head.n);\n view.setUint32(48, Math.floor(head.ts / 1000));\n return out;\n}\nfunction unpackHead(bytes: Uint8Array): CommunityHead | null {\n if (bytes.length !== HEAD_BYTES) return null;\n try {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), s = toZ32(bytes.slice(0, 32));\n publicKeyFromZ32(s);\n const h = Array.from(bytes.slice(36, 44), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return { s, e: view.getUint32(32), h, n: view.getUint32(44), ts: view.getUint32(48) * 1000 };\n } catch { return null; }\n}\n/** A frame can be a head: a member key, and numbers that fit. */\nexport function validHead(head: CommunityHead | null | undefined): head is CommunityHead {\n if (!head || !/^[0-9a-f]{16}$/.test(head.h) || ![head.e, head.n].every(n => Number.isSafeInteger(n) && n >= 0 && n <= 0xffffffff) || !Number.isSafeInteger(head.ts) || head.ts < 0 || head.ts / 1000 > 0xffffffff) return false;\n try { publicKeyFromZ32(head.s); return true; } catch { return false; }\n}\n/** The newer of two heads, by time; a head from more than a minute ahead of now is not taken. */\nexport function newerHead(a: CommunityHead | null, b: CommunityHead | null, now = Date.now()): CommunityHead | null {\n const ok = (h: CommunityHead | null) => (h && h.ts <= now + 60_000 ? h : null);\n const x = ok(a), y = ok(b);\n return !x ? y : !y ? x : y.ts > x.ts ? y : x;\n}\n\nexport function beaconRecords(keys: { key: Uint8Array; aad: Uint8Array }, hubs: Hub[], head?: CommunityHead | null): GhostRecord[] {\n return [...seal(BEACON_LABEL, keys, pack(hubs.slice(0, COMMUNITY_TOPOLOGY.maxHubs), true)),\n ...(validHead(head) ? seal(HEAD_LABEL, headKeys(keys), packHead(head)) : [])];\n}\n/** The head a beacon packet carries, if a hub of this revision wrote it last (an older hub's publication drops it). */\nexport function readBeaconHead(keys: { key: Uint8Array; aad: Uint8Array }, records: GhostRecord[]): CommunityHead | null {\n const body = open(HEAD_LABEL, headKeys(keys), records);\n return body ? unpackHead(body) : null;\n}\nexport function readBeacon(keys: { key: Uint8Array; aad: Uint8Array }, records: GhostRecord[]): Hub[] {\n const body = open(BEACON_LABEL, keys, records);\n return body ? unpack(body, true, COMMUNITY_TOPOLOGY.maxHubs) : [];\n}\nexport function lobbyRecords(keys: { key: Uint8Array; aad: Uint8Array }, entries: LobbyEntry[]): GhostRecord[] {\n return seal(LOBBY_LABEL, keys, pack(entries.slice(-COMMUNITY_TOPOLOGY.lobbyEntries), false));\n}\nexport function readLobby(keys: { key: Uint8Array; aad: Uint8Array }, records: GhostRecord[]): LobbyEntry[] {\n const body = open(LOBBY_LABEL, keys, records);\n return body ? unpack(body, false, COMMUNITY_TOPOLOGY.lobbyEntries).map(({ key, ts }) => ({ key, ts })) : [];\n}\n\n/**\n * The beacon to publish: my entry (or none, `mine` null, when I step down) with the other fresh\n * hubs, newest first, at most `maxHubs`. A hub not in the roster any more is dropped.\n *\n * Anyone holding the rendezvous secret writes this record, so what is in it does not decide what stays: my entry always\n * does, then the keys I know as members (`known`) before keys I do not, and an entry dated ahead of now ranks as one of\n * now. Entries stay as their hubs dated them.\n */\nexport function mergeBeacon(existing: Hub[], me: string, mine: Hub | null, now = Date.now(), isMember: (key: string) => boolean = () => true, known: (key: string) => boolean = () => true): Hub[] {\n const fresh = existing.filter(h => h.key !== me && now - h.ts < COMMUNITY_TOPOLOGY.beaconFreshMs && h.ts <= now + 60_000 && isMember(h.key));\n const rank = (h: Hub) => (known(h.key) ? 0 : 1);\n const others = fresh.sort((a, b) => rank(a) - rank(b) || Math.min(b.ts, now) - Math.min(a.ts, now));\n return (mine ? [mine, ...others] : others).slice(0, COMMUNITY_TOPOLOGY.maxHubs);\n}\n\n/** The lobby to publish: my request refreshed, others' still fresh, newest last. */\nexport function mergeLobby(existing: LobbyEntry[], mine: LobbyEntry, now = Date.now()): LobbyEntry[] {\n const fresh = existing.filter(e => e.key !== mine.key && now - e.ts < COMMUNITY_TOPOLOGY.lobbyFreshMs && e.ts <= now + 60_000);\n return [...fresh.sort((a, b) => a.ts - b.ts).slice(-(COMMUNITY_TOPOLOGY.lobbyEntries - 1)), mine];\n}\n\n/** Fresh hubs of a beacon, as a member sees them. */\nexport function freshHubs(hubs: Hub[], now = Date.now()): Hub[] {\n return hubs.filter(h => now - h.ts < COMMUNITY_TOPOLOGY.beaconFreshMs && h.ts <= now + 60_000);\n}\n\nconst rankHash = (subject: string, hubKey: string): Uint8Array => sha256(concatBytes(utf8Encode(\"ghostly-group-community/1 rank\"), publicKeyFromZ32(subject), publicKeyFromZ32(hubKey)));\n/** Rendezvous hashing: how strongly a hub is responsible for someone (a knock, a member). Highest first. */\nexport function hubRank(subject: string, hubKey: string): string {\n return toBase64Url(rankHash(subject, hubKey));\n}\n/**\n * `hubs` by `hubRank` for `subject`, highest first. Each key's rank is worked out once: in the sort's comparator it\n * was two hashes a comparison, ~16 a key for a community's roster, which members rank on each tick of a hub's step-in.\n */\nexport function rankHubs(subject: string, hubs: string[]): string[] {\n const rank = new Map(hubs.map(key => [key, hubRank(subject, key)]));\n return [...hubs].sort((a, b) => { const ra = rank.get(a)!, rb = rank.get(b)!; return ra < rb ? 1 : ra > rb ? -1 : 0; });\n}\n\n/**\n * The hubs a member asks for edges: fresh ones with room, at most `hubsPerMember`, by rendezvous hashing weighted by\n * the room each has left, so the members picking at once spread over the hubs in proportion to it. The members a\n * closing hub carried all pick in the same second: each took the least loaded hub, all of them the same one, which\n * opened their 12 or 16 edges at once on its relays' budget and brought none up for minutes, then the next hub did the\n * same, and 6 of them stepped up as hubs with nobody on them (36 members, bug hunt, 2026-11-11).\n */\nexport function pickHubs(me: string, hubs: Hub[], now = Date.now(), avoid: ReadonlySet<string> = new Set()): string[] {\n // A hub that republished lately first (one whose app closed stays listed a while).\n const lately = (h: Hub) => now - h.ts < COMMUNITY_TOPOLOGY.beaconEveryMs * 1.5 ? 0 : 1;\n const open = freshHubs(hubs, now).filter(h => h.key !== me && !avoid.has(h.key) && h.load < COMMUNITY_TOPOLOGY.hubCapacity)\n .map(h => ({ key: h.key, lately: lately(h), score: spreadScore(me, h) }))\n .sort((a, b) => a.lately - b.lately || b.score - a.score);\n return open.slice(0, COMMUNITY_TOPOLOGY.hubsPerMember).map(h => h.key);\n}\n\n/** Weighted rendezvous hashing: room / -ln(u), u in (0, 1) from this member's rank of the hub; the highest is picked. */\nfunction spreadScore(me: string, hub: Hub): number {\n const r = rankHash(me, hub.key);\n const u = (r[0] * 65_536 + r[1] * 256 + r[2] + 0.5) / 16_777_216;\n return (COMMUNITY_TOPOLOGY.hubCapacity - hub.load) / -Math.log(u);\n}\n\n/** Should this member be a hub? Too few fresh hubs, or all full, and room in the beacon. */\nexport function shouldBeHub(me: string, hubs: Hub[], now = Date.now()): boolean {\n const fresh = freshHubs(hubs, now).filter(h => h.key !== me);\n if (fresh.length >= COMMUNITY_TOPOLOGY.maxHubs) return false;\n return fresh.length < COMMUNITY_TOPOLOGY.minHubs || fresh.every(h => h.load >= COMMUNITY_TOPOLOGY.hubCapacity);\n}\n","import { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { toBase64Url, utf8Encode } from \"./bytes\";\nimport { COMMUNITY_TOPOLOGY, freshHubs, rankHubs, type Hub } from \"./communityRendezvous\";\nimport { MEMBER_KEY } from \"./groupCommits\";\n\n/**\n * Hubs in a private (mesh) group (WISP 902 · Group Mesh § Hubs). Up to `threshold` members a group is a full mesh, as\n * before. Past it, members that stay online (the Desktop app and the CLI, or members the admin pins) become **hubs**:\n * they keep edges with every other hub and with the members that ask them, and pass on every frame they take. The\n * other members keep edges with `hubsPerMember` hubs only. Frames are author-signed and sealed under the epoch key, and\n * hubs are members, so what a hub passes on is what any member hands on in a catch-up (§ Catch-up): it can withhold a\n * frame, never read more than it could already, alter or forge one.\n *\n * Where hubs are found is the community profile's machinery (`communityRendezvous.ts`): a sealed Pkarr **beacon**\n * listing them, and a **lobby** per hub where a member asks for an edge. The community derives both from the secret its\n * link carries; a private group has no such secret, so they derive from a rendezvous secret of the **current epoch**\n * (`meshRendezvous`). The beacon moves with every commit, and someone removed cannot read or write the next one.\n */\nexport const MESH_HUBS = {\n /** Members up to which a group stays a full mesh, whatever hubs there are. */\n threshold: 16,\n /** Hubs a member keeps edges with, when there are that many: one to spare, so losing a hub loses nothing. */\n hubsPerMember: 2,\n /** Hubs listed at most (the beacon's own bound). */\n maxHubs: COMMUNITY_TOPOLOGY.maxHubs,\n /** Members one hub holds before members prefer another: hubs with room first, a full one rather than none. */\n hubCapacity: COMMUNITY_TOPOLOGY.hubCapacity,\n /** Members the admin pins, and excludes, at most. */\n pinned: 8,\n excluded: 32,\n} as const;\n\n/** The `paired-groups` version an app announces when it takes part in a mesh group's hubs (it may pass frames on). */\nexport const GROUP_VERSION_HUBS = 4;\n\n/**\n * The epoch's rendezvous secret, which `beaconKeys` and `lobbyKeys` take as the community takes its link's: HKDF-SHA-256\n * of the epoch secret, salted by the group id and the epoch, under a label of its own (it can never be the message key).\n */\nexport function meshRendezvous(epochSecret: Uint8Array, groupId: string, epoch: number): string {\n if (epochSecret.length !== 32) throw new Error(\"Invalid epoch secret\");\n return toBase64Url(hkdf(sha256, epochSecret, utf8Encode(`${groupId}/${epoch}`), utf8Encode(\"ghostly-group-mesh/1 rendezvous\"), 32));\n}\n\n/** What the admin says about hubs, in the group's metadata (`hubs` in the body): members pinned as hubs, and excluded. */\nexport interface MeshHubPolicy { pin: string[]; no: string[] }\nexport const NO_HUB_POLICY: MeshHubPolicy = { pin: [], no: [] };\n\n/** A policy as the body carries it: distinct member keys, within the bounds, none both pinned and excluded. Null when it is not one. */\nexport function parseHubPolicy(raw: unknown): MeshHubPolicy | null {\n if (raw === undefined) return NO_HUB_POLICY;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const { pin, no } = raw as Record<string, unknown>;\n const keys = (v: unknown, max: number): string[] | null => {\n if (v === undefined) return [];\n if (!Array.isArray(v) || v.length > max || !v.every(k => typeof k === \"string\" && MEMBER_KEY.test(k)) || new Set(v).size !== v.length) return null;\n return [...v as string[]].sort();\n };\n const p = keys(pin, MESH_HUBS.pinned), n = keys(no, MESH_HUBS.excluded);\n if (!p || !n || p.some(k => n.includes(k))) return null;\n return { pin: p, no: n };\n}\n\n/** The policy as the body writes it: nothing when it says nothing. */\nexport function wireHubPolicy(policy: MeshHubPolicy): MeshHubPolicy | undefined {\n return policy.pin.length || policy.no.length ? { pin: [...policy.pin].sort(), no: [...policy.no].sort() } : undefined;\n}\n\n/**\n * Whether a member may be a hub: in the roster, not excluded, and either pinned by the admin or on an app that stays\n * online (`staysOnline`, which only the member's own app knows; others go by what the beacon says).\n */\nexport function mayBeHub(key: string, policy: MeshHubPolicy, inRoster: (key: string) => boolean, staysOnline: boolean): boolean {\n return inRoster(key) && !policy.no.includes(key) && (staysOnline || policy.pin.includes(key));\n}\n\n/**\n * The hubs of the beacon a member counts on: fresh, in the roster, not excluded, not itself. Everyone filters the same\n * way, so a member the admin excluded, or someone removed, who lists itself anyway is listed for nobody.\n */\nexport function meshHubs(hubs: Hub[], me: string, policy: MeshHubPolicy, inRoster: (key: string) => boolean, now = Date.now()): Hub[] {\n return freshHubs(hubs, now).filter(h => h.key !== me && inRoster(h.key) && !policy.no.includes(h.key));\n}\n\n/**\n * The hubs a member keeps edges with: `hubsPerMember` of them, by rendezvous rank for this member, so the members\n * spread over the hubs and a hub that goes moves only its own members. First hubs with room that republished lately,\n * then full ones (a hub keeps an edge with every member, so a full one is only a busier one), then hubs that may be\n * gone (their app closed; they stay listed a while), and hubs to `avoid` (they did not take me) last.\n */\nexport function pickMeshHubs(me: string, hubs: Hub[], now = Date.now(), avoid: ReadonlySet<string> = new Set()): string[] {\n const lately = (h: Hub) => now - h.ts < COMMUNITY_TOPOLOGY.beaconEveryMs * 1.5;\n const room = (h: Hub) => h.load < MESH_HUBS.hubCapacity;\n const ranked = (list: Hub[]) => rankHubs(me, list.map(h => h.key));\n const tiers = [(h: Hub) => lately(h) && room(h), (h: Hub) => lately(h), () => true];\n const order: string[] = [];\n for (const tier of tiers) for (const key of ranked(hubs.filter(h => h.key !== me && !avoid.has(h.key) && tier(h)))) if (!order.includes(key)) order.push(key);\n for (const key of ranked(hubs.filter(h => h.key !== me && avoid.has(h.key)))) if (!order.includes(key)) order.push(key);\n return order.slice(0, MESH_HUBS.hubsPerMember);\n}\n","import { fromBase64Url, toBase64Url } from \"./bytes\";\nimport { GROUP_ID, MEMBER_KEY } from \"./groupCommits\";\nimport type { Identity } from \"./identity\";\nimport { createRelayPayload, newerPacket, parseRelayPayload, RELAY_PAYLOAD_MAX_BYTES, type GhostRecord, type SignedPacket } from \"./pkarr\";\nimport { budgetRetryMs, isDiscoveryBudgetError, type PkarrRequestOptions, type PkarrTransport } from \"./transport\";\n\n/**\n * Edge signaling through members (WISP 902 · Group Mesh § Signaling through members). An edge of a private group is a\n * paired link, and its presence, offer and answer are Pkarr packets: each costs relay requests, of which an app allows\n * itself 30 a minute per relay, and each is seen at the other end's next poll. A member that joins a group of eight\n * opens seven edges at once, and the admin reads the link's knocks meanwhile: the minute was spent before the edges\n * were up, and what was left waited for it to free (40 to 75 s for a fifth member on two relays, 2026-10-01).\n *\n * Two members about to open an edge usually both have an open link to a third: the admin that just admitted one of\n * them, any member both already reach. That member **carries** the packet: the very bytes a relay would store, signed\n * by the edge's key, which only the two ends can derive. The carrier can neither read nor forge it (to it, as to a\n * relay, it is an opaque signed blob), and the receiver takes it exactly as it takes a relay's answer. The relays still\n * get the packet, a moment later and only the newest one, so an edge that opens through members costs one publish\n * where it cost three and several reads.\n */\n\n/** The `paired-groups` version an app announces when it carries and takes edge signaling through members. */\nexport const GROUP_VERSION_SIGNALS = 5;\nexport const GROUP_SIGNAL_FRAME = \"group-signal\" as const;\n/**\n * How long a packet handed to carriers waits before it goes to the relays too. An edge that opens meanwhile publishes\n * its settled packet instead, and this one never goes; with nothing heard from the other end by then (its app is older,\n * or no member reaches both), the relays get it and the edge goes on as before, this much later, once.\n */\nexport const CARRIED_DEFER_MS = 1_500;\n/** Carriers a packet is handed to at most: two members down at once is rare, and every copy costs the receiver a frame. */\nexport const SIGNAL_CARRIERS = 2;\n/** Frames of one member a carrier passes on per minute: a member joining a group of 32 sends about a hundred. */\nexport const SIGNALS_PER_MINUTE = 240;\n/**\n * How long after a carried packet came from the other end the way through members counts as known to work: its own\n * packets then wait before going to the relays (`CARRIED_DEFER_MS`).\n */\nexport const SIGNAL_PROVEN_MS = 10_000;\n/**\n * How long a member keeps a frame it cannot pass on yet: the edge to whom it is for is often a moment from up (the\n * member was just admitted, or its app just came back and its edges open one after the other).\n */\nexport const SIGNAL_HOLD_MS = 5_000;\n/** After a carried packet came from a member, mine goes back the same way at most this often. */\nexport const SIGNAL_REPLY_MS = 30_000;\n/**\n * How far from this clock a carried packet's time may be. Signaling is live: an offer is answered within seconds or\n * given up. A member that kept another's old offer cannot hand it on later as if it were new; a packet from a clock\n * further off than this is left to the relays, as before.\n */\nexport const SIGNAL_FRESH_MS = 2 * 60_000;\nconst B64 = /^[A-Za-z0-9_-]+$/;\nconst MAX_B64 = Math.ceil(RELAY_PAYLOAD_MAX_BYTES * 4 / 3);\n\n/** `p`: the relay payload (signature, timestamp, DNS packet) as a relay would take it. `h`: passed on once already. */\nexport interface GroupSignalFrame { t: typeof GROUP_SIGNAL_FRAME; g: string; to: string; from: string; p: string; h?: 1 }\n\nexport function groupSignalFrame(g: string, from: string, to: string, payload: Uint8Array, hop = false): GroupSignalFrame {\n return { t: GROUP_SIGNAL_FRAME, g, to, from, p: toBase64Url(payload), ...(hop ? { h: 1 as const } : {}) };\n}\n\n/** A well-formed `group-signal`, or null. Its packet is checked by whoever it is for (`CarriedTransport.accept`). */\nexport function readGroupSignal(raw: unknown): { g: string; to: string; from: string; payload: Uint8Array; hop: boolean } | null {\n if (!raw || typeof raw !== \"object\") return null;\n const f = raw as Record<string, unknown>;\n if (f.t !== GROUP_SIGNAL_FRAME || typeof f.g !== \"string\" || !GROUP_ID.test(f.g)) return null;\n if (typeof f.to !== \"string\" || !MEMBER_KEY.test(f.to) || typeof f.from !== \"string\" || !MEMBER_KEY.test(f.from) || f.to === f.from) return null;\n if (typeof f.p !== \"string\" || f.p.length > MAX_B64 || !B64.test(f.p)) return null;\n if (f.h !== undefined && f.h !== 1) return null;\n try { return { g: f.g, to: f.to, from: f.from, payload: fromBase64Url(f.p), hop: f.h === 1 }; } catch { return null; }\n}\n\nexport interface CarriedHooks {\n /**\n * Hands my packet for this edge to links that may pass it on. `taken`: how many took it (0: nobody could). `sure`:\n * one of them reaches the other end as far as anyone can tell (a link of the two of us beside the edge, or the\n * admin, which keeps an edge with everyone), so the relays can wait even before anything came back that way.\n */\n carry(payload: Uint8Array): { taken: number; sure: boolean };\n /** Whether `carry` would hand a packet to any link now (none: every member that could pass it on is away). */\n canCarry?(): boolean;\n /** The edge's own data link is open: it carries everything, and nothing is handed to anyone. */\n open(): boolean;\n /** A carried packet of the member's is here and no read is under way: look now. */\n look(): void;\n /**\n * Hands my packet to the member over this edge's own data link while it is open: false when it could not go (the\n * member's app takes no carried packets, or the link closed).\n */\n direct?(payload: Uint8Array): boolean;\n /** `CARRIED_DEFER_MS`, for tests. */\n deferMs?: number;\n /**\n * The date of the last packet an earlier transport of this edge signed (`lastDated`), before the edge started again:\n * mine are dated past it. Dated by the clock alone, the first packet of an edge started again in the same millisecond\n * (its WebRTC gave up, `edgeWithoutRtc`) was no newer than the last one, and a relay refused it (409).\n */\n after?: bigint;\n}\n\n/**\n * The Pkarr transport of one edge, with members carrying its packets beside the relays. Publishes under the edge's own\n * key and reads of the member's key go through it; anything else goes straight to the transport underneath.\n */\nexport class CarriedTransport implements PkarrTransport {\n /** My last packet while the edge is down: what a member that just became reachable is handed. */\n private mine: Uint8Array | null = null;\n /** The records `mine` holds, as members last took them, and when. */\n private handed: { said: string; at: number } | null = null;\n private lastTimestamp = 0n;\n /** The date each packet `stamp` signed carries: the relays' transport takes it rather than check the signature again. */\n private readonly dated = new WeakMap<Uint8Array, bigint>();\n /** My newest packet, wherever it went: what the edge hands the member over itself once it is ready (`linkReady`). */\n private newest: Uint8Array | null = null;\n /** The newest packet of the member's that came through a carrier, and the timestamp of the one a read last returned. */\n private carried: SignedPacket | null = null;\n private returned = -1n;\n /** The newest packet of the member's any read returned, from the relays or a carrier: nothing older is taken after it. */\n private seen = -1n;\n /** A read under way: resolved when a carried packet comes meanwhile. */\n private waiting: (() => void) | null = null;\n /** The records of a publish refused before they were signed, while nobody could carry them: signed when one can (`latest`). */\n private unsigned: { identity: Identity; records: GhostRecord[] } | null = null;\n /** The packet the relays have not got yet. */\n private pending: { identity: Identity; records: GhostRecord[]; payload: Uint8Array; options?: PkarrRequestOptions; timer: ReturnType<typeof setTimeout>; heardBefore: number; ended: Promise<\"ended\">; end: () => void } | null = null;\n /** How many carried packets of the member's came: a deferral that ends with none more says no member reaches it. */\n private heard = 0;\n /** When the last one came (`SIGNAL_PROVEN_MS`). */\n private heardAt = -Infinity;\n /** No member reached the other end: packets go to the relays at once until one does. */\n private quiet = false;\n private stopped = false;\n readonly publishPayload?: PkarrTransport[\"publishPayload\"];\n readonly discovery?: PkarrTransport[\"discovery\"];\n readonly subscribe?: PkarrTransport[\"subscribe\"];\n readonly networkChanged?: PkarrTransport[\"networkChanged\"];\n readonly configure?: PkarrTransport[\"configure\"];\n\n constructor(private readonly inner: PkarrTransport, private readonly myKey: string, private readonly peerKey: string, private readonly hooks: CarriedHooks) {\n this.lastTimestamp = hooks.after ?? 0n;\n if (inner.publishPayload) this.publishPayload = (key, payload, options) => inner.publishPayload!(key, payload, options);\n if (inner.discovery) this.discovery = () => inner.discovery!();\n if (inner.subscribe) this.subscribe = listener => inner.subscribe!(listener);\n if (inner.networkChanged) this.networkChanged = () => inner.networkChanged!();\n if (inner.configure) this.configure = options => inner.configure!(options);\n // No `publishHeld` for the link above: down, its packet goes through members whatever the relays say (`publish`).\n }\n\n describe(): { protocol: string; relays: string[] } { return this.inner.describe(); }\n\n async publish(identity: Identity, records: GhostRecord[], options?: PkarrRequestOptions): Promise<void> {\n if (this.stopped || identity.pubKeyZ32 !== this.myKey) return this.inner.publish(identity, records, options);\n this.drop();\n this.unsigned = null;\n // Up: the edge carries everything, and its packet on the relays (it is here, its offer is settled) is nothing\n // anyone waits for. It goes as a background write, behind the links that are signaling (a new offer of its own aside).\n if (this.hooks.open()) {\n const relayOptions = options?.signal ? options : { ...options, background: true };\n // No relay takes it now: refused before it is signed and dated, as a chat's (`RelayTransport.publishDated`); the\n // link tries again when the wait says. A hub at its budget signed ~450-670 edge packets a minute that never went\n // out, 8-10% of its busy CPU (agents#1573). Down, a packet is signed whatever the relays say: members carry it.\n const held = this.inner.publishHeld?.(identity.pubKeyZ32, relayOptions);\n if (held) throw held;\n this.mine = null;\n const payload = this.newest = this.stamp(identity, records);\n const published = this.toRelays(identity, records, payload, relayOptions);\n if (this.hooks.direct && this.inner.publishPayload) void published.then(() => this.handDirect(payload), () => { /* the link publishes again, and hands it then */ });\n return published;\n }\n // Down, and no member to hand it to: refused before it is signed when no relay takes it either, as when up. Its\n // records wait for a member that can carry them (`latest`). With every member away, 10 groups' 30 edges signed ~80\n // packets a minute that went nowhere.\n if (this.hooks.canCarry && !this.hooks.canCarry()) {\n const held = this.inner.publishHeld?.(identity.pubKeyZ32, options);\n if (held) { this.unsigned = { identity, records }; throw held; }\n }\n // The records members took a moment ago (`SIGNAL_REPLY_MS`), again: the link trying once more what the relays' budget\n // held back. Members have them: the relays get that very packet. Signed and handed again at each try, an edge to a\n // member who left sent two frames every few seconds that no member could pass on (35 KB a minute on an idle web app\n // with two such edges, bug hunt 2026-11-08). A member who can pass it on later is handed it then (`latest`).\n const said = JSON.stringify(records);\n if (this.mine && this.handed?.said === said && Date.now() - this.handed.at < SIGNAL_REPLY_MS) return this.toRelays(identity, records, this.mine, options);\n const payload = this.newest = this.stamp(identity, records);\n this.mine = payload;\n let carried = { taken: 0, sure: false };\n try { carried = this.hooks.carry(payload); } catch { /* nobody took it */ }\n this.handed = carried.taken ? { said, at: Date.now() } : null;\n // The relays wait only when the way through members is known to work, or as good as: a member that took the\n // packet may not reach the other end (after a restart, two members answering the same one each hold the other's\n // answer), and an answer held back for nothing is read a poll later.\n const proven = Date.now() - this.heardAt < SIGNAL_PROVEN_MS;\n if (!carried.taken || this.quiet || !(carried.sure || proven)) return this.toRelays(identity, records, payload, options);\n let end!: () => void;\n const ended = new Promise<\"ended\">(resolve => { end = () => resolve(\"ended\"); });\n this.pending = { identity, records, payload, options, heardBefore: this.heard, ended, end, timer: setTimeout(() => this.flush(), this.hooks.deferMs ?? CARRIED_DEFER_MS) };\n }\n\n /**\n * My next packet for this edge, signed and dated: each newer than the last, as the relays' copy keeps them, and past\n * `after` (what a relay that refused one holds).\n */\n private stamp(identity: Identity, records: GhostRecord[], after = 0n): Uint8Array {\n const now = BigInt(Date.now()) * 1000n, floor = after > this.lastTimestamp ? after : this.lastTimestamp;\n this.lastTimestamp = now > floor ? now : floor + 1n;\n const payload = createRelayPayload(identity, records, this.lastTimestamp);\n this.dated.set(payload, this.lastTimestamp);\n return payload;\n }\n\n /** The date of the last packet this transport signed (0 for none): an edge started again dates its own past it. */\n lastDated(): bigint { return this.lastTimestamp; }\n\n /**\n * The relays get the very packet members carried or the edge itself handed over, byte for byte, where the transport\n * can put a payload signed here: a copy dated again by the relays' transport was a packet the member had not seen,\n * and its first read after this app said goodbye took it for a sign that the app was back already. It dialled: two\n * writes and fast looks for an app that was gone, and an offer left on the relays that this app could answer after\n * its restart and then wait 40 s for (7 of 16 goodbyes on the admin in the member-back runs, 1 of 16 on dev, 2026-10-03).\n */\n // `publishPayload` does not move `RelayTransport.nextTimestamp` for this key: a packet the relays' transport dates\n // later (the goodbye after `stop()`) is dated by its own clock, past this one unless both fall in one millisecond.\n // Signed here, it says its date (`signedAt`): about 200 ms a minute of a hub's CPU went to checking its own packets.\n // A relay holding a copy dated at or after it (409) gets the same records signed again past that copy (`redate`),\n // while this is still my newest packet.\n private toRelays(identity: Identity, records: GhostRecord[], payload: Uint8Array, options?: PkarrRequestOptions): Promise<void> {\n const signedAt = this.dated.get(payload);\n let current = payload;\n const redate = (after: bigint) => {\n if (this.newest !== current) return null;\n const again = this.stamp(identity, records, after);\n if (this.mine === current) this.mine = again;\n this.newest = current = again;\n return { payload: again, signedAt: this.lastTimestamp };\n };\n return this.inner.publishPayload\n ? this.inner.publishPayload(identity.pubKeyZ32, payload, signedAt === undefined ? options : { ...options, signedAt, redate })\n : this.inner.publish(identity, records, options);\n }\n\n /**\n * The packet the relays just took, handed to the member over the edge itself while it is up. An edge up reads nothing\n * from the relays until its slow look, so the member's app would otherwise meet that packet first after a goodbye.\n */\n private handDirect(payload: Uint8Array): void {\n if (this.stopped || !this.hooks.open()) return;\n try { this.hooks.direct?.(payload); } catch { /* it closed */ }\n }\n\n /**\n * The edge is up and the member's app takes carried packets: my newest packet goes over it. The one that went as the\n * edge opened (before its session was ready, so to the relays, or to members) is often one the member never read.\n * A packet it has already is dropped on its side.\n */\n linkReady(): void {\n if (this.newest && this.inner.publishPayload) this.handDirect(this.newest);\n }\n\n /** The deferred packet goes to the relays: the edge did not open meanwhile. Tried again while it is still the newest. */\n private flush(): void {\n const pending = this.pending;\n if (!pending || this.stopped) return;\n pending.end();\n // Nothing came back through a member: none reaches the other end (or its app does not take carried packets).\n if (this.heard === pending.heardBefore) this.quiet = true;\n this.toRelays(pending.identity, pending.records, pending.payload, pending.options).then(\n () => { if (this.pending === pending) this.pending = null; },\n error => {\n if (this.pending !== pending || this.stopped) return;\n pending.heardBefore = this.heard;\n pending.timer = setTimeout(() => this.flush(), isDiscoveryBudgetError(error) ? budgetRetryMs(error, 250, 4_000) : 4_000);\n });\n }\n\n private drop(): void {\n if (this.pending) { clearTimeout(this.pending.timer); this.pending.end(); }\n this.pending = null;\n }\n\n async resolve(pubKeyZ32: string, options?: PkarrRequestOptions): Promise<SignedPacket | null> {\n if (pubKeyZ32 !== this.peerKey) return this.inner.resolve(pubKeyZ32, options);\n // One that came since the last read: that is the news, and it costs no request.\n if (this.carried && this.carried.timestampMicros > this.returned) return this.take(null);\n // Up, through packets members carried a moment ago: the relays hold nothing newer than what brought the edge up,\n // and the look a link takes right after it opens would be a request for nothing. The slow look of a connected\n // link, a minute on, asks them as before.\n if (this.carried && this.hooks.open() && Date.now() - this.heardAt < SIGNAL_PROVEN_MS) return this.take(null);\n let came!: () => void;\n const carried = new Promise<\"carried\">(resolve => { came = () => resolve(\"carried\"); });\n this.waiting = came;\n try {\n // My packet is with members and not yet on the relays: the answer comes back the way it went, and a relay asked\n // now would only say it has nothing. The relays are read once that wait is over.\n if (this.pending && await Promise.race([carried, this.pending.ended]) === \"carried\") return this.take(null);\n const read = this.inner.resolve(pubKeyZ32, options).then(packet => ({ packet }), (error: unknown) => ({ error }));\n const first = await Promise.race([read, carried]);\n if (first === \"carried\") return this.take(null);\n if (\"error\" in first) {\n // The relays did not answer (their budget, an outage): what a member carried is what is known.\n if (this.carried) return this.take(null);\n throw first.error;\n }\n return this.take(first.packet);\n } finally {\n if (this.waiting === came) this.waiting = null;\n }\n }\n\n private take(read: SignedPacket | null): SignedPacket | null {\n if (this.carried) this.returned = this.carried.timestampMicros;\n const newest = newerPacket(read, this.carried);\n if (newest && newest.timestampMicros > this.seen) this.seen = newest.timestampMicros;\n return newest;\n }\n\n /**\n * A packet a member carried here. True when it is the member's (its signature holds under the edge's key), of now\n * (`SIGNAL_FRESH_MS`) and newer than any seen before, carried or read: the next read answers with it, at once.\n * `direct`: the member handed it over this edge itself while it was up (`CarriedHooks.direct`), which says nothing\n * about whether other members reach it.\n */\n accept(payload: Uint8Array, direct = false): boolean {\n if (this.stopped) return false;\n let packet: SignedPacket;\n try { packet = parseRelayPayload(this.peerKey, payload); } catch { return false; }\n const age = BigInt(Date.now()) * 1000n - packet.timestampMicros, fresh = BigInt(SIGNAL_FRESH_MS) * 1000n;\n if (age > fresh || age < -fresh || packet.timestampMicros <= this.seen) return false;\n if (this.carried && packet.timestampMicros <= this.carried.timestampMicros) return false;\n this.carried = packet;\n if (!direct) {\n this.heard++;\n this.heardAt = Date.now();\n this.quiet = false;\n }\n const waiting = this.waiting;\n this.waiting = null;\n if (waiting) waiting(); else this.hooks.look();\n return true;\n }\n\n /** My newest packet for this edge while it is down, for a member that can pass it on now; null once it is up. */\n latest(): Uint8Array | null {\n if (this.stopped || this.hooks.open()) return null;\n if (this.unsigned) {\n const { identity, records } = this.unsigned;\n this.unsigned = null;\n // Other records than the ones handed last: a publish of those must not send this packet (`handed`).\n this.handed = null;\n this.mine = this.newest = this.stamp(identity, records);\n }\n return this.mine;\n }\n\n /** The edge is going: nothing more is deferred or carried, and a last packet goes straight to the relays. */\n stop(): void {\n this.stopped = true;\n this.drop();\n this.mine = null;\n this.unsigned = null;\n const waiting = this.waiting;\n this.waiting = null;\n waiting?.();\n }\n}\n","import { formatFileSize, sanitizeFileName, sanitizeMime } from \"./files\";\nimport { parseImageMeta, type ImageMeta } from \"./image\";\nimport { parseVideoMeta, type VideoMeta } from \"./video\";\nimport { fileMessageText, formatVoiceDuration, parseVoiceMeta, type VoiceMeta } from \"./voice\";\n\n/**\n * Files and voice messages in groups (WISP 503 · Group Files). A file is announced as a group message carrying its\n * description; its bytes go over `files/3` between two members, from a member that holds it to one that asks for it.\n * The limits below are the profile's first numbers, kept in one place so they are easy to change.\n */\nexport const GROUP_FILE_LIMITS = {\n /** The largest file a group takes. */\n maxBytes: 100 * 1024 * 1024,\n /** A file this size or smaller is fetched without asking, a voice message too (one recorded is well inside it). */\n autoBytes: 8 * 1024 * 1024,\n /** What a device keeps of a group's files it fetched without asking; past it, every file is asked about. */\n autoBytesPerGroup: 256 * 1024 * 1024,\n /** Bytes of group files a device serves to others in a day, when serving is on. */\n serveBytesPerDay: 1024 * 1024 * 1024,\n /** Transfers a holder serves at once, all groups together. */\n serveAtOnce: 3,\n /** Bytes a served transfer gets confirmed (or the rest of its file) for it to count as moving in `wantWaitMs`. */\n serveMoveBytes: 16 * 1024,\n /** How long a served transfer keeps its place while all are taken and another member asks: past it, the place is theirs. */\n servePlaceMs: 5 * 60_000,\n /**\n * A served transfer's pace is what it confirmed in the last `servePaceMs` (at most twice that), counted from its offer.\n * While all places are taken and a member holding none asks or waits, the slowest served that long gives it its place,\n * if at its pace more is left to go than it has been served and than `servePaceMs`: members on fast links do not wait\n * for slow ones that asked first. Each member's transfer of a file loses its place so once per holder.\n */\n servePaceMs: 10_000,\n /** File announcements a member sends to one group in a minute. */\n announcePerMinute: 8,\n /** File announcements of one member of a group fetched by themselves in `announceWindowMs`; past it, kept for a Download. */\n announceTaken: 30,\n announceWindowMs: 10 * 60_000,\n /** Holders remembered per file. */\n holders: 8,\n /**\n * Message ids a `group-have` named before their message came (a member back from away hears who holds what as its\n * catch-up begins), remembered with their holders for when it does.\n */\n heardAhead: 256,\n /** Message ids in one `group-have`. */\n haveIds: 32,\n /**\n * `group-have` frames a private group's edge takes in `haveWindowMs`: what is to say is gathered for a second, then\n * goes. A community's, from a member, goes every `communityHaveEveryMs`.\n */\n haveFrames: 10,\n haveWindowMs: 10_000,\n /**\n * `group-have` frames a private group's edge takes from its member in `haveWindowMs`, the rest dropped: twice what it\n * may send, as frames sent at that pace and late by different delays on the way still come in under it.\n */\n haveFramesTaken: 20,\n communityHaveEveryMs: 60_000,\n /**\n * `group-want` frames an edge sends in `wantWindowMs`, and takes from its member, the rest dropped before anything is\n * looked up: twice what it may send, as for `group-have`. A member back from away in a group of 16 asked one member\n * for at most 47 in 10 seconds, its files coming as fast as the network lets them.\n */\n wantFrames: 50,\n wantFramesTaken: 100,\n wantWindowMs: 10_000,\n /**\n * How long a want waits for an offer before the next holder is asked; a transfer that does not move for as long is\n * left for the next holder too.\n */\n wantWaitMs: 30_000,\n /**\n * A holder that served a file this long, at a pace that leaves more than `wantWaitMs` to go, is left for another that\n * said it holds the file since (its place free): the next one goes on from the bytes stored. A phone's slow upload\n * then holds up no member that a free holder could serve.\n */\n slowAfterMs: 5_000,\n /**\n * How long a served transfer with all its bytes confirmed waits for the member's word that its check passed once the\n * member's next want has overtaken it.\n */\n doneWaitMs: 5_000,\n /**\n * What a transfer must bring in `wantWaitMs` (or the rest of its file, when less) to count as moving: a holder that\n * sends a few bytes at a time is left as one that stalls.\n */\n wantMoveBytes: 16 * 1024,\n /** A file session closes this long after its last transfer ends. */\n sessionIdleMs: 60_000,\n /** File sessions opening at once, and open at once, all groups together. */\n sessionsOpening: 2,\n sessionsOpen: 4,\n /** The longest file name and type kept from a description. */\n nameChars: 255,\n mimeChars: 255,\n} as const;\n\n/** The `paired-groups` version an app announces when it takes group files: it answers wants and takes `group-have`. */\nexport const GROUP_VERSION_FILES = 6;\n\n/**\n * The frames of WISP 503 § Getting the bytes, on an edge between two apps that announced `GROUP_VERSION_FILES`:\n * `group-want {g, id}` asks a holder for the file of message `id`; `group-want-no {g, id, why}` is a holder's no;\n * `group-have {g, ids}` says which files a member keeps (in a community, an application frame `{t, ids}` instead).\n */\nexport const GROUP_WANT_FRAME = \"group-want\";\nexport const GROUP_WANT_NO_FRAME = \"group-want-no\";\nexport const GROUP_HAVE_FRAME = \"group-have\";\n/**\n * Why a holder does not serve a file (`group-want-no`). `day`: it served its day's bytes already\n * (`serveBytesPerDay`), so asking it again soon is no use; an app from before reads it as `busy`.\n */\nexport type GroupWantRefusal = \"gone\" | \"busy\" | \"refused\" | \"day\";\nconst REFUSALS: readonly string[] = [\"gone\", \"busy\", \"refused\", \"day\"];\n\n/** A group message's id, as a private group (`<s>:<e>:<n>`) or a community (`<s>:<e>:<h>:<n>`) names it. */\nconst MESSAGE_ID = /^[a-z0-9]{52}:\\d{1,15}(:[A-Za-z0-9_-]{1,64})?:\\d{1,15}$/;\nexport const isGroupMessageId = (value: unknown): value is string => typeof value === \"string\" && MESSAGE_ID.test(value);\n\nfunction frameOf(value: unknown, t: string, groupId?: string): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const f = value as Record<string, unknown>;\n return f.t === t && (groupId === undefined || f.g === groupId) ? f : null;\n}\n\n/** A `group-want` of group `groupId`: the message whose file is asked for, or null. */\nexport function readGroupWant(value: unknown, groupId: string): { id: string } | null {\n const f = frameOf(value, GROUP_WANT_FRAME, groupId);\n return f && isGroupMessageId(f.id) ? { id: f.id } : null;\n}\n\n/** A holder's `group-want-no` of group `groupId`, or null. A reason this app does not know reads as `busy`. */\nexport function readGroupWantNo(value: unknown, groupId: string): { id: string; why: GroupWantRefusal } | null {\n const f = frameOf(value, GROUP_WANT_NO_FRAME, groupId);\n if (!f || !isGroupMessageId(f.id)) return null;\n return { id: f.id, why: typeof f.why === \"string\" && REFUSALS.includes(f.why) ? f.why as GroupWantRefusal : \"busy\" };\n}\n\n/**\n * The message ids of a `group-have`: of group `groupId` on an edge, or (no `groupId`) a community's application frame.\n * At most `haveIds` message ids; a frame with more, or anything else, is null.\n */\nexport function readGroupHave(value: unknown, groupId?: string): string[] | null {\n const f = frameOf(value, GROUP_HAVE_FRAME, groupId);\n if (!f || !Array.isArray(f.ids) || !f.ids.length || f.ids.length > GROUP_FILE_LIMITS.haveIds || !f.ids.every(isGroupMessageId)) return null;\n return [...new Set(f.ids as string[])];\n}\n\n/** A group file's description as the author's app puts it in the message (WISP 503 § The announcement). */\nexport interface GroupFileMeta {\n name: string;\n mime: string;\n size: number;\n /** SHA-256 of the file, base64url: what every receiver checks the stored bytes against. */\n d: string;\n voice?: VoiceMeta;\n video?: VideoMeta;\n image?: ImageMeta;\n}\n\nconst DIGEST = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * A description read from the wire, cleaned: the name made a display name (never a path), the type untrusted, the\n * size within the group limit, the digest the right shape. A malformed voice, video or picture description is dropped\n * on its own and the file is still a file; anything else malformed is no file at all (null), and the text shows.\n */\nexport function readGroupFileMeta(value: unknown): GroupFileMeta | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const v = value as Record<string, unknown>;\n if (typeof v.name !== \"string\" || !v.name.trim() || [...v.name].length > GROUP_FILE_LIMITS.nameChars) return null;\n if (typeof v.mime !== \"string\" || v.mime.length > GROUP_FILE_LIMITS.mimeChars) return null;\n if (!Number.isSafeInteger(v.size) || (v.size as number) < 1 || (v.size as number) > GROUP_FILE_LIMITS.maxBytes) return null;\n if (typeof v.d !== \"string\" || !DIGEST.test(v.d)) return null;\n const mime = sanitizeMime(v.mime);\n const voice = v.voice === undefined ? undefined : parseVoiceMeta(v.voice, mime);\n const video = v.video === undefined ? undefined : parseVideoMeta(v.video, mime);\n const image = v.image === undefined ? undefined : parseImageMeta(v.image, mime);\n return { name: sanitizeFileName(v.name), mime, size: v.size as number, d: v.d,\n ...(voice ? { voice } : {}), ...(video ? { video } : {}), ...(image ? { image } : {}) };\n}\n\n/**\n * The text an announcement carries when its author wrote no caption: what an app without group files shows instead\n * of the file. English, as wire text is; an app that knows the file shows the file, not this line.\n */\nexport function groupFileFallback(file: Pick<GroupFileMeta, \"name\" | \"size\" | \"voice\" | \"video\">): string {\n if (file.voice) return `🎤 Voice message (${formatVoiceDuration(file.voice.duration)}): update Ghostly to hear it`;\n return `${fileMessageText(file)} (${formatFileSize(file.size)}): update Ghostly to get files in groups`;\n}\n\n/**\n * Whether a device fetches a file by itself (WISP 503 § Automatic and asked downloads): up to `autoBytes` while what\n * it took that way from the group stays within `autoBytesPerGroup`. A voice message too: one recorded (15 minutes at\n * most, about 3.6 MB) always fits, and a bigger file the author called a voice message is asked about like any other.\n */\nexport function fetchesByItself(file: Pick<GroupFileMeta, \"size\">, keptAutomatically: number,\n limits: { autoBytes: number; autoBytesPerGroup: number } = GROUP_FILE_LIMITS): boolean {\n return file.size <= limits.autoBytes && keptAutomatically + file.size <= limits.autoBytesPerGroup;\n}\n","import type { PairedTransport } from \"./pairedTransports\";\n\n/**\n * How far a first pairing got, as one side can know it. Shared by the engine (which measures it) and\n * the UI (which shows it), the way a group join's stages are (`GroupJoinStage`).\n */\n\n/** Who this side is: the one who made the invite, or the one who joined with it. */\nexport type PairingRole = \"inviter\" | \"joiner\";\n\n/**\n * The stages, in the order they come. `publishing`: the inviter is putting its invite on the network.\n * `waiting`: the inviter waits for someone to read it. `resolving`: the joiner is looking the invite up\n * (relay, then DHT). `knocking`: this side sent its offer. `answering`: this side is answering the other's\n * offer. `connecting`: offer and answer met; the transport is coming up. `live`: the chat is open.\n * `on-dht`: the contact is pinned over the DHT and no transport is up (yet); the chat carries text on the DHT\n * while layer 1 is retried in the background (WISP 400). `failed`: only what the DHT cannot get past (`reason`:\n * `key-mismatch`, `rejected`, `publish`, `offline`); the engine tries again by itself when `retryable`. On a first pairing the joiner knocks and the inviter answers; an inviter that sees a joiner\n * from before that rule knocks itself after a grace, so either role can be at either.\n */\nexport type PairingStage = \"publishing\" | \"waiting\" | \"resolving\" | \"knocking\" | \"answering\" | \"connecting\" | \"live\" | \"on-dht\" | \"failed\";\n\n/**\n * Why a pairing is `on-dht` (WISP 400): `no-common-transport` (the two apps share none), `transport` (every\n * attempt failed), `chosen` (either side chose DHT only), `waiting` (pinned over the DHT first; still trying).\n */\nexport type PairingOnDhtReason = \"no-common-transport\" | \"transport\" | \"chosen\" | \"waiting\";\n\n/**\n * Why an attempt failed, in a word the UI has words for. `publish`: this side could not publish\n * (discovery unreachable). `timeout`: the offer was not answered in time. `transport`: offer and answer\n * met but no connection came up. `rejected`: the authenticated session failed, or a signal was forged or\n * unauthenticated (never retried). `key-mismatch`: the contact's key is not the one saved (never retried).\n * `offline`: this side went offline. `taken`: a joiner whose inviter answers someone else, who used the same invite\n * first (the inviter's envelopes are sealed to that one); it holds until an envelope of the inviter's reads again.\n */\nexport type PairingFailureReason = \"publish\" | \"timeout\" | \"transport\" | \"rejected\" | \"key-mismatch\" | \"offline\" | \"taken\";\n\nexport interface PairingProgress {\n role: PairingRole;\n stage: PairingStage;\n /** When this stage began (ms since the epoch). */\n since: number;\n /** When the pairing began: the invite was made, or joined (ms since the epoch). */\n startedAt: number;\n /** Connection attempts so far, from 1. A failed attempt is followed by the next one. */\n attempt: number;\n /** A short technical note (an error message, or a code), when there is one: the UI shows it behind an ⓘ, untranslated. */\n detail?: string;\n /** When `stage` is `failed` or `on-dht`: why, and whether the engine tries again on its own. */\n reason?: PairingFailureReason | PairingOnDhtReason;\n retryable?: boolean;\n /** The contact's packet was seen (they are on the network); their offer or answer is what is awaited. */\n peerSeen?: boolean;\n /** `connecting` and `live`: the transport coming up, or in use. */\n transport?: PairedTransport;\n /**\n * `publishing`: the relays' request budget (`REQUESTS_PER_MINUTE`) holds this side's first packet back; it goes out\n * once the budget frees a request, about then (ms since the epoch).\n */\n relayWaitUntil?: number;\n}\n\nconst FIRST_STAGE: Record<PairingRole, PairingStage> = { inviter: \"publishing\", joiner: \"resolving\" };\n\n/**\n * Keeps one side's `PairingProgress` from what the link reports, and says when it changed. Stops at\n * `live`: what happens to a paired chat afterwards is its connection state, not its pairing.\n */\nexport class PairingTracker {\n progress: PairingProgress;\n private peerSeen = false;\n /** An attempt is open from its offer until it ends (live, failed, or torn down). */\n private attemptOpen = false;\n private attempts = 0;\n /** The contact was pinned over the DHT: stream attempts that fail leave the pairing `on-dht`, not `failed`. */\n private dhtPinned = false;\n\n constructor(role: PairingRole, startedAt: number, private readonly changed: (progress: PairingProgress) => void, private readonly now: () => number = Date.now) {\n this.progress = { role, stage: FIRST_STAGE[role], since: startedAt, startedAt, attempt: 1 };\n }\n\n /**\n * Live, or stopped by a security rejection (a key mismatch, a forged or refused session), or by an invite someone else\n * took: nothing moves it after (the last one only `untaken`).\n */\n get done(): boolean {\n return this.progress.stage === \"live\" || (this.progress.stage === \"failed\" && (this.progress.reason === \"key-mismatch\" || this.progress.reason === \"rejected\" || this.progress.reason === \"taken\"));\n }\n\n /** This side's packet is on the network (its first, or the one after a publish that failed). */\n published(): void {\n const { stage, reason } = this.progress;\n if (stage === \"publishing\" || (stage === \"failed\" && reason === \"publish\")) this.set(this.idle());\n }\n\n /** This side's first packet waits for the relays' request budget, which frees one at `until`: said, still `publishing`. */\n heldBack(until: number): void {\n if (this.progress.stage !== \"publishing\") return;\n this.progress = { ...this.progress, relayWaitUntil: until };\n this.changed(this.progress);\n }\n\n /** The contact's packet was seen: they are on the network. */\n sawPeer(): void {\n if (this.peerSeen) return;\n this.peerSeen = true;\n this.set(this.progress.stage);\n }\n\n offerSent(): void { this.attempt(\"knocking\"); }\n offerReceived(): void { this.attempt(\"answering\"); }\n answerSent(): void { if (this.progress.stage === \"answering\") this.set(\"connecting\"); }\n answerReceived(): void { if (this.progress.stage === \"knocking\") this.set(\"connecting\"); }\n\n live(transport?: PairedTransport): void {\n this.attemptOpen = false;\n this.set(\"live\", transport ? { transport } : undefined);\n }\n\n failed(reason: PairingFailureReason, retryable: boolean, detail?: string): void {\n if (this.done) return;\n this.attemptOpen = false;\n // A stream that did not come up is no failure of the pairing (WISP 400): pinned over the DHT, the chat is\n // on the DHT; not pinned yet, the first contact goes on (on the DHT too) and so do the attempts.\n if (reason === \"timeout\" || reason === \"transport\") {\n if (this.dhtPinned) this.set(\"on-dht\", { reason: \"transport\", retryable: true, ...(detail ? { detail } : {}) });\n // Why, as its code when the attempt brought no error of its own: the UI's words say the stage, never this English.\n else this.set(this.idle(), { detail: detail ?? reason });\n return;\n }\n this.set(\"failed\", { reason, retryable, ...(detail ? { detail } : {}) });\n }\n\n /**\n * The contact was pinned over the DHT: nothing to show yet (a stream attempt is usually a moment away or under\n * way), but from now on a stream that fails ends the pairing `on-dht`, not back between attempts.\n */\n pinnedOverDht(): void { if (!this.done) this.dhtPinned = true; }\n\n /**\n * The contact is pinned over the DHT (its first-contact envelope verified first), or the chat is kept there:\n * the pairing ends `on-dht`, and later attempts only count until one goes `live`.\n */\n onDht(reason: PairingOnDhtReason): void {\n if (this.done) return;\n this.dhtPinned = true;\n // A stream attempt under way goes on to its end (live, or on-dht if it fails): a pin over the DHT a moment\n // before the stream opens is not a stage of its own. DHT only chosen ends the attempts.\n if (this.attemptOpen && reason !== \"chosen\") return;\n this.attemptOpen = false;\n this.set(\"on-dht\", { reason, retryable: reason !== \"chosen\" });\n }\n\n /** The inviter's envelope reads again after `taken` (that one was forged by someone holding the invite): still trying. */\n untaken(): void {\n if (this.progress.stage !== \"failed\" || this.progress.reason !== \"taken\") return;\n const { role, startedAt } = this.progress;\n this.progress = { role, stage: this.dhtPinned ? \"on-dht\" : this.idle(), since: this.now(), startedAt, attempt: Math.max(1, this.attempts),\n ...(this.peerSeen ? { peerSeen: true } : {}), ...(this.dhtPinned ? { reason: \"waiting\" as const, retryable: true } : {}) };\n this.changed(this.progress);\n }\n\n /** The attempt ended without a word (the connection went away before the session was ready). */\n reset(): void {\n if (this.done || !this.attemptOpen) return;\n this.attemptOpen = false;\n if (this.progress.stage === \"on-dht\") return;\n this.set(this.idle());\n }\n\n private attempt(stage: \"knocking\" | \"answering\"): void {\n if (this.done) return;\n if (!this.attemptOpen) this.attempts++;\n this.attemptOpen = true;\n // On the DHT the chat is already usable: background attempts do not take the pairing back to its steps.\n if (this.progress.stage === \"on-dht\") return;\n this.set(stage);\n }\n\n /** The stage this side is at between attempts. */\n private idle(): PairingStage { return this.progress.role === \"inviter\" ? \"waiting\" : \"resolving\"; }\n\n private set(stage: PairingStage, extra?: Pick<PairingProgress, \"detail\" | \"reason\" | \"retryable\" | \"transport\">): void {\n if (this.done) return;\n const { role, startedAt, since } = this.progress;\n // A stage that only gained a detail (the contact was seen) keeps the moment it began.\n this.progress = { role, stage, since: stage === this.progress.stage ? since : this.now(), startedAt, attempt: Math.max(1, this.attempts),\n ...(this.peerSeen ? { peerSeen: true } : {}), ...extra };\n this.changed(this.progress);\n }\n}\n","import type { RatchetBox } from \"./ratchet\";\nimport { DhtDelivery, DHT_PACKET_BUDGET, DHT_TEXT_TOO_LONG, type DeliveryMode, type DhtDeliveryState, type DhtDeliveryView , type DhtPacketFacts } from \"./dhtDelivery\";\nimport type { DhtFileAnnouncement, DhtFileOffer } from \"./dhtFiles\";\nimport { PairedFiles } from \"./pairedFiles\";\nimport { TransportSwitch, allowedTransports, type SwitchPlan } from \"./transportSwitch\";\nimport { proofHash, type ProofAdapter, type ProofScope } from \"./peerProofs\";\nimport { IDENTITY_FRAME_LIMIT, IDENTITY_FRAME_WINDOW_MS, IDENTITY_MAX_FRAME, type IdentityScope } from \"./identityProofs\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { identityFromSeedB64, publicKeyFromZ32 } from \"./identity\";\nimport { TRANSPORTS, automaticTransport, irohRelayUrl, checkedDescriptors, rankTransports, relayedTransports, transportOrder, type NativeEndpoint, type NativeBinding, type NativeTransport, type PairedTransport, type TransportDescriptors } from \"./pairedTransports\";\nimport { dialDescriptors, encodePacketTransports, parsePacketTransports } from \"./capsRecord\";\nimport { sanitizeNick } from \"./text\";\nimport { sanitizeAvatar } from \"./avatar\";\nimport { parseLinkPreview, type LinkPreview } from \"./linkPreview\";\nimport { pairedReplyAuthor, readReply, wireReply, type WireReply } from \"./replies\";\nimport { readForwarded } from \"./forwards\";\nimport { readStatusCard, type StatusCard } from \"./statusCards\";\nimport { randomBytes, toBase64Url, toZ32, utf8Encode } from \"./bytes\";\nimport { fitSignedPairedSignal, fitSignedPairedSignalWith, verifyPairedSignal } from \"./pairedSignal\";\nimport { deviceFrameCapability, signDeviceTransports, unsignedDeviceTransports, verifyDeviceTransports, type DeviceCapability, type DeviceFrame } from \"./deviceLink\";\nimport { parseRtcSignal, type SignalSight } from \"./signal\";\nimport { PairedSession, SESSION_FRAME_MAX, type PairingState, type PairingCredentials, type PaymentMethodName } from \"./pairedSession\";\nimport { DataLink, type DataLinkState } from \"./datalink\";\nimport type { DirectEvidence } from \"./directPath\";\nimport {\n CHUNK_KIND,\n LIMITS,\n PROTOCOL_VERSION,\n decodeChunk,\n decodeControl,\n encodeControl,\n type FrameChannel,\n} from \"./frames\";\nimport { FileTransfers, type FileInfo, type FileSink } from \"./files\";\nimport {\n HttpClient,\n HttpHost,\n GhostlyHttpError,\n type ClientRequest,\n type ClientResponse,\n type HostedHttpService,\n type LocalFetch,\n} from \"./http\";\nimport type { LinkParams } from \"./invite\";\nimport type { Payment, PaymentAsk, PaymentRequest, PaymentResult } from \"./payments\";\nimport { EXPECT_PEER_MS, OFFER_FAST_MS, WATCH_PEER_MS, LinkSession, presenceSeenAt, type LinkStatus, type PeerPresence, type PollIntervals } from \"./link\";\nimport type { ResolvedLink } from \"./records\";\nimport { servicesFromWire, servicesToWire, type ServiceAd } from \"./services\";\nimport { PairedHttp, type PairedHttpBodies } from \"./pairedHttp\";\nimport { CALLS_CAPABILITY, FILES_CAPABILITY, FILES_BINARY_CAPABILITY, KNOWN_SESSION_CAPABILITIES, SERVICES_CAPABILITY, SESSION_CAPABILITIES_FRAME, SessionCapabilities, TYPING_CAPABILITY, STATUS_CAPABILITY, REACTIONS_CAPABILITY, EDIT_CAPABILITY, WAKE_SESSION_CAPABILITY, PIN_CAPABILITY, STATUS_CARD_CAPABILITY, BUTTONS_CAPABILITY, UPGRADE_CAPABILITY, APPS_CAPABILITY, APP_RANGES_CAPABILITY, type SessionCapability } from \"./pairedCapabilities\";\nimport { APP_DATA_MAX_BYTES, APP_FRAME, APP_RESUME_GRACE_MS, AppSessions, appDataBytes, appCloseFrame, appDataFrame, appOpenFrame, type AppFrameEvent, type AppSendError } from \"./pairedApps\";\nimport { APP_RANGE_DATA_KIND, APP_RANGE_FRAMES, APP_RANGE_LIMITS, AppRanges, appRangeChunk, appRangeDataFrame, appRangeErrorFrame, decodeAppRangeData, encodeAppRangeData, readAppRangeFrame, type AppRangeTask } from \"./pairedAppRanges\";\nimport { WAKE_FRAME, parseWakeFrame, wakeFrame, type WakeTarget } from \"./pairedWake\";\nimport { CONTACT_ASKER_FRAME, type ContactAskerFrame } from \"./contactRecords\";\nimport { REACTED_FRAME, REACTION_FRAME, REACTION_LIMITS, ReactionWindow, parseReactedFrame, parseReactionFrame, reactedFrame, reactionFrame, type WireReaction } from \"./reactions\";\nimport { PINNED_FRAME, PIN_FRAME, PIN_LIMITS, parsePinFrame, parsePinnedFrame, pinFrame, pinnedFrame, type WirePin } from \"./pins\";\nimport { TYPING_FRAME, TypingReceiver, TypingSender, type TypingActivity } from \"./pairedTyping\";\nimport { STATUS_FRAME, StatusReceiver, StatusSender, type StatusState } from \"./pairedStatus\";\nimport { EDIT_FRAME, EDIT_RATE_WINDOW_MS, EDIT_RECEIVE_LIMIT, EDITED_FRAME, RateWindow, dhtEditId, editFrame, editedFrame, parseEditFrame, parseEditedFrame, validEditMessage, validEditNumber, type WireEdit } from \"./pairedEdits\";\nimport { FILE_FRAMES, FILE_LIMITS, decodeFileData, encodeFileData } from \"./chatFiles\";\nimport { CALL_RATE_WINDOW_MS, CALL_RECEIVE_LIMIT, PAIRED_CALL_FRAME, PairedCalls, parsePairedCallFrame } from \"./pairedCalls\";\nimport { heardCallSignal } from \"./callSignal\";\nimport { traceLink } from \"./linkTrace\";\nimport { isDiscoveryBudgetError, type PkarrTransport } from \"./transport\";\nimport { GROUP_VERSION_LARGE } from \"./groupCommits\";\nimport { GROUP_VERSION_HUBS } from \"./groupHubs\";\nimport { GROUP_VERSION_SIGNALS } from \"./groupSignals\";\nimport { GROUP_VERSION_FILES } from \"./groupFiles\";\nimport { PairingTracker, type PairingProgress, type PairingRole } from \"./pairingProgress\";\nimport { engineError } from \"./engineErrors\";\n\n/**\n * One link to one peer, complete: Pkarr presence and signaling, the WebRTC\n * data link, and the services multiplexed on top of it. Platform specifics\n * (how to reach Pkarr, how to create a peer connection, how to reach a local\n * HTTP server) are injected, so Desktop and Browser run the same code.\n */\n/** Unanswered offers are repeated less and less often: 1.5, 3, 6, then every 12 minutes. */\n/** After a failed attempt: 20 s, then doubling up to 3 min. Someone opening the chat starts it over. */\nconst AUTO_CONNECT_RETRY_MS = 20_000;\n/**\n * Back after a restart (`resume`), a first automatic dial that failed within this long reached nobody (a HyperDHT hole\n * punch aborted at once on loopback, 4-13 ms): it is tried again after `INSTANT_FAIL_RETRY_MS`, once, before it counts.\n * Counted, it held the chat 40 s while the app's other chats came back in 0.5-3 s (DHT-direct lab, 2026-10-17).\n */\nconst INSTANT_FAIL_MS = 100;\nconst INSTANT_FAIL_RETRY_MS = 3_000;\n/**\n * The same for the first dial after the contact came back (`peerPacketArrived`): an app whose network comes back on\n * publishes before its listener is announced again, and a dial that fast found nobody (HyperDHT's PEER_NOT_FOUND, 200 ms\n * at 100 ms RTT). Counted, it held the chat 41 s while the app's other chats came back in 1-3 s (DHT-direct lab, 2026-10-19).\n */\nconst BACK_INSTANT_FAIL_MS = 500;\n/** A group link with nothing to dial looks fast for the member's `_tr` on this many attempts, then at its own pace. */\nconst PACKET_TRANSPORTS_FAST_ATTEMPTS = 3;\n/** A native transport that fails this many attempts in a row is skipped for `DEMOTE_MS`, while another remains (WISP 100). */\n/** Pinned over the DHT with no stream up this long after, a first pairing shows as on the DHT (WISP 400). */\nexport const DHT_PIN_GRACE_MS = 10_000;\n/** Back after a restart (`resume`), dials wait this long at most for the native endpoint that carried the chat to start. */\nexport const RESUME_WAIT_MS = 10_000;\n/**\n * Two dials crossing: how long the lower key's side waits for its own to connect before it takes the contact's. Two\n * dials that both go through connect within a round trip of each other: each side's preface goes out as the other's\n * dial reaches it. One not connected by then has stalled (a HyperDHT stream that opened and carries nothing, dialled\n * again only 2 s later) or goes to an endpoint the contact no longer runs: waiting for it held a working connection\n * back 0.9-1.9 s (DHT-direct lab, 5 of 20 first pairings). Taken, this side's dial is closed when it lands, and on the\n * contact's side it never authenticates (`attachReplacement`).\n */\nexport const CROSSED_WAIT_MS = 500;\n/**\n * A session this side dialled this recently is one a crossing dial of the contact's may meet (both connected): the\n * lower key keeps its own. Older, the session is one the contact has since lost (its app restarted), and its dial\n * takes over.\n */\nexport const CROSSED_FRESH_MS = 10_000;\n/**\n * A dial of the contact's that meets such a session waits this long for that session to answer a ping. It answers when\n * the dials crossed (the contact holds this side's dial too); it does not when the contact's app ended since and is\n * back: its dial then takes over. Refused outright, that dial left the contact waiting for the dead session's end, 16.6\n * to 18.9 s (CLI daemons over HyperDHT, the contact killed 1 to 3 s after this side's knock, 5 of 5). A round trip is\n * 7 ms on loopback and under 0.5 s over a relayed Iroh.\n */\nexport const CROSSED_PROBE_MS = 1_500;\n/** Frames a connection waiting on `probeCrossed` keeps for the session that may take it: a handshake's few. */\nconst PROBE_EARLY_FRAMES = 8;\n/** A WebRTC attempt under way, not yet open: what a member's packet saying it has no WebRTC ends (`peerPacketTransports`). */\nconst WEBRTC_ATTEMPT: ReadonlySet<DataLinkState> = new Set([\"offering\", \"answering\", \"connecting\"]);\n/** A joiner gathers its offer while it first looks for the inviter (`dialEarly`) only this soon after the join. */\nexport const EARLY_DIAL_JOIN_MS = 60_000;\n/** What a joiner is told when someone else used the invite first (`DhtDeliveryView.inviteTaken`). */\nexport const INVITE_TAKEN = \"Someone else joined with this invite first. Ask your contact for a new one.\";\n/**\n * A dial the contact made while its mailbox, as last read here, said DHT-only waits this long for the read that says\n * it left (the mailbox is read at the DHT pace meanwhile), then closes.\n */\nexport const BLOCKED_DIAL_WAIT_MS = 10_000;\n/**\n * A connection dialled in on a pinned chat must authenticate within this long, or it closes. Anyone who read the\n * endpoint from the record can dial it: until it proves the pinned key it holds no place a person waits on. A native\n * connection this side dialled on a pinned chat has as long too: its path is up when it opens, and the handshake takes\n * a few round trips, so one still unfinished by then carries nothing (a relay path that died with the handshake), and\n * the chat dials again rather than hold it until QUIC's idle timeout (Omarchy, 2026-10-01: the web app had refused the\n * Desktop's knock 15 s in, and the Desktop dialled again only 30 s in).\n */\nexport const UNPROVEN_AUTH_MS = 15_000;\n/**\n * Connections dialled in that authenticate at once beside the one waiting to take over (`contend`). Whoever read the\n * endpoint and dials it over and over pushes out only the oldest of them: the contact's, a few round trips long, is\n * pushed out only by this many dials within those round trips.\n */\nexport const DIALED_IN_CONTENDERS = 8;\n/**\n * A native connection this side dialled that has not authenticated this long after it opened, while the contact's\n * record names a newer way to dial it: the dial went to an old address (the web app's Iroh homed on another relay after\n * a restart), and the chat dials the new one at once. Sooner, it is a handshake still under way.\n */\nexport const REDESCRIBED_GRACE_MS = 3_000;\n/**\n * A WebRTC offer this side made that has no answer after this long: a direct native transport ranked after WebRTC is\n * dialled meanwhile, the offer still standing, and whichever goes live first carries the chat. The contact may not read\n * the offer for a while (a live chat reads every minute), or the relays' request budget may hold its answer back until\n * its answering attempt is over, and the offer would wait out its attempt timeout (`CONNECT_TIMEOUT_MS`, 90 s). A native\n * dial takes a second and no request to the relays.\n */\nexport const RACE_DIRECT_MS = 8_000;\n/**\n * A relayed one waits until a contact reading in the background (every 30 s) has had its look: a chat that went live\n * over a relay stays there (no probing while live, WISP 100), where the answer would have made it direct.\n */\nexport const RACE_RELAYED_MS = 40_000;\n/**\n * A relayed transport dialled ahead of the others (Automatic's Iroh through its relay, WISP 100 revision 2026-11-08) has\n * this long before the next ranked one is dialled too, the first still going: whichever goes live first carries the\n * chat. Through a relay that answers it connects well within it (0.1-0.9 s measured); one that reaches nobody (the\n * relay down, the contact no longer on it) gives up only at Iroh's connect timeout, 20 s, and held the WebRTC offer back\n * that long at every return: 26-30 s to live between two CLIs with the Iroh relay down, 4 s with WebRTC chosen.\n */\nexport const RELAYED_FIRST_MS = 3_000;\n/**\n * A WebRTC offer this side made that was answered, and has not connected this long after the answer was applied: where\n * a path exists ICE finds it in a second or two, so there is none (a VPN's NAT, a firewall that drops UDP, and no TURN\n * server), and every transport ranked after WebRTC is dialled now, the relayed ones too, the attempt still standing.\n * Without it the chat waited for ICE to give up (about 15 s in Chromium, the attempt's 90 s where the connection never\n * says `failed`), then for the next attempt.\n */\nexport const RACE_ANSWERED_MS = 6_000;\n/**\n * WebRTC that could not start an attempt at all (no candidate gathered: UDP blocked, a VPN's browser extension; or no\n * connection could be made) is tried last for this long: each try costs its stall time (`GATHER_STALL_MS` three times\n * over) before the transport that works is dialled.\n */\nexport const RTC_UNSTARTED_MS = 10 * 60_000;\n/** A transport due in the race that cannot be dialled yet (its endpoint still starting, no address of the contact's) is looked at again this often. */\nconst RACE_RETRY_MS = 2_000;\nexport const DEMOTE_AFTER_FAILURES = 3;\nexport const DEMOTE_MS = 60 * 60_000;\nconst AUTO_CONNECT_MAX_RETRY_MS = 3 * 60_000;\n/**\n * WebRTC here refused more answers to this side's offers in a row than the data link offers again at once for\n * (`ANSWER_REFUSED_REDIALS`): libdatachannel's race, which on a loaded core can refuse a whole run of them. The contact\n * was there each time, so the next offer goes after a short pause, doubled each time, up to this many pauses, rather\n * than after the backoff of failed dials (three minutes after five): a member let in to a group over slow relays was\n * up with another member only 34 s after its welcome, and 180 s when that late dial was refused too (meshSignals on\n * CI, 2026-10-11). Past them, the backoff as before: an answer that never goes in must not become a stream of offers.\n */\nexport const ANSWERS_REFUSED_PAUSES = 3;\nexport const ANSWERS_REFUSED_PAUSE_MS = 2_000;\n/**\n * A first pairing is different: the contact is right there, having just read the invite, so an attempt\n * that did not make it in `PAIRING_ATTEMPT_MS` is given up and the next one starts after `PAIRING_RETRY_MS`\n * (doubling up to `PAIRING_MAX_RETRY_MS`), instead of the 90 s and 20 s a saved contact's reconnect waits.\n */\nexport const PAIRING_ATTEMPT_MS = 15_000;\nexport const PAIRING_RETRY_MS = 3_000;\nconst PAIRING_MAX_RETRY_MS = 30_000;\n/**\n * How long a first pairing that has not gone live keeps a first pairing's dials (`firstPairing`): both sides, at\n * `PAIRING_RETRY_MS`. Past it, a chat that only ever ran on the DHT dials as a saved contact's does.\n */\nexport const FIRST_PAIRING_PACE_MS = 10 * 60_000;\n/** A packet published this recently is fresh enough for whoever comes back to the chat. */\nconst RECENTLY_PUBLISHED_MS = 5_000;\n/** An inviter that sees the joiner without its offer waits this long for one before offering itself. */\nexport const INVITER_DIAL_GRACE_MS = 2_500;\n/**\n * Liveness of a paired session: a ping this often, and the session is taken for dead after this many\n * pings in a row with nothing at all back. Counted in pings, not seconds, so a throttled background\n * tab (timers once a minute) is not mistaken for a dead peer. Only once the peer has answered a ping:\n * older apps drop the frame and must not be cut off for it.\n */\nexport const LIVENESS_PING_MS = 15_000;\n/**\n * After a live switch the old channel stays open this long, unread, before it is closed: the contact swaps on its own\n * side a round trip later, and seeing its current channel close first would make it drop the whole session.\n */\nexport const SWITCH_RETIRE_MS = 3_000;\n/**\n * A move's native dial that found no announce of the contact (HyperDHT's PEER_NOT_FOUND) is made again this long after,\n * for as long as the move lasts: the contact is live (its policy came over the open session), and its endpoint is not\n * announced while a channel is live: a move back to HyperDHT within ~5 s of leaving it, before the session left behind\n * had retired (`SWITCH_RETIRE_MS`) and the endpoint was announced again, found nobody. The move gave up at once and the\n * chat waited the 20 s retry (20.0-20.1 s in 3 of 3 cycles on two CLI daemons, a 2 s gap between moves).\n */\nconst SWITCH_FIND_RETRY_MS = 1_000;\n/**\n * A receiver takes at most this many `paired-rtc` frames from a contact per `RTC_SIGNAL_RATE_WINDOW_MS`, counted before\n * their signature is checked; the rest are dropped. Each offer taken builds a new peer connection (and gathers for it).\n * A person's busiest minute is under half of it, 30 frames: five moves to WebRTC (one every 12 s, back and forth), each\n * with every offer again that refused answers bring (`ANSWER_REFUSED_REDIALS`) and both sides offering at once. One\n * move without a refusal takes one or two. A signal dropped here is a move that does not connect: the chat stays where\n * it is, as with any failed move.\n */\nexport const RTC_SIGNAL_RECEIVE_LIMIT = 60;\nexport const RTC_SIGNAL_RATE_WINDOW_MS = 60_000;\nexport const LIVENESS_MISSED_PINGS = 3;\n/**\n * Frames that keep a session going rather than say something of the two people's: what the contact sent last outside\n * these is when the chat was last in use (`canYieldEndpoint`). Every other frame (a text, a receipt, typing, a\n * reaction, an edit, a file, a call, a payment) is use; what this side sends is answered with one of them.\n */\n/** How long a session giving its listener up waits after its goodbye before it closes, so the goodbye gets there. */\nconst YIELD_BYE_MS = 300;\nconst QUIET_FRAMES = new Set([\"paired-ping\", \"paired-pong\", \"paired-bye\", \"paired-policy\", \"paired-switch-plan\", \"paired-switch-ready\",\n \"paired-switch-failed\", \"paired-switch-keep\", \"paired-rtc\", \"paired-adapters\", \"paired-nick\", \"paired-avatar\", \"paired-capabilities\",\n \"paired-wake\", \"paired-hold\", \"paired-payments\", \"paired-groups\", \"paired-services\", CONTACT_ASKER_FRAME]);\n/**\n * What a session a move replaced still reads while its channel retires (`SWITCH_RETIRE_MS`): the contact's texts,\n * reactions, pins and edits, and its receipts of this side's, which it sends on that session until its own side moves.\n * Its files/3 frames too (a cancel, a pause, a file's check): `ChatFiles` answers them on the session now.\n */\nconst RETIRING_FRAMES = new Set([\"paired-message\", \"paired-received\", REACTION_FRAME, REACTED_FRAME, PIN_FRAME, PINNED_FRAME, EDIT_FRAME, EDITED_FRAME, ...FILE_FRAMES]);\n/**\n * A ping with nothing at all back this long after it went: the contact may have crashed and started again, with its new\n * offer waiting on the relays, while this side still holds the old session and reads them at a live chat's pace (30 s).\n * They are read now. Nothing more: the session is let go only by `LIVENESS_MISSED_PINGS`, or by the contact's offer\n * (`DataLink.handleSignal`). A connection whose close this side does not hear (node-datachannel never says\n * `disconnected`) otherwise went on until its consent checks gave up, 27 s after the crash (CI run 36741701666).\n */\nexport const PONG_WAIT_MS = 4_000;\n/** How long `handled` waits for the contact to answer its ping before it says it is late. */\nexport const HANDLED_WAIT_MS = 10_000;\n/**\n * Back in front after an absence (`wake`), a live session that ends this soon after it was lost while the app was\n * away (a phone that put it to sleep): the chat resumes as after a restart, not as a session the contact closed.\n */\nexport const WAKE_LOST_MS = 10_000;\n/**\n * Back in front after an absence, an answer this side made to the contact's offer while it was away, still connecting\n * this long after the wake, is let go and the chat dials as a resume. A path that exists connects within a second or\n * two; on a phone the app had answered from the background, the connection sat there until ICE gave up (15 s), and only\n * then did the resume dial: a chat opened on return went live 21 s after the tap (Android emulator, 2026-10-29).\n */\nexport const WAKE_ANSWER_GRACE_MS = 3_000;\n\nexport interface IncomingMessage {\n id?: string;\n text: string;\n timestamp: number;\n nick?: string;\n via: \"pkarr\" | \"datalink\";\n batch?: ResolvedLink;\n /** A paired chat's text from the DHT floor: the envelope it came in (`DhtPacketFacts`). */\n packet?: DhtPacketFacts;\n /** The link preview the sender's app attached (`pv`, WISP 401 § Link previews), already checked against the text. */\n preview?: LinkPreview;\n /**\n * The message this one answers (`r`, WISP 401 § Replies), its line cleaned. Over the DHT only the id comes\n * (`s` empty, `f` absent): the receiver finds the rest in its own history.\n */\n reply?: WireReply | { i: string };\n /** How many times it has been forwarded (`fw`, WISP 401 § Forwards); absent for a message written in this chat. */\n forwarded?: number;\n /** A status card (`sc`, WISP 405 · Status Cards), already checked; the text is its fallback. Live session only. */\n card?: StatusCard;\n}\n\n/** Frames the contact says of itself and this side saves when they change, each read within its own window. */\ntype PeerSaidKind = \"paired-nick\" | \"paired-avatar\" | \"paired-hold\" | \"paired-payments\" | \"paired-adapters\";\nfunction peerSaidWindow() {\n return { window: new RateWindow(6, 60_000), read: null as (() => void | Promise<void>) | null, timer: null as ReturnType<typeof setTimeout> | null };\n}\n\n/**\n * What files/3 may hold on a session's channel (WISP 501, Backpressure): a quarter of its send budget (native and iroh\n * channels throw past 120 KiB), or the high water mark of a WebRTC channel, which has none.\n */\nfunction filesCap(channel: FrameChannel): number {\n return channel.sendBudget ? channel.sendBudget / 4 : LIMITS.sendHighWaterMark;\n}\n\n/** Files on a channel (`GhostLink.filesUsing`). */\ninterface FilesUse { channel: FrameChannel; at: number; waiting: number; appAhead: number }\n\n/**\n * How long after files last wrote on a channel, or last waited for room on it, an app's data keeps its own quarter above\n * their line (WISP 1200 § In a chat): a file waiting for `pf-got` holds its share meanwhile.\n */\nconst FILES_IN_USE_MS = 2_000;\n\n/**\n * How far an app's data may get ahead of a file's bytes while the file waits for room on the channel (WISP 1200 § In a\n * chat): a frame goes only while the app has sent less than this more than the file since (`FilesUse.appAhead`, below\n * zero by what files wrote beyond the app, at most what files may hold). A small frame (a Chess move) still goes at\n * once; one streaming at its limit gets about half the link, and the file the other half.\n */\nconst APP_AHEAD_OF_FILES = 16 * 1024;\n\n/**\n * How much of an app's data may be on its way to the contact, not yet handled there (WISP 1200 § In a chat): a ping\n * follows it, and the pong says it arrived. A transport holds what it sends in flight beyond the channel's\n * `bufferedAmount` (UDX's window, an SCTP congestion window), so on a link slower than the app sends, the local buffer\n * stayed under its line while the queue under it grew and every chat text waited 0.5-2.3 s behind the app's data.\n */\nconst APP_IN_FLIGHT = 64 * 1024;\n\n/** Largest `paired-message` frame sent with a preview: a session fails on a frame over 60 KiB (`PairedSession`). */\nexport const MAX_PAIRED_MESSAGE_FRAME = 56 * 1024;\n\n/**\n * Texts a contact's link takes: a burst per short window (a reconnect flushes every queued text at once) and a total\n * per hour, both well above what a person or a bot sends. The rest go unconfirmed and come again (the sender's outbox\n * resends with backoff), so a catch-up only slows.\n */\nexport const MESSAGE_RECEIVE_LIMITS = { burst: 200, burstWindowMs: 10_000, hourly: 1_800, hourWindowMs: 3_600_000 } as const;\n/** What `sendMessage` says of a text the contact's windows have no room for yet: it did not go (`MessagePace`). */\nexport const MESSAGE_PACED = \"Your contact takes a limited number of texts at a time. It goes by itself once they can take more.\";\n/** How long a text sent with no receipt yet counts as taken past its send: one in flight is taken when it lands. */\nconst PACE_UNANSWERED_MS = 60_000;\n\n/**\n * The texts this side sent on a paired session, counted against the contact's windows (`MESSAGE_RECEIVE_LIMITS`), so\n * none goes that the contact would refuse. A refused text went unconfirmed and came again with the outbox's backoff,\n * after texts written later that found room meanwhile: the contact read them out of order. Past the hour's total it\n * was sent until its attempts ran out, well inside the hour, and ended failed. Each counts from its receipt, the latest\n * the contact can have taken it: counted from its send, a frame that sat in a queue was taken later than counted.\n */\nexport class MessagePace {\n private sent: { id: string; at: number; answered?: number }[] = [];\n constructor(private readonly now: () => number = Date.now) {}\n /** The contact's windows have room for one more text now. */\n room(): boolean {\n const now = this.now(), { burst, burstWindowMs, hourly, hourWindowMs } = MESSAGE_RECEIVE_LIMITS;\n const counts = (entry: { at: number; answered?: number }, windowMs: number) =>\n entry.answered !== undefined ? now - entry.answered < windowMs : now - entry.at < windowMs + PACE_UNANSWERED_MS;\n this.sent = this.sent.filter(entry => counts(entry, hourWindowMs));\n return this.sent.length < hourly && this.sent.filter(entry => counts(entry, burstWindowMs)).length < burst;\n }\n took(id: string): void { this.sent.push({ id, at: this.now() }); }\n /** Its receipt came: the contact counted it by now. */\n answered(id: string): void {\n for (let i = this.sent.length - 1; i >= 0; i--) if (this.sent[i].id === id && this.sent[i].answered === undefined) { this.sent[i].answered = this.now(); return; }\n }\n}\n\n/**\n * A `paired-message` frame. The preview (`pv`) is left out when the frame would pass `MAX_PAIRED_MESSAGE_FRAME`\n * with it: the text matters, the card does not. A reply (`r`, WISP 401 § Replies) is a few hundred bytes at most\n * and always goes, and so does a forwarded message's hop count (`fw`, WISP 401 § Forwards) and a status card (`sc`,\n * WISP 405 · Status Cards), whose 8 KiB with the text's 16 stay well inside the frame.\n */\nexport function pairedMessageFrame(id: string, ts: number, m: string, preview?: LinkPreview, reply?: WireReply, forwarded?: number, card?: StatusCard): string {\n const r = { ...(reply && { r: wireReply(reply) }), ...(readForwarded(forwarded) && { fw: forwarded }), ...(card && { sc: card }) };\n const plain = JSON.stringify({ t: \"paired-message\", id, ts, m, ...r });\n if (!preview) return plain;\n const withPreview = JSON.stringify({ t: \"paired-message\", id, ts, m, pv: preview, ...r });\n return withPreview.length <= MAX_PAIRED_MESSAGE_FRAME ? withPreview : plain;\n}\n\n/** A text whose `paired-message` frame would pass what a session takes: it never arrives, and is refused at send. */\nexport const PAIRED_FRAME_TOO_LARGE = \"Message too long once encoded. Shorten it or send it as a file.\";\n\n/**\n * The `paired-message` frame of this text fits a session (`SESSION_FRAME_MAX`, UTF-16 units of the JSON). Within 16 KiB\n * of UTF-8 a text can still pass it: JSON writes each control character as six (`\\u0001`). The preview is left out,\n * as the frame drops one that does not fit.\n */\nexport function pairedMessageFits(ts: number, m: string, reply?: WireReply, forwarded?: number, card?: StatusCard): boolean {\n return pairedMessageFrame(\"A\".repeat(22), ts, m, undefined, reply, forwarded, card).length <= SESSION_FRAME_MAX;\n}\n\n/**\n * The `paired-edit` frame of this edit fits a session, as `pairedMessageFits` says of a text's: an edit within 16 KiB\n * can pass it the same way, and the contact's session ends on it each time it is said again.\n */\nexport function pairedEditFits(edit: WireEdit): boolean {\n return editFrame(edit).length <= SESSION_FRAME_MAX;\n}\n\n/**\n * A native descriptor from the contact's capability record against the one known (a session's, or an older record's).\n * The record carries only how to dial, never an address: the Iroh endpoint id and the relay it is homed on, the\n * HyperDHT key and the relay a browser's goes through. For the same endpoint, a known Iroh descriptor keeps its\n * addresses and takes the record's relay. `newer`: the record was just read, so what it says replaces what is known;\n * otherwise it only fills a relay the known one lacks. The known one itself when nothing changes. `listed`: the record\n * names the transport. One just read that names it with no descriptor says its endpoint is not up (WISP 03: still\n * starting, or no free listener there): the one known is not dialled meanwhile (none, `undefined`).\n */\n/** The endpoint a descriptor names (Iroh's endpoint id, HyperDHT's public key), whatever relay it is homed on. */\nfunction endpointId(transport: NativeTransport, descriptor: unknown): unknown {\n const d = descriptor as { id?: unknown; publicKey?: unknown } | undefined;\n return transport === \"iroh/1\" ? d?.id : d?.publicKey;\n}\n\nfunction recordDescriptor(transport: NativeTransport, known: unknown, record: unknown, newer: boolean, listed: boolean): unknown {\n if (!record) return newer && listed ? undefined : known;\n if (!known) return record;\n const k = known as { id?: unknown; publicKey?: unknown; relay?: unknown }, r = record as typeof k;\n if (transport === \"iroh/1\" ? k.id !== r.id : k.publicKey !== r.publicKey) return newer ? record : known;\n // The same Iroh relay spelled another way (with or without the trailing dot) is no change.\n const same = r.relay === k.relay || (transport === \"iroh/1\" && typeof r.relay === \"string\" && typeof k.relay === \"string\" && irohRelayUrl(r.relay) === irohRelayUrl(k.relay));\n if (!r.relay || same || (k.relay && !newer)) return known;\n return transport === \"iroh/1\" ? { ...k, relay: r.relay } : record;\n}\n\n/**\n * The transport a chat is set to reach and is not on yet (WISP 100, \"A chosen transport not reached yet\"): waited for,\n * never failed. `by`: whose choice names it (absent: a policy alone, such as Fallback off, limits the chat to it).\n */\nexport interface TransportWait {\n transport: PairedTransport;\n by?: \"you\" | \"contact\";\n /**\n * - `unknown`: the contact's app has not said whether it has it (no capability record read, no session lists it);\n * - `starting`: the contact's record lists it, but there is no way to dial it yet (its endpoint is starting);\n * - `connecting`: a switch to it is under way;\n * - `unreachable`: both have it, and the last attempt did not connect (`error`, when this side knows);\n * - `waiting`: both have it and nothing failed yet: the next attempt goes when the contact is there;\n * - `contact-lacks`: the contact's latest record does not list it: its app does not have it;\n * - `app-lacks`: this app does not run it (the contact chose it, or this side's adapter is gone).\n */\n reason: \"unknown\" | \"starting\" | \"connecting\" | \"unreachable\" | \"waiting\" | \"contact-lacks\" | \"app-lacks\";\n /** The chat is live on another transport meanwhile (both allow a fallback); otherwise it is on the DHT. */\n live?: PairedTransport;\n /** Attempts that did not connect in a row, and why the last one did not, when this side dialled it. */\n failures: number;\n error?: string;\n /** When the next attempt goes, when one is scheduled on this side. */\n retryAt?: number;\n}\n\n/**\n * The last attempt to go live that did not, as one side saw it (WISP 100, \"Why a chat is not live\"): shown so that a\n * chat on the DHT is never a silent retry loop.\n */\nexport interface LiveAttempt {\n /** When it ended (ms since the epoch). */\n at: number;\n /** This side dialled it (the side with the lower rendezvous key, or a joiner), or answered the contact's offer. */\n side: \"dialled\" | \"answered\";\n /** Each transport tried and why it did not connect, in the order tried. An answering side knows only its own part. */\n failed: { transport: PairedTransport; error: string }[];\n /** Why nothing could be tried, when nothing was (no transport both apps have and can dial yet). */\n reason?: string;\n /** When this side dials again (it dials): about then, once the contact is seen. */\n retryAt?: number;\n}\n\nexport interface GhostLinkEvents {\n onDhtDelivery?(view: DhtDeliveryView): void;\n onDiscoveryError?(error: string | null): void;\n onPeerProof?(frame: Record<string, unknown>): Promise<void>;\n /** An `idp-*` identity-proof frame from the paired contact (only when both sides offer `identity-proof/1`). */\n onIdentityProof?(frame: Record<string, unknown>): Promise<void>;\n onTransportsChanged?(): void;\n /**\n * The contact chose a transport for this chat just now (its switch intent went up on the open session), or went\n * back to automatic (its intent fell to 0). `apart`: heard with no session to raise an intent on, from its capability\n * record, or from the first policy of a session it chose before (WISP 100, \"A choice made while not live\"); the\n * owner may have told it already.\n */\n onPeerTransportChoice?(transport: PairedTransport | \"automatic\", apart?: boolean): void;\n /**\n * A switch to `target` could not connect and the session stayed where it was (both allow fallback). `reason` is\n * known on the side that dialled; the other side learns only that it did not happen.\n */\n onTransportSwitchFailed?(target: PairedTransport, reason?: string): void;\n /** The transport the chat waits for, or why, changed (`transportWait`); undefined once nothing is waited for. */\n onTransportWait?(wait: TransportWait | undefined): void;\n /** An attempt to go live ended without it (`liveAttempt`), or the chat went live (undefined). */\n onLiveAttempt?(attempt: LiveAttempt | undefined): void;\n /** A live transport switch completed: the session now runs over `to`, and nothing reconnected. */\n onTransportSwitched?(from: PairedTransport | undefined, to: PairedTransport): void;\n /** Round trip of a liveness ping on the open session, in milliseconds. */\n onRtt?(ms: number): void;\n onTransportDiscovery?(descriptors: TransportDescriptors, transports: PairedTransport[], fallback: boolean): Promise<void>;\n /**\n * With `packetTransports`: the member's packet said which transports its app runs on this link and how to dial them.\n * Without `webrtc/1` among them, it has none, and a session takes native endpoints on this side too.\n */\n onPacketTransports?(transports: PairedTransport[], descriptors: TransportDescriptors): void;\n /**\n * With `packetTransports`: the member's packet has carried no `_tr` for `TRANSPORTS_GONE_MS` (link.ts), so its app\n * publishes none, as one with WebRTC that runs no native endpoint on this link does. What an earlier packet said is\n * forgotten here, and the owner forgets what it kept of it.\n */\n onPacketTransportsGone?(): void;\n /**\n * With `packetTransports`: the member's packet carries no `_tr` where the last one read did (`true`), or one again\n * (`false`). News only: what it said before is kept, and on a device link only a signed value counts.\n */\n onPacketTransportsUnsaid?(unsaid: boolean): void;\n onPairingState?(state: PairingState): void;\n /** How far a first pairing got (`pairingProgress` option): every change, up to `live`. */\n onPairingProgress?(progress: PairingProgress): void;\n onMessage?(message: IncomingMessage): void | Promise<void>;\n onPresence?(presence: PeerPresence): void;\n /** A paired contact's profile picture, already checked; `null` when they removed it. */\n onPeerAvatar?(avatar: string | null): void;\n /**\n * The name a paired contact asked to be shown by, already checked; `null` when they have none (never set,\n * removed, or not shared). Said on every session, so what arrives here is the contact's current choice.\n */\n onPeerNick?(nick: string | null): void;\n onMessageReceipt?(id: string): void | Promise<void>;\n /**\n * A file's offer the contact said on the DHT floor (WISP 403 § Files), already checked: its bubble takes its place\n * now, and its bytes come on the live session under the same wire id. Without this event it is dropped (receipted).\n */\n onFileAnnounced?(file: DhtFileAnnouncement & { timestamp: number; reply?: { i: string }; forwarded?: number }, packet: DhtPacketFacts): void | Promise<void>;\n /**\n * What the contact's app says about held items (`hold/1`): whether it accepts them (from the handshake, or\n * a `paired-hold` frame on the session) and the highest sequence it has held for this side, if it said.\n */\n onHold?(state: { peerAllows: boolean; peerTop?: number }): void | Promise<void>;\n onPeerAck?(ackTimestamp: number): void;\n onCallSignal?(signal: string): void;\n /**\n * The contact started or stopped typing (`typing/1`, WISP 401 § Typing), or said something new while it goes on\n * (recording, thinking, a bot's status); only changes, never stored.\n */\n onPeerTyping?(typing: boolean, activity: TypingActivity | null): void;\n /**\n * What the contact says of itself changed (`status/1`, WISP 401 § Presence and status): its presence, which ends with\n * the session, and a status it set; only changes, never stored here.\n */\n onPeerStatus?(state: StatusState): void;\n /**\n * The contact reacted to a message (`react/1`, WISP 401 § Reactions), already checked. True: confirm it (it was\n * taken: shown, kept for its message, or older than what is shown); false: not now, it comes again.\n */\n onReaction?(reaction: WireReaction): boolean | Promise<boolean>;\n /** The contact confirmed this side's reaction numbered `n`. */\n onReactionReceipt?(n: number): void | Promise<void>;\n /** The contact's DHT envelope said it took this side's reactions up to number `n`. */\n onReactionsTaken?(n: number): void | Promise<void>;\n /** Both sides offer `react/1` on the open session (true), or no longer (false). */\n onReactionsSupport?(supported: boolean): void;\n /**\n * The contact edited one of its messages (`edit/1`, WISP 401 § Edits), already checked. True: confirm it now (it\n * was shown, or was not newer, or its message is gone); false: not yet (its message is not here), and\n * `confirmEdit` says so once it is.\n */\n onMessageEdit?(edit: WireEdit): boolean | Promise<boolean>;\n /** The contact confirmed edit `e` of one of this side's messages. */\n onEditReceipt?(id: string, e: number): void | Promise<void>;\n /** Both sides offer `edit/1` on the open session (true), or no longer (false). */\n onEditSupport?(supported: boolean): void;\n /**\n * The contact pinned a message, or unpinned (`pin/1`, WISP 401 § Pinned message), already checked. True: confirm it\n * (taken, or older than the pin shown); false: not now, it comes again.\n */\n onPin?(pin: WirePin): boolean | Promise<boolean>;\n /** The contact confirmed this side's pin numbered `n`. */\n onPinReceipt?(n: number): void | Promise<void>;\n /** Both sides offer `pin/1` on the open session (true), or no longer (false). */\n onPinSupport?(supported: boolean): void;\n /**\n * The contact shared how to wake its closed web app (`wake/1`, WISP 401 § Wake-up push), already checked; null:\n * it stopped sharing (forget it). Kept by the caller: it is what makes a wake-up possible while the contact is away.\n */\n onPeerWake?(target: WakeTarget | null): void;\n /** Both sides offer `wake/1` on the open session (true), or no longer (false): the moment to share this side's. */\n onWakeSupport?(supported: boolean): void;\n /**\n * The contact said it holds the asker key of the contact request that started this chat (WISP 8xx § Accept), not\n * checked yet: only the caller knows which key it waits for. With this chat's two participation keys.\n */\n onContactAsker?(frame: unknown, keys: { mine: string; peer: string }): void;\n /**\n * The contact's app opened, closed or sent data in one of this chat's mini-apps (`apps/1`, WISP 1200 § In a chat),\n * already checked against the receiver's limits; or, as a `close` with `offline`, the session ended while it had one\n * open. Never stored.\n */\n onAppFrame?(event: AppFrameEvent): void;\n /** Both sides offer `apps/1` on the open session (true), or no longer (false). */\n onAppsSupport?(supported: boolean): void;\n /**\n * The contact's app asks for a range of a file this side's app serves (`app-ranges/1`): read it and give the bytes to\n * `sendAppRange`, or say why not with `failAppRange`. Already checked against the serve ids and the requests in\n * flight; `task.live` turns false when it no longer matters. Settle every task, live or not, with one of the two: a\n * task the contact cancelled holds its place among the app's requests in flight until then.\n */\n onAppRangeTask?(task: AppRangeTask): void;\n onStatus?(status: LinkStatus): void;\n onDataLinkState?(state: DataLinkState): void;\n /** What a WebRTC attempt of this link said about direct connections from this device (`directPath.ts`). */\n onDirectEvidence?(evidence: DirectEvidence): void;\n /**\n * WebRTC here refused this side's answers in a row through every pause after them (`ANSWERS_REFUSED_PAUSES`): the next\n * offer waits the backoff of failed dials, minutes, while the contact is there.\n */\n onAnswersRefused?(): void;\n /**\n * A group link's WebRTC offer of this side's was answered and nothing connected `RACE_ANSWERED_MS` later: there is no\n * direct path, as a chat's race takes it (`scheduleRace`). Said once per offer; the attempt itself goes on. Not for an\n * answer read late (`LATE_ANSWER_MS`): the link gives that attempt up and offers again.\n */\n onRtcStalled?(): void;\n /** The contact's packet came between two reads of its record: its clock against this one (`LinkSessionEvents.onPeerClock`). */\n onPeerClock?(packetAt: number, readBefore: number, readAt: number): void;\n onPoll?(poll: { polling: boolean; nextInMs: number }): void;\n /** The peer is sending a file. Return where to put it, or null (or a reason) to refuse. */\n onFileStored?(file: FileInfo): Promise<string | undefined>;\n onFileIncoming?(file: FileInfo): FileSink | string | null;\n /** The room this device has left for files (null: it does not say): a files/2 file larger than that is refused. */\n onFileRoom?(): Promise<number | null>;\n onFileProgress?(fileId: string, transferred: number, direction: \"in\" | \"out\"): void;\n onFileComplete?(fileId: string, direction: \"in\" | \"out\"): void;\n onFileFailed?(fileId: string, reason: string, direction: \"in\" | \"out\"): void;\n /**\n * A files/3 frame (`FILE_FRAMES`), only while both sides agreed `files/3` on the open session. A file's data that came\n * as a binary message (`files/4`) is the `pf-data` frame it stands for, its `data` the bytes themselves.\n */\n onFilesFrame?(frame: Record<string, unknown>): void | Promise<void>;\n /**\n * files/3 can flow (a session agreed it and is open), or no longer can. Said again, open, after a live\n * transport switch: frames on the old channel may be lost, and offering again puts both sides in step.\n */\n onFilesSession?(open: boolean): void;\n onPaymentRequest?(request: PaymentRequest): void | Promise<void>;\n /** A contact asking to pay this side (paired chats): answer with a request carrying the ask's id. */\n onPaymentAsk?(ask: PaymentAsk): void | Promise<void>;\n onPayment?(payment: Payment): void | Promise<void>;\n onPaymentResult?(result: PaymentResult): void | Promise<void>;\n /** A `group-*` frame (WISP 900) from the peer, only while both sides announced `paired-groups`. */\n onGroupFrame?(frame: Record<string, unknown>): void | Promise<void>;\n /** Group frames can flow (both announced), or no longer can. */\n onGroupsSupport?(supported: boolean): void;\n /**\n * A frame between two of a person's devices (WISP 06, `deviceLink.ts`), on a device link only, and only while both\n * ends announced the capability its type travels under.\n */\n onDeviceFrame?(frame: DeviceFrame): void | Promise<void>;\n /** The device capabilities both ends announced on the open session changed: what is agreed now. */\n onDeviceCapabilities?(agreed: DeviceCapability[]): void;\n /**\n * A session was refused because the other end authenticated with another participation key than the one pinned.\n * A device's one-time enrollment link (WISP 06 § Adding a device) tells the person that a second device tried its code.\n * Also once for each further key that signs a signal in the other end's packet: every holder of the code writes that\n * one packet, so a second key there is a second device, whether or not a key was pinned yet.\n */\n onPeerKeyRefused?(): void;\n}\n\n/** How many keys' signals a one-time enrollment link remembers: past these, further keys are not counted. */\nconst SIGNAL_SIGNERS_MAX = 16;\nconst PAYMENT_METHODS: PaymentMethodName[] = [\"cashu\", \"lightning\", \"arkade\", \"usdt\", \"bark\", \"bitcoin\", \"fedimint\", \"spark\"];\n\n/** For each way of paying, the networks (real money, test coins) this side has a wallet on. */\nexport type PaymentNetworks = Partial<Record<PaymentMethodName, (\"mainnet\" | \"testnet\")[]>>;\n\n/** A `paired-payments` networks map from the contact, or null when it is not a valid one (it is then ignored). */\nexport function parsePaymentNetworks(value: unknown): PaymentNetworks | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length > 16) return null;\n const networks: PaymentNetworks = {};\n for (const [method, list] of entries) {\n if (!Array.isArray(list) || list.length > 2 || !list.every((n) => n === \"mainnet\" || n === \"testnet\")) return null;\n // A method this app does not know yet is left out, like in the methods list.\n if (PAYMENT_METHODS.includes(method as PaymentMethodName)) networks[method as PaymentMethodName] = [...new Set(list as (\"mainnet\" | \"testnet\")[])];\n }\n return networks;\n}\n\nexport interface GhostLinkOptions {\n /** Ways of paying this chat allows. One that is off is not offered in the handshake, sent or accepted. Absent: allowed. */\n paymentMethods?: Partial<Record<PaymentMethodName, boolean>>;\n /**\n * The networks of this side's wallets, per way of paying: said with the methods on the open session, so the\n * contact offers only cards whose networks meet. Older apps ignore it.\n */\n paymentNetworks?: PaymentNetworks;\n arkPaymentsSupport?: boolean;\n usdtPaymentsSupport?: boolean;\n barkPaymentsSupport?: boolean;\n /** Announce private groups (WISP 900) on the open session. Announced after the handshake, like `paired-payments`, so a full offer stays within what older apps accept. */\n groupsSupport?: boolean;\n /** Offer `hold/1`: accept items held for this side, and hold items for the contact while it is away. */\n holdSupport?: boolean;\n /** Offer `calls/1` on paired sessions: this app can place and take calls (WebRTC media and capture). */\n callsSupport?: boolean;\n /** Why this app cannot call, when `callsSupport` is off and the platform can say more (what to install). */\n callsMissing?: string;\n /** Offer `services/1` on paired sessions: this app can serve granted local web apps and open the contact's. */\n servicesSupport?: boolean;\n /** Offer `files/3` on paired sessions: files of any size, offered, resumed and checked (`chatFiles.ts`). */\n largeFilesSupport?: boolean;\n /**\n * With `largeFilesSupport`, offer `files/4` on a session whose channel carries binary messages: a file's bytes as\n * they are, not as text (WISP 501 § files/4). The owner's `onFilesFrame` then takes a `pf-data` whose `data` is bytes.\n */\n binaryFilesSupport?: boolean;\n /** Offer `typing/1` on paired sessions: say and show when either side is writing (1:1 chats, not group edges). */\n typingSupport?: boolean;\n /** Offer `status/1` on paired sessions: say and show presence and a set status (1:1 chats, not group edges). */\n statusSupport?: boolean;\n /** Offer `react/1` on paired sessions: reactions to messages (1:1 chats, not group edges). */\n reactionsSupport?: boolean;\n /** Offer `edit/1` on paired sessions: sent texts can be edited (1:1 chats, not group edges). */\n editSupport?: boolean;\n /** Offer `pin/1` on paired sessions: a pinned message (1:1 chats, not group edges). */\n pinSupport?: boolean;\n /** Offer `status-card/1` on the paired session: this app shows status cards (WISP 405 · Status Cards). */\n statusCardSupport?: boolean;\n /** Offer `buttons/1` on the paired session: this app shows and presses message buttons (WISP 406 · Message Buttons). */\n buttonsSupport?: boolean;\n /** Offer `wake/1` on paired sessions: this app wakes a contact's closed web app with a push (1:1 chats, not group edges). */\n wakeSupport?: boolean;\n /**\n * Offer `upgrade/1` on paired sessions (1:1 chats): a session live on a relayed transport, nobody having chosen it,\n * moves once to a direct one ranked first; and back after an absence, a relayed transport is knocked on at once too,\n * where the contact's capability record says it moves as well (`peerUpgrades`).\n */\n upgradeSupport?: boolean;\n /**\n * Offer `apps/1` on paired sessions (1:1 chats, not group edges): mini-apps talk to the same app on the contact's\n * side (WISP 1200 § In a chat). Behind the apps feature flag.\n */\n appsSupport?: boolean;\n /**\n * With `appsSupport`, offer `app-ranges/1`: the contact's app reads, in ranges, a file this side's app serves, and\n * the other way (WISP 1200 § A read lane to the contact). The owner's `onAppRangeTask` then reads the bytes.\n */\n appRangesSupport?: boolean;\n /**\n * The apps this side has open in this chat (chat app id to version), kept by the caller across this link's restarts.\n * Each new session says `open` for each. Without it the link keeps its own.\n */\n appsOpen?: Map<string, string>;\n /** How long the contact's open apps are held across a session change (`APP_RESUME_GRACE_MS`); tests shorten it. */\n appResumeGraceMs?: number;\n /** The contact's capability record, as last read, says `upgrade/1` (WISP 03). */\n peerUpgrades?: () => boolean;\n /**\n * Whether this device has no network now. A native dial that fails then says nothing about its transport, so it\n * counts toward no demotion. By default the browser's `navigator.onLine`; a host that cannot tell is never offline.\n */\n offline?: () => boolean;\n /**\n * A device link (WISP 06): the capabilities it announces on the open session, and so the device frames it carries\n * (`sendDeviceFrame`, `onDeviceFrame`). Never given for a chat or a group's link, which drop every device frame.\n */\n deviceCapabilities?: readonly DeviceCapability[];\n dht?: {\n state?: DhtDeliveryState; save(state: DhtDeliveryState): Promise<void>; pollMs?: number;\n /** How often a contact that chose DHT only is read with the chat in the background (a CLI daemon's, `DhtDelivery`). */\n peerDhtPollMs?: number;\n /** A chat already paired, started again: its first control envelope waits this long (`DhtDelivery`). */\n firstControlAfterMs?: number;\n /** This side's capability-record revision, told in every envelope (WISP 03). */\n capsRev?(): number | undefined;\n /** An envelope from the contact named this revision of its capability record. */\n peerCapsRev?(rev: number): void;\n /** Whether the contact's capability record accepts DHT text; absent or unknown: it does. */\n peerAcceptsText?(): boolean;\n /** Whether the contact's capability record takes a file's offer on the floor (`dht-file/1`); absent: it does not. */\n peerAcceptsFile?(): boolean;\n /** This side's reactions the contact has not confirmed, oldest first: they ride on the envelopes. */\n reactions?(): readonly WireReaction[];\n /** The chat's ratchet (WISP 4xx) and whether the contact's record lists `ratchet/1`: the floor is sealed with it. */\n ratchet?: { box: RatchetBox; peerSupports(): boolean };\n };\n rtcAvailable?: boolean;\n /** `automatic`: the chat follows the app's rule (no transport chosen for it); `preferred` is then the rule's. Absent: automatic unless `preferred` is given. */\n native?: { peerDescriptors?: TransportDescriptors; peerTransports?: PairedTransport[]; peerFallback?: boolean; preferred?: PairedTransport; fallback?: boolean; automatic?: boolean };\n params: LinkParams;\n pairing?: { credentials: PairingCredentials; pinPeer: (key: string, signedSignals?: boolean) => Promise<void>; verifyPeer?: (key: string) => Promise<void>; trustOnFirstUse?: boolean };\n /**\n * A chat that was never paired: follow its first pairing (`onPairingProgress`), and pace its attempts\n * for a contact who is right there. `startedAt`: when the invite was made or joined.\n */\n pairingProgress?: { role: PairingRole; startedAt: number };\n /** When the chat was made, for a saved one: a contact never seen is awaited from then, not from this start (`LinkSessionOptions.awaitingSince`). */\n madeAt?: number;\n transport: PkarrTransport;\n nick?: string;\n /** This side's profile picture (a small JPEG data URL), told to a paired peer directly. */\n avatar?: string;\n lastSeenTimestamp?: number;\n pollIntervals?: PollIntervals;\n /** A contact that left a live session is read no slower than the idle pace this long (a CLI daemon's, `DAEMON_WATCH_PEER_IDLE_MS`). */\n watchPeerIdleMs?: number;\n /**\n * The transport this chat was live on when the app last ran (it quit, or crashed, with the session up). The contact is\n * probably still there, holding a session that is dead now: that transport is dialled first, and a native one is\n * dialled at once by either side, not only by the side whose turn it is (WISP 100, \"Back after a restart\").\n */\n resume?: PairedTransport;\n /**\n * When the session that was live when this app last ran began (ms). A contact's offer made before it is the one that\n * set that session up, or an older one, read from a relay that never got the packet clearing it: it is not answered,\n * and a resumed link dials instead. An offer made after it (the contact noticed the session go, during a long\n * downtime) is answered as any. Unknown (never live, a log lost): every offer is taken as before (bug hunt r7a).\n */\n resumeFloor?: number;\n /**\n * Only this link's two ends can write its records: a group's edge or entry session, whose keys come from the two\n * members' own keys. A chat's records are under keys from its invite, which whoever holds a copy of it can write.\n */\n ownRecords?: boolean;\n /**\n * Open the data link on its own whenever the peer is online, instead of on\n * first use. Chat and call signaling then travel peer to peer and Pkarr is\n * only polled once a minute, which is what keeps relays happy.\n */\n autoConnect?: boolean;\n /** When its first packet goes out (`LinkSessionOptions.firstPublish`): after its first look, the side that dials puts its offer in it. */\n firstPublish?: \"at-start\" | \"after-first-poll\";\n /**\n * A link for one exchange, closed right after it (a group's entry session): once connected, it leaves\n * its offer or answer in its packet rather than publishing again to clear it.\n */\n oneShot?: boolean;\n /**\n * A group's link (an edge, an entry session), which has no capability record: once this side runs a native endpoint on\n * it, its transports and how to dial them ride its own packet (`_tr`), and the member's are read from its packet\n * (WISP 902 § Transports). The owner starts endpoints only where one side has no WebRTC (`onPacketTransports`).\n */\n packetTransports?: boolean;\n /**\n * With `packetTransports`: this side published a `_tr` on this link before (in an earlier run of the app). It goes on\n * saying what it runs now, with or without a native endpoint: the member's app kept the last value it read, and a\n * packet with no `_tr` at all takes nothing back from an app that acts only on one that is there (WISP 902 § Transports).\n */\n packetTransportsSaid?: boolean;\n createPeerConnection: () => RTCPeerConnection;\n localFetch: LocalFetch;\n /** Everything this peer currently offers on this link. */\n getServices: () => ServiceAd[] | undefined;\n /** Web apps a paired contact may reach: told to that contact alone, on the open session, never published. */\n getPairedServices?: () => ServiceAd[];\n /** Resolves an advertised `http` service id to its local target. */\n getHostedHttpService: (id: string) => HostedHttpService | undefined;\n events?: GhostLinkEvents;\n}\n\n/**\n * What a link says when its connection details could not go out: the transport's reason (the Desktop's Rust client\n * rejects with a string, not an Error), and when it is tried again, the soonest a relay is asked (\"asked again in N s\").\n */\nexport function publishFailure(error: unknown): string {\n const reason = error instanceof Error ? error.message : typeof error === \"string\" && error ? error : \"discovery unavailable\";\n const waits = [...reason.matchAll(/asked again in (\\d+) s/g)].map((m) => Number(m[1]));\n const text = reason.replace(/; asked again in \\d+ s/g, \"\").replace(/\\.$/, \"\");\n return `Could not publish connection details: ${text}. ${waits.length ? `Retrying in ${Math.min(...waits)} s.` : \"Retrying.\"}`;\n}\n\n/** A connection that takes over from the session open now once it authenticated (`GhostLink.attach`'s `migration`). */\ninterface LinkCandidate { channel: FrameChannel; session: PairedSession; binding?: NativeBinding; plan?: SwitchPlan; reject(error: Error): void }\n\nexport class GhostLink {\n readonly session: LinkSession;\n private readonly dht: DhtDelivery | null;\n private deliveryMode: DeliveryMode;\n private securityRejected = false;\n readonly dataLink: DataLink;\n private readonly options: GhostLinkOptions;\n private channel: FrameChannel | null = null;\n private endpoints = new Map<PairedTransport, NativeEndpoint>();\n private activeBinding?: NativeBinding;\n private dialing = false;\n /** A joiner's dial made as the link starts (`dialEarly`): its offer goes once the first look finds the inviter. */\n private dialGate?: Promise<boolean>;\n private firstLookDone?: (online: boolean) => void;\n private dhtPinGrace: ReturnType<typeof setTimeout> | null = null;\n /** Native attempts that failed in a row, and transports demoted until when (WISP 100, demotion). */\n private nativeFailures = new Map<PairedTransport, number>();\n private demotedUntil = new Map<PairedTransport, number>();\n private connectionEpoch = 0;\n private readonly switcher: TransportSwitch;\n /** `plan`: a switch both sides agreed; without one, a replacement the contact dialled (`attachReplacement`). */\n private candidate: LinkCandidate | null = null;\n /**\n * Connections that authenticate beside a `candidate` dialled in and unproven (`contend`), oldest first: whichever\n * authenticates first takes over, so one that never does neither holds the place nor takes it from the contact's.\n */\n private contenders: LinkCandidate[] = [];\n private candidateEpoch = 0;\n /** The native dial a transport change has in flight, per transport (`prepareSwitch`). */\n private readonly switchDials = new Map<PairedTransport, Promise<void>>();\n /** Channels a switch replaced, closed after `SWITCH_RETIRE_MS` (or at once on disconnect). */\n private retiring = new Map<FrameChannel, { timer: ReturnType<typeof setTimeout>; close(): void; rtc: boolean; closed: Promise<void> }>();\n private rtcCandidateWaiter: { resolve(): void; reject(error: Error): void } | null = null;\n private transitionTarget?: PairedTransport;\n private transitionError?: string;\n private applicationOpen = false;\n private stopped = false;\n /** Connection details this side could not publish were reported as a pairing error, which the next packet out ends. */\n private signalPublishFailed = false;\n private peerDescriptors: TransportDescriptors;\n private peerTransports?: PairedTransport[];\n /** A group link: this side published a `_tr` on it, in this run or an earlier one (`packetTransportsSaid`). */\n private saidTransports: boolean;\n /** A group link: what is known of the member's transports came from its packet (`_tr`), read now or kept from before. */\n private peerPacketSaid: boolean;\n private peerFallback: boolean;\n private preferred: PairedTransport;\n private fallback: boolean;\n /** No transport chosen for this chat: `preferred` is the app's rule. */\n private automatic: boolean;\n /** What the contact's latest capability record says its app runs (WISP 03); unknown until one is read. */\n private peerRecordTransports?: PairedTransport[];\n /**\n * The contact's explicit choice for this chat as last heard, from its capability record or a session's switch\n * intent; none on Automatic, or before either said (WISP 100, \"A choice made while not live\").\n */\n private peerChoice?: PairedTransport;\n /** The attempt to go live under way on this side, and what failed in it so far. */\n private attempt: { side: LiveAttempt[\"side\"]; failed: LiveAttempt[\"failed\"] } | null = null;\n private lastAttempt?: LiveAttempt;\n /** The transport the chat waits for (WISP 100): attempts that failed in a row, the last error, the next retry. */\n private waiting: { transport: PairedTransport; failures: number; told?: boolean; error?: string; retryAt?: number; timer?: ReturnType<typeof setTimeout> } | null = null;\n /** Why the target of the switch this side dialled did not connect, when a later choice may still carry the chat. */\n private switchMissed?: { transport: PairedTransport; reason: string };\n private paired: PairedSession | null = null;\n private pairedPending = new Map<string, number>();\n private httpHost: HttpHost | null = null;\n /** HTTP to and from shared web apps over a paired session. */\n private pairedHttp: PairedHttp | null = null;\n private httpClient: HttpClient | null = null;\n private files: FileTransfers | null = null;\n private pairedFiles: PairedFiles | null = null;\n private peerServicesOverride: ServiceAd[] | null = null;\n /** A paired peer's name arrives over the channel; nothing about it is published. */\n /** Ways of paying the contact allows, as it last said on this session; null until it does. */\n private peerPaymentMethods: Set<PaymentMethodName> | null = null;\n /** The contact's networks per way of paying, as it last said; null while it said none (an older app). */\n private peerNetworks: PaymentNetworks | null = null;\n /** The contact's word on held items on this session; null until it says. */\n private peerHoldOverride: boolean | null = null;\n private peerNickOverride: string | null = null;\n /** Group protocol versions the peer announced on this session; null until it does. */\n private peerGroupVersions: number[] | null = null;\n /**\n * Groups were on on this session. Off again, they stay off until the next session: each \"on\" runs a group edge's\n * whole opening, and the peer says its versions once a session.\n */\n private peerGroupsWereOn = false;\n /** What each side announced after the handshake (`paired-capabilities`): calls, services. */\n private readonly sessionCapabilities = new SessionCapabilities(() => this.offeredCapabilities());\n private readonly pairedCalls = new PairedCalls();\n /** The channel holding this side's call hang-up, to be sent by the transport should the page go first (`leaveHangUp`). */\n private partingOn: FrameChannel | null = null;\n /** Typing on this session (`typing/1`): when to say `start` again, and the contact's word with its timeout. */\n private readonly typingSender = new TypingSender();\n private readonly typingReceiver = new TypingReceiver((typing, activity) => this.options.events?.onPeerTyping?.(typing, activity));\n /** Presence and status on this session (`status/1`): this side's word (kept across sessions) and the contact's. */\n private readonly statusSender = new StatusSender();\n private readonly statusReceiver = new StatusReceiver(state => this.options.events?.onPeerStatus?.(state));\n /** A status frame waiting for the send interval to pass. */\n private statusTimer: ReturnType<typeof setTimeout> | null = null;\n /** Mini-apps on this session (`apps/1`): this side's open apps (kept across sessions), the peer's, the limits. */\n private readonly apps: AppSessions;\n /** The read lane on this session (`app-ranges/1`): what this side serves and what it asked; none of it outlives the session. */\n private readonly appRanges = new AppRanges(frame => { if (this.supportsAppRanges && this.channel) try { this.channel.send(JSON.stringify(frame)); } catch { /* the session is going: reset ends it */ } });\n /** Reaction frames the contact may send per window; the rest go unconfirmed and come again. */\n private readonly reactionsReceived = new ReactionWindow(REACTION_LIMITS.receive);\n /** Pin frames the contact may send per window; the rest go unconfirmed and come again. */\n private readonly pinsReceived = new ReactionWindow(PIN_LIMITS.receive, PIN_LIMITS.windowMs);\n /** Edit frames the contact may send per window; the rest go unconfirmed and come again. */\n private readonly editsReceived = new RateWindow(EDIT_RECEIVE_LIMIT, EDIT_RATE_WINDOW_MS);\n /** Text frames the contact may send per window (`MESSAGE_RECEIVE_LIMITS`); the rest go unconfirmed and come again. */\n private readonly messagesReceived = [\n new RateWindow(MESSAGE_RECEIVE_LIMITS.burst, MESSAGE_RECEIVE_LIMITS.burstWindowMs),\n new RateWindow(MESSAGE_RECEIVE_LIMITS.hourly, MESSAGE_RECEIVE_LIMITS.hourWindowMs),\n ];\n /** The texts sent to the contact, against their `messagesReceived` (`MessagePace`). */\n private readonly messagesSent = new MessagePace();\n /** Call signals the contact may send per window; the rest are dropped. */\n private readonly callsReceived = new RateWindow(CALL_RECEIVE_LIMIT, CALL_RATE_WINDOW_MS);\n /** WebRTC signals the contact may send on the session (`paired-rtc`) per window; the rest are dropped. */\n private readonly rtcSignalsReceived = new RateWindow(RTC_SIGNAL_RECEIVE_LIMIT, RTC_SIGNAL_RATE_WINDOW_MS);\n private readonly wakeReceived = new RateWindow(6, 60_000);\n /** Said once a session by the requester's app: a few a minute at most. */\n private readonly askerReceived = new RateWindow(4, 60_000);\n /**\n * The contact's name and picture, its word on held items, its ways of paying and its transport descriptors, each saved\n * on this side when it changes: said once a session and when changed, so a handful a minute each. Past that only the\n * newest waits, read once the window has room again.\n */\n private readonly peerSaid = {\n \"paired-nick\": peerSaidWindow(),\n \"paired-avatar\": peerSaidWindow(),\n \"paired-hold\": peerSaidWindow(),\n \"paired-payments\": peerSaidWindow(),\n \"paired-adapters\": peerSaidWindow(),\n };\n /** Identity-proof frames the contact may send per window; the rest are dropped before they are read. */\n private readonly identityReceived = new RateWindow(IDENTITY_FRAME_LIMIT, IDENTITY_FRAME_WINDOW_MS);\n private livenessTimer: ReturnType<typeof setInterval> | null = null;\n private peerAnswersPings = false;\n /** When the ping awaiting its pong went, and the round trip last measured on this session. */\n private pingSentAt = 0;\n private rtt?: number;\n /** The contact's transport policy as last seen on this session, to tell its explicit choices apart. */\n private peerPolicySeen: { intent: number } | null = null;\n private unansweredPings = 0;\n /**\n * Pings sent on this session and pongs heard on it, counted from its start: the contact answers each ping in the order\n * frames come, so the pong to ping n says it handled everything sent before it (`handled`).\n */\n private pingsSent = 0;\n private pongsHeard = 0;\n /** The liveness ping whose pong measures the round trip: its number in `pingsSent`. */\n private rttPing = 0;\n /**\n * Apps' data sent on this session and not yet answered (`APP_IN_FLIGHT`): the bytes each ping that followed them\n * covers, and those sent since the last such ping, which the next one covers.\n */\n private appInFlight: { ping: number; bytes: number }[] = [];\n private appUnmarked = 0;\n /** `handled` callers, each waiting for the pong to its ping. */\n private handledWaiters: { ping: number; done: (exact: boolean | \"late\") => void }[] = [];\n /** The last ping's `PONG_WAIT_MS`: running until something comes back from the contact. */\n private pongWait: ReturnType<typeof setTimeout> | null = null;\n /** The last ping's wait ran out with nothing back, and nothing came since (`restartedRedial`). */\n private pongLate = false;\n private openWaiters: { resolve: () => void; reject: (e: Error) => void }[] = [];\n /** Set while a WebRTC attempt this side dialled is pending: the ranked transports to try if it fails. */\n private afterRtc?: { epoch: number; rest: PairedTransport[] };\n /** When the transports after WebRTC are dialled while its offer is still out (`race`). */\n private raceTimer: ReturnType<typeof setTimeout> | null = null;\n /** Pauses taken after a run of refused answers since WebRTC last opened, and the one under way (`ANSWERS_REFUSED_PAUSES`). */\n private refusedPauses = 0;\n private refusedPause: ReturnType<typeof setTimeout> | null = null;\n /** Set while `race` dials: the offer ending meanwhile is followed up by the race. */\n private racing = false;\n /**\n * The WebRTC offer this side's dial made last, with fallback allowed: what a transport that comes up meanwhile joins.\n * `resume`: the dial that made it is this side back after an absence, over WebRTC (`resuming`); `woke`: the absence\n * was the app's in the background, not a restart (`resumeAfterAbsence`). `knockMissed`: the dial that made it followed a\n * resume's knock that found nothing (`resumeKnockMissed`).\n */\n private offered?: { epoch: number; at: number; resume?: boolean; woke?: boolean; knockMissed?: boolean };\n /**\n * The WebRTC offer this side's dial made last, fallback allowed or not: one made before the contact's record was read\n * races once it is (`raceStandingOffer`).\n */\n private offerMade?: { epoch: number; at: number };\n /** The attempt (its epoch) whose direct transports were knocked on as its offer went out (`knockEarly`), and whether that is under way. */\n private knockedEarly = -1;\n private knockingEarly = false;\n /** The attempt (its epoch) of a resume over WebRTC whose offer Iroh joined, its endpoint up only after the dial (`joinRace`). */\n private irohJoinedResume = -1;\n /** The same for HyperDHT (direct, and already in the race's `afterRtc`). */\n private hyperdhtJoinedResume = -1;\n /** When this side's offer's answer was applied (`RACE_ANSWERED_MS`); 0 while the data link is not connecting on it. */\n private answeredAt = 0;\n /** This side's offer is out unanswered, or answered and not connected yet: what is ranked after WebRTC may race it. */\n private get offerOut(): boolean {\n return this.dataLink.state === \"offering\" || (this.dataLink.state === \"connecting\" && this.answeredAt > 0);\n }\n /** The attempt (`connectionEpoch`) in which the data link began answering the contact's offer. */\n private answeringEpoch = -1;\n /** Set while a dial waits for its WebRTC offer to be made: ends that wait, the contact's offer being answered instead. */\n private offerReplaced?: () => void;\n private lastAutoConnectAt = 0;\n private autoConnectFailures = 0;\n /** The wait (dial and count of failures) whose `dial-backoff` line is written: the looks during it write none. */\n private backoffTraced = \"\";\n /** The look due when a failed dial's backoff ends (`lookAtRetry`). */\n private retryLook: ReturnType<typeof setTimeout> | null = null;\n /** This side's offer is out to the data link and has not reached the relays yet. */\n private offerUnsent = false;\n /** The last dial ended with its offer never out (`offerUnsent`): the contact saw nothing of it. */\n private dialUnseen = false;\n /** Native transports a record just read listed with no way to dial them (`record-undescribed`), until one describes them again. */\n private readonly undescribed = new Set<NativeTransport>();\n /**\n * The native dial under way (`dialNative`): its attempt, its transport, the endpoint it went to (`redescribedDial`),\n * and whether it started with this device offline (`networkBack`).\n */\n private nativeDial: { epoch: number; transport: NativeTransport; endpoint: unknown; offline: boolean } | null = null;\n /** When the device's network last came back (`wake({ network: true })`): a dial under way across it is no failure. */\n private networkBackAt = -Infinity;\n /** The peer's packet I last looked fast for its offer after (its timestamp): once per packet. */\n private offerAwaitedFor = 0;\n /** Whether the stream was blocked (DHT-only on either side) when last looked at. */\n private streamWasBlocked: boolean;\n /** The contact's latest `_rtc` signal while the stream was blocked. */\n private heldSignal: { signal: string; sight?: SignalSight } | null = null;\n /** The link packet of a DHT-only contact its mailbox was last read early for (its timestamp): once per packet. */\n private leftDhtSeenFor = 0;\n /** A first contact under way: its mailbox was read on the contact's first sight (`onPresence`), once per session. */\n private firstSightRead = false;\n /** The first pairing of this chat, while it is one (`pairingProgress` option, no peer key yet). */\n private readonly tracker: PairingTracker | null;\n private lastDataLinkState: DataLinkState = \"idle\";\n /** When an inviter first saw the joiner on the network (0: not yet). */\n private peerSeenAt = 0;\n /** When the channel carrying the chat now was attached. */\n private channelSince = 0;\n /** When the contact last sent something other than the session's upkeep (`QUIET_FRAMES`) on a session. */\n private activityAt = 0;\n /** Set while `yieldEndpoint` ends the session to let its listener go: nothing dials meanwhile. */\n private yielding = false;\n /**\n * The contact said goodbye on the live session (`paired-bye`): its app is going away, likely to restart. Its packet\n * then was `packet`; it is dialled again once a newer one shows it back, or after `until`.\n */\n private departed: { packet: number; until: number } | null = null;\n /**\n * The contact gave the session's listener up (`peerYielded`) when its packet was `packet`: that packet still describes\n * the listener, so nothing is dialled before a newer one (which lists the transport undescribed), or `until`.\n */\n private yielded: { packet: number; until: number } | null = null;\n /** The contact's link packet last seen (its timestamp), to tell a new one from the same one read again. */\n private peerPacketSeen = 0;\n /** A live session ended without this side ending it (`peerLost`): until when the contact's next new packet is news. */\n private lostUntil = 0;\n /** Counts the signals a signer was asked to sign: only the latest one goes out. */\n private signalTurn = 0;\n /** Puts this side's packet out again as it is: another writer of its key may have replaced it. */\n republish(): void {\n if (!this.stopped) this.session.republish();\n }\n /** The keys that signed a signal in the other end's packet, on a link that tells of refused keys (`onPeerKeyRefused`). */\n private signalSigners = new Set<string>();\n /**\n * A one-time enrollment link (WISP 06 § Adding a device: one session per invite): every device that reads the code\n * writes the same packet, each signing its signals with its own device signing key, and the later one replaces the\n * earlier. A validly signed signal by a key other than the one pinned, or than the first one seen there, is a second\n * device on the code: said once per key, before a pin as after it.\n */\n private noteSignalSigner(signal: string): void {\n const events = this.options.events, credentials = this.options.pairing?.credentials;\n if (!events?.onPeerKeyRefused || !credentials?.signer || !this.options.params.profile || this.signalSigners.size >= SIGNAL_SIGNERS_MAX) return;\n if (!verifyPairedSignal(signal, this.options.params.peerPubKeyZ32, this.myPubKeyZ32, undefined, true)) return;\n const key = (JSON.parse(signal) as { auth: { key: string } }).auth.key;\n if (this.signalSigners.has(key)) return;\n this.signalSigners.add(key);\n if (this.signalSigners.size > 1 || (credentials.peerKey && key !== credentials.peerKey)) {\n traceLink(this.myPubKeyZ32, \"signal-second-key\", { keys: this.signalSigners.size });\n events.onPeerKeyRefused();\n }\n }\n /** A signal ready to go: on the live session during a switch to WebRTC, in this side's packet otherwise. */\n private signalOut(signed: string | null, report: (error: unknown) => void): void {\n // During migration the authenticated channel already reaches the peer.\n // Carry signed ICE signaling there instead of waiting for DHT polling.\n if (this.switcher?.pending?.choices.includes(\"webrtc/1\") && this.channel && this.paired?.state.status === \"ready\") {\n if (signed) { this.channel.send(JSON.stringify({ t: \"paired-rtc\", signal: signed })); this.rtcViaChannel = true; }\n return;\n }\n if (!signed) this.rtcViaChannel = false;\n void this.session.setRtcSignal(signed, !!this.options.params.profile).catch(report);\n }\n\n /** A WebRTC signal of this attempt went over the authenticated channel (a migration), not the relays. */\n private rtcViaChannel = false;\n\n /** This app is going away (`depart`): no more dials. */\n private leaving = false;\n /** `resume` still to act on: the first dial after the start goes to it, and a native one is knocked on. */\n private resuming: PairedTransport | undefined;\n /** Until then, a dial waits for the native endpoint `resuming` names to start (it is knocked on as it does). */\n private resumeWaitUntil = 0;\n /** The contact's other native transports were knocked on while this resume waited (`knockWhileResuming`). */\n private resumeKnocked = false;\n /** The resume's knock found nothing (`knock`): the next dial is still the resume's, made whatever the key. */\n private resumeKnockMissed = false;\n /** What the last live session ran on, kept after it ended: a wake resumes on it (`resumeAfterAbsence`). */\n private lastLiveOn: PairedTransport | undefined;\n /** `resuming` is a wake's, not a restart's. */\n private resumingWoke = false;\n /** Until then, a session that ends was lost while the app was away (`WAKE_LOST_MS`). */\n private wokeUntil = 0;\n /** Back after a restart, the first automatic dial is still to go (`INSTANT_FAIL_MS`). */\n private resumeDial = false;\n /** The contact is back (`peerPacketArrived`), and the first automatic dial since is still to go (`BACK_INSTANT_FAIL_MS`). */\n private backDial = false;\n /** That dial failed at once: the next waits `INSTANT_FAIL_RETRY_MS`, not `dialWait`'s backoff. */\n private instantRetry = false;\n\n constructor(options: GhostLinkOptions) {\n this.options = options;\n this.apps = new AppSessions(options.appsOpen);\n // A link that signs through a signer (a device link) has no seed for what a chat signs beside its session.\n if (options.pairing?.credentials.signer && (options.dht || options.params.deliveryMode === \"dht\")) throw new Error(\"A link that signs through a signer has no DHT delivery\");\n this.deliveryMode = options.params.deliveryMode ?? \"stream\";\n // A joiner that pinned its inviter, then read that someone else used the invite first (`inviteTaken`), never paired:\n // the engine asks no progress of a pinned chat, yet after a restart its pairing is still the one stopped there, not\n // a chat on the DHT waiting for a contact who is paired with someone else.\n const dhtState = options.dht?.state;\n const takenAtStart = !!options.pairing?.credentials.peerKey && !!dhtState?.inviteTaken && !dhtState.wasLive;\n const firstPairing = options.pairingProgress ?? (takenAtStart ? { role: \"joiner\" as const, startedAt: options.madeAt ?? Date.now() } : undefined);\n // A DHT-only invite pairs through its mailbox, not through these stages.\n this.tracker = firstPairing && options.pairing && (!options.pairing.credentials.peerKey || takenAtStart) && this.deliveryMode !== \"dht\"\n ? new PairingTracker(firstPairing.role, firstPairing.startedAt, progress => {\n traceLink(this.myPubKeyZ32, \"progress\", { stage: progress.stage, attempt: progress.attempt, peerSeen: progress.peerSeen, reason: progress.reason, retryable: progress.retryable, transport: progress.transport });\n options.events?.onPairingProgress?.(progress);\n }) : null;\n // This side's invite, nobody used yet, or one this side joined whose inviter never came: read less often the longer\n // nobody does, once no longer awaited (counted from the join). Joined chats whose inviter deleted its chat or is\n // gone were read at the background pace for as long as the app ran: 15 of them, 30 reads a minute (bug hunt 1014-0136).\n const invite = !!options.pairingProgress && !!options.pairing && !options.pairing.credentials.peerKey;\n // A joined chat whose inviter never answered, pinned from the envelope it put out before anyone joined (`unanswered`).\n let unanswered = options.dht?.state?.unanswered !== undefined;\n const backsOff = invite || unanswered;\n this.dht = options.params.profile && options.pairing && options.dht ? new DhtDelivery({\n params: options.params, mode: this.deliveryMode, state: options.dht.state, credentials: options.pairing.credentials, transport: options.transport,\n save: options.dht.save, pollMs: options.dht.pollMs, firstControlAfterMs: options.dht.firstControlAfterMs,\n ...(options.dht.peerDhtPollMs && { peerDhtPollMs: options.dht.peerDhtPollMs }),\n ...(backsOff && { inviteMadeAt: options.madeAt ?? Date.now() }),\n capsRev: options.dht.capsRev, peerCapsRev: options.dht.peerCapsRev, peerAcceptsText: options.dht.peerAcceptsText, peerAcceptsFile: options.dht.peerAcceptsFile,\n ...(options.dht.ratchet && { ratchet: options.dht.ratchet }),\n // Reactions ride on the envelopes off the live session (WISP 403 § Reactions).\n ...(options.reactionsSupport && {\n reactions: options.dht.reactions,\n reaction: async reaction => { await options.events?.onReaction?.(reaction); },\n reactionsTaken: async n => { await options.events?.onReactionsTaken?.(n); },\n }),\n // A first contact verified on the DHT pins the contact: the pairing is on the DHT until a stream is up.\n pin: async key => {\n await options.pairing!.pinPeer(key, true);\n // An invite read slowly while nobody used it: its contact's key is looked at now, not at the end of that wait.\n if (invite) this.session.lookNow();\n if (this.isDataLinkOpen || !this.tracker || this.tracker.done) return;\n if (this.deliveryMode === \"dht\") { this.tracker.onDht(\"chosen\"); return; }\n // A stream is usually a moment away: the pairing shows its steps, and ends on the DHT only if no stream\n // makes it (an attempt fails), or none is under way a little later.\n this.tracker.pinnedOverDht();\n if (!this.dhtPinGrace) this.dhtPinGrace = setTimeout(() => {\n this.dhtPinGrace = null;\n if (!this.isDataLinkOpen && this.tracker?.progress.stage !== \"on-dht\") this.tracker?.onDht(\"waiting\");\n }, DHT_PIN_GRACE_MS);\n },\n message: async (message, packet) => {\n // An edit (WISP 403 § Edits) is not a message of its own: it changes one, on an app that takes edits.\n const { edit, file, ...text } = message;\n // A file's offer (WISP 403 § Files) is its bubble, never a text with its name.\n if (file) { await options.events?.onFileAnnounced?.({ ...file, timestamp: message.timestamp, ...(message.reply && { reply: message.reply }), ...(message.forwarded && { forwarded: message.forwarded }) }, packet); return; }\n // Its text holds as a live edit's must (never blank): one that does not is dropped, never shown as a text.\n if (edit && options.editSupport) { if (validEditMessage(message.text)) await options.events?.onMessageEdit?.({ id: edit.i, e: edit.e, ts: message.timestamp, m: message.text }); return; }\n await options.events?.onMessage?.({ ...text, via: \"pkarr\", packet });\n },\n receipt: async id => { await options.events?.onMessageReceipt?.(id); },\n changed: view => {\n options.events?.onDhtDelivery?.(view);\n // The inviter answered the join at last: its key is looked at now, not at the end of that wait.\n const stillUnanswered = this.dht!.unanswered;\n if (unanswered && !stillUnanswered) this.session.lookNow();\n unanswered = stillUnanswered;\n // Someone else used the invite first (the contact's envelopes are sealed to them): the pairing says so, and\n // stops saying it if an envelope of the contact's reads here again.\n if (view.inviteTaken) this.tracker?.failed(\"taken\", false, INVITE_TAKEN);\n else this.tracker?.untaken();\n this.takenChanged();\n this.streamBlockChanged();\n // A contact who chose DHT only (a ghostly1 code carries no mode) paired through the mailbox: the first\n // pairing ends on the DHT, chosen (WISP 400), and the stream attempt it will never answer is not a failure.\n if (this.dht?.peerMode === \"dht\" && options.pairing?.credentials.peerKey && this.tracker && !this.tracker.done && this.tracker.progress.reason !== \"chosen\") this.tracker.onDht(\"chosen\");\n if (this.streamBlocked) {\n if (this.channel || this.dialing || this.dataLink.state !== \"idle\") this.disconnect();\n this.emitDeliveryState();\n } else if (!this.paired) this.maybeAutoConnect(this.session.peerPresence);\n },\n }) : null;\n this.streamWasBlocked = this.streamBlocked;\n this.quietForTaken = this.takenFromUs;\n this.peerDescriptors = checkedDescriptors(options.native?.peerDescriptors);\n this.peerTransports = options.native?.peerTransports;\n this.saidTransports = !!options.packetTransports && !!options.packetTransportsSaid;\n this.peerPacketSaid = !!options.packetTransports && !!options.native?.peerTransports;\n this.peerFallback = options.native?.peerFallback ?? false;\n this.preferred = options.native?.preferred ?? \"webrtc/1\";\n this.fallback = options.native?.fallback ?? true;\n this.automatic = options.native?.automatic ?? !options.native?.preferred;\n this.resuming = options.pairing?.credentials.peerKey && options.params.profile ? options.resume : undefined;\n this.resumeDial = !!this.resuming && !options.packetTransports;\n const events = options.events ?? {};\n\n this.session = new LinkSession({\n params: options.params,\n transport: options.transport,\n nick: options.nick,\n lastSeenTimestamp: options.lastSeenTimestamp,\n pollIntervals: options.pollIntervals,\n awaitingSince: options.madeAt,\n ...(backsOff && { invite: () => !options.pairing!.credentials.peerKey || !!this.dht?.unanswered }),\n ...(invite && { ownInvite: () => !options.pairing!.credentials.peerKey && !options.pairing!.credentials.expectedPeerKey }),\n getServices: options.getServices,\n // A joiner dials the moment it sees the inviter, and an app back after a restart (`resume`) the moment it reads its\n // contact: its offer goes in its first packet, not in a second one right behind its presence. A joiner with no WebRTC\n // (a Linux Desktop) has no offer to wait for: its presence goes at once, and the inviter sees it a read sooner.\n firstPublish: options.firstPublish ?? ((this.tracker && options.pairingProgress?.role === \"joiner\" && options.rtcAvailable !== false) || this.resuming ? \"after-first-poll\" : \"at-start\"),\n // …so those reads say they are a resume's: a group edge's go on the edges' floor at the relays.\n resumed: !!this.resuming,\n events: {\n // The first look decided nothing to dial: say we are here now (a dial says it with its offer).\n onFirstPoll: () => {\n const online = this.session.peerPresence.online, early = this.firstLookDone;\n this.firstLookDone = undefined;\n early?.(online);\n // Nothing to dial: say we are here now (a dial says it with its offer).\n if (!this.dialing || (early && !online)) this.session.ensureAdvertised();\n },\n onMessages: (messages, batch) => {\n if (options.params.profile) return;\n for (const m of messages) events.onMessage?.({ ...m, via: \"pkarr\", batch });\n },\n onPresence: (presence) => {\n if (presence.online) this.tracker?.sawPeer();\n this.peerPacketArrived(presence);\n // A first contact under way, or a joined chat whose inviter never answered (read at its unused-invite wait): a\n // fresh packet of the contact says its envelope is a read away. A first contact's first sight, however old the\n // packet (an inviter back from a restart notices a join late), reads the mailbox now: that read pins the contact,\n // which a mailbox read at the pace of an unused invite would leave up to minutes away. Not once the invite was\n // taken (`takenFromUs`): there is nobody to pair with.\n const firstContact = !options.pairing?.credentials.peerKey;\n if (presence.online && (firstContact || this.dht?.unanswered) && !this.takenFromUs) {\n if (Date.now() - presenceSeenAt(presence) < EXPECT_PEER_MS) this.dht?.expect();\n else if (firstContact && !this.firstSightRead) this.dht?.expect(0);\n if (firstContact) this.firstSightRead = true;\n }\n events.onPresence?.(this.mergePresence(presence));\n this.peerMayHaveLeftDht(presence);\n this.maybeAutoConnect(presence);\n },\n onPublish: result => {\n // Held back by the relays' request budget: nothing failed, and the session sends it when the budget frees a request.\n if (result.waiting) { if (result.retryInMs !== undefined) this.tracker?.heldBack(Date.now() + result.retryInMs); return; }\n if (result.error) { this.tracker?.failed(\"publish\", true, result.error); return; }\n // An offer or answer the relays held back (their budget, an outage) has its whole attempt from when it went out.\n if (result.signalOut) { this.offerUnsent = false; this.dataLink.signalWentOut(); }\n this.tracker?.published();\n this.publishRecovered();\n this.dialSeenNow();\n },\n onPeerAck: (ack) => events.onPeerAck?.(ack),\n onCallSignal: (signal) => { if (!options.params.profile) events.onCallSignal?.(heardCallSignal(signal)); },\n onRtcSignal: (signal, sight) => {\n traceLink(this.myPubKeyZ32, \"rtc-signal-in\", { held: this.streamBlocked });\n // Going away: an answer now would pair the contact with a connection about to die, and it would wait on it.\n if (this.leaving) return;\n // Seen once only: kept, and answered as soon as nothing blocks the stream any more.\n if (this.streamBlocked) { this.heldSignal = { signal, sight }; this.peerDialsFromDht(signal); return; }\n this.handleRtcSignal(signal, sight);\n },\n onPeerClock: (packetAt, readBefore, readAt) => events.onPeerClock?.(packetAt, readBefore, readAt),\n onPeerTransports: value => this.peerPacketTransports(value),\n onPeerTransportsGone: () => this.peerPacketTransportsGone(),\n onPeerTransportsUnsaid: (unsaid) => { if (options.packetTransports && !this.stopped) events.onPacketTransportsUnsaid?.(unsaid); },\n onDiscoveryError: error => events.onDiscoveryError?.(error),\n onStatus: (status) => events.onStatus?.(status),\n onPoll: (poll) => events.onPoll?.(poll),\n },\n });\n\n this.dataLink = new DataLink({\n myPubKeyZ32: this.session.identity.pubKeyZ32,\n peerPubKeyZ32: options.params.peerPubKeyZ32,\n createPeerConnection: options.createPeerConnection,\n publishSignal: signal => {\n // Stopped: its data link closing clears a signal nobody will read.\n if (this.stopped) return;\n // A one-exchange link connected: it closes in a moment, and a packet clearing its offer would only spend the relays' budget.\n if (!signal && options.oneShot && this.dataLink.state === \"open\") return;\n const report = (error: unknown) => {\n // The relays' request budget held it back: the session publishes it once the budget frees a request, and\n // the pairing goes on meanwhile. Waiting for the budget is no connection issue.\n if (isDiscoveryBudgetError(error)) return;\n if (!signal || !options.params.profile) return;\n this.signalPublishFailed = true;\n this.sayPairingState({ status: \"error\",\n error: publishFailure(error) });\n };\n try {\n if (signal && this.tracker) {\n const kind = (JSON.parse(signal) as { t?: string }).t;\n if (kind === \"o\") this.tracker.offerSent(); else if (kind === \"a\") this.tracker.answerSent();\n }\n const signer = options.params.profile ? options.pairing?.credentials.signer : undefined;\n if (signer) {\n // A device link (WISP 06): its signer signs asynchronously. Signals go out in the order they were made,\n // and one that a later signal (or a cleared one) overtook while it was being signed is dropped.\n const turn = ++this.signalTurn;\n if (signal) {\n void fitSignedPairedSignalWith(signal, signer, this.myPubKeyZ32, options.params.peerPubKeyZ32, candidate => this.session.fitsRtcSignal(candidate))\n .then(signed => { if (turn === this.signalTurn && !this.stopped) this.signalOut(signed, report); })\n // What the seed's path throws to the data link: the attempt ends, and the next one starts afresh.\n .catch(error => { report(error); if (turn === this.signalTurn && !this.stopped) this.dataLink.close(); });\n return;\n }\n }\n const signed = signal && options.params.profile && options.pairing\n ? fitSignedPairedSignal(signal, options.pairing.credentials.seedB64, this.myPubKeyZ32,\n options.params.peerPubKeyZ32, candidate => this.session.fitsRtcSignal(candidate)) : signal;\n this.signalOut(signed, report);\n } catch (error) { report(error); throw error; }\n },\n // An offer to a saved contact: its answer may be a while (the contact may still hold this app's old session),\n // so the look for it slows after its first seconds (`OFFER_FAST_MS`). A first pairing looks fast throughout.\n setFastPoll: (fast, offer) => this.session.setFastPoll(fast, !!offer && !!options.pairing?.credentials.peerKey),\n // An answer that did not connect is made again only while the contact's packet still carries that offer.\n offerStanding: ts => !this.leaving && !this.stopped && !this.streamBlocked && this.peerOfferTs() === ts,\n onAnswerReplaced: () => this.redial(),\n onDirect: evidence => events.onDirectEvidence?.(evidence),\n // An answer the relays' budget held back for the whole attempt never reached the offerer (agents#1637).\n signalOut: () => this.rtcViaChannel || this.session.rtcSignalPublished,\n onAnswersRefused: () => this.answersRefused(),\n onOpen: channel => {\n if (this.streamBlocked || this.keyStopped) { channel.close(); return; }\n // Its offer was made or answered before the pin: whatever pinned meanwhile, this session began unpinned.\n if (this.rtcStartedUnpinned) this.openedUnpinned.add(channel);\n const plan = this.switcher.pending;\n if (plan?.choices.includes(\"webrtc/1\") && this.paired?.state.status === \"ready\") {\n void this.attachCandidate(channel, undefined, plan).catch(() => {});\n } else if (this.activeBinding) this.rtcOverHeld(channel); else this.attach(channel);\n },\n onClose: () => {\n if (this.activeBinding) return;\n // A live WebRTC session that closed: dialled again at once, and the contact watched for it to come back.\n const wasLive = !!this.channel && this.paired?.state.status === \"ready\";\n this.detach();\n if (!wasLive) return;\n // Ended here, not by an offer of the contact's (the data link is idle): its network changed, say, and the\n // contact's connection may hold on for half a minute (node-datachannel never says `disconnected`). The side\n // whose key does not dial resumes as after an absence: it dials once, and the contact's offer, should one cross\n // it, is settled by key. It waited for the contact's connection to give up: 31-34 s offline with a CLI contact.\n if (this.dataLink.state === \"idle\" && this.awaitsContactDial()) this.resumeAfterAbsence();\n this.peerLost(\"closed\");\n },\n onState: (state) => {\n const was = this.lastDataLinkState;\n traceLink(this.myPubKeyZ32, \"datalink\", { state });\n this.trackDataLink(state);\n if (state === \"offering\" || state === \"answering\") this.rtcStartedUnpinned = !options.pairing?.credentials.peerKey && !options.pairing?.credentials.expectedPeerKey;\n if (this.activeBinding) return;\n events.onDataLinkState?.(state);\n if (state === \"open\") { this.afterRtc = undefined; this.refusedPauses = 0; }\n if (state === \"offering\") { this.offerUnsent = true; this.dialUnseen = false; }\n if (state === \"answering\") {\n this.answeringEpoch = this.connectionEpoch;\n this.offerReplaced?.();\n if (this.resumingOverRtc) { const epoch = this.connectionEpoch; setTimeout(() => this.maybeKnockAnswering(epoch), 0); }\n }\n this.answeredAt = 0;\n // This side's offer was answered: what is ranked after WebRTC is dialled soon after, if nothing connects.\n if (state === \"connecting\" && was === \"offering\" && this.offerMade?.epoch === this.connectionEpoch) {\n const answeredAt = this.answeredAt = Date.now();\n if (this.offered?.epoch === this.connectionEpoch) this.scheduleRace(this.offered.epoch, this.offered.at);\n // A group link has nothing to race (it runs no native endpoint between two apps with WebRTC): its owner hears\n // of it, and starts the link again over one (node.ts `edgeWithoutRtc`). Left to ICE, it waited for it to give\n // up (15 s in Chromium, the attempt's 90 s where the connection never says `failed`), then for the `_tr` both ways.\n if (options.packetTransports) setTimeout(() => {\n if (this.answeredAt !== answeredAt || this.channel || this.stopped || this.dataLink.state !== \"connecting\") return;\n // An answer read late (`LATE_ANSWER_MS`): the member's ICE may have given up on it meanwhile, which says\n // nothing about the network. The attempt is given up and the edge offers again, WebRTC left on: taken for\n // a network that blocks, the edge went native on both sides after a restart, and past the native slots the\n // member stayed unreachable for the whole of a 12-minute lab (agents#971).\n if (this.dataLink.answerLate) {\n traceLink(this.myPubKeyZ32, \"rtc-stalled\", { late: true });\n this.dataLink.abandon();\n this.redial();\n return;\n }\n traceLink(this.myPubKeyZ32, \"rtc-stalled\", {});\n events.onRtcStalled?.();\n }, RACE_ANSWERED_MS);\n }\n if (state !== \"idle\") return;\n this.dialUnseen = was === \"offering\" && this.offerUnsent;\n this.offerUnsent = false;\n // An answer that could not even be made (no candidate at all), in an attempt nothing else ended: this side has\n // no WebRTC to give for now, and dials what else it runs, whatever its key. The contact, its offer standing,\n // would dial a relayed transport only after `RACE_RELAYED_MS`.\n const unanswerable = was === \"answering\" && this.answeringEpoch === this.connectionEpoch && !this.channel && !this.stopped && !this.leaving;\n if (unanswerable) this.rtcUnstarted();\n this.clearRace();\n // Transports ranked after WebRTC are being dialled: what comes next is theirs to say.\n if (this.racing) return;\n const next = this.afterRtc;\n if (next && next.epoch === this.connectionEpoch && !this.stopped && !this.channel && !this.streamBlocked) {\n // Still inside dial() (WebRTC failed while starting): the dial loop goes on by itself.\n if (this.dialing) return;\n this.afterRtc = undefined;\n void this.dialAfterRtc(next); return;\n }\n this.afterRtc = undefined;\n if (!this.dialing) { this.attemptEnded(); this.lookAtRetry(); }\n this.rejectWaiters(new GhostlyHttpError(\"unreachable\", \"Could not connect to the peer\"));\n if (unanswerable && this.dialsPastRtc()) this.redial();\n },\n // Asked as each attempt starts: once the first pairing is over, the contact reads at its chat's pace (30 s in the\n // background), and a short offer would be withdrawn before it looked.\n attemptTimeoutMs: () => this.tracker && !this.tracker.done ? PAIRING_ATTEMPT_MS : undefined,\n // The contact may have restarted: its offer (a restarted app offers whatever its key, `resume`) is read now and\n // fast while the connection stays so, not at the minute pace of a live chat, and answered at once, which ends the\n // dead session (`DataLink.handleSignal`).\n onDisconnected: disconnected => {\n if (!disconnected) { this.session.setDataLinkStalled(false); return; }\n if (this.activeBinding || !this.channel) return;\n traceLink(this.myPubKeyZ32, \"rtc-disconnected\", {});\n this.session.setDataLinkStalled(true);\n },\n });\n this.switcher = new TransportSwitch({\n key: this.myPubKeyZ32, peerKey: options.params.peerPubKeyZ32,\n policy: () => ({ preferred: this.ownPreferred, fallback: this.fallback, available: this.availableTransports,\n descriptors: Object.fromEntries([...this.endpoints].map(([transport, endpoint]) => [transport, endpoint.descriptor])) }),\n send: frame => {\n try { if (this.channel && this.paired?.state.status === \"ready\") this.channel.send(JSON.stringify(frame)); }\n catch { /* Channel closure is handled by its owner; retry uses a fresh session. */ }\n },\n peer: policy => {\n const before = this.peerPolicySeen;\n this.peerPolicySeen = { intent: policy.intent };\n if (before && policy.intent > before.intent) { this.peerChoice = policy.preferred; options.events?.onPeerTransportChoice?.(policy.preferred); }\n // Intent 0 is only ever \"automatic\": the contact dropped its standing choice.\n else if (before && before.intent > 0 && policy.intent === 0) { this.peerChoice = undefined; options.events?.onPeerTransportChoice?.(\"automatic\"); }\n // A session's first policy that stands for a choice not heard of yet: made while no session was open, and its\n // record not read (yet). Said once, and the owner knows what it already told.\n else if (!before && policy.intent > 0 && policy.preferred !== this.peerChoice) { this.peerChoice = policy.preferred; options.events?.onPeerTransportChoice?.(policy.preferred, true); }\n this.peerDescriptors = policy.descriptors;\n this.peerTransports = transportOrder(policy.available, policy.preferred, true);\n this.peerFallback = policy.fallback;\n void options.events?.onTransportDiscovery?.(policy.descriptors, this.peerTransports, policy.fallback).catch(() => {});\n this.emitPairingState();\n },\n state: (error, target) => {\n this.transitionError = error;\n // Trying again for a transport the chat already waits for is not a switch starting: the wait says it.\n this.transitionTarget = target && this.waiting?.transport === target && this.waiting.failures > 0 ? undefined : target;\n this.emitPairingState();\n },\n prepare: (plan, dial) => { if (dial) void this.prepareSwitch(plan); },\n cancel: () => this.cancelCandidate(),\n kept: (target, reason) => {\n // The chat stayed live on a fallback, or moved to one: said once per choice (a row), then tried again quietly.\n // Moved: why the target did not connect is known on the side that dialled it (`prepareSwitch`).\n reason ??= this.switchMissed?.transport === target ? this.switchMissed.reason : undefined;\n if (this.unreached(target, reason)) options.events?.onTransportSwitchFailed?.(target, reason);\n },\n unreached: (target, reason) => { this.unreached(target, reason); },\n upgrade: () => !!this.options.upgradeSupport && this.sessionCapabilities.agreed(UPGRADE_CAPABILITY),\n });\n // A transport chosen before this link started (the owner says `automatic: false`: kept from a run before a\n // restart) is still a choice (WISP 100, \"A choice made while not live\"): the first session begins with it as a\n // switch intent. Without it both sides' intents start at none, and the chat stays wherever the first dial landed,\n // waiting for nothing. A `preferred` alone is only where to dial first.\n if (options.native?.automatic === false) this.switcher.choseApart();\n // Pinned over the DHT: if the inviter's envelope reads here again (`untaken`), the chat is on the DHT, still trying.\n if (takenAtStart) { this.tracker?.pinnedOverDht(); this.tracker?.failed(\"taken\", false, INVITE_TAKEN); }\n }\n\n get myPubKeyZ32(): string {\n return this.session.identity.pubKeyZ32;\n }\n\n /** The first pairing's stages, read off the data link's states. */\n private trackDataLink(state: DataLinkState): void {\n const was = this.lastDataLinkState;\n this.lastDataLinkState = state;\n // WebRTC as a way to go live, not as the candidate of a switch on a session already open.\n if (!this.activeBinding) {\n if (state === \"answering\") this.attempt ??= { side: \"answered\", failed: [] };\n else if (state === \"idle\" && (was === \"offering\" || was === \"answering\" || was === \"connecting\"))\n this.attemptFailed(\"webrtc/1\", was === \"offering\" ? \"The offer was not answered\" : \"No connection came up\");\n }\n const tracker = this.tracker;\n if (!tracker || tracker.done) return;\n if (state === \"answering\") tracker.offerReceived();\n // On a busy page the channel opens before the answer is applied (`DataLink.handleSignal`): the answer came all the same.\n else if ((state === \"connecting\" || state === \"open\") && was === \"offering\") tracker.answerReceived();\n else if (state === \"idle\") {\n if (was === \"offering\") tracker.failed(\"timeout\", true);\n else if (was === \"answering\" || was === \"connecting\") tracker.failed(\"transport\", true);\n else if (was === \"open\") tracker.reset();\n }\n }\n\n /** How far the first pairing got; absent for a chat that was paired before, or has no `pairingProgress`. */\n get pairingProgress(): PairingProgress | undefined { return this.tracker?.progress; }\n\n /**\n * A contact's offer from before the session that was live when this app last ran began (`resumeFloor`): answering\n * it held the resumed link on a connection the contact no longer offers, until ICE gave up (about 30 s), and its\n * resume dial never went (bug hunt r7a). Dropped; the resumed link dials when it sees the contact.\n *\n * The floor is this device's clock and the offer's time is the contact's: the two are compared only for an offer\n * the first read of this run found, which nothing else dates. One this run saw arrive (`sight`: the contact's record\n * did not have it at an earlier read, and it is not dated before the contact's packet that read found) was made\n * since this app is back. Held against the floor, the offers of a contact whose clock is behind were all dropped\n * until that clock passed the moment the last session began: minutes without a live chat after a restart.\n */\n private predatesLastSession(verified: string, sight?: SignalSight): boolean {\n const floor = this.options.resumeFloor;\n if (floor === undefined) return false;\n const offer = parseRtcSignal(verified);\n if (offer?.t !== \"o\" || offer.ts >= floor) return false;\n if (sight && (sight.after === null || offer.ts >= sight.after)) return false;\n traceLink(this.myPubKeyZ32, \"stale-offer\", { beforeMs: floor - offer.ts });\n this.maybeAutoConnect(this.presence);\n return true;\n }\n\n /** The time of the offer the contact's packet carries, as last read (verified as `handleRtcSignal` does); null for none. */\n private peerOfferTs(): number | null {\n const signal = this.session.peerSignal, credentials = this.options.pairing?.credentials;\n if (!signal) return null;\n const verified = this.options.params.profile ? verifyPairedSignal(signal, this.options.params.peerPubKeyZ32,\n this.myPubKeyZ32, credentials?.peerKey, credentials?.requireSignedSignals) : signal;\n const parsed = verified ? parseRtcSignal(verified) : null;\n return parsed?.t === \"o\" ? parsed.ts : null;\n }\n\n private handleRtcSignal(signal: string, seen?: SignalSight): void {\n // A read that found nothing of the contact's leaves nothing to hold the offer's own time against. A first contact\n // goes by it all the same, its first packet being the one with its offer: a first pairing, before the pin, and a\n // group's link, whose records only its two members write. A pinned contact's offer in a chat is then judged by\n // its own time, as one the first read finds.\n const firstContact = !!this.options.ownRecords || (!!this.options.pairing && !this.options.pairing.credentials.peerKey);\n const sight = seen && seen.after === null && !firstContact ? undefined : seen;\n const options = this.options, credentials = options.pairing?.credentials;\n this.noteSignalSigner(signal);\n const verified = options.params.profile ? verifyPairedSignal(signal, options.params.peerPubKeyZ32,\n this.myPubKeyZ32, credentials?.peerKey, credentials?.requireSignedSignals) : signal;\n if (verified && this.predatesLastSession(verified, sight)) return;\n if (verified) void this.dataLink.handleSignal(verified, sight);\n else if (credentials?.peerKey) {\n // The link's records are published under keys derived from the invite: anyone holding a copy of it can put a\n // signal there, signed by a key of their own or by none. After the pin such a signal is dropped, never a reason\n // to stop the chat; one validly signed by another key is a passive warning (WISP 400).\n if (verifyPairedSignal(signal, options.params.peerPubKeyZ32, this.myPubKeyZ32, undefined, true)) this.dht?.foreignKeySeen(\"signal\");\n else traceLink(this.myPubKeyZ32, \"signal-dropped\", {});\n } else if (credentials?.requireSignedSignals && !this.isDataLinkOpen) {\n this.securityRejected = true;\n this.tracker?.failed(\"rejected\", false);\n this.sayPairingState({ status: \"error\", keyMismatch: false,\n error: \"Ignored an unauthenticated discovery signal. Keep both peers on the updated version; the saved key has not been replaced.\" });\n }\n }\n\n /**\n * Leaving DHT-only takes both sides: each is blocked from a live link until it has seen the other one\n * leave too. The moment it is not, the link is dialled or answered at once: the wait between failed\n * attempts starts over, the contact's offer (or its presence) is looked for fast, and an offer that\n * came in while blocked is answered now instead of timing out on the contact's side (90 s, then its\n * backoff) before it offers again.\n */\n private streamBlockChanged(): void {\n const blocked = this.streamBlocked, was = this.streamWasBlocked;\n this.streamWasBlocked = blocked;\n if (blocked || !was) return;\n traceLink(this.myPubKeyZ32, \"unblocked\", { held: !!this.heldSignal });\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n // The contact's offer is due now, out already if it left first: its first reads are signaling (`SIGNAL_DUE_READS`).\n this.session.expectPeer(false, true);\n const held = this.heldSignal;\n this.heldSignal = null;\n if (held) this.handleRtcSignal(held.signal, held.sight);\n const parked = this.blockedDial;\n if (parked) { this.blockedDial = null; clearTimeout(parked.timer); parked.channel.onClose = null; this.takeDialIn(parked.channel, parked.binding); }\n }\n\n /**\n * A DHT-only contact runs no link session, so it does not advertise itself on the link's key: a fresh\n * packet there that does is it leaving DHT-only. Its mailbox, which says so, is read now rather than at\n * the next poll, and at the DHT pace for a while after: the link packet can reach a relay before the\n * envelope saying so does (back from `chat disconnect --hold`), and a read that still finds DHT-only\n * would otherwise keep the chat off a live link until the next background read, 30 s on.\n */\n private peerMayHaveLeftDht(presence: PeerPresence): void {\n if (!this.dht || this.dht.peerMode !== \"dht\" || this.deliveryMode === \"dht\" || !presence.online) return;\n if (Date.now() - presenceSeenAt(presence) >= EXPECT_PEER_MS || presence.lastPacketAt === this.leftDhtSeenFor) return;\n this.leftDhtSeenFor = presence.lastPacketAt;\n // Held to a growing wait while the contact's mailbox still says DHT only after the reads one started (`peerLinkPacket`).\n const read = this.dht.peerLinkPacket(EXPECT_PEER_MS);\n traceLink(this.myPubKeyZ32, \"peer-link-packet\", { age: Date.now() - presenceSeenAt(presence), ...(!read && { held: true }) });\n }\n\n /**\n * The contact dials (a WebRTC offer signed by its pinned key, or a connection on a native endpoint) while its\n * mailbox last said DHT-only: it has left, and the envelope saying so is on its way. The offer's packet often has no\n * room for the presence `peerMayHaveLeftDht` looks at, so the mailbox is read now and at the DHT pace for a while\n * here too. The offer is kept and answered, and the dial taken, once that read unblocks the stream. False when\n * something else blocks it (this side is DHT-only, the contact is not pinned, or the offer is not the contact's).\n * A connection on a native endpoint (no `signal`) proves nothing yet: anyone who can dial the endpoint can open one,\n * with any identities, and only the session it carries, which waits for this read, authenticates it. The reads it\n * starts are held as a fresh link packet's are (`peerLinkPacket`); the connection is kept for them all the same.\n */\n private peerDialsFromDht(signal?: string): boolean {\n if (!this.dht || this.dht.peerMode !== \"dht\" || this.deliveryMode === \"dht\") return false;\n const credentials = this.options.pairing?.credentials;\n if (!credentials?.peerKey) return false;\n if (signal !== undefined && !verifyPairedSignal(signal, this.options.params.peerPubKeyZ32, this.myPubKeyZ32, credentials.peerKey, true)) return false;\n let read = true;\n if (signal !== undefined) this.dht.expect(EXPECT_PEER_MS, true);\n else read = this.dht.peerLinkPacket(EXPECT_PEER_MS);\n traceLink(this.myPubKeyZ32, \"peer-dials\", { signal: signal !== undefined, ...(!read && { held: true }) });\n return true;\n }\n\n get isDataLinkOpen(): boolean {\n return !this.streamBlocked && this.channel !== null && (!this.options.params.profile || (this.paired?.state.status === \"ready\" && this.currentTransportAllowed()));\n }\n\n private currentTransportAllowed(): boolean {\n const actual = this.paired?.state.transport;\n const remote = this.switcher?.peerPolicy;\n return !!actual && this.transportOffer().includes(actual) && (!remote || allowedTransports(remote).includes(actual));\n }\n /**\n * A packet went out after connection details could not be: the session kept trying (every few seconds), so the\n * error that was reported is over and the pairing carries on from where it is.\n */\n private publishRecovered(): void {\n if (!this.signalPublishFailed) return;\n this.signalPublishFailed = false;\n if (this.stopped || this.keyStopped || this.securityRejected) return;\n if (this.streamBlocked) this.emitDeliveryState();\n else if (this.paired?.state) this.emitPairingState();\n else this.sayPairingState({ status: \"connecting\" });\n }\n\n private emitPairingState(): void {\n this.syncWait();\n const state = this.paired?.state;\n if (!state) { this.notifyWait(); return; }\n const blocked = state.status === \"ready\" && !this.currentTransportAllowed();\n const open = this.isDataLinkOpen;\n if (open !== this.applicationOpen) {\n this.applicationOpen = open;\n // While layer 1 carries the chat its mailbox is read every 5 minutes; lost, at once (WISP 403).\n this.dht?.setLive(open);\n if (!open) this.pairedFiles?.closeAll();\n this.options.events?.onDataLinkState?.(open ? \"open\" : \"idle\");\n }\n this.sayPairingState({ ...state,\n ...(blocked ? { status: this.transitionError ? \"error\" as const : \"negotiating\" as const, error: this.transitionError } : {}),\n transitionTarget: this.transitionTarget, transitionError: this.transitionError,\n });\n this.emitFilesSession();\n this.notifyWait();\n }\n\n get presence(): PeerPresence {\n return this.mergePresence(this.session.peerPresence);\n }\n\n /**\n * Someone else used the invite first: there is nobody to pair with, whether or not this side's look-up pinned its\n * inviter from the envelope put out before anyone joined (said only while unproven: never live, nothing confirmed).\n */\n get takenFromUs(): boolean { return !!this.dht?.inviteTaken; }\n /**\n * The session runs on the joiner's link key, which every copy of the invite derives: while the invite is taken from\n * this side, its packets there read as those of whoever joined first. Republished every 4 minutes, they kept that\n * joiner online at the inviter for good once it quit, dialled at an endpoint long dead (bug hunt 1016-2110). So the\n * session stops without a goodbye (one would say the joiner left) and the native listeners go; only the mailbox's\n * slow read stays, to notice the invite was not taken after all, and that starts it all again.\n */\n private quietForTaken = false;\n private takenChanged(): void {\n const taken = this.takenFromUs;\n if (taken === this.quietForTaken || this.stopped) return;\n this.quietForTaken = taken;\n traceLink(this.myPubKeyZ32, \"taken-quiet\", { taken });\n if (taken) {\n void this.session.stop(false);\n void Promise.allSettled([...this.endpoints.keys()].map(t => this.releaseEndpoint(t)));\n } else if (this.deliveryMode !== \"dht\") this.session.start();\n }\n private get streamBlocked(): boolean { return this.deliveryMode === \"dht\" || this.dht?.peerMode === \"dht\"; }\n /**\n * A stream authenticated a participation key other than the pinned one: a security rejection, which stops the chat\n * on both layers until the person acts (WISP 400), never a reason to fall back to the other path. Only a stream can\n * prove it: the DHT mailbox and the link's signals are written under keys any copy of the invite derives, so another\n * key there is ignored instead.\n */\n private keyStopped = false;\n /** A connection whose failure to authenticate says nothing about the contact: dialled in on a pinned chat. */\n private unproven(channel: FrameChannel): boolean { return this.dialedIn.has(channel) && !!this.options.pairing?.credentials.peerKey; }\n /**\n * A session that started before the pin and was refused for another key: the pin came by another path meanwhile (the\n * DHT's first contact), and whoever this session reached held only a copy of the invite. It proves nothing either.\n */\n private pinnedSince(channel: FrameChannel, paired: PairedSession): boolean { return this.openedUnpinned.has(channel) && !!paired.state.keyMismatch; }\n get textDelivery(): \"stream\" | \"dht\" | \"unavailable\" {\n if (this.isDataLinkOpen) return \"stream\";\n if (!this.dht || this.securityRejected || this.keyStopped) return \"unavailable\";\n if (this.deliveryMode === \"dht\") return \"dht\";\n // A session that the policies keep from carrying the chat (a transport waited for with Fallback off) is not live:\n // text goes over the DHT floor meanwhile, as with no session (WISP 100).\n return (!this.channel || this.sessionBlocked) && !!this.options.pairing?.credentials.peerKey && !!this.dht.peerMode ? \"dht\" : \"unavailable\";\n }\n /** A session is ready, but on a transport the policies do not allow: it coordinates a switch and carries nothing else. */\n private get sessionBlocked(): boolean { return this.paired?.state.status === \"ready\" && !this.currentTransportAllowed(); }\n validateText(text: string, timestamp: number, id: string, reply?: WireReply): string | null {\n // Nobody reads this side's texts: the contact seals everything to whoever used the invite first.\n if (!this.isDataLinkOpen && this.dht?.view.inviteTaken) return INVITE_TAKEN;\n if (this.textDelivery === \"dht\") return this.dht!.validate(text, timestamp, id, reply?.i);\n return this.canSendText ? null : \"No authenticated text delivery method is available.\";\n }\n get canSendText(): boolean { return this.textDelivery !== \"unavailable\"; }\n /** A text on the live session would find room in the contact's windows now (`MessagePace`); the DHT floor has its own pace. */\n get textRoom(): boolean { return this.textDelivery !== \"stream\" || this.messagesSent.room(); }\n get dhtDelivery(): DhtDeliveryView | undefined { return this.dht?.view; }\n /** The chat is on screen: on the DHT its mailbox is read at the signaling pace (WISP 403, poll pace). */\n setChatActive(active: boolean): void {\n this.session.setActive(active);\n this.dht?.setActive(active);\n }\n /**\n * What `emitDeliveryState` said last, cleared by any other pairing state: every mailbox read and publication of a\n * DHT-only chat asks for it again, and one that changed nothing builds no engine state (bug hunt 1109-chat-perf).\n */\n private saidDeliveryState: string | undefined;\n private sayPairingState(state: PairingState): void {\n this.saidDeliveryState = undefined;\n this.options.events?.onPairingState?.(state);\n }\n private emitDeliveryState(): void {\n if (!this.streamBlocked) return;\n const credentials = this.options.pairing?.credentials;\n const error = this.dht?.view.error;\n const state: PairingState = { status: error ? \"error\" : credentials?.peerKey ? \"ready\" : \"connecting\",\n peerKey: credentials?.peerKey, code: this.dht?.comparisonCode, verified: !!credentials?.peerKey && credentials.verifiedPeerKey === credentials.peerKey, error };\n const said = JSON.stringify([state.status, state.peerKey, state.code, state.verified, state.error]);\n if (said === this.saidDeliveryState) return;\n this.saidDeliveryState = said;\n this.options.events?.onPairingState?.(state);\n }\n async setDeliveryMode(mode: DeliveryMode): Promise<void> {\n if (!this.dht) throw new Error(\"DHT delivery is unavailable for this conversation.\");\n traceLink(this.myPubKeyZ32, \"set-mode\", { mode, peerMode: this.dht.peerMode, dials: this.myPubKeyZ32 < this.options.params.peerPubKeyZ32 });\n this.deliveryMode = mode;\n // Someone chose this just now: attempts that failed before are no reason to wait.\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n if (mode === \"dht\") { this.disconnect(); this.heldSignal = null; }\n // The link session runs before the contact can learn the new method (from the envelope setMode publishes). Where the\n // contact dials (the lower key offers), this side's first presence is what it dials on: signaling (`LinkSession.presenceDue`).\n else if (!this.quietForTaken) {\n if (this.myPubKeyZ32 > this.options.params.peerPubKeyZ32) this.session.presenceDue();\n this.session.start();\n }\n await this.dht.setMode(mode);\n if (mode === \"dht\") {\n await this.session.stop(false);\n await Promise.allSettled([...this.endpoints.keys()].map(t => this.releaseEndpoint(t)));\n }\n this.streamBlockChanged();\n this.emitDeliveryState();\n }\n start(): void {\n // What this side runs on a group link now goes in its first packet (`packetTransportsSaid`).\n if (this.saidTransports) this.publishPacketTransports();\n // Back after a restart: the contact, if it still holds the old session, dials or offers as soon as it notices;\n // its offer is looked for fast rather than at the background pace, from the first read on.\n if (this.resuming && this.deliveryMode !== \"dht\") {\n this.session.expectPeer();\n this.resumeWaitUntil = Date.now() + RESUME_WAIT_MS;\n }\n if (this.deliveryMode !== \"dht\" && !this.quietForTaken) this.session.start();\n // A joiner has just opened the invite: the inviter is there, and its first-contact envelope is worth reading\n // at the signaling pace now (an inviter speeds up when the joiner's fresh packet shows).\n if (this.tracker && !this.tracker.done && this.options.pairingProgress?.role === \"joiner\") { this.dht?.expect(); this.dialEarly(); }\n void this.dht?.start();\n }\n\n /**\n * A joiner's offer is gathered as the link starts, while its first look at the inviter's record is under way, and goes\n * once that look finds the inviter (`dialGate`): the two used to come one after the other, the read (0.15 to 0.8 s)\n * then the gathering (0.2 s to 2 s).\n */\n private dialEarly(): void {\n if (!this.options.params.profile || !this.options.autoConnect || this.deliveryMode === \"dht\" || this.streamBlocked || this.dialing || this.channel) return;\n // No WebRTC here (a Linux Desktop): no offer to gather, and nothing to dial before the inviter's record is read.\n if (this.options.rtcAvailable === false) return;\n // Only as the person joins: a joined chat whose inviter never came, started again later, gathers nothing until it shows.\n const startedAt = this.options.pairingProgress?.startedAt ?? 0;\n if (Date.now() - startedAt > EARLY_DIAL_JOIN_MS) return;\n // The offer that goes counts as a dial (`maybeAutoConnect`): one that fails waits the backoff before the next, or a\n // joiner with the lower key offered again at once, and the inviter, answering each, stayed `connecting` (not `on-dht`).\n this.dialGate = new Promise<boolean>(resolve => {\n this.firstLookDone = online => {\n if (online) { this.lastAutoConnectAt = Date.now(); this.autoConnectFailures++; }\n resolve(online);\n };\n });\n traceLink(this.myPubKeyZ32, \"dial\", { early: true });\n void this.dial().catch(error => {\n this.tracker?.failed(\"transport\", true);\n this.dialFailed(error instanceof Error ? error.message : String(error));\n this.lookAtRetry();\n });\n }\n\n async stop(announce = true): Promise<void> {\n this.stopped = true;\n this.clearRace();\n if (this.refusedPause) clearTimeout(this.refusedPause);\n if (this.retryLook) clearTimeout(this.retryLook);\n if (this.dhtPinGrace) clearTimeout(this.dhtPinGrace);\n if (this.waiting?.timer) clearTimeout(this.waiting.timer);\n await this.dht?.stop();\n this.disconnect();\n // This link is over: the contact's apps it held are closed now, not after the grace.\n this.appsEnded();\n await Promise.allSettled([...this.endpoints.values()].map(endpoint => endpoint.close()));\n this.endpoints.clear();\n await this.session.stop(announce);\n }\n\n /** Opens the data link if needed and resolves once it is usable. */\n connect(timeoutMs = 90_000): Promise<void> {\n if (this.streamBlocked) return Promise.reject(new Error(\"DHT-only delivery does not open a live connection. Both peers must choose a live method first.\"));\n if (this.paired?.state.status === \"ready\") { this.switcher.retry(); return Promise.resolve(); }\n if (this.isDataLinkOpen) return Promise.resolve();\n const epoch = this.connectionEpoch;\n return new Promise<void>((resolve, reject) => {\n const waiter = {\n resolve: () => { clearTimeout(timer); resolve(); },\n reject: (error: Error) => { clearTimeout(timer); reject(error); },\n };\n this.openWaiters.push(waiter);\n const timer = setTimeout(() => {\n const index = this.openWaiters.indexOf(waiter);\n if (index < 0) return;\n this.openWaiters.splice(index, 1);\n reject(new GhostlyHttpError(\"timeout\", \"Timed out connecting to the peer\"));\n }, timeoutMs);\n void this.dial().catch(error => {\n if (epoch !== this.connectionEpoch) return;\n const message = error instanceof Error ? error.message : String(error);\n this.tracker?.failed(\"transport\", true, message);\n // Waiting for a chosen transport is not a connection error (WISP 100): the wait says why.\n if (!this.dialFailed(message)) this.sayPairingState({ status: \"error\", error: message });\n this.rejectWaiters(error instanceof Error ? error : new Error(message));\n });\n });\n }\n\n /**\n * `connect` for what only needs the link (a request, a file, a payment step): on a live session it does nothing, where\n * `connect` is a retry that says this side's transport policy again, and the contact reads 10 a minute\n * (POLICY_RECEIVE_LIMIT). A shared app's every file, each file sent and each payment step used to spend one.\n */\n private open(): Promise<void> {\n return this.paired?.state.status === \"ready\" && !this.streamBlocked ? Promise.resolve() : this.connect();\n }\n\n /** Closes what a switch replaced once the contact has had time to move too. */\n private retire(old: FrameChannel, also: () => void, rtc = false): void {\n if (this.retiring.has(old)) return;\n let closed = () => {};\n const done = new Promise<void>(resolve => { closed = resolve; });\n const close = () => { this.retiring.delete(old); old.close(); also(); closed(); };\n this.retiring.set(old, { close, timer: setTimeout(close, SWITCH_RETIRE_MS), rtc, closed: done });\n }\n /**\n * Where the receipt of a frame read on `channel` goes: that session while it carries the chat, the one now when a move\n * replaced it (or moved while the frame was shown), or nowhere.\n */\n private answerOn(channel: FrameChannel): FrameChannel | null {\n const live = this.channel;\n return live && (live === channel || this.retiring.has(channel)) && this.isDataLinkOpen ? live : null;\n }\n /** Counts one text the contact sent; false (and not counted) when either of `messagesReceived` is full. */\n private takeMessage(): boolean {\n return this.messagesReceived.every(window => window.wait() === 0) && this.messagesReceived.every(window => window.take());\n }\n /**\n * The WebRTC session a switch moved off is still retiring (`SWITCH_RETIRE_MS`): its data link is open, and a new offer\n * cannot go until it closes. Resolves once it has (at once when none is).\n */\n private rtcRetired(): Promise<void> {\n return Promise.all([...this.retiring.values()].filter(entry => entry.rtc).map(entry => entry.closed)).then(() => {});\n }\n private closeRetired(): void {\n for (const { timer, close } of [...this.retiring.values()]) { clearTimeout(timer); close(); }\n }\n\n disconnect(): void {\n this.closeRetired();\n this.dropCrossed();\n this.dropCrossedProbe();\n this.dropBlockedDial();\n this.switcher.stop(); this.cancelCandidate();\n this.transitionTarget = this.transitionError = undefined;\n this.connectionEpoch++;\n this.dialing = false;\n this.clearRace();\n const channel = this.channel;\n this.detach();\n channel?.close();\n this.dataLink.close();\n this.rejectWaiters(new GhostlyHttpError(\"unreachable\", \"Connection attempt cancelled\"));\n }\n\n /** What the contact's app can use on this link, as it last said (on the open session, or remembered). */\n get peerAvailableTransports(): PairedTransport[] | undefined {\n const now = this.switcher.peerPolicy?.available;\n if (!now) return this.peerTransports;\n // A session can open before every endpoint of the contact's started: its record says what its app runs.\n return [...now, ...(this.peerRecordTransports ?? []).filter(t => !now.includes(t))];\n }\n /** The open session goes through relays (WISP 100, \"Relayed\"): their hosts, this side's first. */\n get relayedPath(): { relays: string[] } | undefined {\n const transport = this.activeBinding?.transport;\n if (!transport || !this.isDataLinkOpen) return undefined;\n const local = this.localDescriptors(), remote = this.switcher.peerPolicy?.descriptors ?? this.peerDescriptors;\n if (!relayedTransports(local, remote).includes(transport)) return undefined;\n const relays: string[] = [];\n for (const descriptor of [local[transport], remote[transport]]) {\n const relay = (descriptor as { relay?: unknown } | undefined)?.relay;\n if (typeof relay !== \"string\") continue;\n try { const host = new URL(relay).host.replace(/\\.$/, \"\"); if (!relays.includes(host)) relays.push(host); } catch { /* Not a URL: not shown. */ }\n }\n return { relays };\n }\n /** The round trip last measured on the open session; unknown until a ping was answered. */\n get rttMs(): number | undefined { return this.isDataLinkOpen ? this.rtt : undefined; }\n\n /**\n * The transports a session with this contact would cross a relay on: those either side reaches only\n * through one (a browser's HyperDHT or Iroh), per the latest descriptors both sides gave.\n */\n get relayedTransports(): PairedTransport[] {\n return relayedTransports(this.localDescriptors(), this.switcher.peerPolicy?.descriptors ?? this.peerDescriptors);\n }\n\n /** This side's native descriptors, for its capability record (WISP 03): what a contact dials without WebRTC first. */\n get nativeDescriptors(): TransportDescriptors {\n return Object.fromEntries([...this.endpoints].map(([transport, endpoint]) => [transport, endpoint.descriptor])) as TransportDescriptors;\n }\n\n /**\n * The contact's capability record named its native transports and how to dial them: a chat whose WebRTC never\n * connected can still try Iroh or HyperDHT. `fresh`: a record just read, the contact's latest word, so a way to dial\n * it gives (a relay its Iroh endpoint homed on after it started, a new endpoint) replaces the one known. Otherwise (the\n * record kept from before) it only fills what is missing: what a session said is fresher, and transcript-bound.\n */\n learnPeerTransports(transports: PairedTransport[], descriptors: TransportDescriptors, fresh = false): void {\n const wanted = this.wanted()?.transport;\n const listed = !!wanted && !!this.peerRecordTransports?.includes(wanted), dialable = !!wanted && !!this.peerDescriptors[wanted as NativeTransport];\n // The record lists every transport the contact's app runs, started or not (WISP 03): what it lacks, it lacks.\n this.peerRecordTransports = [...transports];\n let changed = false, redescribed = false, again = false, news = false;\n const renamed = new Set<NativeTransport>(), reidentified = new Set<NativeTransport>();\n for (const t of [\"iroh/1\", \"hyperdht/1\"] as const) {\n const known = this.peerDescriptors[t], next = recordDescriptor(t, known, descriptors[t], fresh, transports.includes(t));\n if (next === known) continue;\n if (next === undefined) {\n // Its endpoint is down for now: dials to the old one only timed out (each 20 s, the chat \"retrying live\" for\n // minutes after both apps restarted). The record that describes it again is news, and dialled at once.\n const { [t]: _gone, ...rest } = this.peerDescriptors;\n this.peerDescriptors = rest;\n traceLink(this.myPubKeyZ32, \"record-undescribed\", { transport: t });\n this.undescribed.add(t);\n continue;\n }\n this.peerDescriptors = { ...this.peerDescriptors, [t]: next };\n // Described again after a record said its endpoint was down: dialled at once, but the attempts that failed keep\n // counting. A contact whose record keeps going down and up again must not undo the wait between attempts.\n if (this.undescribed.delete(t)) again = true; else news = true;\n changed = true; redescribed ||= t === wanted; renamed.add(t);\n if (known && endpointId(t, known) !== endpointId(t, next)) reidentified.add(t);\n // A new way to dial it: the attempts that failed on the old one say nothing about this one.\n this.nativeFailures.delete(t); this.demotedUntil.delete(t);\n }\n if (!this.peerTransports && transports.length) { this.peerTransports = transports; this.peerFallback = true; changed = news = true; }\n else {\n // Its app runs more than a session said (an endpoint that started later): those go after the session's order.\n const added = transports.filter(t => !this.peerTransports?.includes(t));\n if (added.length) { this.peerTransports = [...this.peerTransports!, ...added]; changed = news = true; }\n }\n // A transport the chat waits for, newly listed or dialable: tried again now, not at the next retry (WISP 100).\n if (wanted && ((!listed && transports.includes(wanted)) || (!dialable && !!this.peerDescriptors[wanted as NativeTransport]) || redescribed)) this.waitNews();\n this.notifyWait();\n if (!changed) return;\n traceLink(this.myPubKeyZ32, \"record-transports\", { transports });\n // A connection of this side's that has not authenticated, dialled where the contact's record no longer says it is:\n // it went to the old address, and the new one is dialled now rather than when that connection gives up.\n const held = this.channel, heldOn = this.activeBinding?.transport as NativeTransport | undefined;\n if (held && heldOn && renamed.has(heldOn) && !this.dialedIn.has(held) && this.paired?.state.status !== \"ready\"\n && Date.now() - this.channelSince >= REDESCRIBED_GRACE_MS) {\n traceLink(this.myPubKeyZ32, \"redescribed-redial\", { transport: heldOn });\n this.disconnect();\n this.redial();\n return;\n }\n if (held && heldOn && reidentified.has(heldOn) && this.restartedRedial(held, heldOn)) return;\n if (this.redescribedDial()) return;\n // An offer out that was made before this record was read races what it says both run (still inside the dial that\n // makes it, the dial does so once the offer is out).\n if (!this.dialing) this.raceStandingOffer();\n // Something new to dial: the next attempt is now, not after the wait that attempts with nothing to try built up.\n if (this.channel || this.dialing) return;\n if (news || !again) { this.autoConnectFailures = 0; this.lastAutoConnectAt = 0; }\n else this.dialOnNews();\n this.maybeAutoConnect(this.presence);\n }\n\n /** When `dialOnNews` last let a dial go before its wait was over. */\n private lastNewsDialAt = -Infinity;\n /**\n * A chat's listener came up, or the contact's record describes again an endpoint it said was down: the next dial goes\n * now rather than after the wait between attempts, once per that wait. An endpoint registered again and again (a\n * listener lost and started anew) or a record going down and up again would otherwise dial every time, each a native\n * dial, Rust work on a Desktop (a Linux Desktop's idle CPU, 2026-10-01). The failures keep counting.\n */\n private dialOnNews(): void {\n if (Date.now() - this.lastNewsDialAt < this.dialWait()) return;\n this.lastNewsDialAt = Date.now();\n this.lastAutoConnectAt = 0;\n }\n\n /**\n * This side's capability record has a new revision: a DHT envelope names it now, so the contact reads it (WISP 03).\n * Only on the DHT with the contact pinned. A live session carries the same news itself, and before the pin the\n * contact reads the record when it pins; either way an envelope would only spend a relay request, the budget the\n * chat's signalling and held items need.\n */\n announceCapsRevision(): void {\n if (this.isDataLinkOpen || !this.options.pairing?.credentials.peerKey) return;\n void this.dht?.announce().catch(() => {});\n }\n\n /** The transport chosen for this chat on this side, for its capability record; none on Automatic. */\n get choice(): PairedTransport | undefined { return this.automatic ? undefined : this.preferred; }\n\n /**\n * The contact's explicit choice as its capability record names it (WISP 100, \"A choice made while not live\"): how a\n * contact with no session hears of it. `fresh`: a record just read. One that names another choice than the last heard\n * is told (`onPeerTransportChoice`, apart) and dialled first from now on. With a session open, its intents are the\n * contact's word, not a record that may be older; the record kept from before only sets where to start.\n */\n learnPeerChoice(choice: string | undefined, fresh = false): void {\n const next = (TRANSPORTS as readonly string[]).includes(choice ?? \"\") ? choice as PairedTransport : undefined;\n if (!fresh) { this.peerChoice = next; return; }\n if (this.isDataLinkOpen || next === this.peerChoice) return;\n this.peerChoice = next;\n this.options.events?.onPeerTransportChoice?.(next ?? \"automatic\", true);\n this.syncWait(); this.notifyWait();\n this.dialNow();\n }\n\n /**\n * The explicit choice that stands with no session to agree in (WISP 100, \"A choice made while not live\"): this\n * side's, or the contact's last heard. When both chose and they differ, the lower rendezvous key's, as a tie is\n * settled on a session. None when neither chose.\n */\n private get choiceApart(): { transport: PairedTransport; by: \"you\" | \"contact\" } | undefined {\n const mine = this.choice, theirs = this.peerChoice;\n if (mine && (!theirs || theirs === mine || this.myPubKeyZ32 < this.options.params.peerPubKeyZ32)) return { transport: mine, by: \"you\" };\n return theirs ? { transport: theirs, by: \"contact\" } : undefined;\n }\n\n /** Something decides where the chat dials first now: the next attempt goes at once, not after the wait failures built up. */\n private dialNow(): void {\n if (this.channel || this.dialing) return;\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n this.maybeAutoConnect(this.presence);\n }\n\n /**\n * Where the chat is set to go and is not yet (WISP 100, \"A chosen transport not reached yet\"). With a session, the\n * agreement of both policies; without one, a limit of this side's (Fallback off), or else an explicit choice (this\n * side's, or the contact's from its record): otherwise any transport will do, and the chat is simply retrying live.\n */\n private wanted(): { transport: PairedTransport; by?: \"you\" | \"contact\" } | undefined {\n if (!this.options.params.profile || this.streamBlocked || this.keyStopped || this.stopped || !this.options.pairing?.credentials.peerKey) return undefined;\n const state = this.paired?.state;\n if (state?.status === \"ready\") {\n if (!this.paired!.peerTransportSwitchSupport) return undefined;\n const wanted = this.switcher.wanted();\n return wanted && wanted.transport !== state.transport ? wanted : undefined;\n }\n if (!this.fallback) return { transport: this.ownPreferred, ...(this.automatic ? {} : { by: \"you\" as const }) };\n // Any transport may carry the chat, but someone chose one (WISP 100, \"A choice made while not live\"): a side that\n // lacks it says so, as with Fallback off.\n return this.choiceApart;\n }\n\n /** The transport this chat waits for, and why; absent when it is on it, or nothing limits where it goes. */\n get transportWait(): TransportWait | undefined {\n const wanted = this.wanted();\n if (!wanted) return undefined;\n const t = wanted.transport, policy = this.switcher.peerPolicy, waiting = this.waiting?.transport === t ? this.waiting : null;\n const sessionHas = !!policy?.available.includes(t), recordHas = !!this.peerRecordTransports?.includes(t);\n const dialable = t === \"webrtc/1\" ? !!this.peerTransports?.includes(t) : !!this.peerDescriptors[t];\n const failures = waiting?.failures ?? 0;\n const reason: TransportWait[\"reason\"] = !this.availableTransports.includes(t) ? \"app-lacks\"\n : this.switcher.pending?.choices[0] === t ? \"connecting\"\n : sessionHas ? (failures ? \"unreachable\" : \"waiting\")\n : this.peerRecordTransports && !recordHas ? \"contact-lacks\"\n : policy || !dialable ? (recordHas ? \"starting\" : \"unknown\")\n : failures ? \"unreachable\" : \"waiting\";\n // Without a session, a wait is about the transport being there on both sides. A contact that has it and is away,\n // or not reached yet, is the chat retrying live, as any chat on the DHT is (WISP 400, `on-dht`).\n if (this.paired?.state.status !== \"ready\" && reason !== \"contact-lacks\" && reason !== \"starting\" && reason !== \"app-lacks\") return undefined;\n const live = this.isDataLinkOpen ? this.paired?.state.transport : undefined;\n return { transport: t, ...(wanted.by ? { by: wanted.by } : {}), reason, ...(live ? { live } : {}), failures,\n ...(waiting?.error ? { error: waiting.error } : {}), ...(waiting?.retryAt ? { retryAt: waiting.retryAt } : {}) };\n }\n\n /**\n * An attempt to reach `target` did not connect. The chat waits for it, and the side that plans switches tries again\n * on the background pace (`schedule`: with a session; without one the dial's own pace does). True the first time\n * for this wait: a fallback that kept the chat live is said once, later attempts are quiet.\n */\n private unreached(target: PairedTransport, error?: string, schedule = true): boolean {\n const same = this.waiting?.transport === target ? this.waiting : null;\n if (same?.timer) clearTimeout(same.timer);\n const failures = (same?.failures ?? 0) + 1, told = !!same?.told;\n const delay = Math.min(AUTO_CONNECT_RETRY_MS * 2 ** (failures - 1), AUTO_CONNECT_MAX_RETRY_MS);\n const coordinates = this.myPubKeyZ32 < this.options.params.peerPubKeyZ32 && this.paired?.state.status === \"ready\";\n this.waiting = { transport: target, failures, told: true, ...(error ?? same?.error ? { error: error ?? same?.error } : {}) };\n if (schedule && coordinates && !this.stopped) {\n this.waiting.retryAt = Date.now() + delay;\n this.waiting.timer = setTimeout(() => this.retryWait(), delay);\n }\n traceLink(this.myPubKeyZ32, \"wait\", { transport: target, failures, retryIn: this.waiting.retryAt ? delay : undefined, error });\n this.notifyWait();\n return !told;\n }\n\n /** A dial with no session failed while the chat waits for a transport: counted there. True when it waits. */\n private dialFailed(message: string): boolean {\n const wait = this.transportWait;\n if (wait) this.unreached(wait.transport, message, false);\n return !!wait;\n }\n\n /** The next attempt for the transport the chat waits for, on the background pace. */\n private retryWait(): void {\n const waiting = this.waiting;\n if (!waiting) return;\n waiting.timer = waiting.retryAt = undefined;\n if (this.stopped || this.paired?.state.status !== \"ready\" || !this.paired.peerTransportSwitchSupport) return;\n traceLink(this.myPubKeyZ32, \"wait-retry\", { transport: waiting.transport, failures: waiting.failures });\n this.switcher.again();\n this.notifyWait();\n }\n\n /** Something new about the transport waited for (the contact's record lists it, or says how to dial it): try now. */\n private waitNews(): void {\n if (this.waiting) {\n if (this.waiting.timer) clearTimeout(this.waiting.timer);\n this.waiting.timer = this.waiting.retryAt = undefined; this.waiting.failures = 0;\n }\n if (this.paired?.state.status === \"ready\" && this.paired.peerTransportSwitchSupport) this.switcher.again();\n }\n\n private clearWait(): void {\n if (this.waiting?.timer) clearTimeout(this.waiting.timer);\n this.waiting = null;\n }\n /** The chat reached what it waited for, or waits for something else now (a new choice, Automatic, a policy change). */\n private syncWait(): void {\n if (this.waiting && this.wanted()?.transport !== this.waiting.transport) this.clearWait();\n }\n private waitSaid = \"\";\n /** Tells the owner when the wait's view changed (its reason, failures, next retry). */\n private notifyWait(): void {\n const view = this.transportWait, said = view ? JSON.stringify(view) : \"\";\n if (said === this.waitSaid) return;\n this.waitSaid = said;\n this.options.events?.onTransportWait?.(view);\n }\n\n get availableTransports(): PairedTransport[] {\n return [...(this.options.rtcAvailable !== false ? [\"webrtc/1\" as const] : []), ...this.endpoints.keys()];\n }\n /**\n * The transport this side's policy names: on Automatic, the app's rule for what runs now (Iroh once its endpoint is\n * up, with Fallback on; with it off, WebRTC where there is one, so an endpoint coming up moves nothing).\n */\n private get ownPreferred(): PairedTransport { return this.automatic ? automaticTransport(this.availableTransports, this.fallback) : this.preferred; }\n private transportOffer(): PairedTransport[] { return transportOrder(this.availableTransports, this.ownPreferred, this.fallback); }\n\n registerEndpoint(endpoint: NativeEndpoint): void {\n if (this.stopped || this.deliveryMode === \"dht\" || this.quietForTaken || !this.options.params.profile) { void endpoint.close(); return; }\n this.endpoints.set(endpoint.transport, endpoint);\n traceLink(this.myPubKeyZ32, \"endpoint-up\", { transport: endpoint.transport });\n endpoint.onConnection = ({ channel, binding }) => {\n traceLink(this.myPubKeyZ32, \"dialed-in\", { transport: binding.transport, held: !!this.channel, dialing: this.dialing });\n this.takeDialIn(channel, binding);\n };\n endpoint.onUnavailable = () => {\n if (this.endpoints.get(endpoint.transport) !== endpoint) return;\n traceLink(this.myPubKeyZ32, \"endpoint-gone\", { transport: endpoint.transport });\n this.endpoints.delete(endpoint.transport);\n this.advertiseTransports(); this.options.events?.onTransportsChanged?.();\n };\n // A way to dial it changed (the Desktop's Iroh homed on a relay a few seconds after it bound): the open session\n // hears it, and the owner republishes the capability record, which is all a contact with no session has.\n endpoint.onDescriptor = () => { this.advertiseTransports(); this.options.events?.onTransportsChanged?.(); };\n endpoint.onRelayBack = () => { if (this.endpoints.get(endpoint.transport) === endpoint) void this.knockAgain(endpoint.transport); };\n // A changed available offer needs a new authenticated session before native\n // transports are usable. Until then descriptors can be saved but not selected.\n this.advertiseTransports();\n if (this.resuming === endpoint.transport) void this.knock(endpoint.transport);\n else this.joinRace(endpoint.transport);\n // Something new to dial, now: a group link whose member's packet already said how to dial this transport, or a\n // chat that had no listener for it (every native slot was taken when the app started) and its contact is there.\n // A chat's attempts that failed keep counting: an endpoint registered again and again (a listener lost and started\n // anew, a slot taken back and given again) must not undo the wait between attempts, each of them a native dial.\n if (!this.channel && !this.dialing && this.dataLink.state === \"idle\" && this.canDial(endpoint.transport)\n && this.peerTransports?.includes(endpoint.transport)) {\n if (this.options.packetTransports) { this.autoConnectFailures = 0; this.lastAutoConnectAt = 0; }\n else this.dialOnNews();\n this.maybeAutoConnect(this.presence);\n }\n }\n\n /**\n * A group link's `_tr` in its packet: what this side runs and how to dial it, once it runs a native endpoint there.\n * Having said one, it goes on saying what it runs with no endpoint up too (`[\"webrtc/1\"]`): the member's app keeps the\n * last value it read and acts only on a packet that carries one, so a `_tr` that just stopped left it dialling a\n * native transport nobody listens on, across restarts of both apps (an edge whose WebRTC failed once, node.ts\n * `edgeWithoutRtc`, in the next run of the app). Never an empty list: an app with no WebRTC whose endpoint is not up\n * yet says nothing, as before, and what it said in the run before holds.\n */\n private publishPacketTransports(): void {\n if (!this.options.packetTransports) return;\n const signer = this.options.pairing?.credentials.signer;\n // A device link (WISP 06) says none without an endpoint, as before.\n if (this.endpoints.size && !signer) this.saidTransports = true;\n const available = this.availableTransports;\n const value = this.endpoints.size || (this.saidTransports && available.length) ? encodePacketTransports(available, this.localDescriptors()) : null;\n if (!signer) { this.session.setTransports(value); return; }\n // A device link (WISP 06): signed with the device signing key, so a holder of `D` cannot write one in its place.\n // The latest value goes out; one overtaken while it was being signed is dropped.\n const turn = ++this.transportsTurn;\n if (value === null) { this.session.setTransports(null); return; }\n void signDeviceTransports(value, signer, this.myPubKeyZ32, this.options.params.peerPubKeyZ32)\n .then(signed => { if (turn === this.transportsTurn && !this.stopped) this.session.setTransports(signed); })\n .catch(() => {});\n }\n /** Counts the `_tr` values a signer was asked to sign (a device link): only the latest goes out. */\n private transportsTurn = 0;\n\n /** The member's packet said which transports its app runs on this group link, and how to dial them. */\n private peerPacketTransports(value: string): void {\n if (!this.options.packetTransports || this.stopped) return;\n const credentials = this.options.pairing?.credentials;\n if (credentials?.signer && !credentials.peerKey && this.options.pairing?.trustOnFirstUse) {\n // An enrollment's one-time link on the inviter's side (WISP 06 § Adding a device), before a key authenticated:\n // there is no key yet to check the signature against. The value only says where to dial; the session that\n // answers there still has to authenticate. Whoever can write this packet holds the code, and could be the first\n // key to authenticate anyway. Without it, an inviter whose key dials first had nothing to dial, and one with\n // WebRTC never learned that the new device has none (a Linux Desktop, 2026-10-03).\n const unsigned = unsignedDeviceTransports(value);\n if (!unsigned) { traceLink(this.myPubKeyZ32, \"packet-transports-refused\", {}); return; }\n value = unsigned;\n } else if (credentials?.signer) {\n // A device link: only a value signed by the device signing key it pinned. Anything else (unsigned, or signed by\n // another key: a holder of `D` writing in the other device's packet) is dropped, and dials nothing.\n const verified = credentials.peerKey ? verifyDeviceTransports(value, this.options.params.peerPubKeyZ32, this.myPubKeyZ32, publicKeyFromZ32(credentials.peerKey)) : null;\n if (!verified) { traceLink(this.myPubKeyZ32, \"packet-transports-refused\", {}); return; }\n value = verified;\n // Newly said by the device itself: whatever an earlier value made fail waits no longer.\n this.autoConnectFailures = 0; this.lastAutoConnectAt = 0;\n this.nativeFailures.clear(); this.demotedUntil.clear();\n }\n const said = parsePacketTransports(value);\n if (!said) return;\n const transports = said.transports as PairedTransport[], descriptors = dialDescriptors(said.descriptors);\n traceLink(this.myPubKeyZ32, \"packet-transports\", { transports });\n this.peerPacketSaid = true;\n // Its app has no WebRTC: an offer out to it is never answered, and an attempt it answered or took an answer for is\n // gone on its side (its edge started again without WebRTC when that attempt failed there, node.ts `edgeWithoutRtc`).\n // Either would hold the data link for its whole attempt (30 s), and this side would neither dial nor say it is here\n // meanwhile: its packet carried the dead answer.\n if (!transports.includes(\"webrtc/1\") && !this.channel && WEBRTC_ATTEMPT.has(this.dataLink.state)) this.disconnect();\n this.options.events?.onPacketTransports?.(transports, descriptors);\n this.learnPeerTransports(transports, descriptors, true);\n }\n\n /**\n * The member's packet advertises and has carried no `_tr` for `TRANSPORTS_GONE_MS`: its app publishes none, which is\n * what an app with WebRTC that runs no native endpoint on this link does. What an earlier packet said (kept by the\n * owner across restarts) no longer holds: an app that said `[\"iroh/1\"]` while its WebRTC failed and came back with\n * WebRTC, from before it said so itself (`packetTransportsSaid`). Left as it was, this side ranked its transports\n * against that list, found a native one nobody listens on or none at all, and never offered WebRTC again.\n * Not on a device link: there only a signed value counts, and a missing one is signed by nobody.\n */\n private peerPacketTransportsGone(): void {\n if (!this.options.packetTransports || this.stopped || !this.peerPacketSaid || this.options.pairing?.credentials.signer) return;\n this.peerPacketSaid = false;\n traceLink(this.myPubKeyZ32, \"packet-transports-gone\", {});\n this.options.events?.onPacketTransportsGone?.();\n // An open session said what the member's app runs itself, later than any packet kept: that stands.\n if (this.channel) return;\n this.peerTransports = undefined; this.peerRecordTransports = undefined; this.peerFallback = false;\n this.peerDescriptors = {};\n this.undescribed.clear();\n for (const t of TRANSPORTS) if (t !== \"webrtc/1\") { this.nativeFailures.delete(t); this.demotedUntil.delete(t); }\n if (this.resuming && this.resuming !== \"webrtc/1\") { this.resuming = undefined; this.resumingWoke = false; }\n // WebRTC is what there is to try now: at once, not after the wait that attempts with nothing to dial built up.\n // The presence this read brings starts it (`maybeAutoConnect`).\n this.autoConnectFailures = 0; this.lastAutoConnectAt = 0;\n this.notifyWait();\n }\n\n /** A connection the contact dialled on one of this side's native endpoints. */\n private takeDialIn(channel: FrameChannel, binding: NativeBinding): void {\n if (this.streamBlocked) {\n // Only the contact's mailbox blocks it, and a dial says the contact left DHT-only: the connection waits for the\n // read that says so. Closed, it would end the contact's whole attempt, and its next only after a backoff.\n if (this.peerDialsFromDht()) this.parkBlockedDial(channel, binding);\n else channel.close();\n return;\n }\n this.dialedIn.add(channel);\n const plan = this.switcher.pending;\n if (this.channel && plan?.choices.includes(binding.transport)) {\n void this.attachCandidate(channel, binding, plan).catch(() => {}); return;\n }\n // While yielding, the listener closes in a moment, and a session taken on it with it.\n if (this.stopped || this.leaving || this.yielding || !this.transportOffer().includes(binding.transport)) { channel.close(); return; }\n if (this.channel) { this.attachReplacement(channel, binding); return; }\n if (this.dialing && this.myPubKeyZ32 < this.options.params.peerPubKeyZ32 && this.options.pairing?.credentials.peerKey) { this.parkCrossed(channel, binding); return; }\n this.attach(channel, binding);\n }\n\n /** A dial that came in while the contact's mailbox still said DHT-only, kept for the read that clears it (`BLOCKED_DIAL_WAIT_MS`). */\n private blockedDial: { channel: FrameChannel; binding: NativeBinding; timer: ReturnType<typeof setTimeout> } | null = null;\n private parkBlockedDial(channel: FrameChannel, binding: NativeBinding): void {\n this.dropBlockedDial();\n traceLink(this.myPubKeyZ32, \"dial-waits-mailbox\", { transport: binding.transport });\n const timer = setTimeout(() => { if (this.blockedDial?.channel === channel) this.dropBlockedDial(); }, BLOCKED_DIAL_WAIT_MS);\n channel.onClose = () => { if (this.blockedDial?.channel === channel) { clearTimeout(timer); this.blockedDial = null; } };\n this.blockedDial = { channel, binding, timer };\n }\n private dropBlockedDial(): void {\n const parked = this.blockedDial;\n if (!parked) return;\n this.blockedDial = null; clearTimeout(parked.timer); parked.channel.close();\n }\n\n /**\n * Back after a restart on a native transport: dialled at once, whichever side's turn it is. The contact likely still\n * holds the old session and would notice only when its liveness gives up (a minute); a dial reaches it now and takes\n * over (`attachReplacement`). Once only, and a knock that does not connect counts as no failure: the contact may\n * simply be away. Two dials crossing are settled by key order (see `registerEndpoint`).\n *\n * A resume's knock that does not connect leaves its dial whatever the key to the next one (`resumeKnockMissed`), whose\n * offer knocks on the contact's other transports (`knockMissed`): a contact holding the old session over HyperDHT\n * announces no listener (endpoint.mjs), so the knock finds nothing, and the higher key waited for the contact to\n * notice (14.5-15.2 s between two CLI daemons, against 0.8-1.6 s with the lower key; under 5 s now).\n */\n private async knock(transport: NativeTransport): Promise<void> {\n const resume = this.resuming === transport;\n if (resume) { this.resuming = undefined; this.resumingWoke = false; }\n const endpoint = this.endpoints.get(transport), descriptor = this.peerDescriptors[transport];\n if (!endpoint || !descriptor || this.channel || this.dialing || this.stopped || this.streamBlocked || this.keyStopped) return;\n if (!this.transportOffer().includes(transport)) return;\n const epoch = this.connectionEpoch;\n this.dialing = true;\n const knocking = this.knocking = { transport, epoch, again: false };\n traceLink(this.myPubKeyZ32, \"knock\", { transport });\n try {\n const { channel, binding } = await endpoint.connect(descriptor);\n if (this.stopped || epoch !== this.connectionEpoch || this.channel) { channel.close(); return; }\n this.attach(channel, binding);\n } catch (error) {\n traceLink(this.myPubKeyZ32, \"knock-failed\", { transport, error: error instanceof Error ? error.message : String(error) });\n if (resume && epoch === this.connectionEpoch) this.resumeKnockMissed = true;\n } finally {\n if (this.knocking === knocking) this.knocking = null;\n if (epoch === this.connectionEpoch) { this.dialing = false; this.settleCrossed(); }\n }\n if (!this.channel) this.maybeAutoConnect(this.presence);\n }\n /**\n * This side's listener on `transport` is up again after it was let go while the contact was away (the engine's\n * `releaseGoneListeners`), and the contact is back: it is dialled once now, whichever side's turn it is, as after a\n * restart. The contact's own dials found no listener here meanwhile, and wait out their backoff (half a minute).\n */\n knockOnReturn(transport: NativeTransport): void { void this.knock(transport); }\n /** The knock under way (`knock`): its transport, its attempt, and whether it was knocked again (`knockAgain`). */\n private knocking: { transport: NativeTransport; epoch: number; again: boolean } | null = null;\n /**\n * The endpoint of a knock still under way is back on its relay (`NativeEndpoint.onRelayBack`): it is knocked again, once,\n * beside the first, and the first live wins. An Android phone back from Doze knocked at once through an Iroh whose relay\n * was gone; Iroh found it again only seconds later (its reconnect backoff, up to 16 s), and what the knock sent meanwhile\n * went nowhere: QUIC sends it again seconds on, and the dial is given 20 s. Live again 4.4 s and 9.8 s after the\n * return (away 5 and 15 minutes), and once not over Iroh at all (the emulator with a CLI bot, 2026-11-01).\n */\n private async knockAgain(transport: NativeTransport): Promise<void> {\n const knocking = this.knocking;\n if (!knocking || knocking.transport !== transport || knocking.again || knocking.epoch !== this.connectionEpoch) return;\n const endpoint = this.endpoints.get(transport), descriptor = this.peerDescriptors[transport];\n if (!endpoint || !descriptor || this.channel || this.stopped || this.streamBlocked || this.keyStopped) return;\n knocking.again = true;\n traceLink(this.myPubKeyZ32, \"knock-again\", { transport });\n try {\n const { channel, binding } = await endpoint.connect(descriptor);\n if (this.stopped || knocking.epoch !== this.connectionEpoch || this.channel) { channel.close(); return; }\n this.attach(channel, binding);\n } catch (error) {\n traceLink(this.myPubKeyZ32, \"knock-again-failed\", { transport, error: error instanceof Error ? error.message : String(error) });\n }\n }\n\n canReleaseEndpoint(transport: PairedTransport): boolean {\n return this.activeBinding?.transport !== transport && this.candidate?.binding?.transport !== transport && !this.dialing && !this.switcher.pending && !this.transitionTarget;\n }\n async releaseEndpoint(transport: PairedTransport): Promise<void> {\n if (!this.canReleaseEndpoint(transport)) return;\n const endpoint = this.endpoints.get(transport);\n if (!endpoint) return;\n this.endpoints.delete(transport); await endpoint.close(); this.advertiseTransports();\n this.options.events?.onTransportsChanged?.();\n }\n\n /** When the chat was last in use on its session: the contact's last frame of use, or the session's start. */\n get lastActivityAt(): number { return Math.max(this.activityAt, this.channelSince); }\n\n /**\n * Whether the live session on this transport may end so another chat takes its listener (`yieldEndpoint`): open, and\n * unused, for `idleMs` at least (a session that just started has been in use for none of it); no call on, no file\n * moving, nothing being dialled or switched. `canReleaseEndpoint` never gives up a live session; this does, once idle.\n */\n canYieldEndpoint(transport: PairedTransport, idleMs: number): boolean {\n if (this.activeBinding?.transport !== transport || !this.isDataLinkOpen || this.paired?.state.status !== \"ready\") return false;\n if (this.candidate || this.dialing || this.switcher.pending || this.transitionTarget) return false;\n if (this.pairedCalls.on || this.pairedFiles?.busy) return false;\n return Date.now() - this.lastActivityAt >= idleMs;\n }\n\n /**\n * Ends the idle live session on this transport and lets its listener go, for a chat in use that found every one\n * taken. The contact hears a goodbye that says so (`yield`, `peerYielded`), rather than finding out when its pings go\n * unanswered, and does not watch for this app as for one that quit; the record then lists the transport undescribed,\n * so it stops dialling here. The chat goes on over the DHT (or WebRTC),\n * and takes a listener again the same way once it is in use. False when the session may not end (see above).\n */\n async yieldEndpoint(transport: PairedTransport, idleMs: number): Promise<boolean> {\n if (!this.canYieldEndpoint(transport, idleMs)) return false;\n traceLink(this.myPubKeyZ32, \"native-yield\", { transport, idle: Date.now() - this.lastActivityAt });\n // Nothing dials meanwhile (the contact closing first would make this side look for it again), so the endpoint\n // is free to go once the goodbye is out.\n this.yielding = true;\n try {\n // `yield`: the app stays, so the contact does not watch for it to come back (older apps read a plain goodbye).\n try { this.channel?.send(JSON.stringify({ t: \"paired-bye\", yield: true })); } catch { /* closing already: its close says as much */ }\n // Closed at once, a HyperDHT stream dropped the goodbye and the contact heard only the close (`peer-lost`).\n await new Promise(resolve => setTimeout(resolve, YIELD_BYE_MS));\n this.disconnect();\n await this.releaseEndpoint(transport);\n } finally { this.yielding = false; }\n return !this.endpoints.has(transport);\n }\n\n private advertiseTransports(): void {\n this.publishPacketTransports();\n if (this.paired?.state.status !== \"ready\" || !this.options.params.profile) return;\n if (this.paired.peerTransportSwitchSupport) { this.switcher.changed(false); return; }\n const descriptors: TransportDescriptors = {};\n for (const endpoint of this.endpoints.values()) descriptors[endpoint.transport] = endpoint.descriptor;\n try { this.channel?.send(JSON.stringify({ t: \"paired-adapters\", descriptors })); } catch { /* Closing channel; exchange again on reconnect. */ }\n }\n\n /**\n * `automatic`: this side stops choosing. Its policy still says `preferred` (the app's default) for the order\n * it dials in, but its switch intent drops to none, so the contact's explicit choice wins on the open session\n * and, without one, the current transport is kept. Never adds an unavailable adapter either way.\n */\n /**\n * `automatic`: back to the app's rule (no choice of this side's). `choice` false: the same transport with another\n * fallback (the Fallback switch), a policy change that raises no switch intent. A choice of the transport this side\n * already chose raises none either while that choice stands (see `TransportSwitch.chose`).\n */\n async setTransportPreference(preferred: PairedTransport, fallback: boolean, automatic = false, choice = true): Promise<void> {\n if (!this.options.params.profile || !this.availableTransports.includes(preferred)) throw new Error(\"Transport unavailable in this runtime\");\n const again = this.preferred === preferred;\n this.preferred = preferred; this.fallback = fallback; this.automatic = automatic;\n // Someone chose: a wait from before starts over (its failures, its retry, the row a failure gets).\n if (automatic || choice) this.clearWait();\n if (this.paired?.state.status === \"ready\") {\n if (!this.paired.peerTransportSwitchSupport) {\n if (automatic) return;\n this.transitionError = \"Your contact needs an updated app to negotiate a transport change.\";\n this.emitPairingState(); return;\n }\n if (automatic) this.switcher.changed(\"automatic\");\n else if (choice) this.switcher.chose(again);\n else this.switcher.changed(false);\n this.emitPairingState(); return;\n }\n this.notifyWait();\n // A choice made with no session open (WISP 100, \"A choice made while not live\") reaches the contact in the\n // capability record, goes first in the dial, and is the choice the next session begins with (a switch intent), so\n // a session that opens elsewhere moves there. Going automatic clears it, and an older one.\n if (automatic) this.switcher.changed(\"automatic\");\n else if (choice) this.switcher.choseApart();\n // Discovery/incoming connections use this offer when a contact arrives. This also applies to a saved contact that\n // is currently offline.\n if (!this.isDataLinkOpen) {\n // Invalidate an older, incomplete attempt. A late native dial must not\n // install a session using preferences that have since been changed.\n if (this.channel || this.dialing || this.dataLink.state !== \"idle\") this.disconnect();\n // Someone chose: the dialling side tries at once, the choice first.\n if (automatic || choice) this.dialNow();\n return;\n }\n }\n\n private async dial(): Promise<void> {\n if (this.streamBlocked || this.dialing || this.channel) return;\n if (!this.options.params.profile) { await this.dataLink.connect(); return; }\n this.dialing = true;\n const knockMissed = this.resumeKnockMissed;\n this.resumeKnockMissed = false;\n const epoch = this.connectionEpoch;\n this.attempt = { side: \"dialled\", failed: [] };\n this.sayPairingState({ status: \"connecting\" });\n try {\n const local = this.transportOffer();\n const relayed = relayedTransports(this.localDescriptors(), this.peerDescriptors);\n // Cached availability is a routing hint, not permission: the fresh signed\n // PairedSession offer enforces the peer's current (possibly offline-edited) policy.\n const remembered = this.peerTransports && rankTransports(local, this.peerFallback ? this.peerTransports : this.peerTransports.slice(0, 1), relayed);\n const ranked = remembered?.length ? remembered : this.peerTransports ? rankTransports(local, this.peerTransports, relayed) : local.filter(t => t === \"webrtc/1\");\n // A standing explicit choice goes first, relayed or not: the session starts where the agreement would move it\n // anyway. With no session behind it, the choice this side or the contact made meanwhile (WISP 100).\n // A resume over WebRTC on Automatic, where Iroh now ranks ahead of it (a chat live on WebRTC before Automatic put\n // Iroh first, WISP 100 revision 2026-11-08): it resumes on Iroh, which a dial in takes over a held session on.\n // The WebRTC offer that follows if that dial fails still resumes (`resume`, `woke`): the contact takes its held session over.\n const resume = this.resuming === \"webrtc/1\", woke = resume && this.resumingWoke;\n if (this.automatic && this.resuming === \"webrtc/1\" && ranked.includes(\"iroh/1\") && ranked.indexOf(\"iroh/1\") < ranked.indexOf(\"webrtc/1\")) this.resuming = \"iroh/1\";\n const chosen = this.switcher.chosenTarget ?? this.choiceApart?.transport ?? this.resuming;\n if (chosen && chosen === this.resuming && ranked.includes(chosen)) { this.resuming = undefined; this.resumingWoke = false; }\n const choices = chosen && ranked.includes(chosen) ? [chosen, ...ranked.filter(t => t !== chosen)] : ranked;\n if (!choices.length) {\n // A group link: the member's app may be starting a native endpoint for this one right now, and says how to dial\n // it in its packet (`_tr`), which is looked for fast meanwhile rather than at the background pace. On the first\n // few attempts only: a member whose app never says one (an older app, no transport in common) is not read fast forever.\n if (this.options.packetTransports && this.autoConnectFailures <= PACKET_TRANSPORTS_FAST_ATTEMPTS) this.session.expectPeer();\n throw new Error(\"No transport both apps allow is available yet\");\n }\n const fallback = this.fallback && this.peerFallback;\n let lastError: unknown;\n // A transport that keeps failing is tried last for an hour, not first on every attempt.\n const now = Date.now(), demoted = (t: PairedTransport) => (this.demotedUntil.get(t) ?? 0) > now;\n const ordered = choices.length > 1 ? [...choices.filter(t => !demoted(t)), ...choices.filter(demoted)] : choices;\n // Native transports dialled before WebRTC in this attempt that did not connect (a chosen one goes first).\n const failedFirst: PairedTransport[] = [];\n // A relayed one dialled ahead of the rest that has not connected within `RELAYED_FIRST_MS`, still going.\n let ahead: Promise<true | Error> | undefined;\n for (const [index, transport] of ordered.entries()) {\n if (index > 0 && !fallback) break;\n if (transport === \"webrtc/1\") {\n // WebRTC settles later (ICE can fail minutes from now): what ranks after it is where a failed attempt\n // goes, typically a relayed Iroh behind a symmetric NAT (WISP 100, \"Relayed\"), before the DHT floor.\n // A native tried first that did not connect races the offer too, once more: after a restart of both apps the\n // contact's endpoint may still be starting (HyperDHT answers PEER_NOT_FOUND at once), and the chosen\n // transport would otherwise wait for the offer's 90 s timeout.\n const rest = [...failedFirst, ...ordered.slice(index + 1)];\n this.afterRtc = fallback && rest.length ? { epoch, rest } : undefined;\n // Dialled again while this attempt's offer is out (the app dials once its native endpoints are up): the offer\n // stands as it was made, its time and whether it resumes with it, or the knock and the race would go by the second.\n const standing = this.offerOut && this.offered?.epoch === epoch ? this.offered : undefined;\n const offeredAt = standing?.at ?? Date.now();\n this.offered = fallback ? standing ?? { epoch, at: offeredAt, ...(resume && { resume }), ...(woke && { woke }), ...(knockMissed && { knockMissed }) } : undefined;\n this.offerMade = { epoch, at: offeredAt };\n const gate = this.dialGate;\n this.dialGate = undefined;\n // The contact's offer, read while this one still gathers, is answered in its place: the dial is over then, not\n // when the wait for the candidates of a connection already closed ends (`OFFER_HOST_GATHER_MS`). Back after an\n // absence, the knock that goes with that answer would find this dial still under way, and not go.\n const replaced = new Promise<void>(resolve => { this.offerReplaced = resolve; });\n const made = await Promise.race([this.dataLink.connect(gate), replaced]);\n this.offerReplaced = undefined;\n if (made === \"held\") {\n // Made early, and the first look did not find the contact: the dial is dropped, as if never made.\n traceLink(this.myPubKeyZ32, \"dial-held\", {});\n this.afterRtc = undefined; this.offered = undefined; this.offerMade = undefined; return;\n }\n if (this.dataLink.state !== \"idle\" || epoch !== this.connectionEpoch) { this.scheduleRace(epoch, offeredAt); this.raceStandingOffer(); return; }\n // WebRTC gave up while starting (no candidate at all, no connection to be made): tried last for a while.\n this.rtcUnstarted();\n const next = this.afterRtc;\n if (!next) return;\n this.afterRtc = undefined;\n // A transport whose endpoint came up meanwhile joined what follows the offer (`joinRace`): it is dialled\n // too, rather than left to the next attempt, 20 s away or more.\n for (const joined of next.rest) if (!ordered.includes(joined)) ordered.push(joined);\n continue;\n }\n const dialled = this.dialNative(transport, epoch);\n let result: true | Error | \"slow\";\n if (fallback && !ahead && index < ordered.length - 1 && relayed.includes(transport)) {\n let headStart: ReturnType<typeof setTimeout> | undefined;\n result = await Promise.race([dialled, new Promise<\"slow\">(resolve => { headStart = setTimeout(() => resolve(\"slow\"), RELAYED_FIRST_MS); })]);\n clearTimeout(headStart);\n if (result === \"slow\") { ahead = dialled; continue; }\n } else result = await dialled;\n if (result === true) return;\n lastError = result;\n failedFirst.push(transport);\n }\n // Nothing after it connected: the one dialled ahead may still.\n if (ahead) { const result = await ahead; if (result === true) return; lastError = result; }\n throw lastError ?? new Error(\"No permitted transport could connect\");\n } catch (error) {\n if (epoch === this.connectionEpoch) this.attemptEnded(error instanceof Error ? error.message : String(error));\n throw error;\n } finally {\n this.dialGate = undefined;\n if (epoch === this.connectionEpoch) {\n this.dialing = false;\n // A WebRTC attempt that already ended, with nothing ranked after it to go on to.\n if (!this.channel && !this.afterRtc && this.dataLink.state === \"idle\") this.attemptEnded();\n this.settleCrossed();\n }\n }\n }\n\n private localDescriptors(): TransportDescriptors {\n return Object.fromEntries([...this.endpoints].map(([transport, endpoint]) => [transport, endpoint.descriptor]));\n }\n\n /** True once attached (or when a newer attempt took over); the error otherwise. */\n private async dialNative(transport: PairedTransport, epoch: number): Promise<true | Error> {\n const endpoint = this.endpoints.get(transport as NativeEndpoint[\"transport\"]);\n const descriptor = this.peerDescriptors[transport as NativeEndpoint[\"transport\"]];\n if (!endpoint || !descriptor) {\n // A WebRTC session tells it. With no WebRTC between the two apps (a Linux Desktop, the CLI), the contact's app says\n // it once it takes this chat's listener back, as the chat is used there: no session of ours can ask for it.\n const rtc = this.availableTransports.includes(\"webrtc/1\") && (!this.peerTransports || this.peerTransports.includes(\"webrtc/1\"));\n return new Error(rtc ? \"Peer native address unavailable; reconnect WebRTC once to exchange endpoints\" : \"Peer native address unavailable; the contact's app has not given it yet\");\n }\n const started = Date.now();\n const dialed = this.nativeDial = { epoch, transport: transport as NativeTransport, endpoint: endpointId(transport as NativeTransport, descriptor), offline: this.isOffline() };\n try {\n const { channel, binding } = await endpoint.connect(descriptor);\n this.nativeFailures.delete(transport); this.demotedUntil.delete(transport);\n if (this.stopped || epoch !== this.connectionEpoch || this.channel) { channel.close(); return true; }\n this.attach(channel, binding); return true;\n } catch (error) {\n traceLink(this.myPubKeyZ32, \"dial-failed\", { transport, error: error instanceof Error ? error.message : String(error), ms: Date.now() - started });\n if (epoch !== this.connectionEpoch) return true;\n this.attemptFailed(transport, error instanceof Error ? error.message : String(error));\n // Started or ended with this device offline, or the network came back meanwhile: no network says nothing of the\n // transport. Three such drops would demote it for an hour (bug hunt r10a, 2026-10-06).\n if (dialed.offline || this.isOffline() || this.networkBackAt >= started) {\n traceLink(this.myPubKeyZ32, \"dial-failed-offline\", { transport });\n return error instanceof Error ? error : new Error(String(error));\n }\n // Three failures in a row demote it for an hour (WISP 100).\n const failures = (this.nativeFailures.get(transport) ?? 0) + 1;\n if (failures >= DEMOTE_AFTER_FAILURES) { this.nativeFailures.delete(transport); this.demotedUntil.set(transport, Date.now() + DEMOTE_MS); traceLink(this.myPubKeyZ32, \"demote\", { transport }); }\n else this.nativeFailures.set(transport, failures);\n return error instanceof Error ? error : new Error(String(error));\n } finally { if (this.nativeDial === dialed) this.nativeDial = null; }\n }\n\n /**\n * The native dial under way went to an endpoint the contact's newer packet no longer names for that transport: its\n * app started again (a page reloading, as both devices of a handoff do), and the endpoint dialled went with the old\n * one. That dial would end only at its connect timeout (Iroh: 20 s, then the next attempt's wait): it is let go, and\n * the endpoint the packet names dialled now. Not while a WebRTC offer of this attempt stands: the race that follows\n * it keeps its own order.\n */\n private redescribedDial(): boolean {\n const dial = this.nativeDial;\n if (!dial || dial.epoch !== this.connectionEpoch || !this.dialing || this.channel || this.dataLink.state !== \"idle\") return false;\n const now = this.peerDescriptors[dial.transport];\n if (!now || endpointId(dial.transport, now) === dial.endpoint) return false;\n traceLink(this.myPubKeyZ32, \"redescribed-dial\", { transport: dial.transport });\n this.nativeDial = null;\n this.connectionEpoch++;\n this.dialing = false;\n this.clearRace();\n this.afterRtc = undefined;\n // The dial let go is no failure: the one that follows waits no longer for it.\n this.autoConnectFailures = Math.max(0, this.autoConnectFailures - 1);\n this.redial();\n return true;\n }\n\n /** Whether this device has no network now (`GhostLinkOptions.offline`). */\n private isOffline(): boolean {\n return this.options.offline ? this.options.offline() : (globalThis as { navigator?: { onLine?: boolean } }).navigator?.onLine === false;\n }\n\n /**\n * The device's network came back. A native dial that started while it was away would end only at its connect timeout\n * (Iroh: 20 s), well past the return: it is let go, and the chat dialled again now. Its WebRTC offer, if one stands,\n * was made with no network too, and goes with it.\n */\n private networkBack(): void {\n this.networkBackAt = Date.now();\n const dial = this.nativeDial;\n if (!dial?.offline || dial.epoch !== this.connectionEpoch || !this.dialing || this.channel) return;\n // Only where the chat dials again on its own (`redial`): otherwise the dial goes on to its end.\n if (this.stopped || this.leaving || this.streamBlocked || this.keyStopped || !this.options.autoConnect) return;\n traceLink(this.myPubKeyZ32, \"offline-dial\", { transport: dial.transport });\n this.nativeDial = null;\n if (this.dataLink.state !== \"idle\") this.disconnect();\n else {\n this.connectionEpoch++;\n this.dialing = false;\n this.clearRace();\n this.afterRtc = undefined;\n }\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n this.redial();\n }\n\n /** A WebRTC attempt this side dialled ended without opening: the next ranked transports, in order. */\n private async dialAfterRtc(next: { epoch: number; rest: PairedTransport[] }): Promise<void> {\n this.dialing = true;\n try {\n let lastError: Error | undefined;\n for (const transport of next.rest) {\n if (transport === \"webrtc/1\") continue;\n const result = await this.dialNative(transport, next.epoch);\n if (result === true) return;\n lastError = result;\n }\n if (next.epoch === this.connectionEpoch) {\n this.attemptEnded();\n this.rejectWaiters(new GhostlyHttpError(\"unreachable\", lastError ? `Could not connect to the peer: ${lastError.message}` : \"Could not connect to the peer\"));\n }\n } finally { if (next.epoch === this.connectionEpoch) { this.dialing = false; this.settleCrossed(); } }\n }\n\n /**\n * WebRTC went first and its offer is out: if no answer came within `RACE_DIRECT_MS` (a direct transport ranked after\n * it) or `RACE_RELAYED_MS` (a relayed one), those are dialled too, the offer standing meanwhile.\n */\n private scheduleRace(epoch: number, offeredAt: number): void {\n this.clearRace();\n const next = this.afterRtc;\n if (!next || next.epoch !== epoch || epoch !== this.connectionEpoch || !this.offerOut) return;\n const relayed = this.relayedTransports, now = Date.now();\n // Answered and still not connected: everything left is due `RACE_ANSWERED_MS` after the answer, if not sooner.\n const answered = this.answeredAt ? this.answeredAt + RACE_ANSWERED_MS : Infinity;\n const at = next.rest.filter(t => t !== \"webrtc/1\").map(t => Math.max(Math.min(offeredAt + (relayed.includes(t) ? RACE_RELAYED_MS : RACE_DIRECT_MS), answered),\n this.canDial(t) ? 0 : now + RACE_RETRY_MS));\n if (!at.length) return;\n // Back after an absence to a contact whose newest packet is old: it is signalling nothing, and reads at a slow pace\n // (a chat in the background, 30 s on the relays), so the offer waits about that long for its answer. The direct\n // transports ranked after WebRTC are knocked on as it goes out rather than `RACE_DIRECT_MS` later: the first live\n // wins, as in the race. A knock that does not connect counts as no failure, and its transport keeps its place in it.\n // Looked at once the dial that made the offer is over: a transport that joins while it still gathers comes here first.\n if ((this.offered?.resume || this.offered?.knockMissed) && this.knockedEarly !== epoch) setTimeout(() => this.maybeKnockEarly(epoch), 0);\n this.raceTimer = setTimeout(() => { this.raceTimer = null; void this.race(epoch, offeredAt); }, Math.max(0, Math.min(...at) - now));\n }\n /**\n * This side's offer went out before the contact's record was read (a joiner's early one, `dialEarly`): nothing was\n * known of what the contact runs, so it was made with no fallback and nothing raced it. Once the record says, and both\n * sides allow it, the offer races what both run as one made then would: answered and not connected `RACE_ANSWERED_MS`\n * later, the relayed ones too. Behind a VPN that drops UDP, a first pairing went live over the relayed Iroh only once\n * the attempt timed out and the next one raced, 32 to 66 s in (zero's VPN lab, 2026-10-13).\n */\n private raceStandingOffer(): void {\n const made = this.offerMade, epoch = this.connectionEpoch;\n if (!made || made.epoch !== epoch || this.offered?.epoch === epoch || !this.offerOut || this.channel || this.stopped) return;\n if (!this.fallback || !this.peerFallback || !this.peerTransports) return;\n const relayed = relayedTransports(this.localDescriptors(), this.peerDescriptors);\n const rest = rankTransports(this.transportOffer(), this.peerTransports, relayed).filter(t => t !== \"webrtc/1\");\n if (!rest.length) return;\n this.offered = { epoch, at: made.at };\n this.afterRtc = { epoch, rest };\n // The record lists no WebRTC (a Linux Desktop): nothing will answer the offer. It ends now, and what both run is\n // dialled at once, as by a joiner with no WebRTC, rather than `RACE_DIRECT_MS` after it: the inviter's own dial was\n // all a pairing waited for, and one that stalled had nothing racing it (0.5 to 4.6 s to live, DHT-direct lab, 2026-10-14).\n if (!this.peerTransports.includes(\"webrtc/1\")) {\n traceLink(this.myPubKeyZ32, \"offer-unanswerable\", { transports: rest });\n this.clearRace();\n this.raceTimer = setTimeout(() => { this.raceTimer = null; this.endUnanswerableOffer(epoch); }, 0);\n return;\n }\n traceLink(this.myPubKeyZ32, \"race-standing\", { transports: rest });\n this.scheduleRace(epoch, made.at);\n }\n /** The offer ends (`raceStandingOffer`), and with it going idle what is ranked after WebRTC is dialled (`dialAfterRtc`). */\n private endUnanswerableOffer(epoch: number): void {\n if (epoch !== this.connectionEpoch || this.channel || this.stopped || !this.offerOut || this.afterRtc?.epoch !== epoch) return;\n // Still inside the dial that made the offer: once it is over.\n if (this.dialing) { this.raceTimer = setTimeout(() => { this.raceTimer = null; this.endUnanswerableOffer(epoch); }, RACE_RETRY_MS); return; }\n this.dataLink.close();\n }\n /**\n * Back after an absence, this side answers an offer the contact made while it was away (it dials whatever its key):\n * the contact looks for that answer at the pace of an offer out a while (every 8 s on the relays), and its attempt may\n * end before it does. The direct transports both run are knocked on meanwhile, and the relayed ones where both apps\n * move off a relay once live (`upgrade/1`): the first live wins, and a knock that does not connect counts as nothing.\n */\n private maybeKnockAnswering(epoch: number): void {\n if (!this.resumingOverRtc || epoch !== this.connectionEpoch || this.knockedEarly === epoch || this.dataLink.state === \"idle\") return;\n // Its offer out longer than `OFFER_FAST_MS`: it looks for the answer every 4 s and then 8 s (on the relays), not 2 s.\n if (this.channel || this.dialing || this.stopped || this.streamBlocked || this.keyStopped || !this.contactQuiet(OFFER_FAST_MS)) return;\n if (!this.fallback || !this.peerFallback) return;\n this.knockedEarly = epoch;\n if (this.resuming === \"webrtc/1\") { this.resuming = undefined; this.resumingWoke = false; }\n const relayed = this.upgradesFromRelay() ? [] : this.relayedTransports;\n const offer = this.transportOffer();\n const direct = TRANSPORTS.filter(t => t !== \"webrtc/1\" && offer.includes(t) && !!this.peerTransports?.includes(t) && !relayed.includes(t) && this.canDial(t));\n if (!direct.length) return;\n void this.knockEarly(epoch, direct, () => this.dataLink.state === \"answering\" || this.dataLink.state === \"connecting\");\n }\n /** Back after an absence over WebRTC: not dialled yet, or this attempt's offer is the resume's (`offered.resume`). */\n private get resumingOverRtc(): boolean {\n return this.resuming === \"webrtc/1\" || (!!this.offered?.resume && this.offered.epoch === this.connectionEpoch);\n }\n /** Both apps move a chat off a relay once live (`upgrade/1`): this one, and the contact's by its capability record. */\n private upgradesFromRelay(): boolean { return !!this.options.upgradeSupport && !!this.options.peerUpgrades?.(); }\n /** The contact's newest packet is older than `EXPECT_PEER_MS`: it is not signalling, and reads at a slow pace. */\n private contactQuiet(ms = EXPECT_PEER_MS): boolean {\n return Date.now() - presenceSeenAt(this.session.peerPresence) >= ms;\n }\n /**\n * The direct transports of an attempt that resumes to a quiet contact, knocked on while its offer stands (`scheduleRace`).\n * So are those of the dial after a resume's knock that found nothing (`knockMissed`), relayed ones too, whatever the\n * contact's newest packet: it holds the old session and reads offers at a live chat's pace.\n */\n private maybeKnockEarly(epoch: number): void {\n const next = this.afterRtc, missed = !!this.offered?.knockMissed;\n if (!(this.offered?.resume || missed) || this.offered?.epoch !== epoch || this.knockedEarly === epoch || next?.epoch !== epoch || epoch !== this.connectionEpoch) return;\n // After a wake, whatever the contact's newest packet: a contact that just ended an attempt of its own, its offer\n // unanswered while this app slept, published a moment ago and still reads at its slow pace (30 s in the background).\n if (this.dialing || this.channel || this.stopped || !this.offerOut) return;\n // On Automatic a resume over WebRTC goes on Iroh where it ranks first (`dial`), the contact maybe still holding the\n // dead session and reading no offer: one whose Iroh came up only after the dial offered WebRTC knocks on it now, the\n // contact quiet or not. Before, the higher key (which the engine dials no more once its endpoints are up) was live\n // again only once the contact noticed: 8.5 to 13.6 s after a kill (two CLI daemons, 2026-11-12), against 0.3 s.\n const iroh = !missed && this.irohJoinedResume === epoch && this.irohRanksFirst();\n // So does a HyperDHT up only after the dial (Iroh's relay out of reach), which the race would dial 8 s on anyway: the\n // higher key was live again 8.5 s after a kill (two CLI daemons, Iroh relay down, 2026-11-13), against 0.9 s.\n const hyperdht = !missed && this.hyperdhtJoinedResume === epoch && next.rest.includes(\"hyperdht/1\")\n && !this.relayedTransports.includes(\"hyperdht/1\") && this.canDial(\"hyperdht/1\");\n if (!iroh && !hyperdht && !(missed || this.offered.woke || this.contactQuiet())) return;\n // A relayed transport too where both apps move off it once live (`upgrade/1`): the chat is live over the relay in a\n // second, and on the direct path a moment later, its signaling on the session (WISP 100 § Back to a quiet contact).\n const relayed = missed || this.upgradesFromRelay() ? [] : this.relayedTransports;\n const direct = iroh || hyperdht ? [...(iroh ? [\"iroh/1\" as const] : []), ...(hyperdht ? [\"hyperdht/1\" as const] : [])]\n : next.rest.filter(t => !relayed.includes(t) && this.canDial(t));\n if (!direct.length) return;\n this.knockedEarly = epoch;\n void this.knockEarly(epoch, direct);\n }\n /**\n * Back after a restart on a native transport whose endpoint has not started yet (Iroh waits up to 10 s for its relay,\n * and does not start at all with the relay out of reach): the contact's other direct transports that are up here are\n * knocked on meanwhile, once per resume, as a resume over WebRTC knocks as its offer goes out. The contact still holds\n * its old session and reads slowly; before, the chat waited out `RESUME_WAIT_MS` and then the race's 8 s (20.5-22.9 s\n * between two CLIs, bh-zero43). The first live wins, and the resumed transport is still knocked once it starts.\n */\n private knockWhileResuming(): void {\n if (this.resumeKnocked || !this.fallback || !this.peerFallback || this.dialing || this.channel) return;\n const relayed = this.upgradesFromRelay() ? [] : this.relayedTransports;\n const offer = this.transportOffer();\n const direct = TRANSPORTS.filter(t => t !== \"webrtc/1\" && t !== this.resuming && this.endpoints.has(t) && offer.includes(t)\n && !!this.peerTransports?.includes(t) && !relayed.includes(t) && this.canDial(t));\n if (!direct.length) return;\n this.resumeKnocked = true;\n void this.knockEarly(this.connectionEpoch, direct, () => true);\n }\n private async knockEarly(epoch: number, transports: PairedTransport[], standing = () => this.offerOut): Promise<void> {\n this.knockingEarly = true;\n try {\n for (const transport of transports) {\n if (epoch !== this.connectionEpoch || this.channel || this.stopped || !standing()) return;\n await this.knock(transport as NativeTransport);\n }\n } finally { this.knockingEarly = false; }\n }\n /**\n * A native endpoint that started while this side's offer is out unanswered: its transport was not up when the dial\n * ranked what to try, and joins the race (and what the offer ending goes on to) if both sides allow it.\n */\n private joinRace(transport: NativeTransport): void {\n const offered = this.offered;\n if (!offered || offered.epoch !== this.connectionEpoch || !this.offerOut || this.channel) return;\n if (!this.peerFallback || !this.peerTransports?.includes(transport) || !this.transportOffer().includes(transport)) return;\n const rest = this.afterRtc?.epoch === offered.epoch ? this.afterRtc.rest : [];\n if (rest.includes(transport)) return;\n this.afterRtc = { epoch: offered.epoch, rest: [...rest, transport] };\n traceLink(this.myPubKeyZ32, \"race-join\", { transport });\n if (offered.resume && transport === \"iroh/1\") this.irohJoinedResume = offered.epoch;\n if (offered.resume && transport === \"hyperdht/1\") this.hyperdhtJoinedResume = offered.epoch;\n // The offer of a resume whose knock found nothing (the contact holds the old session, its HyperDHT listener\n // unannounced): it reads offers at a live chat's pace, and a transport up now, relayed or not, reaches it at once,\n // as the resume's knock would have. Before, the higher key's Iroh waited for the race, and the contact noticed first.\n if (offered.knockMissed && this.canDial(transport)) void this.knockEarly(offered.epoch, [transport]);\n if (!this.racing) this.scheduleRace(offered.epoch, offered.at);\n }\n /**\n * On Automatic with no choice standing, Iroh ranks ahead of WebRTC for this contact and can be dialled now (WISP 100,\n * revision 2026-11-08): where a resume over WebRTC goes on Iroh instead (`dial`).\n */\n private irohRanksFirst(): boolean {\n if (!this.automatic || !this.peerTransports || !this.canDial(\"iroh/1\") || (this.switcher.chosenTarget ?? this.choiceApart?.transport)) return false;\n const ranked = rankTransports(this.transportOffer(), this.peerFallback ? this.peerTransports : this.peerTransports.slice(0, 1), this.relayedTransports);\n return ranked.includes(\"iroh/1\") && ranked.indexOf(\"iroh/1\") < ranked.indexOf(\"webrtc/1\");\n }\n /** WebRTC could not start an attempt here: it goes last in the dial order for `RTC_UNSTARTED_MS`, while another transport remains. */\n private rtcUnstarted(): void {\n traceLink(this.myPubKeyZ32, \"rtc-unstarted\", {});\n this.demotedUntil.set(\"webrtc/1\", Date.now() + RTC_UNSTARTED_MS);\n }\n /**\n * Whether this side dials although its key says it waits for the contact's offer: WebRTC cannot start here for now\n * (`rtcUnstarted`), so an offer of the contact's finds no answer, and this side has a native transport to dial, with\n * fallback allowed on both sides.\n */\n private dialsPastRtc(): boolean {\n return (this.demotedUntil.get(\"webrtc/1\") ?? 0) > Date.now() && this.fallback && this.peerFallback\n && TRANSPORTS.some(t => this.canDial(t) && !!this.peerTransports?.includes(t) && this.transportOffer().includes(t));\n }\n /**\n * A first pairing's inviter has no offer of the joiner's to wait for: WebRTC is missing here, or the joiner's record\n * says its app has none (a Linux Desktop's WebKitGTK), so its first packet carries none. A native transport the record\n * describes is dialled now. Waiting out `INVITER_DIAL_GRACE_MS` left two Linux Desktops 2.5 s more apart, and the\n * joiner, still reading, often went on without dialling for seconds (dht-direct on CI, 2026-10-07). Should the joiner\n * dial too, the two dials cross and the lower key's carries the chat (`parkCrossed`, `attachReplacement`).\n */\n private nothingToAwait(): boolean {\n const rtc = this.availableTransports.includes(\"webrtc/1\") && (!this.peerTransports || this.peerTransports.includes(\"webrtc/1\"));\n return !rtc && TRANSPORTS.some(t => this.canDial(t) && !!this.peerTransports?.includes(t) && this.transportOffer().includes(t));\n }\n /** Whether a native dial of `transport` can go now: this side's endpoint is up and the contact's descriptor known. */\n private canDial(transport: PairedTransport): boolean {\n return transport !== \"webrtc/1\" && this.endpoints.has(transport) && !!this.peerDescriptors[transport];\n }\n /**\n * Whether a dial has anything to try: WebRTC here (the contact's record, once read, listing it), or a native transport\n * both apps run with this side's endpoint up and the contact's descriptor read. A group link counts every dial: its\n * fast looks for the member's `_tr` end after a few (`PACKET_TRANSPORTS_FAST_ATTEMPTS`).\n */\n private anythingToDial(): boolean {\n if (!this.options.params.profile || this.options.packetTransports) return true;\n return this.transportOffer().some(t => t === \"webrtc/1\" ? !this.peerTransports || this.peerTransports.includes(t)\n : this.canDial(t) && !!this.peerTransports?.includes(t));\n }\n /**\n * Neither side can dial the other until something changes, past a first pairing: what the contact runs is known, and\n * no transport both run has WebRTC on both sides or an endpoint up on both (this side's, and the one its record\n * describes). A chat that gave its listener up to another (`yieldEndpoint`), or whose contact did, is so. It dials\n * again when that changes (a listener taken back, `registerEndpoint`; the record describing one, `learnPeerTransports`),\n * and reads at its own pace meanwhile: looks every 20 s for a dial with nothing to try, and the contact's fast looks\n * for an offer that could not come, read its key 2.5x to 4x as often as the background pace, for good (bug hunt,\n * 2026-10-12). A first pairing keeps both: the records are what it is reading for.\n */\n private nothingToDialEitherWay(): boolean {\n const pairing = !!this.tracker && !this.tracker.done && this.tracker.progress.stage !== \"on-dht\";\n return !pairing && !!this.peerTransports && !this.anythingToDial();\n }\n private clearRace(): void {\n if (this.raceTimer) clearTimeout(this.raceTimer);\n this.raceTimer = null;\n }\n\n /**\n * The offer is still unanswered: the transports ranked after WebRTC that are due are dialled now, each once in this\n * attempt (the offer timing out goes on to those left, not to these again). A native session that goes live ends the\n * offer (`attach`); the offer answered first, the native dial is closed.\n */\n private async race(epoch: number, offeredAt: number): Promise<void> {\n const next = this.afterRtc;\n // A knock as the offer went out (`knockEarly`) still under way: the race comes once it is over.\n if (this.knockingEarly && next?.epoch === epoch && epoch === this.connectionEpoch && !this.channel) {\n this.raceTimer = setTimeout(() => { this.raceTimer = null; void this.race(epoch, offeredAt); }, RACE_RETRY_MS); return;\n }\n if (!next || next.epoch !== epoch || epoch !== this.connectionEpoch || this.channel || this.dialing || this.stopped || this.leaving\n || this.streamBlocked || this.keyStopped || !this.offerOut) return;\n const relayed = this.relayedTransports;\n const late = Date.now() - offeredAt >= RACE_RELAYED_MS || (this.answeredAt > 0 && Date.now() - this.answeredAt >= RACE_ANSWERED_MS);\n // One that cannot be dialled yet is not given up on: it stays for later in the race, or for when the offer ends.\n const due = next.rest.filter(t => this.canDial(t) && (late || !relayed.includes(t)));\n const left = next.rest.filter(t => t !== \"webrtc/1\" && !due.includes(t));\n if (!due.length) { this.scheduleRace(epoch, offeredAt); this.raceStandingOffer(); return; }\n this.afterRtc = left.length ? { epoch, rest: left } : undefined;\n traceLink(this.myPubKeyZ32, \"race\", { transports: due, afterMs: Date.now() - offeredAt });\n this.dialing = this.racing = true;\n let live = false;\n try {\n for (const transport of due) if ((live = await this.dialNative(transport, epoch) === true)) break;\n } finally {\n this.racing = false;\n if (epoch === this.connectionEpoch) { this.dialing = false; this.settleCrossed(); }\n }\n if (live || epoch !== this.connectionEpoch || this.channel || this.stopped) return;\n // (Read again: the dials took time.)\n if ((this.dataLink.state as DataLinkState) !== \"idle\") { this.scheduleRace(epoch, offeredAt); this.raceStandingOffer(); return; }\n // The offer ended while these were dialled: on to what is left, or the attempt is over.\n const rest = this.afterRtc;\n this.afterRtc = undefined;\n if (rest && !this.streamBlocked) { void this.dialAfterRtc(rest); return; }\n this.attemptEnded();\n this.rejectWaiters(new GhostlyHttpError(\"unreachable\", \"Could not connect to the peer\"));\n }\n\n /**\n * This side does not dial on its own: the contact's app does (the lower key), and none of what makes this side dial\n * anyway holds (a first pairing's role, a restart, WebRTC set aside). Its own dial, chosen by hand, is not retried.\n */\n private awaitsContactDial(): boolean {\n const pairing = this.firstPairing();\n const role = pairing ? this.options.pairingProgress?.role : undefined;\n return !role && this.myPubKeyZ32 > this.options.params.peerPubKeyZ32 && !this.resuming && !this.resumeKnockMissed && !this.dialsPastRtc();\n }\n\n /** A transport of the attempt under way did not connect. */\n private attemptFailed(transport: PairedTransport, error: string): void {\n if (this.isDataLinkOpen) return;\n const attempt = this.attempt ??= { side: \"dialled\", failed: [] };\n attempt.failed = [...attempt.failed.filter(f => f.transport !== transport), { transport, error }];\n }\n\n /** The attempt under way ended without going live: kept as the last one, and told. `reason`: why, when nothing was tried. */\n private attemptEnded(reason?: string): void {\n const attempt = this.attempt;\n this.attempt = null;\n if (!attempt || this.isDataLinkOpen || this.stopped || (!attempt.failed.length && !reason)) return;\n this.lastAttempt = { at: Date.now(), side: attempt.side, failed: attempt.failed, ...(!attempt.failed.length && reason ? { reason } : {}),\n ...(attempt.side === \"dialled\" && !this.awaitsContactDial() ? { retryAt: Math.max(Date.now(), this.lastAutoConnectAt + this.dialWait()) } : {}) };\n traceLink(this.myPubKeyZ32, \"attempt-ended\", { side: attempt.side, failed: attempt.failed.map(f => f.transport), reason: this.lastAttempt.reason });\n this.options.events?.onLiveAttempt?.(this.lastAttempt);\n }\n\n /** The last attempt to go live that did not (WISP 100, \"Why a chat is not live\"); none while live. */\n get liveAttempt(): LiveAttempt | undefined { return this.isDataLinkOpen ? undefined : this.lastAttempt; }\n /** Automatic dials since the link was last live or its wait started over (`wake`), the one under way included. */\n get dialAttempts(): number { return this.autoConnectFailures; }\n /**\n * Which side dials this chat to go live: the lower rendezvous key, or the joiner of a first pairing (WISP 100). The\n * other side answers, so what it can tell of a failed attempt is only what reached it.\n */\n get dialer(): \"you\" | \"contact\" {\n const pairing = !!this.tracker && !this.tracker.done && this.tracker.progress.stage !== \"on-dht\";\n const role = pairing ? this.options.pairingProgress?.role : undefined;\n return role === \"joiner\" || (role !== \"inviter\" && this.myPubKeyZ32 < this.options.params.peerPubKeyZ32) ? \"you\" : \"contact\";\n }\n\n /**\n * Chat goes over the data link when it is up, through Pkarr otherwise. A `preview` (WISP 401 § Link previews) goes\n * only with a paired message on the live session, and only while the frame stays within what a session takes;\n * the DHT has no room for one, and the text goes without it. A `reply` (WISP 401 § Replies) goes whole on the\n * session; on the DHT only its id does, which the contact looks up in its own history. `forwarded`: the hop count\n * of a forwarded message (WISP 401 § Forwards), on both paths (the DHT drops it when the packet has no room). `card`:\n * a status card (WISP 405 · Status Cards), on the live session only; on the DHT the text, its fallback, goes alone.\n */\n async sendMessage(text: string, timestamp = Date.now(), stableId?: string, preview?: LinkPreview, reply?: WireReply, forwarded?: number, card?: StatusCard): Promise<string | null> {\n const trimmed = text.trim();\n if (!trimmed) return null;\n if (this.textDelivery === \"dht\" && this.dht) return forwarded ? this.dht.send(trimmed, timestamp, stableId ?? toBase64Url(randomBytes(16)), reply?.i, undefined, forwarded)\n : this.dht.send(trimmed, timestamp, stableId ?? toBase64Url(randomBytes(16)), reply?.i);\n if (this.options.params.profile && !this.isDataLinkOpen) return \"Confirm the peer and connect before sending. This chat never falls back to DHT messages.\";\n if (this.options.params.profile && this.channel) {\n if (utf8Encode(trimmed).length > LIMITS.maxChatMessageBytes) return \"Message exceeds 16 KiB\";\n if (this.pairedPending.size >= 128) this.pairedPending.delete(this.pairedPending.keys().next().value!);\n const id = stableId ?? toBase64Url(randomBytes(16));\n if (!/^[A-Za-z0-9_-]{22}$/.test(id)) return \"Invalid message ID\";\n // Past the contact's frame limit its session would end on it, and again on each retry.\n const frame = pairedMessageFrame(id, timestamp, trimmed, preview, reply, forwarded, card);\n if (frame.length > SESSION_FRAME_MAX) return PAIRED_FRAME_TOO_LARGE;\n if (!this.messagesSent.room()) return MESSAGE_PACED;\n this.pairedPending.set(id, timestamp);\n try { this.channel.send(frame); this.messagesSent.took(id); return null; }\n catch { this.pairedPending.delete(id); return \"The connection closed before sending. Reconnect and retry.\"; }\n }\n if (this.channel && trimmed.length <= LIMITS.maxChatMessageBytes / 4) {\n try {\n this.channel.send(encodeControl({ t: \"m\", ts: timestamp, m: trimmed }));\n return null;\n } catch {\n // fall through to Pkarr\n }\n }\n if (this.options.params.profile) return \"Message could not be sent over the negotiated data link.\";\n return this.session.sendMessage(trimmed, timestamp);\n }\n\n /**\n * Says a file's offer on the DHT floor while the chat is not live (WISP 403 § Files), so the contact's chat shows its\n * bubble in its place; the bytes go once live. An error when it cannot go on the floor now: it waits for live then.\n */\n async announceFile(file: DhtFileOffer, timestamp: number, reply?: WireReply, forwarded?: number): Promise<string | null> {\n const error = this.fileAnnounceError(file, timestamp, reply, forwarded);\n return error ?? this.dht!.announceFile(file, timestamp, reply?.i, forwarded);\n }\n /** Why a file's offer cannot go on the DHT floor now (`announceFile`), or null when it can. */\n fileAnnounceError(file: DhtFileOffer, timestamp: number, reply?: WireReply, forwarded?: number): string | null {\n if (!this.options.params.profile || this.textDelivery !== \"dht\" || !this.dht) return \"Files go when you are live\";\n if (this.dht.view.inviteTaken) return INVITE_TAKEN;\n return this.dht.fileError(file, timestamp, reply?.i, forwarded);\n }\n /** What awaits its receipt on the DHT floor now, if anything does. */\n get dhtPendingId(): string | undefined { return this.dht?.pendingId; }\n /** The last DHT send of this text went nowhere: no relay holds it, and it is off the floor (`DhtDelivery.wentNowhereFor`). */\n dhtWentNowhere(id: string): boolean { return !!this.dht?.wentNowhereFor(id); }\n /** What went on the DHT floor under this id needs no more retries there (it went live, or was withdrawn). */\n async settleDht(id: string): Promise<void> { await this.dht?.acknowledge(id); }\n /** Whether the DHT floor holds this text of mine, or an edit of it, awaiting its receipt or not (`DhtDelivery.holds`). */\n dhtHolds(wireId: string): boolean { return !!this.dht?.holds(wireId); }\n /** A text of mine deleted here leaves the DHT floor, an edit of it waiting there too (`DhtDelivery.withdraw`). */\n async withdrawDht(wireId: string): Promise<void> { await this.dht?.withdraw(wireId); }\n\n /** Publishes a `_call` signal; a connected peer also gets it right away over the data link. */\n async setCallSignal(signal: string | null): Promise<void> {\n if (this.options.params.profile) {\n // Kept until cleared, so what the session could not carry goes on the next one while still fresh.\n const frame = this.pairedCalls.set(signal);\n this.leaveHangUp();\n if (!frame) return;\n if (!this.supportsCalls || !this.channel) throw new Error(this.callsUnavailable ?? \"Calls need a live connection\");\n this.channel.send(JSON.stringify(frame));\n return;\n }\n if (signal && this.channel) {\n try {\n this.channel.send(encodeControl({ t: \"call\", s: signal }));\n } catch {\n // Pkarr still carries it\n }\n }\n await this.session.setCallSignal(signal);\n }\n\n /**\n * Hands the transport the hang-up of the call this side is on (`PairedCalls.parting`), for it to send as the app\n * exits should the page be gone by then: a logout or a shutdown ends the Desktop's WebView with the app, and its\n * goodbye (`depart`) never ran, the contact's call stalling until its media gave up 16 s later. Taken back once no\n * call of ours is on, and from a session no longer the chat's.\n */\n private leaveHangUp(): void {\n const channel = this.supportsCalls && this.paired?.state.status === \"ready\" ? this.channel : null;\n const frame = channel ? this.pairedCalls.parting() : null;\n if (this.partingOn && this.partingOn !== channel) this.partingOn.parting?.(null);\n this.partingOn = channel?.parting ? channel : null;\n this.partingOn?.parting?.(frame ? JSON.stringify(frame) : null);\n }\n\n /** Issues an HTTP request to a service the peer advertises. */\n async request(serviceId: string, request: ClientRequest): Promise<ClientResponse> {\n if (this.options.params.profile) {\n await this.open();\n if (!this.supportsServices) throw new GhostlyHttpError(\"unavailable\", this.isDataLinkOpen\n ? \"Your contact's app cannot share services in this chat, or needs an updated Ghostly\" : \"Shared services need a live connection\");\n if (!this.pairedHttp) throw new GhostlyHttpError(\"closed\", \"Data link is closed\");\n return this.pairedHttp.client.request(serviceId, request);\n }\n this.requireLegacyCapabilities();\n await this.connect();\n if (!this.httpClient) throw new GhostlyHttpError(\"closed\", \"Data link is closed\");\n return this.httpClient.request(serviceId, request);\n }\n\n /** Payments only travel over the data link: tokens and invoices do not fit in Pkarr, and should not sit there. */\n async sendPaymentRequest(request: PaymentRequest): Promise<void> {\n await this.requirePaymentSupport();\n if (!this.channel) throw new Error(\"Data link is closed\");\n this.channel.send(\n encodeControl({\n t: \"pay-req\",\n id: request.id,\n ts: request.timestamp,\n v: request.amount.value,\n u: request.amount.asset,\n memo: request.memo,\n e: request.endpoints,\n a: request.ask,\n n: request.network,\n }),\n );\n }\n\n /** Asks the contact for a way to pay it (an address, an invoice): its app answers with a request. */\n async sendPaymentAsk(ask: PaymentAsk): Promise<void> {\n await this.requirePaymentSupport();\n if (!this.options.params.profile) throw new Error(\"Paying without a request needs a paired chat\");\n if (!this.channel) throw new Error(\"Data link is closed\");\n this.channel.send(encodeControl({ t: \"pay-ask\", id: ask.id, ts: ask.timestamp, v: ask.amount.value, u: ask.amount.asset, m: ask.method, memo: ask.memo, n: ask.network }));\n }\n\n async sendPayment(payment: Payment): Promise<void> {\n await this.requirePaymentSupport();\n if (!this.channel) throw new GhostlyHttpError(\"closed\", \"Data link is closed\");\n this.channel.send(\n encodeControl({\n t: \"pay\",\n id: payment.id,\n ts: payment.timestamp,\n rid: payment.requestId,\n v: payment.amount.value,\n u: payment.amount.asset,\n memo: payment.memo,\n e: payment.endpoint,\n }),\n );\n }\n\n sendPaymentResult(result: PaymentResult): void {\n if (this.options.params.profile && !this.supportsPayments) return;\n try {\n this.channel?.send(encodeControl({ t: \"pay-res\", id: result.id, ok: result.ok, v: result.credited, err: result.error, ...(result.closed ? { c: true as const } : {}) }));\n } catch {\n // the peer learns on reconnect that nothing came back\n }\n }\n\n /** Sends a file over the data link, opening it first if needed. Files never travel through Pkarr. */\n async sendFile(file: FileInfo, source: AsyncIterable<Uint8Array>): Promise<void> {\n await this.open();\n if (this.options.params.profile) {\n if (!this.supportsFiles || !this.pairedFiles) throw new Error(\"This contact does not support files. Both peers need an updated Ghostly.\");\n return this.pairedFiles.send(file, source);\n }\n if (!this.files) throw new GhostlyHttpError(\"closed\", \"Data link is closed\");\n await this.files.send(file, source);\n }\n\n /** Call after the set of shared services changed. */\n async refreshServices(): Promise<void> {\n if (this.options.params.profile) { this.sendPairedServices(); return; }\n if (this.channel) {\n try {\n this.channel.send(encodeControl({ t: \"svc\", svc: servicesToWire(this.options.getServices() ?? []) }));\n } catch {\n // channel closing\n }\n }\n await this.session.refreshAdvertisement();\n }\n\n /**\n * Only the lower key offers, so two peers coming online together do not collide. A first pairing is\n * the exception: the joiner offers, whatever its key, in the very packet that says it is here (one hop\n * less than presence, then the inviter's offer), and the inviter waits for that offer. An inviter that\n * sees the joiner but no offer for `INVITER_DIAL_GRACE_MS` (an app from before this rule) offers itself,\n * and dials at once when no offer can come (`nothingToAwait`); the lower-key rule settles any collision, on both sides.\n */\n private maybeAutoConnect(presence: PeerPresence): void {\n // Stopping (its loops end after an await): a poll finishing meanwhile must not dial again.\n if (this.stopped || this.leaving || this.yielding || this.streamBlocked || this.keyStopped || !this.options.autoConnect || !presence.online || this.channel || this.dialing || this.dataLink.state !== \"idle\") return;\n // The invite was taken, before or after a look-up pinned the inviter: its inviter answers nobody here, and neither a\n // dial nor a fast look for its offer is worth the relays' budget at each of its heartbeats (bug hunts 1014-1317,\n // 1017-0534). The mailbox's slow read still hears it if it was not so (`untaken`), and dials go again then.\n if (this.takenFromUs) return;\n // On the DHT the chat is usable: layer 1 is retried at the background pace (WISP 100), not the pairing's.\n // A pin over the DHT alone changes nothing here: the joiner still knocks and the inviter still answers.\n // Back after a restart on a native transport whose endpoint is still starting: it is knocked on once it has, and a\n // WebRTC offer meanwhile would hold the data link for as long as the contact takes to read it. A knock holds none.\n if (this.resuming && this.resuming !== \"webrtc/1\" && !this.endpoints.has(this.resuming) && Date.now() < this.resumeWaitUntil) {\n this.knockWhileResuming(); return;\n }\n // The contact said it was going: its old packet says nothing about whether it is back. Its next one does.\n if (this.departed) {\n if (presence.lastPacketAt === this.departed.packet && Date.now() < this.departed.until) return;\n this.departed = null;\n }\n // The contact let its listener go: its old packet describes a listener that is closing.\n if (this.yielded) {\n if (presence.lastPacketAt === this.yielded.packet && Date.now() < this.yielded.until) return;\n this.yielded = null;\n }\n const pairing = !!this.tracker && !this.tracker.done && this.tracker.progress.stage !== \"on-dht\";\n const role = pairing ? this.options.pairingProgress?.role : undefined;\n if (role === \"inviter\") {\n this.peerSeenAt ||= Date.now();\n if (Date.now() - this.peerSeenAt < INVITER_DIAL_GRACE_MS && !this.nothingToAwait()) { this.session.expectPeer(); return; }\n } else if (this.awaitsContactDial()) {\n // Back after a restart (`resume`), this side dials once whatever its key: the contact may still hold the old\n // session, and would not dial. A WebRTC offer from it reaches that session as \"the contact lost the connection\"\n // (`DataLink.handleSignal`), and two offers crossing are settled by key there.\n // The other side dials as soon as it sees me. A packet of its that is new to me and fresh says it just\n // (re)appeared, so its offer is a poll away; an old one (a contact online for a while, as when this app\n // starts) says nothing is coming now, and looking fast for it would only spend the relays' budget.\n // A contact that has nothing to dial here (`nothingToDialEitherWay`) sends no offer either.\n const fresh = Date.now() - presenceSeenAt(presence) < EXPECT_PEER_MS;\n if (fresh && presence.lastPacketAt !== this.offerAwaitedFor && !this.nothingToDialEitherWay()) {\n this.offerAwaitedFor = presence.lastPacketAt; this.session.expectPeer();\n }\n return;\n }\n const wait = this.dialWait();\n if (Date.now() - this.lastAutoConnectAt < wait) {\n // Once per wait: the Desktop writes each line to its log, and a look every few seconds only changed `left`.\n const backoff = `${this.lastAutoConnectAt}:${this.autoConnectFailures}`;\n if (backoff !== this.backoffTraced) {\n this.backoffTraced = backoff;\n traceLink(this.myPubKeyZ32, \"dial-backoff\", { failures: this.autoConnectFailures, left: wait - (Date.now() - this.lastAutoConnectAt) });\n }\n // The contact waits for this side's dial (the higher key, not lost from a live session, where it may come back and\n // offer): a read before the wait is over can only end here again. The look at its end is armed (`lookAtRetry`),\n // and the chat reads at its own pace until then, not every 0.7 s for the rest of an app start's window (45 reads).\n // A paired chat only: a group's link (`packetTransports`) keeps its fast looks for the member's `_tr` and offers,\n // which its own restart and native fallback rely on (WISP 902 § Transports).\n if (!pairing && !this.options.packetTransports && this.myPubKeyZ32 < this.options.params.peerPubKeyZ32 && Date.now() >= this.lostUntil) this.session.calm();\n this.lookAtRetry();\n return;\n }\n traceLink(this.myPubKeyZ32, \"dial\", { failures: this.autoConnectFailures });\n this.autoDial();\n }\n\n /**\n * An automatic dial. One with nothing to try (`anythingToDial`) still says why (`liveAttempt`) and keeps the pace, but\n * is no failed attempt: the wait between attempts does not grow, and a first pairing does not turn `on-dht` for it.\n * Two Linux Desktops pairing over a slow DHT, neither having read the other's record yet, counted three such dials in\n * 12 s: the pairing turned `on-dht` and the next dial waited 160 s, though nothing had been tried.\n */\n private autoDial(): void {\n const tries = this.anythingToDial(), started = Date.now();\n const instantMs = !tries ? 0 : this.resumeDial ? INSTANT_FAIL_MS : this.backDial ? BACK_INSTANT_FAIL_MS : 0;\n if (tries) this.resumeDial = this.backDial = false;\n this.instantRetry = false;\n this.lastAutoConnectAt = started;\n if (tries) this.autoConnectFailures++;\n void this.dial().catch(error => {\n // A restart's, or a contact back's, first dial that failed at once (`INSTANT_FAIL_MS`, `BACK_INSTANT_FAIL_MS`):\n // once more soon, and it does not count.\n if (Date.now() - started < instantMs && this.lastAutoConnectAt === started && this.autoConnectFailures > 0) {\n this.autoConnectFailures--;\n this.instantRetry = true;\n traceLink(this.myPubKeyZ32, \"dial-instant-fail\", { ms: Date.now() - started });\n } else if (tries) this.tracker?.failed(\"transport\", true);\n this.dialFailed(error instanceof Error ? error.message : String(error));\n this.lookAtRetry();\n });\n }\n\n /**\n * The contact answered this side's offer again, and the data link gave the attempt up (`DataLink.onAnswerReplaced`):\n * the contact is there, so this side dials again now. Its packet with that answer often has no room for its presence,\n * and waiting for a packet that says it is online left the edge to the next look at the background pace (60 s, CLI\n * bug hunt 2026-09-30).\n */\n private redial(): void {\n if (this.stopped || this.leaving || this.streamBlocked || this.keyStopped || !this.options.autoConnect || this.channel || this.dialing || this.dataLink.state !== \"idle\") return;\n traceLink(this.myPubKeyZ32, \"dial\", { failures: this.autoConnectFailures, again: true });\n this.autoDial();\n }\n\n /** WebRTC here refused a run of answers to this side's offers (`ANSWERS_REFUSED_PAUSES`): the next offer goes after a short pause. */\n private answersRefused(): void {\n if (this.refusedPause || this.stopped) return;\n // Past them, the owner hears it: a group's edge goes on over a native transport for the run (node.ts `edgeWithoutRtc`).\n if (this.refusedPauses >= ANSWERS_REFUSED_PAUSES) { traceLink(this.myPubKeyZ32, \"answers-refused-out\", {}); this.options.events?.onAnswersRefused?.(); return; }\n const ms = ANSWERS_REFUSED_PAUSE_MS * 2 ** this.refusedPauses++;\n traceLink(this.myPubKeyZ32, \"answers-refused-pause\", { pause: this.refusedPauses, ms });\n this.refusedPause = setTimeout(() => { this.refusedPause = null; this.redial(); }, ms);\n }\n\n /**\n * A failed dial waits `dialWait` before the next, and only a look at the contact's record dials: the next one came at\n * the link's own pace (30 s in the background), which knows nothing of the backoff. A member let in to a group\n * reached one of its members 72 s after its welcome, 40 s of backoff and 32 s more for its next look (meshSignals on\n * CI, 2026-10-06). One look goes when the backoff ends (`liveAttempt.retryAt`), and its read decides, as any look's\n * does. A dial or a reset of the backoff since makes it moot: what comes next arms its own.\n */\n private lookAtRetry(): void {\n if (this.retryLook) clearTimeout(this.retryLook);\n this.retryLook = null;\n const from = this.lastAutoConnectAt;\n if (!from || this.stopped || this.leaving || this.streamBlocked || this.keyStopped || !this.options.autoConnect) return;\n // Nothing to dial: the look would only read the contact's key again (`nothingToDialEitherWay`).\n if (this.nothingToDialEitherWay()) return;\n this.retryLook = setTimeout(() => {\n this.retryLook = null;\n if (this.lastAutoConnectAt !== from || this.stopped || this.leaving || this.yielding || this.streamBlocked || this.keyStopped || this.channel || this.dialing || this.dataLink.state !== \"idle\") return;\n traceLink(this.myPubKeyZ32, \"retry-look\", { failures: this.autoConnectFailures });\n this.session.lookNow();\n }, Math.max(0, from + this.dialWait() - Date.now()));\n }\n\n /**\n * A packet of this link reached the relays after a dial whose offer never did (the relays failed, or their budget held\n * it, for the whole attempt): the contact saw nothing of that dial, so it is no reason to wait, and the next goes now.\n * Without this a dial made during an outage set the wait, three minutes once it had grown, from when the relays\n * answered again.\n */\n private dialSeenNow(): void {\n if (!this.dialUnseen) return;\n this.dialUnseen = false;\n if (this.channel || this.dialing || this.dataLink.state !== \"idle\") return;\n traceLink(this.myPubKeyZ32, \"dial-unseen\", { failures: this.autoConnectFailures });\n this.lastAutoConnectAt = 0;\n this.maybeAutoConnect(this.presence);\n }\n\n /**\n * Still a first pairing, for its dials (`dialWait`, `awaitsContactDial`): not live yet (nor stopped for good), and\n * not on the DHT, or on it only because a native stream dial failed, within `FIRST_PAIRING_PACE_MS`. That dial was\n * the first contact between two apps that just read each other's records, and one that aborts in milliseconds (a\n * hole punch on a lossy network) dropped the pairing to a saved contact's pace, the lower key alone dialling 20 s,\n * 40 s, 80 s later: two first dials failing went live after 40 s, and not in 180 s at 15% loss (agents#1657). A\n * WebRTC offer that connected nothing keeps the saved contact's pace: the other side answers each one, and offers at\n * a pairing's pace kept it answering, never shown on the DHT.\n */\n private firstPairing(): boolean {\n const progress = this.tracker && !this.tracker.done ? this.tracker.progress : undefined;\n if (!progress) return false;\n if (progress.stage !== \"on-dht\") return true;\n if (progress.retryable === false || Date.now() - progress.startedAt > FIRST_PAIRING_PACE_MS) return false;\n return !!(this.attempt ?? this.lastAttempt)?.failed.some(f => f.transport !== \"webrtc/1\");\n }\n\n /** How long after the last automatic dial the next one may go. A first pairing tries again sooner: the contact just read the invite and is waiting. */\n private dialWait(): number {\n if (this.instantRetry) return INSTANT_FAIL_RETRY_MS;\n const pairing = this.firstPairing();\n return pairing ? Math.min(PAIRING_RETRY_MS * 2 ** this.autoConnectFailures, PAIRING_MAX_RETRY_MS)\n : Math.min(AUTO_CONNECT_RETRY_MS * 2 ** this.autoConnectFailures, AUTO_CONNECT_MAX_RETRY_MS);\n }\n\n /** The name this side shows, told to a paired peer directly. */\n setNick(nick: string | undefined): void {\n this.options.nick = nick || undefined;\n this.session.setNick(nick);\n this.sendPairedNick();\n }\n\n /** The picture this side shows, told to a paired peer directly. Legacy chats have no room for it. */\n setAvatar(avatar: string | undefined): void {\n this.options.avatar = avatar || undefined;\n this.sendPairedAvatar();\n }\n\n /** Older apps drop this frame (it carries no id). An empty `a` says the picture was removed. */\n private sendPairedAvatar(): void {\n if (!this.options.params.profile || !this.channel || !this.isDataLinkOpen) return;\n try { this.channel.send(JSON.stringify({ t: \"paired-avatar\", a: this.options.avatar ?? \"\" })); } catch { /* sent again on the next session */ }\n }\n\n /** An empty `n` says there is no name to show (none set, removed, or not shared). */\n private sendPairedNick(): void {\n if (!this.options.params.profile || !this.channel || !this.isDataLinkOpen) return;\n try { this.channel.send(JSON.stringify({ t: \"paired-nick\", n: this.options.nick ?? \"\" })); } catch { /* sent again on the next session */ }\n }\n\n private mergePresence(presence: PeerPresence): PeerPresence {\n if (!this.channel) return presence;\n return { ...presence, online: true, nick: this.peerNickOverride ?? presence.nick,\n services: this.peerServicesOverride ?? presence.services };\n }\n\n get peerProofAdapters(): ProofAdapter[] { return this.options.events?.onPeerProof && this.isDataLinkOpen ? this.paired?.peerProofAdapters ?? [] : []; }\n get peerProofSupport(): boolean { return !!this.options.events?.onPeerProof && !!this.paired?.peerProofSupport && this.isDataLinkOpen; }\n\n async peerProofScope(): Promise<ProofScope> {\n const credentials = this.options.pairing?.credentials;\n if (!credentials?.peerKey || !this.paired || !this.peerProofSupport) throw new Error(\"Connect to a confirmed peer supporting optional proofs first\");\n const paired = this.paired;\n const context = await proofHash(JSON.stringify([\"ghostly-conversation\", 1, [this.myPubKeyZ32, this.options.params.peerPubKeyZ32].sort()]));\n if (this.paired !== paired || !this.peerProofSupport) throw new Error(\"Connection changed\");\n return { subject: credentials.signer ? toZ32(credentials.signer.publicKey) : identityFromSeedB64(credentials.seedB64).pubKeyZ32, audience: credentials.peerKey, context, session: paired.proofSession };\n }\n\n get proofSession(): string | undefined { return this.peerProofSupport ? this.paired?.proofSession : undefined; }\n /**\n * The transcript hash of the session that is open and ready (WISP 401), lower-case hex, whatever proofs it offers:\n * what a device's enrollment (WISP 06) signs and derives its digits from. Undefined while no session is ready.\n */\n get sessionTranscriptHash(): string | undefined { return this.paired?.state.status === \"ready\" ? this.paired.proofSession || undefined : undefined; }\n\n /** Identity proofs can be exchanged now: both offers carry `identity-proof/1` and the channel is open. */\n get identitySupport(): boolean { return !!this.options.events?.onIdentityProof && !!this.paired?.identitySupport && this.isDataLinkOpen; }\n\n /** This side's view of the authenticated channel, for identity presentations. */\n identityScope(): IdentityScope {\n const credentials = this.options.pairing?.credentials;\n if (!credentials?.peerKey || !this.paired || !this.identitySupport) throw new Error(\"Connect to this contact first\");\n const conversation = [this.myPubKeyZ32, this.options.params.peerPubKeyZ32].sort();\n const context = Array.from(sha256(utf8Encode(JSON.stringify([\"ghostly-conversation\", 1, conversation]))), b => b.toString(16).padStart(2, \"0\")).join(\"\");\n return { subject: credentials.signer ? toZ32(credentials.signer.publicKey) : identityFromSeedB64(credentials.seedB64).pubKeyZ32, audience: credentials.peerKey, context, session: this.paired.proofSession };\n }\n\n sendIdentityProof(frame: object): void {\n if (!this.identitySupport || !this.channel) throw new Error(\"Identity proofs are unavailable on this connection\");\n const data = JSON.stringify(frame);\n if (data.length > IDENTITY_MAX_FRAME) throw new Error(\"Identity proof too large\");\n this.channel.send(data);\n }\n\n sendPeerProof(frame: object): void {\n if (!this.peerProofSupport || !this.channel) throw new Error(\"Peer proof channel unavailable\");\n const data = JSON.stringify(frame);\n if (data.length > 8192) throw new Error(\"Proof too large\");\n this.channel.send(data);\n }\n\n async confirmPair(code: string): Promise<void> {\n if (this.streamBlocked && this.dht?.comparisonCode) {\n const credentials = this.options.pairing!.credentials;\n if (code !== this.dht.comparisonCode) throw new Error(\"Compare the current code again.\");\n await this.options.pairing!.verifyPeer?.(credentials.peerKey!);\n credentials.verifiedPeerKey = credentials.peerKey; this.emitDeliveryState(); return;\n }\n if (!this.paired) throw new Error(\"No peer is waiting for confirmation\");\n await this.paired.confirm(code);\n }\n\n get supportsFiles(): boolean { return this.options.params.profile ? this.isDataLinkOpen && !!this.paired?.supports(\"files/2\") : true; }\n /** This device allows the way of paying in this chat. */\n paymentEnabled(method: PaymentMethodName): boolean { return this.options.paymentMethods?.[method] !== false; }\n /** Both sides allow it. A chat from before pairing negotiates nothing: Cashu and Lightning as this device allows. */\n allowsPayment(method: PaymentMethodName): boolean {\n if (!this.paymentEnabled(method)) return false;\n if (!this.options.params.profile) return method === \"cashu\" || method === \"lightning\";\n if (!this.isDataLinkOpen || this.paired?.state.status !== \"ready\") return false;\n // The contact's latest word in this session wins over its handshake offer.\n return this.peerPaymentMethods ? this.peerPaymentMethods.has(method) : this.paired.peerAllowsPayment(method);\n }\n get supportsUsdtPayments(): boolean { return this.allowsPayment(\"usdt\"); }\n get supportsArkPayments(): boolean { return this.allowsPayment(\"arkade\"); }\n get supportsBarkPayments(): boolean { return this.allowsPayment(\"bark\"); }\n /** On-chain: only ever through the contact's `paired-payments` list (see PaymentMethodName). */\n get supportsBitcoinPayments(): boolean { return this.allowsPayment(\"bitcoin\"); }\n /** Fedimint: only ever through the contact's `paired-payments` list, like on-chain. */\n get supportsFedimintPayments(): boolean { return this.allowsPayment(\"fedimint\"); }\n /** Spark: like on-chain, only ever through the contact's `paired-payments` list. */\n get supportsSparkPayments(): boolean { return this.allowsPayment(\"spark\"); }\n /** Payment messages flow at all: some way of paying is allowed by both sides. */\n get supportsPayments(): boolean { return PAYMENT_METHODS.some(m => this.allowsPayment(m)); }\n /** The contact accepts held items: its latest word on this session, else its handshake offer. */\n get peerAllowsHold(): boolean {\n if (!this.options.params.profile || !this.paired || this.paired.state.status !== \"ready\") return false;\n return this.peerHoldOverride ?? this.paired.peerHoldSupport;\n }\n /** Both sides offer `hold/1` on this session. */\n get supportsHold(): boolean { return !!this.options.holdSupport && this.isDataLinkOpen && this.peerAllowsHold; }\n /** The contact's own choice about one way of paying, as it last said on this session or offered in the handshake. */\n peerAllowsPayment(method: PaymentMethodName): boolean {\n if (!this.options.params.profile || !this.paired || this.paired.state.status !== \"ready\") return false;\n return this.peerPaymentMethods ? this.peerPaymentMethods.has(method) : this.paired.peerAllowsPayment(method);\n }\n /**\n * The contact's choice about a way of paying in this chat, whether or not it has a wallet for it. Its session list\n * leaves out a way it has no wallet of (its networks name none): that one is as its handshake offer said. What is\n * remembered for a later request, which goes when the chat is live: a wallet made meanwhile then counts.\n */\n peerChoosesPayment(method: PaymentMethodName): boolean {\n if (!this.options.params.profile || !this.paired || this.paired.state.status !== \"ready\") return false;\n if (!this.peerPaymentMethods || this.peerPaymentMethods.has(method)) return this.peerAllowsPayment(method);\n return !!this.peerNetworks && this.peerNetworks[method] === undefined && this.paired.peerAllowsPayment(method);\n }\n /** Takes effect at once; a connected contact is told on the open session, and the next handshake offers it. */\n setHoldSupport(on: boolean, top?: number): void { this.options.holdSupport = on; this.sendHoldState(top); }\n /** Older apps drop this frame (it carries no id) and keep using the handshake offer. */\n private sendHoldState(top?: number): void {\n if (!this.options.params.profile || !this.channel || !this.isDataLinkOpen || this.paired?.state.status !== \"ready\") return;\n try { this.channel.send(JSON.stringify({ t: \"paired-hold\", on: !!this.options.holdSupport, ...(top !== undefined ? { top } : {}) })); } catch { /* the next session offers it */ }\n }\n /** Takes effect at once, and a connected contact is told on the open session; the next handshake offers it too. */\n setPaymentMethods(methods: Partial<Record<PaymentMethodName, boolean>>): void { this.options.paymentMethods = { ...methods }; this.sendPaymentMethods(); }\n /** This side's wallets changed (one was created): a connected contact is told at once. */\n setPaymentNetworks(networks: PaymentNetworks): void {\n if (JSON.stringify(networks) === JSON.stringify(this.options.paymentNetworks ?? null)) return;\n this.options.paymentNetworks = networks; this.sendPaymentMethods();\n }\n /**\n * The networks the contact has a wallet on for this way of paying, as it said on this session. Undefined: it did\n * not say (an older app, or before its first word): any network may meet.\n */\n peerPaymentNetworks(method: PaymentMethodName): (\"mainnet\" | \"testnet\")[] | undefined { return this.peerNetworks ? this.peerNetworks[method] ?? [] : undefined; }\n /** The whole map as the contact said it: a way of paying it has no wallet of is not in it. Undefined: it did not say. */\n peerWalletNetworks(): PaymentNetworks | undefined { return this.peerNetworks ? { ...this.peerNetworks } : undefined; }\n /** The apps this contact may reach, said on the open session. Older apps drop the frame (no id). */\n private sendPairedServices(): void {\n if (!this.options.params.profile || !this.channel || !this.supportsServices || this.paired?.state.status !== \"ready\") return;\n try { this.channel.send(JSON.stringify({ t: \"paired-services\", s: servicesToWire(this.options.getPairedServices?.() ?? []) })); } catch { /* sent again on the next session */ }\n }\n private offeredCapabilities(): SessionCapability[] {\n const offered: SessionCapability[] = [];\n if (this.options.callsSupport) offered.push(CALLS_CAPABILITY);\n if (this.options.servicesSupport) offered.push(SERVICES_CAPABILITY);\n if (this.options.largeFilesSupport) offered.push(FILES_CAPABILITY);\n if (this.options.largeFilesSupport && this.options.binaryFilesSupport && this.channel?.binary) offered.push(FILES_BINARY_CAPABILITY);\n if (this.options.typingSupport) offered.push(TYPING_CAPABILITY);\n if (this.options.statusSupport) offered.push(STATUS_CAPABILITY);\n if (this.options.reactionsSupport) offered.push(REACTIONS_CAPABILITY);\n if (this.options.editSupport) offered.push(EDIT_CAPABILITY);\n if (this.options.wakeSupport) offered.push(WAKE_SESSION_CAPABILITY);\n if (this.options.pinSupport) offered.push(PIN_CAPABILITY);\n if (this.options.statusCardSupport) offered.push(STATUS_CARD_CAPABILITY);\n if (this.options.buttonsSupport) offered.push(BUTTONS_CAPABILITY);\n if (this.options.upgradeSupport) offered.push(UPGRADE_CAPABILITY);\n if (this.options.appsSupport) offered.push(APPS_CAPABILITY);\n if (this.options.appsSupport && this.options.appRangesSupport) offered.push(APP_RANGES_CAPABILITY);\n if (this.options.deviceCapabilities) offered.push(...this.options.deviceCapabilities);\n return offered;\n }\n /** Both ends announced this device capability on the open session (a device link only). */\n supportsDevice(capability: DeviceCapability): boolean {\n return !!this.options.deviceCapabilities?.includes(capability) && this.isDataLinkOpen && this.sessionCapabilities.agreed(capability);\n }\n /** A frame to the person's other device. Only while both ends announced the capability its type travels under; never queued. */\n sendDeviceFrame(frame: DeviceFrame): void {\n const capability = deviceFrameCapability(frame.t);\n if (!capability || !this.supportsDevice(capability) || !this.channel) throw new Error(\"This device is not connected\");\n const data = JSON.stringify(frame);\n if (data.length > LIMITS.maxControlFrameBytes) throw new Error(\"Device frame too large\");\n this.channel.send(data);\n }\n /** Both sides offer `calls/1` on the open session: call signals can flow. Calls need a live session. */\n get supportsCalls(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(CALLS_CAPABILITY); }\n /** Both sides offer `services/1` on the open session: shared web apps can be listed and reached. */\n get supportsServices(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(SERVICES_CAPABILITY); }\n /** Both sides offer `files/3` on the open session: files of any size, offered and resumed. */\n get supportsLargeFiles(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(FILES_CAPABILITY); }\n /** Both sides offer `files/4` beside `files/3` on the open session: a file's bytes go as binary messages. */\n get supportsBinaryFiles(): boolean { return this.supportsLargeFiles && this.sessionCapabilities.agreed(FILES_BINARY_CAPABILITY); }\n /** Both sides offer `typing/1` on the open session: typing can be said and shown. */\n get supportsTyping(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(TYPING_CAPABILITY); }\n /** Both sides offer `react/1` on the open session: reactions can be said and confirmed here. */\n get supportsReactions(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(REACTIONS_CAPABILITY); }\n /**\n * Says a reaction of this side (WISP 401 § Reactions) on the live session, once both sides offer `react/1`. An\n * error when it could not go now: the caller keeps it, and it goes again later (or on the DHT).\n */\n /**\n * This side has reactions the contact has not confirmed (`reactions` in the DHT options): off the live session they\n * ride on the DHT envelopes, and one goes now (WISP 403 § Reactions).\n */\n reactionsPending(): void { if (this.options.params.profile) void this.dht?.announceReactions(); }\n sendReaction(reaction: WireReaction): string | null {\n if (!this.options.params.profile) return \"Reactions need a current chat\";\n if (!this.channel || !this.isDataLinkOpen) return \"Reactions go when you are live\";\n if (!this.supportsReactions) return \"Your contact's app does not show reactions yet\";\n try { this.channel.send(reactionFrame(reaction)); return null; } catch { return \"The connection closed before sending\"; }\n }\n /** The contact is typing now, as it said on this session. */\n get peerTyping(): boolean { return this.typingReceiver.peerTyping; }\n /** What the contact is doing now (typing, recording, thinking, and a bot's status), or null. */\n get peerTypingActivity(): TypingActivity | null { return this.typingReceiver.peerActivity; }\n /** Both sides offer `status/1` on the open session: presence and a set status can be said and shown. */\n get supportsStatus(): boolean { return !!this.options.params.profile && this.isDataLinkOpen && this.sessionCapabilities.agreed(STATUS_CAPABILITY); }\n /** What the contact says of itself: presence while this session is live and it shares it, a status while it lasts. */\n get peerStatus(): StatusState { return this.statusReceiver.peer; }\n /**\n * This side's presence and status (the whole state: `presence` left out when the person does not share it). Said on\n * the live session once both sides offer `status/1`, at most one frame per few seconds; kept for every next session.\n */\n setStatus(state: StatusState): void {\n this.statusSender.set(state);\n this.flushStatus();\n }\n private flushStatus(): void {\n if (this.statusTimer || !this.channel || !this.supportsStatus) return;\n const next = this.statusSender.take();\n if (!next) return;\n if (\"wait\" in next) { this.statusTimer = setTimeout(() => { this.statusTimer = null; this.flushStatus(); }, next.wait); return; }\n try { this.channel.send(JSON.stringify(next.frame)); } catch { this.statusSender.reset(); /* the next session says it */ }\n }\n /** The session ended: the contact is not online here any more, and the next session is owed this side's whole state. */\n private endStatusSession(): void {\n if (this.statusTimer) { clearTimeout(this.statusTimer); this.statusTimer = null; }\n this.statusSender.reset();\n this.statusReceiver.endSession();\n }\n /** Both sides offer `wake/1` on the open session: push subscriptions can be shared (WISP 401 § Wake-up push). */\n get supportsWake(): boolean { return !!this.options.params.profile && this.isDataLinkOpen && this.sessionCapabilities.agreed(WAKE_SESSION_CAPABILITY); }\n /**\n * Shares how to wake this side's closed web app (null: stop, forget it) on the live session, once both sides offer\n * `wake/1`. False when it could not go now: the caller shares it again on the next session.\n */\n sendWake(target: WakeTarget | null): boolean {\n if (!this.channel || !this.supportsWake) return false;\n try { this.channel.send(JSON.stringify(wakeFrame(target))); return true; } catch { return false; }\n }\n /**\n * This side's participation key and the pinned contact's, on a paired session that is open and ready: what the asker's\n * proof of a contact request is made for (WISP 8xx § Accept). Undefined otherwise.\n */\n get participationKeys(): { mine: string; peer: string } | undefined {\n const credentials = this.options.pairing?.credentials;\n if (!this.options.params.profile || !credentials?.peerKey || !this.channel || !this.isDataLinkOpen || this.paired?.state.status !== \"ready\") return undefined;\n return { mine: credentials.signer ? toZ32(credentials.signer.publicKey) : identityFromSeedB64(credentials.seedB64).pubKeyZ32, peer: credentials.peerKey };\n }\n /**\n * Says on the live session that this side asked through the contact's link (WISP 8xx § Accept). No capability: an app\n * that does not know the frame drops it. False when it could not go now: the caller says it again on the next session.\n */\n sendContactAsker(frame: ContactAskerFrame): boolean {\n if (!this.channel || !this.participationKeys) return false;\n try { this.channel.send(JSON.stringify(frame)); return true; } catch { return false; }\n }\n /** Both sides offer `pin/1` on the open session: a pin can be said and confirmed. */\n get supportsPins(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(PIN_CAPABILITY); }\n /**\n * Says this side's pin (WISP 401 § Pinned message) on the live session, once both sides offer `pin/1`. An error when\n * it could not go now: the caller keeps it, and it goes on the next session.\n */\n sendPin(pin: WirePin): string | null {\n if (!this.options.params.profile) return \"Pins need a current chat\";\n if (!this.channel || !this.isDataLinkOpen) return \"A pin goes when you are live\";\n if (!this.supportsPins) return \"Your contact's app does not show pins yet\";\n try { this.channel.send(pinFrame(pin)); return null; } catch { return \"The connection closed before sending\"; }\n }\n /** Both sides offer `edit/1` on the open session: edits can be said and confirmed. */\n get supportsEdits(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(EDIT_CAPABILITY); }\n /** Both sides offer `status-card/1` on the open session: the contact shows cards and takes a card's edits past 100. */\n get supportsStatusCards(): boolean { return this.isDataLinkOpen && this.sessionCapabilities.agreed(STATUS_CARD_CAPABILITY); }\n /**\n * Says an edit of one of this side's messages (WISP 401 § Edits): on the live session once both sides offer `edit/1`;\n * while not live, on the DHT floor when `dht` says the contact's app takes edits there (WISP 403 § Edits). An error\n * when it could not go now; the caller keeps it and says it again later.\n */\n async sendEdit(edit: WireEdit, { dht = false }: { dht?: boolean } = {}): Promise<string | null> {\n if (!this.options.params.profile) return \"Edits need a current chat\";\n if (this.channel && this.isDataLinkOpen) {\n if (!this.supportsEdits) return \"Your contact's app does not show edits yet\";\n // Past a text's edits only an app that shows cards takes one (WISP 405 · Status Cards); an older one would drop it.\n // A removal goes whatever its number: an app that knows removals takes it, an older one shows or drops its fallback.\n if (!edit.rm && !validEditNumber(edit.e) && !(edit.sc && this.supportsStatusCards)) return \"Your contact's app takes no more edits of this message\";\n // One past what a session takes would end the contact's session, again on every new one.\n if (!pairedEditFits(edit)) return PAIRED_FRAME_TOO_LARGE;\n try { this.channel.send(editFrame(edit)); return null; } catch { return \"The connection closed before sending\"; }\n }\n // A card's edit waits for the live session: on the floor the card would read as its text until the next one.\n if (edit.sc) return \"A card's update goes when you are live\";\n // A removal never goes on the floor (WISP 403 § Edits): an older reader would show its fallback as the new text.\n if (edit.rm) return \"A removal goes when you are live\";\n if (dht && this.dht && this.textDelivery === \"dht\") return this.dht.send(edit.m, edit.ts, dhtEditId(edit.id, edit.e), undefined, [edit.id, edit.e]);\n return \"Edits go when you are live\";\n }\n /**\n * Why the DHT floor can never carry this edit, or null (WISP 403 § Edits): it goes there as a text with the edit's\n * element, which must fit the packet once sealed, as a text must (`validateText`). One past the 256 bytes never fits\n * it either, and says so with the same reason. Null off the floor, and for what only makes it wait there (a text\n * awaiting its receipt): that one goes in its turn.\n */\n dhtEditTooBig(edit: WireEdit): string | null {\n if (this.isDataLinkOpen || this.textDelivery !== \"dht\") return null;\n const error = this.dht!.validate(edit.m, edit.ts, dhtEditId(edit.id, edit.e), undefined, [edit.id, edit.e]);\n return error === DHT_PACKET_BUDGET || error === DHT_TEXT_TOO_LONG ? DHT_PACKET_BUDGET : null;\n }\n /** Confirms an edit of the contact's that waited for its message (`onMessageEdit` returned false). */\n confirmEdit(id: string, e: number): void {\n if (!this.channel || !this.supportsEdits) return;\n try { this.channel.send(editedFrame(id, e)); } catch { /* the contact says it again */ }\n }\n /**\n * This side is typing (true) or stopped (false). Said only on the live session and only when both sides offer\n * `typing/1`; never on the DHT. A `start` goes at most every few seconds (at once when `activity` changes), a\n * `stop` only after a `start`.\n */\n setTyping(typing: boolean, activity?: TypingActivity): void {\n if (!this.options.params.profile) return;\n // Nothing can carry it now (between a switch's two sessions, or before typing/1 is agreed): kept for the next one.\n if (typing && !this.supportsTyping) { this.typingSender.want(activity); return; }\n const frame = typing ? this.typingSender.typing(activity) : this.typingSender.stopped();\n if (!frame || !this.channel || !this.supportsTyping) return;\n try { this.channel.send(JSON.stringify(frame)); } catch { /* the session is going; the contact's timeout ends it */ }\n }\n private resumeTyping(): void {\n const frame = this.typingSender.resume();\n if (!frame || !this.channel) return;\n try { this.channel.send(JSON.stringify(frame)); } catch { /* the session is going; the next one says it again */ }\n }\n /** Both sides offer `apps/1` on the open session: mini-apps can talk (WISP 1200 § In a chat). */\n get supportsApps(): boolean { return !!this.options.params.profile && this.isDataLinkOpen && this.sessionCapabilities.agreed(APPS_CAPABILITY); }\n /** The apps the contact has open on this session (chat app id to version). */\n get peerApps(): ReadonlyMap<string, string> { return this.apps.peerOpen; }\n /**\n * This side opened an app in this chat (or updated it): `open` goes now when both sides offer `apps/1` on the live\n * session, and again on every session that comes back while the app stays open. Never on the DHT.\n */\n openApp(app: string, version: string): void {\n const frame = JSON.stringify(appOpenFrame(app, version));\n this.apps.open.set(app, version);\n if (this.supportsApps && this.channel) try { this.channel.send(frame); } catch { /* said again on the next session */ }\n }\n /** This side closed an app in this chat: `close` goes now when it can; nothing is said later. */\n closeApp(app: string): void {\n const frame = JSON.stringify(appCloseFrame(app));\n if (!this.apps.open.delete(app)) return;\n // Its page is gone, so nothing reads for the contact any more: the places it held free now.\n this.appRanges.closeApp(app, \"offline\", true);\n if (this.supportsApps && this.channel) try { this.channel.send(frame); } catch { /* the session is going: the contact hears it ended */ }\n }\n /**\n * One data frame of an app open on both sides, on the live session only. An error when it did not go: nothing is\n * kept to send later. While the channel already holds a quarter of what it may queue (its send budget, or the high\n * water mark of a WebRTC channel), the frame is refused with `too-fast`, so the chat's messages and pings never wait\n * behind an app's data on a link slower than it sends (WISP 1200 § In a chat). While a file goes, that quarter sits\n * above what files may hold (`filesWritable`): files keep the channel at their own line for the whole transfer. While\n * the file waits for room, the app gets no further than `APP_AHEAD_OF_FILES` ahead of it, so it cannot refill the\n * channel each time it drains to files' line and keep the file from moving. With a contact that answers pings, it is\n * also refused while `APP_IN_FLIGHT` of the apps' data has not been answered for: what the transport holds in flight\n * under the channel counts too.\n */\n sendAppData(app: string, data: unknown): AppSendError | null {\n if (!this.apps.open.has(app)) return \"not-open\";\n if (appDataBytes(data) > APP_DATA_MAX_BYTES) return \"too-large\";\n if (!this.channel || !this.isDataLinkOpen) return \"offline\";\n if (!this.supportsApps) return \"peer-closed\";\n const use = this.filesUse?.channel === this.channel ? this.filesUse : null;\n const files = use && (use.waiting > 0 || Date.now() - use.at < FILES_IN_USE_MS) ? use : null;\n if (use && !files) use.appAhead = 0;\n if (this.channel.bufferedAmount >= (files ? filesCap(this.channel) : 0) + (this.channel.sendBudget ?? LIMITS.sendHighWaterMark) / 4) return \"too-fast\";\n if (files && files.waiting > 0 && files.appAhead >= APP_AHEAD_OF_FILES) return \"too-fast\";\n if (this.peerAnswersPings && this.appUnanswered() >= APP_IN_FLIGHT) return \"too-fast\";\n const refused = this.apps.canSend(app, data);\n if (refused) return refused;\n const frame = JSON.stringify(appDataFrame(app, data));\n try { this.channel.send(frame); } catch { return \"offline\"; }\n if (files) files.appAhead = Math.min(files.appAhead + frame.length, APP_AHEAD_OF_FILES + APP_DATA_MAX_BYTES);\n if (this.peerAnswersPings) {\n this.appUnmarked += frame.length;\n // One ping a round trip for small frames (a Chess move), one every quarter of the window for a stream.\n if (this.appInFlight.length === 0 || this.appUnmarked >= APP_IN_FLIGHT / 4) this.markAppData(this.channel);\n }\n return null;\n }\n /** Apps' data sent on this session that the contact has not answered for yet (`APP_IN_FLIGHT`). */\n private appUnanswered(): number {\n return this.appInFlight.reduce((sum, mark) => sum + mark.bytes, this.appUnmarked);\n }\n /** A ping after the apps' data sent since the last one: its pong says the contact handled it. */\n private markAppData(channel: FrameChannel): void {\n try { this.sendPing(channel, false); } catch { return; /* the session is going: a new one starts from nothing */ }\n this.appInFlight.push({ ping: this.pingsSent, bytes: this.appUnmarked });\n this.appUnmarked = 0;\n }\n /** Both sides offer `app-ranges/1` (and `apps/1`) on the open session: an app's files can be read from the other side. */\n get supportsAppRanges(): boolean { return this.supportsApps && this.sessionCapabilities.agreed(APP_RANGES_CAPABILITY); }\n /** Why the read lane cannot be used for `app` now, or null when it can: open on both sides, on a live session that has it. */\n private appRangesRefusal(app: string): \"not-open\" | \"offline\" | \"peer-closed\" | null {\n if (!this.apps.open.has(app)) return \"not-open\";\n if (!this.channel || !this.isDataLinkOpen) return \"offline\";\n return this.supportsAppRanges && this.apps.peerOpen.has(app) ? null : \"peer-closed\";\n }\n /**\n * Lets the contact's `app` read `file` (what this side's app calls it) for as long as both have the app open, across\n * a session change the apps are held across: the serve id to tell it, or why not.\n */\n serveAppFile(app: string, file: string): { serve: string } | { error: \"not-open\" | \"offline\" | \"peer-closed\" } {\n const error = this.appRangesRefusal(app);\n return error ? { error } : { serve: this.appRanges.serve(app, file) };\n }\n /** Ends a serve; false when it was not served (any more). */\n unserveAppFile(serve: string): boolean { return this.appRanges.unserve(serve); }\n /** The serve ids `app` has given out and not ended. */\n appServes(app: string): string[] { return this.appRanges.servesOf(app); }\n /**\n * Reads `length` bytes at `offset` of what the contact's `app` serves as `serve`: the bytes (fewer at the end of the\n * file) and the file's size. Rejects with an `Error` whose message is an `AppRangeReadError` or `not-open`.\n */\n readAppRange(app: string, serve: string, offset: number, length: number): Promise<{ bytes: Uint8Array; size: number }> {\n const error = this.appRangesRefusal(app);\n return error ? Promise.reject(new Error(error)) : this.appRanges.read(app, serve, offset, length);\n }\n /**\n * The bytes `task` asked for (fewer at the end of the file, none past it) and the file's size: sent in chunks as the\n * channel has room, sharing files' line (`filesWritable`), as binary messages where `files/4` is agreed, then\n * `ar-end`. Stops when the task is no longer live or the session changes.\n */\n async sendAppRange(task: AppRangeTask, bytes: Uint8Array, size: number): Promise<void> {\n bytes = bytes.subarray(0, task.length);\n const channel = this.channel;\n try {\n if (!channel) return;\n for (let at = 0; at < bytes.length; at += APP_RANGE_LIMITS.chunkBytes) {\n // Room is asked again right before the send: the app's other requests wake on the same drain, and each that\n // sent first took some of it, so they would all send at once and fill a native channel past its budget.\n for (let room = this.filesWritable(); room; room = this.channel === channel ? this.filesWritable() : undefined) await room;\n if (!task.live || this.channel !== channel || !this.supportsAppRanges) return;\n const chunk = bytes.subarray(at, at + APP_RANGE_LIMITS.chunkBytes);\n const message = this.supportsBinaryFiles ? encodeAppRangeData(task.app, task.request, task.offset + at, chunk) : JSON.stringify(appRangeDataFrame(task.app, task.request, task.offset + at, chunk));\n try { channel.send(message); } catch {\n // A full channel (files beside it woke on the same drain) is tried again later, as a file's chunk is: given up\n // on, the contact's read would wait for good. A session that ends drops the task, which stops this.\n await new Promise(resolve => setTimeout(resolve, FILE_LIMITS.sendRetryMs));\n at -= APP_RANGE_LIMITS.chunkBytes;\n continue;\n }\n this.filesWrote(channel, typeof message === \"string\" ? message.length : message.byteLength);\n }\n this.appRanges.finish(task, size);\n } finally {\n // Stopped early or not, the task's place among its app's requests in flight frees now.\n this.appRanges.release(task);\n }\n }\n /** `task`'s file cannot be read: `changed` or `gone` goes in place of its bytes (nothing once it is no longer live, but its place frees). */\n failAppRange(task: AppRangeTask, error: \"changed\" | \"gone\"): void { this.appRanges.fail(task, error); }\n /** Whether `task` still holds a place until it is answered (`AppRanges.holds`): one that does not needs no answer. */\n holdsAppRange(task: AppRangeTask): boolean { return this.appRanges.holds(task); }\n /** An `ar-*` frame from the contact, on a session that agreed `app-ranges/1`. */\n private receiveAppRange(frame: Record<string, unknown>): void {\n const read = readAppRangeFrame(frame);\n if (!read.ok) return;\n const ranges = read.frame;\n switch (ranges.t) {\n case \"ar-get\": {\n // Only for an app open on both sides (WISP 1200 § A read lane to the contact): any other is not served.\n if (this.appRangesRefusal(ranges.a)) {\n try { this.channel?.send(JSON.stringify(appRangeErrorFrame(ranges.a, ranges.r, \"not-served\"))); } catch { /* the session is going */ }\n return;\n }\n const task = this.appRanges.receiveGet(ranges);\n if (task) this.options.events?.onAppRangeTask?.(task);\n return;\n }\n case \"ar-cancel\": return this.appRanges.receiveCancel(ranges);\n case \"ar-data\": return this.appRanges.receiveData(ranges.a, ranges.r, ranges.o, appRangeChunk(ranges.d)!);\n default: return this.appRanges.receiveAnswer(ranges);\n }\n }\n /** What the contact had open is gone (`apps/1` is no longer agreed, or this link stopped): each app hears it now. */\n private appsEnded(): void {\n this.appRanges.reset();\n if (this.appsGrace) { clearTimeout(this.appsGrace); this.appsGrace = null; }\n for (const event of this.apps.sessionEnded()) this.options.events?.onAppFrame?.(event);\n }\n private appsGrace: ReturnType<typeof setTimeout> | null = null;\n /**\n * The session ended or a new one took its place (a transport switch, a resume, a re-dial): what the contact had open\n * is held for `APP_RESUME_GRACE_MS` (WISP 1200 § In a chat). The next session's `open` takes each back, and the app\n * hears only that open, not a close first; one not said again by then is closed with `offline`. Each suspension\n * gives what it held its own grace: a later one's apps do not close at an earlier one's time.\n */\n private appsSuspended(): void {\n // Requests last one session; serve ids are held with the apps, and end when an app closes (WISP 1200).\n this.appRanges.suspend();\n this.apps.sessionSuspended(this.options.appResumeGraceMs ?? APP_RESUME_GRACE_MS);\n this.armAppsGrace();\n }\n /** A timer for the next held app's grace, as long as any is held. */\n private armAppsGrace(): void {\n if (this.appsGrace) { clearTimeout(this.appsGrace); this.appsGrace = null; }\n const until = this.apps.heldUntil;\n if (until === undefined) return;\n this.appsGrace = setTimeout(() => {\n this.appsGrace = null;\n for (const event of this.apps.heldExpired()) {\n if (\"o\" in event && event.o === \"close\") this.appRanges.closeApp(event.app, \"offline\");\n this.options.events?.onAppFrame?.(event);\n }\n this.armAppsGrace();\n }, Math.max(0, until - Date.now()));\n }\n /** Whether files/3 was agreed on the session open now; kept to say when that changes. */\n private filesOpen = false;\n private emitFilesSession(again = false): void {\n const open = this.supportsLargeFiles;\n if (open === this.filesOpen && !(open && again)) return;\n this.filesOpen = open;\n this.options.events?.onFilesSession?.(open);\n }\n /** A files/3 frame to the contact, on the open session. False when files/3 cannot flow now. */\n sendFilesFrame(frame: Record<string, unknown>): boolean {\n if (!this.supportsLargeFiles || !this.channel) return false;\n try { this.channel.send(JSON.stringify(frame)); return true; } catch { return false; }\n }\n /**\n * A file's bytes to the contact, on the open session: one binary message while both sides agreed `files/4` on it,\n * the `pf-data` frame with them as base64url text otherwise (WISP 501 § files/4). The form is chosen for each chunk,\n * so a transfer follows the session it is on. False when files/3 cannot flow now, or the channel has no room.\n */\n sendFileData(id: string, offset: number, data: Uint8Array): boolean {\n if (!this.supportsLargeFiles || !this.channel) return false;\n try {\n const frame = this.supportsBinaryFiles ? encodeFileData(id, offset, data) : JSON.stringify({ t: \"pf-data\", id, offset, data: toBase64Url(data) });\n this.channel.send(frame);\n this.filesWrote(this.channel, typeof frame === \"string\" ? frame.length : frame.byteLength);\n return true;\n } catch { return false; }\n }\n /** Files (or a shared service's body, `PairedHttpBodies`) wrote `bytes` on a channel. */\n private filesWrote(channel: FrameChannel, bytes: number): void {\n const use = this.filesUsing(channel);\n use.at = Date.now();\n // What files write is the app's to send too, up to what files may hold: a WebRTC channel drains to its low water\n // mark before files write again, so they write in bursts of most of it, and the app's share is the same burst.\n use.appAhead = Math.max(-filesCap(channel), use.appAhead - bytes);\n }\n /**\n * A shared service's body on a channel counts as files there (WISP 1200 § In a chat): it keeps a WebRTC channel at the\n * same 1 MiB line, so an app's data gets its quarter above it, and about half the link while the body waits for room.\n */\n private bodiesOn(channel: FrameChannel): PairedHttpBodies {\n return {\n wrote: bytes => this.filesWrote(channel, bytes),\n waiting: async drained => {\n const use = this.filesUsing(channel);\n use.waiting++;\n try { await drained; } finally { use.waiting--; use.at = Date.now(); }\n },\n };\n }\n /**\n * Files on a channel: when they last wrote on it, how many wait for room, and how many bytes an app's data has sent\n * on it beyond theirs since. An app's data gets room above theirs.\n */\n private filesUse: FilesUse | null = null;\n private filesUsing(channel: FrameChannel): FilesUse {\n if (this.filesUse?.channel !== channel) this.filesUse = { channel, at: 0, waiting: 0, appAhead: 0 };\n return this.filesUse;\n }\n /**\n * Resolves once the open session can take another files/3 data frame; undefined when it can now. A channel with a send budget (native and\n * iroh ones throw past 120 KiB) gives files a quarter of it, so a ping, a message or any other frame still fits\n * while a file goes; others keep under the high water mark, as files/2 does. An app's data gets a quarter above that\n * line meanwhile (`sendAppData`).\n */\n filesWritable(): Promise<void> | undefined {\n const channel = this.channel;\n if (!channel) return;\n const cap = filesCap(channel);\n // Room now: nothing to wait for, and nothing made for each frame of a large file.\n if (channel.bufferedAmount < cap) return;\n const use = this.filesUsing(channel);\n use.waiting++;\n return (async () => {\n try {\n while (this.channel === channel && channel.bufferedAmount >= cap) {\n await channel.drained().catch(() => {});\n // A drain that resolved above the cap (a low water mark higher than it) is not waited on in a loop of promises.\n if (this.channel === channel && channel.bufferedAmount >= cap) await new Promise((resolve) => setTimeout(resolve, 20));\n }\n } finally {\n use.waiting--;\n use.at = Date.now();\n }\n })();\n }\n /** What each side offers on the open session, for showing why something is unavailable. `peer` is null until it says. */\n get sessionOffers(): { mine: SessionCapability[]; peer: string[] | null } {\n const known = KNOWN_SESSION_CAPABILITIES;\n return { mine: this.offeredCapabilities(),\n peer: this.isDataLinkOpen && this.sessionCapabilities.peerAnnounced ? known.filter(c => this.sessionCapabilities.peerOffers(c)) : null };\n }\n /** Why a call cannot be placed in this paired chat right now, or null when it can. */\n get callsUnavailable(): string | null {\n if (!this.options.params.profile || this.supportsCalls) return null;\n if (!this.options.callsSupport) return this.options.callsMissing ?? \"Calls are not available in this app\";\n if (!this.isDataLinkOpen) return \"Calls need a live connection\";\n return this.sessionCapabilities.peerAnnounced ? \"Your contact's app cannot take calls\" : \"Your contact needs an updated Ghostly for calls\";\n }\n /** Says what this side offers on the open session. Older apps drop the frame (no id). */\n private sendSessionCapabilities(): void {\n if (!this.options.params.profile || !this.channel || !this.isDataLinkOpen) return;\n try { this.channel.send(JSON.stringify(this.sessionCapabilities.announcement())); } catch { /* said again on the next session */ }\n }\n /** The contact said what it offers: start what both sides now agree on. */\n private sessionCapabilitiesChanged(changed: SessionCapability[]): void {\n if (changed.includes(SERVICES_CAPABILITY)) {\n if (this.supportsServices) this.sendPairedServices();\n else if (this.peerServicesOverride) { this.peerServicesOverride = null; this.options.events?.onPresence?.(this.presence); }\n }\n if (changed.includes(CALLS_CAPABILITY) && this.supportsCalls && this.channel) {\n const pending = this.pairedCalls.pending();\n if (pending) try { this.channel.send(JSON.stringify(pending)); } catch { /* the next session */ }\n }\n if (changed.includes(CALLS_CAPABILITY)) this.leaveHangUp();\n if (changed.includes(TYPING_CAPABILITY)) {\n if (!this.supportsTyping) { this.typingSender.reset(); this.typingReceiver.clear(); }\n // A new session (a transport switch, a reconnect): the contact's reader cleared what this side said on the old\n // one, so a start still standing is said again (a frame said between the two sessions was lost).\n else this.resumeTyping();\n }\n if (changed.includes(STATUS_CAPABILITY)) {\n // A new session, or the contact (or this side) offers it again: the whole state goes; off, presence ends here.\n if (this.supportsStatus) this.flushStatus();\n else this.endStatusSession();\n }\n if (changed.includes(REACTIONS_CAPABILITY)) this.options.events?.onReactionsSupport?.(this.supportsReactions);\n if (changed.includes(EDIT_CAPABILITY)) this.options.events?.onEditSupport?.(this.supportsEdits);\n if (changed.includes(PIN_CAPABILITY)) this.options.events?.onPinSupport?.(this.supportsPins);\n if (changed.includes(WAKE_SESSION_CAPABILITY)) this.options.events?.onWakeSupport?.(this.supportsWake);\n if (changed.includes(UPGRADE_CAPABILITY)) this.switcher.reconsider();\n if (changed.includes(APPS_CAPABILITY)) {\n // Back on a session: each app this side has open says so again, and catches up once the contact's says so too.\n if (this.supportsApps && this.channel) for (const [app, version] of this.apps.open) try { this.channel.send(JSON.stringify(appOpenFrame(app, version))); } catch { /* the next session */ }\n if (!this.supportsApps) this.appsEnded();\n this.options.events?.onAppsSupport?.(this.supportsApps);\n }\n if (changed.includes(APP_RANGES_CAPABILITY) && !this.supportsAppRanges) this.appRanges.reset();\n const devices = this.options.deviceCapabilities;\n if (devices && changed.some(capability => (devices as readonly string[]).includes(capability))) this.options.events?.onDeviceCapabilities?.(devices.filter(capability => this.supportsDevice(capability)));\n this.emitPairingState();\n }\n /** Both sides announced groups on this session and it is open. */\n get groupsSupport(): boolean { return !!this.options.groupsSupport && this.isDataLinkOpen && !!this.peerGroupVersions?.includes(1); }\n /** Both sides announced this version of groups (1: `group-mesh/1`, 2: `group-community/1` too). */\n supportsGroupVersion(version: number): boolean { return this.groupsSupport && !!this.peerGroupVersions?.includes(version); }\n /** A `group-*` frame to the peer. Only while both sides support groups; never queued. */\n sendGroupFrame(frame: object): void {\n if (!this.groupsSupport || !this.channel) throw new Error(\"This contact is not connected, or needs an updated Ghostly for groups\");\n const data = JSON.stringify(frame);\n if (data.length > LIMITS.maxControlFrameBytes) throw new Error(\"Group frame too large\");\n this.channel.send(data);\n }\n /** Older apps drop this frame (it carries no id): to them this contact has no groups. */\n private sendGroupsSupport(): void {\n if (!this.options.groupsSupport || !this.options.params.profile || !this.channel || !this.isDataLinkOpen) return;\n try { this.channel.send(JSON.stringify({ t: \"paired-groups\", v: [1, 2, GROUP_VERSION_LARGE, GROUP_VERSION_HUBS, GROUP_VERSION_SIGNALS, GROUP_VERSION_FILES] })); } catch { /* the next session announces it */ }\n }\n /** Older apps drop this frame (it carries no id) and keep using the handshake offer. */\n private sendPaymentMethods(): void {\n if (!this.options.params.profile || !this.channel || !this.isDataLinkOpen || this.paired?.state.status !== \"ready\") return;\n // Offered: the ways this chat has on and (once this app says its wallets' networks) has a wallet of; a way with\n // no wallet is nothing the contact can pay to. A wallet whose networks are all off here still names the way.\n const networks = this.options.paymentNetworks;\n const methods = PAYMENT_METHODS.filter(m => this.paymentEnabled(m) && (!networks || networks[m] !== undefined));\n // The networks go for every wallet, on or off here: a way turned off is told apart from one with no wallet.\n try { this.channel.send(JSON.stringify({ t: \"paired-payments\", m: methods, ...(networks ? { n: networks } : {}) })); } catch { /* the next session offers it */ }\n }\n /**\n * The contact said goodbye on the last live session (its app quit or stopped) and has published nothing since but its\n * leave packet: its app is not running, so a dial now waits for nobody until it gives up.\n */\n get contactAway(): boolean {\n const presence = this.session.peerPresence;\n return !this.isDataLinkOpen && !!this.departed && (presence.lastPacketAt === this.departed.packet || !presence.online);\n }\n\n async requirePaymentSupport(): Promise<void> {\n if (!PAYMENT_METHODS.some(m => this.paymentEnabled(m))) throw new Error(\"Payments are turned off in this chat.\");\n // Said at once: before, the dial below waited out its 90 s for an app that had said it was going.\n if (this.contactAway) throw engineError(\"contactAway\");\n await this.open();\n if (this.supportsPayments) return;\n // As the app's chat says it: networks that name no wallet are a contact that offers no way until it makes one.\n const networks = this.peerNetworks;\n throw engineError(networks && !Object.keys(networks).length ? \"contactNoWallet\" : \"contactNoPayments\");\n }\n\n private requireLegacyCapabilities(): void {\n if (this.options.params.profile) throw new Error(\"This experimental paired profile supports chat only.\");\n }\n\n /** `closeRtc`: a WebRTC attempt under way beside a native session is this change's, and ends with it. */\n private cancelCandidate(closeRtc = true): void {\n this.candidateEpoch++;\n const candidate = this.candidate;\n this.candidate = null;\n candidate?.session.stop();\n candidate?.reject(new Error(\"Transport change cancelled\"));\n candidate?.channel.close();\n this.dropContenders(\"Transport change cancelled\");\n this.rtcCandidateWaiter?.reject(new Error(\"Transport change cancelled\"));\n this.rtcCandidateWaiter = null;\n if (this.activeBinding && closeRtc) this.dataLink.close();\n }\n\n private async prepareSwitch(plan: SwitchPlan): Promise<void> {\n const epoch = ++this.candidateEpoch;\n let lastError: unknown;\n this.switchMissed = undefined;\n for (const transport of plan.choices) {\n if (epoch !== this.candidateEpoch || this.switcher.pending !== plan || this.stopped) return;\n if (this.paired?.state.transport === transport) {\n this.switcher.keep(lastError instanceof Error ? lastError.message : undefined); return;\n }\n try {\n await new Promise<void>((resolve, reject) => {\n let active = true, notFound: Error | undefined;\n const timer = setTimeout(() => { active = false; reject(notFound ?? new Error(`${transport} did not connect in time`)); }, 8_000);\n const done = { resolve: () => { active = false; clearTimeout(timer); resolve(); }, reject: (error: Error) => { active = false; clearTimeout(timer); reject(error); } };\n if (transport === \"webrtc/1\") {\n this.rtcCandidateWaiter = done;\n // Back to WebRTC a moment after leaving it: the session left behind still holds the data link, and an offer\n // goes once it has closed. Before, nothing was offered: the plan gave up after its 8 s and waited for the\n // 20 s retry (28 s on two CLIs, bug hunt r9g).\n void this.rtcRetired().then(() => {\n if (!active || epoch !== this.candidateEpoch || this.switcher.pending !== plan) return;\n this.switcher.dialing(plan);\n return this.dataLink.connect();\n }).catch(done.reject);\n } else {\n const endpoint = this.endpoints.get(transport), descriptor = plan.remote.descriptors[transport];\n if (!endpoint || !descriptor) { done.reject(new Error(\"Peer native address unavailable\")); return; }\n // One switch dial in flight per transport: a cancelled one runs to its own timeout (it cannot be aborted),\n // and the next waits for it rather than stacking another beside it.\n const turn = (this.switchDials.get(transport) ?? Promise.resolve()).then(async () => {\n for (;;) {\n if (!active || epoch !== this.candidateEpoch || this.switcher.pending !== plan) return;\n this.switcher.dialing(plan);\n try {\n const { channel, binding } = await endpoint.connect(descriptor);\n if (!active || epoch !== this.candidateEpoch || this.switcher.pending !== plan) { channel.close(); return; }\n void this.attachCandidate(channel, binding, plan).then(done.resolve, done.reject);\n return;\n } catch (error) {\n const failure = error instanceof Error ? error : new Error(String(error));\n if (!/^PEER_NOT_FOUND\\b/.test(failure.message)) { done.reject(failure); return; }\n // Not announced again yet (`SWITCH_FIND_RETRY_MS`): dialled again until the move's 8 s are up.\n notFound = failure;\n await new Promise(resolve => setTimeout(resolve, SWITCH_FIND_RETRY_MS));\n }\n }\n });\n this.switchDials.set(transport, turn);\n void turn.then(() => { if (this.switchDials.get(transport) === turn) this.switchDials.delete(transport); });\n }\n });\n return;\n } catch (error) {\n lastError = error;\n if (transport === plan.choices[0]) this.switchMissed = { transport, reason: error instanceof Error ? error.message : String(error) };\n if (epoch !== this.candidateEpoch || this.switcher.pending !== plan) return;\n const candidate = this.candidate; this.candidate = null;\n candidate?.session.stop(); candidate?.reject(new Error(\"Candidate failed\")); candidate?.channel.close();\n this.dropContenders(\"Candidate failed\");\n this.rtcCandidateWaiter = null;\n if (transport === \"webrtc/1\") this.dataLink.close();\n }\n }\n if (epoch === this.candidateEpoch && this.switcher.pending === plan)\n this.switcher.fail(`Transport change failed: ${lastError instanceof Error ? lastError.message : \"no permitted transport connected\"}. Retry or choose another transport.`);\n }\n\n private attachCandidate(channel: FrameChannel, binding: NativeBinding | undefined, plan: SwitchPlan): Promise<void> {\n // One dialled in first and unproven keeps no place of its own: the contact's, or this side's own dial, authenticates\n // beside it (`contend`). So does the WebRTC session a move to WebRTC opened beside one dialled in as a replacement:\n // refused, the move off a relay failed and was never planned again.\n const rtcMove = !binding && plan.choices[0] === \"webrtc/1\";\n if ((this.candidate && !this.contendable(rtcMove ? this.candidate.plan : plan)) || this.switcher.pending !== plan || !plan.choices.includes(binding?.transport ?? \"webrtc/1\")) {\n channel.close(); return Promise.reject(new Error(\"Obsolete or duplicate transport candidate\"));\n }\n return new Promise<void>((resolve, reject) => this.contend(channel, binding, { plan, resolve, reject }));\n }\n\n /** The candidate waiting for `plan` (none: a replacement) was dialled in and has not authenticated yet. */\n private contendable(plan?: SwitchPlan): boolean {\n const held = this.candidate;\n return !!held && held.plan === plan && this.unproven(held.channel) && held.session.state.status !== \"ready\";\n }\n /**\n * A connection that authenticates beside the candidate held (`contenders`), or takes the place if none is. With\n * `DIALED_IN_CONTENDERS` waiting already, the oldest dialled in and unproven of them gives its place up.\n */\n private contend(channel: FrameChannel, binding: NativeBinding | undefined, migration: { plan?: SwitchPlan; resolve(): void; reject(error: Error): void }): void {\n if (this.candidate && this.contenders.length >= DIALED_IN_CONTENDERS) {\n const at = this.contenders.findIndex(c => this.unproven(c.channel));\n if (at < 0) { channel.close(); migration.reject(new Error(\"Obsolete or duplicate transport candidate\")); return; }\n const [oldest] = this.contenders.splice(at, 1);\n traceLink(this.myPubKeyZ32, \"dialed-in-dropped\", { transport: oldest.binding?.transport });\n oldest.session.stop(); oldest.reject(new Error(\"A newer connection took its place\")); oldest.channel.close();\n }\n this.attach(channel, binding, migration);\n }\n /** One of the `contenders` authenticated first: it takes the candidate's place, and the candidate held closes. */\n private promoteContender(channel: FrameChannel): boolean {\n const at = this.contenders.findIndex(c => c.channel === channel);\n if (at < 0) return false;\n const [won] = this.contenders.splice(at, 1), held = this.candidate;\n this.candidate = won;\n if (held) { held.session.stop(); held.reject(new Error(\"Another connection authenticated first\")); held.channel.close(); }\n return true;\n }\n private dropContenders(reason: string): void {\n for (const c of this.contenders.splice(0)) { c.session.stop(); c.reject(new Error(reason)); c.channel.close(); }\n }\n\n /**\n * Both sides dialled at once (two apps back after a restart, each knocking): the lower key's dial carries the chat, on\n * both sides; the higher key's side takes it over as a replacement (`attachReplacement`). Here, on the lower key's\n * side, the contact's connection waits: dropped once this side's own dial connects, taken if that dial fails, or has\n * not connected within `CROSSED_WAIT_MS` (it stalled, or goes to an endpoint the contact no longer runs, for as long\n * as it takes to give up).\n */\n private crossed: { channel: FrameChannel; binding: NativeBinding; timer: ReturnType<typeof setTimeout> } | null = null;\n private parkCrossed(channel: FrameChannel, binding: NativeBinding): void {\n this.dropCrossed();\n traceLink(this.myPubKeyZ32, \"dial-crossed\", { transport: binding.transport });\n const timer = setTimeout(() => {\n if (this.crossed?.channel !== channel) return;\n this.crossed = null;\n if (this.channel || this.stopped || this.leaving) { channel.close(); return; }\n // This side's dial did not connect in time: the contact's carries the chat, and this one is closed if it does yet.\n this.connectionEpoch++; this.dialing = false; this.attempt = null;\n this.attach(channel, binding);\n }, CROSSED_WAIT_MS);\n channel.onClose = () => { if (this.crossed?.channel === channel) { clearTimeout(timer); this.crossed = null; } };\n this.crossed = { channel, binding, timer };\n }\n private dropCrossed(): void {\n const crossed = this.crossed;\n if (!crossed) return;\n this.crossed = null; clearTimeout(crossed.timer); crossed.channel.close();\n }\n /** This side's dial ended: a connection of the contact's that waited is dropped, or, if nothing connected, taken now. */\n private settleCrossed(): void {\n const crossed = this.crossed;\n if (!crossed) return;\n if (this.channel || this.stopped || this.leaving) { this.dropCrossed(); return; }\n this.crossed = null; clearTimeout(crossed.timer);\n this.attach(crossed.channel, crossed.binding);\n }\n\n /**\n * The pinned contact dialled in while this side still holds a session with it. A contact dials only with no session\n * of its own (a switch both agreed goes through `attachCandidate`): its app restarted, or lost the session, and the\n * one held here is dead without this side having heard (a crash, a quit that said nothing, a network change). The new\n * connection authenticates first, then takes over; a dial that does not authenticate closes and changes nothing.\n * Before the pin a held session keeps the chat, as it always did.\n */\n private attachReplacement(channel: FrameChannel, binding: NativeBinding): void {\n if (!this.options.pairing?.credentials.peerKey || !this.options.params.profile) { channel.close(); return; }\n // A replacement dialled in that has not authenticated yet keeps no place of its own: a newer one authenticates beside\n // it, and whichever does first takes over (`contend`). Whoever read the endpoint could otherwise hold the place, or\n // take it from the contact's over and over, while the contact, back after a restart, is turned away.\n if (this.contendable()) { this.contend(channel, binding, { resolve: () => {}, reject: () => {} }); return; }\n if (this.candidate) { channel.close(); return; }\n // Two dials crossed and both connected: the lower key's carries the chat. Here, the lower key's side, holding the\n // one it just dialled, refuses the contact's; the contact takes this one over as a replacement.\n const held = this.channel;\n if (held && this.activeBinding && !this.dialedIn.has(held) && Date.now() - this.channelSince < CROSSED_FRESH_MS\n && this.myPubKeyZ32 < this.options.params.peerPubKeyZ32) {\n // Still authenticating: the dials crossed, or the held one fails its authentication by itself.\n if (this.paired?.state.status !== \"ready\") { traceLink(this.myPubKeyZ32, \"dial-crossed\", { transport: binding.transport, held: true }); channel.close(); return; }\n this.probeCrossed(held, channel, binding); return;\n }\n this.replaceWith(channel, binding);\n }\n /**\n * The contact's WebRTC opened while this side holds a native session, with no switch under way. A contact offers only\n * with no session of its own: its app is back after a crash, with no way to the held transport (its Iroh relay out of\n * reach, its listener not up yet), and the held session is dead without this side having heard. Closed at once, the\n * contact counted a failed dial and waited its backoff: live again 52.8 s after its start (two CLIs over a chosen Iroh\n * whose relay stopped, bug hunt 2026-10-17). The held session is pinged as for a crossing (`probeCrossed`): heard from,\n * the WebRTC closes, as before; silent, it takes over. Before the pin, or while the held one authenticates, it closes.\n */\n private rtcOverHeld(channel: FrameChannel): void {\n const held = this.channel;\n if (!held || this.candidate || !this.options.pairing?.credentials.peerKey || !this.options.params.profile\n || this.paired?.state.status !== \"ready\") { channel.close(); return; }\n this.probeCrossed(held, channel);\n }\n private replaceWith(channel: FrameChannel, binding?: NativeBinding): void {\n traceLink(this.myPubKeyZ32, \"replacing\", { transport: binding?.transport ?? \"webrtc/1\", held: this.paired?.state.transport });\n this.attach(channel, binding, { resolve: () => {}, reject: () => {} });\n }\n\n /**\n * The contact dialled in while this side's own fresh dial holds the chat (`CROSSED_FRESH_MS`): the dials crossed, or\n * the contact's app ended since that dial and is back. The held session is pinged; heard from within\n * `CROSSED_PROBE_MS`, the contact holds this side's dial too and its own closes. Not heard from, the contact's dial\n * takes over.\n */\n private crossedProbe: { channel: FrameChannel; timer: ReturnType<typeof setTimeout> } | null = null;\n /** Frames heard on the open session, counted from its start: whether the contact answered `probeCrossed`. */\n private framesHeard = 0;\n private probeCrossed(held: FrameChannel, channel: FrameChannel, binding?: NativeBinding): void {\n this.dropCrossedProbe();\n traceLink(this.myPubKeyZ32, \"dial-crossed\", { transport: binding?.transport ?? \"webrtc/1\", held: true, probe: true });\n const heard = this.framesHeard;\n try { this.sendPing(held, false); } catch { /* closing: the dial in is taken below */ }\n // What the contact sends meanwhile (its offer, sent as its side opened) waits for the session taken below: a WebRTC\n // data channel drops what comes with no reader, and that session would fail on the proof of an offer it never had.\n const early: (string | Uint8Array)[] = [];\n channel.onMessage = data => { if (early.length < PROBE_EARLY_FRAMES) early.push(data); };\n const take = (attach: () => void) => {\n channel.onMessage = null; attach();\n const read = channel.onMessage as FrameChannel[\"onMessage\"];\n for (const data of early) read?.(data);\n };\n const timer = setTimeout(() => {\n if (this.crossedProbe?.channel !== channel) return;\n this.crossedProbe = null;\n if (this.stopped || this.leaving || this.candidate) { channel.close(); return; }\n if (!this.channel) { take(() => this.attach(channel, binding)); return; }\n if (this.channel === held && this.framesHeard !== heard) { channel.close(); return; }\n traceLink(this.myPubKeyZ32, \"crossed-held-silent\", { transport: binding?.transport ?? \"webrtc/1\" });\n take(() => this.replaceWith(channel, binding));\n }, CROSSED_PROBE_MS);\n channel.onClose = () => { if (this.crossedProbe?.channel === channel) { clearTimeout(timer); this.crossedProbe = null; } };\n this.crossedProbe = { channel, timer };\n }\n private dropCrossedProbe(): void {\n const probe = this.crossedProbe;\n if (!probe) return;\n this.crossedProbe = null; clearTimeout(probe.timer); probe.channel.close();\n }\n\n /**\n * Connections that came in on this side's native endpoints. Their address was in the capability record, which before\n * the pin anyone holding a copy of the invite could read: a key other than the pinned one on such a connection proves\n * no more than on the DHT, so it closes that connection and nothing else.\n */\n private readonly dialedIn = new WeakSet<FrameChannel>();\n /** Connections whose session started with no key pinned nor named by the invite. */\n private readonly openedUnpinned = new WeakSet<FrameChannel>();\n /** The WebRTC offer under way was made or answered with no key pinned nor named by the invite (its channel opens later). */\n private rtcStartedUnpinned = false;\n\n /**\n * `migration`: the channel is a candidate that takes over from the session open now once it authenticated. With a\n * `plan`, a live switch both sides agreed; without one, a replacement (`attachReplacement`): the contact dialled\n * afresh, having no session with this side any more.\n */\n private attach(channel: FrameChannel, binding?: NativeBinding, migration?: { plan?: SwitchPlan; resolve(): void; reject(error: Error): void }): void {\n if (this.options.params.profile) {\n const fingerprints = this.dataLink.fingerprints;\n if ((!binding && !fingerprints) || !this.options.pairing) { channel.close(); migration?.reject(new Error(\"Connection binding unavailable\")); return; }\n channel.onClose = () => {\n if (this.candidate?.channel === channel) { this.candidate.session.stop(); this.candidate = null; migration?.reject(new Error(\"Candidate connection closed\")); }\n const contender = this.contenders.findIndex(c => c.channel === channel);\n if (contender >= 0) { this.contenders.splice(contender, 1)[0].session.stop(); migration?.reject(new Error(\"Candidate connection closed\")); }\n if (this.channel === channel) {\n const wasLive = this.paired?.state.status === \"ready\";\n this.rejectWaiters(new Error(\"The peer closed this connection. Check that both transport preferences allow a common transport, then reconnect.\"));\n this.detach();\n if (wasLive) this.peerLost(\"closed\");\n // A native connection that never authenticated (the contact refused it, or its path died): the side whose turn\n // it is dials again now, not when a later look at the contact's packet happens to ask.\n else if (binding) this.maybeAutoConnect(this.presence);\n }\n };\n const unproven = this.unproven(channel);\n if (!this.options.pairing.credentials.peerKey && !this.options.pairing.credentials.expectedPeerKey) this.openedUnpinned.add(channel);\n if (!migration) {\n this.activeBinding = binding; this.channel = channel; this.channelSince = Date.now();\n // One dialled in is nobody until it authenticated: the DHT keeps its pace meanwhile (set once it is ready).\n if (!unproven) this.session.setDataLinkOpen(true);\n }\n const paired = new PairedSession(channel, {\n ...this.options.pairing,\n trustOnFirstUse: this.options.pairing.trustOnFirstUse ?? true,\n rendezvousKeys: [this.myPubKeyZ32, this.options.params.peerPubKeyZ32],\n fingerprints: fingerprints ?? undefined,\n binding, transports: migration?.plan?.choices ?? this.transportOffer(), allowFallback: migration?.plan?.local.fallback ?? this.fallback,\n transportSwitchSupport: true,\n // Dialled in, or dialled out on a native transport (its path was up when it opened): bounded either way on a pinned chat.\n ...(unproven || (binding && this.options.pairing.credentials.peerKey) ? { authTimeoutMs: UNPROVEN_AUTH_MS } : {}),\n holdSupport: !!this.options.holdSupport,\n proofSupport: !!this.options.events?.onPeerProof,\n identitySupport: !!this.options.events?.onIdentityProof,\n filesSupport: !!this.options.events?.onFileIncoming,\n arkPaymentsSupport: this.options.arkPaymentsSupport && this.paymentEnabled(\"arkade\"),\n usdtPaymentsSupport: this.options.usdtPaymentsSupport && this.paymentEnabled(\"usdt\"),\n barkPaymentsSupport: this.options.barkPaymentsSupport && this.paymentEnabled(\"bark\"),\n cashuPaymentsSupport: this.paymentEnabled(\"cashu\"),\n lightningPaymentsSupport: this.paymentEnabled(\"lightning\"),\n paymentsSupport: PAYMENT_METHODS.some(m => this.paymentEnabled(m)) && !!this.options.events?.onPayment && !!this.options.events?.onPaymentRequest && !!this.options.events?.onPaymentResult,\n // A connection dialled in on a pinned chat says nothing until it authenticated: one refused leaves no trace in the state.\n onState: () => { if (this.channel === channel && (!this.unproven(channel) && !this.pinnedSince(channel, paired) || paired.state.status === \"ready\")) this.emitPairingState(); },\n onFailure: () => {\n // A session a move replaced, still reading while its channel retires: it says nothing of the one now.\n const retiring = this.channel !== channel ? this.retiring.get(channel) : undefined;\n if (retiring) { clearTimeout(retiring.timer); retiring.close(); return; }\n // Another participation key than the one pinned: a device's one-time enrollment link says so (WISP 06).\n if (paired.state.keyMismatch) this.options.events?.onPeerKeyRefused?.();\n // Dialled in and unproven, started before a pin made by another path, a connection that carried nothing in\n // time, or one that brought more than this side could handle at once (`overloaded`): none says anything about\n // the contact. The chat dials again, and its DHT layer goes on meanwhile.\n if (this.unproven(channel) || this.pinnedSince(channel, paired) || paired.authTimedOut || paired.overloaded) {\n if (paired.state.keyMismatch) this.dht?.foreignKeySeen(\"stream\");\n if (this.unproven(channel)) traceLink(this.myPubKeyZ32, \"dialed-in-refused\", { keyMismatch: !!paired.state.keyMismatch });\n else if (this.pinnedSince(channel, paired)) traceLink(this.myPubKeyZ32, \"pinned-since-refused\", { transport: binding?.transport ?? \"webrtc/1\" });\n else if (paired.overloaded) traceLink(this.myPubKeyZ32, \"receive-overload\", { transport: binding?.transport ?? \"webrtc/1\" });\n else traceLink(this.myPubKeyZ32, \"auth-timeout\", { transport: binding?.transport ?? \"webrtc/1\" });\n migration?.reject(new Error(paired.state.error ?? \"Candidate authentication failed\"));\n channel.close(); if (this.channel === channel) this.detach();\n if (!this.channel && binding) this.maybeAutoConnect(this.presence);\n return;\n }\n this.securityRejected = true;\n // Another key on the stream than the one pinned: the chat stops on both layers, the DHT's too.\n if (paired.state.keyMismatch) { this.keyStopped = true; traceLink(this.myPubKeyZ32, \"key-stop\", { path: \"stream\" }); }\n this.tracker?.failed(paired.state.keyMismatch ? \"key-mismatch\" : \"rejected\", !paired.state.keyMismatch, paired.state.error);\n migration?.reject(new Error(paired.state.error ?? \"Candidate authentication failed\"));\n channel.close(); if (this.channel === channel) this.detach();\n },\n onReady: () => {\n let carried: PairedFiles | null = null;\n let switched: { from?: PairedTransport; to: PairedTransport } | null = null, replaced = false;\n if (migration) {\n if (this.candidate?.channel !== channel && !this.promoteContender(channel)) { paired.stop(); channel.close(); return; }\n const oldChannel = this.channel, oldPaired = this.paired, oldBinding = this.activeBinding;\n const from = oldPaired?.state.transport;\n this.candidate = null;\n this.dropContenders(\"Another connection authenticated first\");\n // Transfers in flight carry on over the new channel; they end only if it cannot take files. A replacement is a\n // new session on the contact's side: nothing of the old one carries over.\n const files = this.pairedFiles; this.pairedFiles = null;\n if (files && migration.plan && paired.supports(\"files/2\")) { files.rebind(channel); carried = files; } else files?.closeAll();\n this.pairedHttp?.close(); this.pairedHttp = null;\n this.channel = channel; this.paired = paired; this.activeBinding = binding; this.channelSince = Date.now();\n // Off WebRTC: its peer connection goes with the channel, unless WebRTC carries the chat again by then. Only\n // that connection: the contact's offer back to WebRTC can be under way on the link by then (its own old\n // session retired first), and closing it left the move to its 8 s and the 20 s retry (bh-zero43).\n const oldRtc = oldBinding ? null : this.dataLink.connection;\n // The old session reads on while its channel retires: a text or a receipt the contact sent on it before its\n // own side moved still arrives (`onApplication`). Stopped here, it dropped those of the move's moment.\n if (oldChannel) this.retire(oldChannel, () => { oldPaired?.stop(); if (oldRtc && this.activeBinding && this.dataLink.connection === oldRtc) this.dataLink.close(); }, !oldBinding);\n else oldPaired?.stop();\n // A move that lands on a native transport while its own WebRTC try still connects (the contact's app ended\n // and is back over the chat's native transport, which the move allows): that try goes to the app that\n // ended, and held the data link until it failed (30 s on the CLI's WebRTC), so the next move to WebRTC\n // offered nothing and waited 40 s more (CLI twoPeers on CI).\n if (migration.plan && binding && oldBinding && WEBRTC_ATTEMPT.has(this.dataLink.state)) this.dataLink.close();\n this.session.setDataLinkOpen(true);\n if (migration.plan) switched = { from, to: paired.state.transport! };\n else { replaced = true; traceLink(this.myPubKeyZ32, \"replaced\", { from, to: paired.state.transport }); }\n }\n if (this.channel !== channel) return;\n this.session.setDataLinkOpen(true);\n this.securityRejected = false;\n const events = this.options.events ?? {};\n if (carried) this.pairedFiles = carried;\n else if (paired.supports(\"files/2\")) this.pairedFiles = new PairedFiles(channel, {\n onIncoming: file => events.onFileIncoming?.(file) ?? null,\n onStored: events.onFileStored,\n replaced: () => this.supportsLargeFiles,\n room: events.onFileRoom,\n onProgress: events.onFileProgress,\n onComplete: events.onFileComplete,\n onFailed: events.onFileFailed,\n });\n this.peerPolicySeen = null;\n if (paired.peerTransportSwitchSupport) this.switcher.begin(paired.proofSession, paired.state.transport!, !!migration?.plan);\n else this.advertiseTransports();\n this.peerPaymentMethods = null; this.peerNetworks = null;\n this.peerHoldOverride = null;\n this.sessionCapabilities.reset();\n this.peerGroupsWereOn = false;\n this.leaveHangUp();\n this.typingSender.reset(); this.typingReceiver.clear();\n this.endStatusSession();\n this.appsSuspended();\n this.pairedHttp?.close();\n this.pairedHttp = new PairedHttp(channel, this.options.getHostedHttpService, this.options.localFetch, this.bodiesOn(channel));\n this.emitPairingState();\n this.sendPairedNick();\n this.sendPairedAvatar();\n this.sendPaymentMethods();\n this.sendSessionCapabilities();\n this.sendGroupsSupport();\n this.sendHoldState();\n void this.options.events?.onHold?.({ peerAllows: paired.peerHoldSupport });\n migration?.resolve();\n this.rtcCandidateWaiter?.resolve(); this.rtcCandidateWaiter = null;\n // The wait between attempts is for attempts that failed: a link that worked and then dropped\n // (the contact reloaded, or came back) is dialled again as soon as the contact is seen.\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n this.resumeKnockMissed = false;\n traceLink(this.myPubKeyZ32, \"paired-ready\");\n this.attempt = null;\n if (this.lastAttempt) { this.lastAttempt = undefined; this.options.events?.onLiveAttempt?.(undefined); }\n this.tracker?.live(paired.state.transport);\n // A native session carries the chat: a WebRTC attempt still under way (an offer out, an answer held back by the\n // relays' budget) ends, and with it its fast reads of the relays. Its record's signal is cleared once.\n if (binding && !migration?.plan && (this.dataLink.state === \"offering\" || this.dataLink.state === \"answering\" || this.dataLink.state === \"connecting\")) {\n this.afterRtc = undefined; this.dataLink.close();\n }\n this.startLiveness(channel, paired.peerAnswersPings);\n for (const waiter of this.openWaiters.splice(0)) waiter.resolve();\n this.options.events?.onPresence?.(this.presence);\n if (switched) this.options.events?.onTransportSwitched?.(switched.from, switched.to);\n if (switched) this.emitFilesSession(true);\n // A new session in place of a dead one, live all along as the owner saw it: what the old one may have lost\n // (the outbox's unconfirmed text, a file offer) goes again now, as after any reconnect.\n if (replaced) { this.options.events?.onDataLinkState?.(\"open\"); this.emitFilesSession(true); }\n },\n onApplication: async data => {\n // A session a move replaced, while its channel retires: only what `RETIRING_FRAMES` names is read on it.\n const retired = this.channel !== channel;\n if (retired && !this.retiring.has(channel)) return;\n // Anything from the peer shows the session is alive.\n if (!retired) { this.unansweredPings = 0; this.heardFromPeer(); this.framesHeard++; }\n else if (typeof data !== \"string\") return;\n if (typeof data !== \"string\") {\n // app-ranges/1 beside files/4: a served file's bytes, for a request of this side's.\n if (data[0] === APP_RANGE_DATA_KIND) {\n const range = this.supportsAppRanges && this.supportsBinaryFiles ? decodeAppRangeData(data) : null;\n if (range) this.appRanges.receiveData(range.a, range.r, range.o, range.data);\n return;\n }\n // files/4: a file's bytes. Any other binary message, or one nobody agreed to, is dropped (WISP 100).\n const chunk = this.supportsBinaryFiles ? decodeFileData(data) : null;\n if (!chunk) return;\n this.activityAt = Date.now();\n await this.options.events?.onFilesFrame?.({ t: \"pf-data\", ...chunk });\n return;\n }\n if (data.length > 60 * 1024) return;\n let frame: Record<string, unknown>;\n try { frame = JSON.parse(data); } catch { return; }\n if (retired && !RETIRING_FRAMES.has(String(frame?.t))) return;\n // What the two people do (texts, receipts, typing, files, calls, payments...), not the session's upkeep.\n if (frame && typeof frame === \"object\" && !QUIET_FRAMES.has(String(frame.t))) this.activityAt = Date.now();\n if (frame?.t === \"paired-ping\") { try { channel.send(JSON.stringify({ t: \"paired-pong\" })); } catch { /* closing */ } return; }\n if (frame?.t === \"paired-pong\") {\n this.peerAnswersPings = true;\n const answered = ++this.pongsHeard;\n if (this.pingSentAt && answered >= this.rttPing) { this.rtt = Date.now() - this.pingSentAt; this.pingSentAt = 0; this.options.events?.onRtt?.(this.rtt); }\n for (const waiter of this.handledWaiters.filter(w => w.ping <= answered)) waiter.done(true);\n while (this.appInFlight.length > 0 && this.appInFlight[0]!.ping <= answered) this.appInFlight.shift();\n if (this.appInFlight.length === 0 && this.appUnmarked > 0 && this.channel === channel) this.markAppData(channel);\n return;\n }\n if (frame?.t === \"paired-bye\") {\n if (paired.state.status === \"ready\") { if (frame.yield === true) this.peerYielded(channel); else this.peerDeparted(channel); }\n return;\n }\n if (!frame || typeof frame !== \"object\") return;\n if (paired.peerTransportSwitchSupport && this.switcher.handle(frame)) return;\n if (frame.t === \"paired-rtc\") {\n // Counted before its signature is checked, as call signals are: each offer taken builds a peer connection.\n if (!this.rtcSignalsReceived.take()) return;\n if (this.switcher.pending?.choices.includes(\"webrtc/1\") && typeof frame.signal === \"string\") {\n const credentials = this.options.pairing!.credentials;\n const signal = verifyPairedSignal(frame.signal, this.options.params.peerPubKeyZ32,\n this.myPubKeyZ32, credentials.peerKey, true);\n if (signal) void this.dataLink.handleSignal(signal, { since: Date.now(), after: null, live: true });\n }\n return;\n }\n if (!this.isDataLinkOpen) return;\n if (typeof frame?.t === \"string\" && FILE_FRAMES.has(frame.t)) {\n if (this.supportsLargeFiles) await this.options.events?.onFilesFrame?.(frame);\n return;\n }\n if (typeof frame?.t === \"string\" && frame.t.startsWith(\"pf-\")) {\n if (this.supportsFiles) await this.pairedFiles?.handle(frame);\n return;\n }\n if ([\"pay\", \"pay-req\", \"pay-res\", \"pay-ask\"].includes(String(frame?.t))) {\n if (this.supportsPayments) {\n const payment = decodeControl(data);\n if (payment?.t === \"pay\") await this.options.events?.onPayment?.({ id: payment.id, timestamp: payment.ts, requestId: payment.rid, amount: { value: payment.v, asset: payment.u }, memo: payment.memo, endpoint: payment.e });\n else if (payment?.t === \"pay-req\") await this.options.events?.onPaymentRequest?.({ id: payment.id, timestamp: payment.ts, amount: { value: payment.v, asset: payment.u }, memo: payment.memo, endpoints: payment.e, ask: payment.a, network: payment.n });\n else if (payment?.t === \"pay-ask\") await this.options.events?.onPaymentAsk?.({ id: payment.id, timestamp: payment.ts, amount: { value: payment.v, asset: payment.u }, method: payment.m, memo: payment.memo, network: payment.n });\n else if (payment?.t === \"pay-res\") await this.options.events?.onPaymentResult?.({ id: payment.id, ok: payment.ok, credited: payment.v, error: payment.err, ...(payment.c ? { closed: true } : {}) });\n }\n return;\n }\n if (typeof frame?.t === \"string\" && frame.t.startsWith(\"idp-\") && this.identitySupport) {\n if (this.identityReceived.take()) await this.options.events?.onIdentityProof?.(frame);\n return;\n }\n if (typeof frame?.t === \"string\" && frame.t.startsWith(\"proof-\") && this.peerProofSupport) {\n await this.options.events?.onPeerProof?.(frame); return;\n }\n if (frame?.t === \"paired-avatar\" || frame?.t === \"paired-nick\") {\n this.peerSaysOfItself(channel, frame.t, frame);\n return;\n }\n if (frame?.t === SESSION_CAPABILITIES_FRAME) {\n const devices = this.options.deviceCapabilities;\n const changed = devices ? this.sessionCapabilities.receive(frame, [...KNOWN_SESSION_CAPABILITIES, ...devices]) : this.sessionCapabilities.receive(frame);\n if (changed) this.sessionCapabilitiesChanged(changed);\n return;\n }\n if (frame?.t === WAKE_FRAME) {\n // Only once both said wake/1; a handful per minute at most (it changes when the contact rotates it).\n if (!this.supportsWake || !this.wakeReceived.take()) return;\n const target = parseWakeFrame(frame);\n if (target !== undefined) this.options.events?.onPeerWake?.(target);\n return;\n }\n if (frame?.t === CONTACT_ASKER_FRAME) {\n const keys = this.participationKeys;\n if (keys && this.askerReceived.take()) this.options.events?.onContactAsker?.(frame, keys);\n return;\n }\n if (frame?.t === STATUS_FRAME) {\n // Only on the authenticated session with the pinned contact, and only once both said status/1.\n if (this.supportsStatus) this.statusReceiver.receive(frame);\n return;\n }\n if (frame?.t === TYPING_FRAME) {\n // Only on the authenticated session with the pinned contact, and only once both said typing/1.\n if (this.supportsTyping) this.typingReceiver.receive(frame);\n return;\n }\n if (frame?.t === APP_FRAME) {\n // Only once both said apps/1; counted per app before it is read (WISP 1200 § In a chat).\n if (!this.supportsApps) return;\n const event = this.apps.receive(frame);\n // The contact's app closed: what it served here ends, and so does what it was reading.\n if (event && \"o\" in event && event.o === \"close\") this.appRanges.closeApp(event.app);\n if (event) this.options.events?.onAppFrame?.(event);\n return;\n }\n if (APP_RANGE_FRAMES.has(String(frame?.t))) {\n // Only once both said app-ranges/1; every request is checked against the serves not ended (WISP 1200).\n if (this.supportsAppRanges) this.receiveAppRange(frame);\n return;\n }\n if (frame?.t === REACTION_FRAME) {\n // Counted before it is read: a flood of malformed frames costs as much as one of reactions.\n if (!this.supportsReactions || !this.reactionsReceived.take()) return;\n const reaction = parseReactionFrame(frame);\n if (!reaction) return;\n const reacted = await this.options.events?.onReaction?.(reaction), live = this.answerOn(channel);\n if (reacted && live) try { live.send(reactedFrame(reaction.n)); } catch { /* it comes again */ }\n return;\n }\n if (frame?.t === REACTED_FRAME) {\n const n = parseReactedFrame(frame);\n if (n !== null) await this.options.events?.onReactionReceipt?.(n);\n return;\n }\n if (frame?.t === PIN_FRAME) {\n // Counted before it is read, as reactions are.\n if (!this.supportsPins || !this.pinsReceived.take()) return;\n const pin = parsePinFrame(frame);\n if (!pin) return;\n const pinned = await this.options.events?.onPin?.(pin), live = this.answerOn(channel);\n if (pinned && live) try { live.send(pinnedFrame(pin.n)); } catch { /* it comes again */ }\n return;\n }\n if (frame?.t === PINNED_FRAME) {\n const n = parsePinnedFrame(frame);\n if (n !== null) await this.options.events?.onPinReceipt?.(n);\n return;\n }\n if (frame?.t === EDIT_FRAME) {\n // Counted before it is read: a flood of malformed frames costs as much as one of edits.\n if (!this.supportsEdits || !this.editsReceived.take()) return;\n const edit = parseEditFrame(frame);\n if (!edit) return;\n const edited = await this.options.events?.onMessageEdit?.(edit), live = this.answerOn(channel);\n if (edited && live) live.send(editedFrame(edit.id, edit.e));\n return;\n }\n if (frame?.t === EDITED_FRAME) {\n const receipt = parseEditedFrame(frame);\n if (!receipt) return;\n await this.options.events?.onEditReceipt?.(receipt.id, receipt.e);\n // The same edit waiting on the DHT floor is not published again.\n await this.dht?.acknowledge(dhtEditId(receipt.id, receipt.e));\n return;\n }\n if (frame?.t === PAIRED_CALL_FRAME) {\n // Counted before it is read, as edits are: a contact's app that loops its signals runs the call only so often.\n if (!this.supportsCalls || !this.callsReceived.take()) return;\n const signal = parsePairedCallFrame(frame);\n // One already heard on an earlier session is not handed on again (`PairedCalls.heard`).\n if (signal && this.pairedCalls.heard(signal)) this.options.events?.onCallSignal?.(signal);\n return;\n }\n if (frame?.t === \"ph\") { if (this.supportsServices) this.pairedHttp?.handle(frame); return; }\n if (frame?.t === \"paired-services\") {\n if (!this.supportsServices) return;\n const services = servicesFromWire(frame.s);\n if (services) { this.peerServicesOverride = services; this.options.events?.onPresence?.(this.presence); }\n return;\n }\n if (frame?.t === \"paired-payments\") {\n // A method this app does not know yet (a newer contact) is left out, not a reason to drop the list.\n if (!Array.isArray(frame.m) || frame.m.length > 16 || !frame.m.every(m => typeof m === \"string\")) return;\n const methods = new Set((frame.m as string[]).filter((m): m is PaymentMethodName => PAYMENT_METHODS.includes(m as PaymentMethodName)));\n const networks = frame.n === undefined ? null : parsePaymentNetworks(frame.n);\n this.peerSays(channel, \"paired-payments\", () => {\n this.peerPaymentMethods = methods;\n this.peerNetworks = frame.n === undefined ? null : networks ?? this.peerNetworks;\n this.emitPairingState();\n });\n return;\n }\n if (frame?.t === \"paired-groups\") {\n if (!Array.isArray(frame.v) || frame.v.length > 8 || !frame.v.every(v => Number.isSafeInteger(v) && v > 0)) return;\n const before = this.groupsSupport;\n if (!before && this.peerGroupsWereOn && frame.v.includes(1)) return;\n this.peerGroupVersions = frame.v as number[];\n if (this.groupsSupport) this.peerGroupsWereOn = true;\n if (this.groupsSupport !== before) this.options.events?.onGroupsSupport?.(this.groupsSupport);\n return;\n }\n if (typeof frame?.t === \"string\" && frame.t.startsWith(\"group-\")) {\n if (this.groupsSupport) await this.options.events?.onGroupFrame?.(frame);\n return;\n }\n // A device link's own frames (WISP 06): handed on only under a capability both ends announced.\n if (this.options.deviceCapabilities) {\n const capability = deviceFrameCapability(frame?.t);\n if (capability) {\n if (this.supportsDevice(capability)) await this.options.events?.onDeviceFrame?.(frame as DeviceFrame);\n return;\n }\n }\n if (frame?.t === \"paired-hold\") {\n // The contact's latest word on held items; an older app never sends it and keeps its handshake offer.\n if (typeof frame.on !== \"boolean\" || (frame.top !== undefined && !(Number.isSafeInteger(frame.top) && (frame.top as number) >= 0))) return;\n const on = frame.on, top = frame.top as number | undefined;\n this.peerSays(channel, \"paired-hold\", () => {\n this.peerHoldOverride = on;\n // Not awaited: the owner may be picking up held items (from the contact's storage, seconds or more), and\n // every frame after this one would wait for it, the edits, texts and pings that keep this session alive too.\n void Promise.resolve(this.options.events?.onHold?.({ peerAllows: on, peerTop: top })).catch(() => {});\n this.emitPairingState();\n });\n return;\n }\n if (frame?.t === \"paired-adapters\") {\n if (!frame.descriptors || typeof frame.descriptors !== \"object\" || JSON.stringify(frame.descriptors).length > 4096) return;\n const descriptors = checkedDescriptors(frame.descriptors);\n await this.peerSays(channel, \"paired-adapters\", async () => {\n const transports = [...(this.paired?.peerTransports ?? [])] as PairedTransport[];\n const fallback = this.paired?.peerAllowsFallback ?? false;\n await this.options.events?.onTransportDiscovery?.(descriptors, transports, fallback);\n this.peerDescriptors = descriptors; this.peerTransports = transports; this.peerFallback = fallback;\n });\n return;\n }\n if (!frame || typeof frame.id !== \"string\" || !/^[A-Za-z0-9_-]{22}$/.test(frame.id)) return;\n // Counted before it is read; one past the window is not confirmed, so the contact's app sends it again.\n if (frame.t === \"paired-message\" && !this.takeMessage()) return;\n if (frame.t === \"paired-message\" && typeof frame.m === \"string\" &&\n utf8Encode(frame.m).length <= LIMITS.maxChatMessageBytes &&\n typeof frame.ts === \"number\" && Number.isSafeInteger(frame.ts) && frame.ts > 0) {\n // A bad preview is dropped, never the message (older apps ignore `pv` altogether).\n const preview = frame.pv === undefined ? undefined : parseLinkPreview(frame.pv, frame.m);\n // What the contact was typing arrived: it is not typing any more.\n this.typingReceiver.clear();\n // The same for a reply: one that does not hold is left out (older apps ignore `r`).\n const reply = frame.r === undefined ? undefined : readReply(frame.r, pairedReplyAuthor);\n // A hop count that is not one is left out: the message arrives as written here (older apps ignore `fw`).\n const forwarded = readForwarded(frame.fw);\n // A card that does not hold is left out: the message shows its text, as an older app shows it.\n const card = frame.sc === undefined ? undefined : readStatusCard(frame.sc);\n await this.options.events?.onMessage?.({ id: frame.id, text: frame.m, timestamp: frame.ts, via: \"datalink\", ...(preview && { preview }), ...(reply && { reply }), ...(forwarded && { forwarded }), ...(card && { card }) });\n const live = this.answerOn(channel);\n if (live) live.send(JSON.stringify({ t: \"paired-received\", id: frame.id }));\n } else if (frame.t === \"paired-received\") {\n this.messagesSent.answered(frame.id);\n const timestamp = this.pairedPending.get(frame.id);\n if (timestamp !== undefined) {\n await this.options.events?.onMessageReceipt?.(frame.id);\n await this.dht?.acknowledge(frame.id);\n this.pairedPending.delete(frame.id);\n }\n }\n },\n });\n if (migration) {\n const entry: LinkCandidate = { channel, session: paired, binding, ...(migration.plan && { plan: migration.plan }), reject: migration.reject };\n if (this.candidate) this.contenders.push(entry); else this.candidate = entry;\n }\n else this.paired = paired;\n paired.start();\n return;\n }\n this.channel = channel;\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n this.httpClient = new HttpClient(channel);\n this.httpHost = new HttpHost(channel, this.options.getHostedHttpService, this.options.localFetch);\n const events = this.options.events ?? {};\n this.files = new FileTransfers(channel, {\n onIncoming: (file) => events.onFileIncoming?.(file) ?? null,\n onProgress: (id, transferred, direction) => events.onFileProgress?.(id, transferred, direction),\n onComplete: (id, direction) => events.onFileComplete?.(id, direction),\n onFailed: (id, reason, direction) => events.onFileFailed?.(id, reason, direction),\n });\n this.session.setDataLinkOpen(true);\n\n channel.onMessage = (data) => this.handleFrame(data);\n channel.send(\n encodeControl({\n t: \"hello\",\n v: PROTOCOL_VERSION,\n svc: servicesToWire(this.options.getServices() ?? []),\n nick: this.options.nick,\n }),\n );\n // Whatever was still waiting in Pkarr for the peer's next poll goes now.\n for (const message of this.session.takeUnacknowledged()) {\n channel.send(encodeControl({ t: \"m\", ts: message.t, m: message.m }));\n }\n this.options.events?.onPresence?.(this.presence);\n for (const waiter of this.openWaiters.splice(0)) waiter.resolve();\n }\n\n /**\n * Pings the paired peer; a session that stopped answering is closed, so it can be dialled again. A peer\n * that said in its offer that it answers pings counts from the open; any other counts once it answered\n * one (an app that never does is never cut off for it).\n */\n private startLiveness(channel: FrameChannel, peerAnswersPings = false): void {\n this.stopLiveness();\n this.peerAnswersPings = peerAnswersPings;\n // One ping at the open, not counted as missed: the round trip is known at once, not 15 s later.\n const ping = () => {\n this.sendPing(channel, true);\n // An app that never answers pings (an older one) would cost a read of the relays at each.\n if (!this.peerAnswersPings || this.pongWait) return;\n this.pongWait = setTimeout(() => {\n this.pongWait = null;\n if (this.channel !== channel || this.stopped) return;\n traceLink(this.myPubKeyZ32, \"pong-late\", { unanswered: this.unansweredPings });\n this.pongLate = true;\n this.session.pollNow();\n }, PONG_WAIT_MS);\n };\n if (peerAnswersPings) try { ping(); } catch { /* closing: the timer below finds out */ }\n this.livenessTimer = setInterval(() => {\n if (this.channel !== channel) { this.stopLiveness(); return; }\n if (this.peerAnswersPings && this.unansweredPings >= LIVENESS_MISSED_PINGS) { this.dropDeadSession(channel); return; }\n this.unansweredPings++;\n try { ping(); } catch { this.dropDeadSession(channel); }\n }, LIVENESS_PING_MS);\n }\n private stopLiveness(): void {\n if (this.livenessTimer) clearInterval(this.livenessTimer);\n this.livenessTimer = null;\n this.heardFromPeer();\n this.unansweredPings = 0;\n this.peerAnswersPings = false;\n this.pingSentAt = 0;\n this.rtt = undefined;\n this.pingsSent = this.pongsHeard = this.rttPing = 0;\n this.appInFlight = [];\n this.appUnmarked = 0;\n for (const waiter of [...this.handledWaiters]) waiter.done(false);\n }\n /** `live`: a liveness ping, whose pong measures the round trip. */\n private sendPing(channel: FrameChannel, live: boolean): void {\n if (live) this.pingSentAt = Date.now();\n channel.send(JSON.stringify({ t: \"paired-ping\" }));\n this.pingsSent++;\n if (live) this.rttPing = this.pingsSent;\n }\n /**\n * Resolves once the contact's app handled every frame sent on this session so far: it answers a ping in the order\n * frames come (every app since 1.0), so the pong to one sent now says so, however slowly it handles them. A group\n * member's catch-up answer goes a slice at a time on it (`GroupSessionHooks.handled`). `false` when it cannot tell:\n * no session, or a contact that answers no ping. `\"late\"` with no answer within `HANDLED_WAIT_MS`: a contact that\n * answers pings is still handling what came before (a phone with a long history), not one that cannot say.\n */\n handled(): Promise<boolean | \"late\"> {\n const channel = this.channel;\n if (!channel || !this.peerAnswersPings || this.paired?.state.status !== \"ready\") return Promise.resolve(false);\n try { this.sendPing(channel, false); } catch { return Promise.resolve(false); }\n return new Promise(resolve => {\n const waiter = {\n ping: this.pingsSent,\n done: (exact: boolean | \"late\") => {\n clearTimeout(timer);\n const at = this.handledWaiters.indexOf(waiter);\n if (at >= 0) this.handledWaiters.splice(at, 1);\n resolve(exact);\n },\n };\n const timer = setTimeout(() => waiter.done(\"late\"), HANDLED_WAIT_MS);\n this.handledWaiters.push(waiter);\n });\n }\n /** Frames the contact sent on this session that this app received and has not handled yet: 0 without a session. */\n framesWaiting(): number { return this.paired?.waiting ?? 0; }\n /** Something came back on the session: the ping's wait is over. */\n private heardFromPeer(): void {\n if (this.pongWait) clearTimeout(this.pongWait);\n this.pongWait = null;\n this.pongLate = false;\n }\n /**\n * The session runs on a native transport, its last ping went unanswered, and the contact's newer packet names another\n * endpoint for that transport: the contact's app started again (a web page reloading, as a device that takes the\n * profile does twice), and the endpoint this session runs on went with it, with nothing said. A browser's relay-only\n * Iroh closes nothing as a page goes, and QUIC notices only at its idle timeout (30 s): until then this side held a\n * session nothing answered, and the contact, whose key does not dial, waited for it to dial (a Use here said hello\n * into that session and gave up \"unreachable\", Omarchy 2026-10-05). The session is let go, and the new endpoint\n * dialled now, as when the session closes.\n */\n private restartedRedial(channel: FrameChannel, transport: NativeTransport): boolean {\n if (!this.pongLate || this.channel !== channel || this.paired?.state.status !== \"ready\") return false;\n traceLink(this.myPubKeyZ32, \"restarted-redial\", { transport });\n this.stopLiveness();\n this.disconnect();\n this.peerLost(\"restarted\");\n return true;\n }\n\n private dropDeadSession(channel: FrameChannel): void {\n this.stopLiveness();\n if (this.channel !== channel) return;\n // Everything of the dead session goes (channel, peer connection), as a hang-up would.\n this.disconnect();\n this.peerLost(\"liveness\");\n }\n\n /**\n * A live session ended without this side ending it (its channel closed, or its liveness gave up): tried again at\n * once, and the contact is watched closely for a while, since an app that went away is usually back in seconds.\n */\n private peerLost(why: string): void {\n if (this.stopped || this.leaving || this.yielding) return;\n traceLink(this.myPubKeyZ32, \"peer-lost\", { why });\n if (Date.now() < this.wokeUntil) { this.wokeUntil = 0; this.resumeAfterAbsence(); }\n const idleMs = this.options.watchPeerIdleMs ?? 0;\n this.lostUntil = Date.now() + Math.max(WATCH_PEER_MS, idleMs);\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n this.session.watchPeer(idleMs);\n this.maybeAutoConnect(this.presence);\n }\n\n /**\n * The contact said goodbye on the live session: its app is closing (and, often, starting again). The session ends now\n * rather than when liveness gives up, and the contact is watched closely: the side that dials does so once a newer\n * packet shows it back, the other looks fast for its dial or offer.\n */\n private peerDeparted(channel: FrameChannel): void {\n if (this.channel !== channel || this.stopped) return;\n traceLink(this.myPubKeyZ32, \"peer-departed\", {});\n this.departed = { packet: this.session.peerPresence.lastPacketAt, until: Date.now() + WATCH_PEER_MS };\n this.disconnect();\n this.peerLost(\"bye\");\n }\n\n /**\n * The contact gave this session's listener up to another chat (`yieldEndpoint`): its app is still there, and its\n * record now lists the transport undescribed, so there is nothing to dial and no return to watch for. The session\n * ends now, and the chat reads the contact at its own pace; the contact dials once it takes a listener back. Taken\n * as a goodbye, it was watched as an app that quit: 89 reads of its key in the 2 minutes after a yield on the\n * Desktop, against 6 at the background pace (bug hunt, 2026-10-15). The side whose key dials waits for the contact's\n * next packet: dialled at once, the listener being given up took the dial and closed it, a goodbye-less loss watched\n * the same way (bug hunt, 2026-10-16).\n */\n private peerYielded(channel: FrameChannel): void {\n if (this.channel !== channel || this.stopped) return;\n traceLink(this.myPubKeyZ32, \"peer-yielded\", {});\n this.yielded = { packet: this.session.peerPresence.lastPacketAt, until: Date.now() + WATCH_PEER_MS };\n this.disconnect();\n }\n\n /**\n * A packet of the contact's not seen before, fresh, while nothing is live, soon after a live session ended: it is back\n * (its app restarted), so the wait that the attempts since built up is over, and the next dial goes now. Once per\n * loss: a contact that is there but unreachable publishes often, and the wait between attempts is what spares the\n * relays then.\n */\n private peerPacketArrived(presence: PeerPresence): void {\n const before = this.peerPacketSeen;\n this.peerPacketSeen = presence.lastPacketAt;\n if (!before) { this.leftAsThisStarted(presence); return; }\n if (presence.lastPacketAt === before || !presence.online || this.dialing || this.channel) return;\n if (!this.options.pairing?.credentials.peerKey || Date.now() - presenceSeenAt(presence) >= EXPECT_PEER_MS) return;\n if (Date.now() > this.lostUntil) return;\n this.lostUntil = 0;\n traceLink(this.myPubKeyZ32, \"peer-back\", {});\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n this.backDial = true;\n }\n\n /**\n * The first packet of the contact's read since this link started is the one it leaves as it quits (it does not\n * advertise), put moments ago: both apps stopped and start again together (two bots a service manager restarts, a host\n * that reboots). The one that stopped first was live then and resumes; this one's session had ended on its goodbye, so\n * it does not, and read as any contact away, the resumed app's offer waited for the background pace (35 s on the\n * relays, bug hunt 2026-11-14). Watched instead as a contact that just left a live session is (`peerLost`).\n */\n private leftAsThisStarted(presence: PeerPresence): void {\n if (!presence.lastPacketAt || presence.online || this.dialing || this.channel) return;\n if (!this.options.pairing?.credentials.peerKey || !this.options.params.profile) return;\n if (Date.now() - presenceSeenAt(presence) >= EXPECT_PEER_MS) return;\n this.peerLost(\"left-as-this-started\");\n }\n\n /**\n * This app is going away (it quits, the page closes): the contact hears it on the live session now, rather than when\n * its liveness gives up about a minute later, and watches for this app to come back. Older apps drop the frame (it\n * carries no id). Synchronous, so it goes before anything else an app does on its way out. `quitting`: the app itself\n * quits (the Desktop app, a CLI daemon), not a web page that may be reloading: only then is a contact's call still\n * ringing here declined.\n */\n depart(options: { quitting?: boolean } = {}): void {\n // Going: nothing is dialled or answered from now on, whatever the contact does in the moments left.\n this.leaving = true;\n if (!this.channel || this.paired?.state.status !== \"ready\") return;\n traceLink(this.myPubKeyZ32, \"depart\", {});\n // A call still on is hung up first: the goodbye ends the contact's session, so a hang-up after it never arrives,\n // and the contact's call went on until its media gave up (half a minute).\n const hangUp = this.supportsCalls ? this.pairedCalls.hangUp({ declineRinging: options.quitting === true }) : null;\n if (hangUp) try { this.channel.send(JSON.stringify(hangUp)); } catch { /* closing already */ }\n this.leaveHangUp();\n try { this.channel.send(JSON.stringify({ t: \"paired-bye\" })); } catch { /* closing already: the contact's liveness finds out */ }\n }\n\n /**\n * A link made just now for a peer that is about to show up (a group's entry session): look fast for a while.\n * `awaited`: nothing reaches the peer until this link reads it (the edge to a member just let in): its reads go on the\n * relays' floor meanwhile (`LinkSession.expectPeer`).\n */\n expectPeer(awaited = false): void {\n this.session.expectPeer(awaited);\n }\n\n /** The peer's packet is at hand without a relay (a member of the group carried it, `CarriedTransport`): read it now. */\n look(): void {\n this.session.lookNow();\n }\n\n /**\n * Someone is here again (the chat was opened, the window came back): look now, and try at once rather\n * than after the wait between failed attempts. `network`: the device's network just came back.\n */\n wake(params: { network?: boolean } = {}): void {\n if (params.network) { this.dht?.networkBack(); this.networkBack(); }\n this.autoConnectFailures = 0;\n this.lastAutoConnectAt = 0;\n this.session.pollNow();\n if (this.channel) {\n // The session may have died while the app was away, and its transport not have noticed yet: its end, now or in\n // the next seconds (a ping it does not answer), is the absence's, and the chat resumes as after a restart.\n this.wokeUntil = Date.now() + WAKE_LOST_MS;\n this.probeAfterWake(this.channel);\n } else {\n this.resumeAfterAbsence();\n // The side that does not dial makes sure the other one sees it here, fresh — unless it just did:\n // a second packet right behind the first is one relays hold back for seconds.\n if (!this.session.publishedRecently(RECENTLY_PUBLISHED_MS)) void this.session.refreshAdvertisement();\n this.maybeAutoConnect(this.presence);\n }\n }\n\n /**\n * Back in front with no session, after one was live: the contact likely did not notice this app go (a phone puts a\n * backgrounded app to sleep without a word), and reads this chat at its slow pace (30 s on the relays in the\n * background), so an offer or a fresh packet of this side's waited about that long for it. The chat resumes as after a\n * restart (WISP 100, \"Back after a restart\"): this side dials whatever its key, on the transport it was live on, and\n * knocks on the contact's other transports as its offer goes out, which reaches the contact at once.\n */\n private resumeAfterAbsence(): void {\n const transport = this.lastLiveOn;\n // A contact that said it was going did notice: it dials or offers when it is back, as after any goodbye.\n if (!transport || this.resuming || this.departed || !this.options.pairing?.credentials.peerKey || !this.options.params.profile || this.deliveryMode === \"dht\") return;\n this.lastLiveOn = undefined;\n this.resuming = transport;\n this.resumingWoke = true;\n // A knock goes once per attempt (`knockedEarly`, by epoch), and a session that the contact closed leaves the epoch\n // as it was: the knock of an earlier return would count for this one, and none went from the second on.\n this.knockedEarly = -1;\n traceLink(this.myPubKeyZ32, \"wake-resume\", { transport });\n if (transport !== \"webrtc/1\") { this.resumeWaitUntil = Date.now() + RESUME_WAIT_MS; this.resumeKnocked = false; return; }\n // The session's close was heard just before the wake, and this side answers the contact's offer already: it knocks\n // meanwhile, as an app back after a restart does.\n if (this.dataLink.state === \"answering\" && this.answeringEpoch === this.connectionEpoch) {\n const epoch = this.connectionEpoch;\n setTimeout(() => this.maybeKnockAnswering(epoch), 0);\n return;\n }\n // Or its answer went out while it was away, and connects still: given a moment, then let go for the resume's dial.\n if (this.dataLink.state === \"connecting\" && this.answeringEpoch === this.connectionEpoch) {\n const epoch = this.connectionEpoch;\n setTimeout(() => this.dropAnswerAfterWake(epoch), WAKE_ANSWER_GRACE_MS);\n return;\n }\n // Or it dialled at that close: its offer is out already, and becomes the resume's, so its knock goes now.\n const offered = this.offered;\n if (!offered || offered.resume || offered.epoch !== this.connectionEpoch || !this.offerOut && !this.dialing) return;\n this.resuming = undefined;\n this.resumingWoke = false;\n offered.resume = true;\n offered.woke = true;\n // Still gathering: the race is scheduled once it is out, and knocks then (`scheduleRace`).\n if (!this.dialing) setTimeout(() => this.maybeKnockEarly(offered.epoch), 0);\n }\n\n /** The answer of `epoch`, made while the app was away, has not connected since the wake: the resume dials instead. */\n private dropAnswerAfterWake(epoch: number): void {\n if (epoch !== this.connectionEpoch || this.channel || this.stopped || this.resuming !== \"webrtc/1\") return;\n if (this.dataLink.state !== \"connecting\" || this.answeringEpoch !== epoch || this.offered?.epoch === epoch) return;\n traceLink(this.myPubKeyZ32, \"wake-answer-dropped\", {});\n this.dataLink.abandon();\n }\n\n /** A name or picture the contact said, once it is one (reading it costs little; saving it is what counts). */\n private peerSaysOfItself(channel: FrameChannel, kind: \"paired-nick\" | \"paired-avatar\", frame: Record<string, unknown>): void {\n let read: () => void;\n if (kind === \"paired-avatar\") {\n const avatar = sanitizeAvatar(frame.a);\n if (avatar === undefined) return;\n read = () => this.options.events?.onPeerAvatar?.(avatar);\n } else {\n // Something that is not text clears what is shown, and is not said as a removal.\n const nick = sanitizeNick(frame.n) ?? null, said = typeof frame.n === \"string\";\n read = () => {\n if (said) this.options.events?.onPeerNick?.(nick);\n if (nick !== this.peerNickOverride) {\n this.peerNickOverride = nick;\n this.options.events?.onPresence?.(this.presence);\n }\n };\n }\n this.peerSays(channel, kind, read);\n }\n /**\n * Something the contact said that this side saves, read within its window: past it the newest waits for room on this\n * session (handed on unawaited then), so the last word still counts. What `read` returns when read at once is returned.\n */\n private peerSays(channel: FrameChannel, kind: PeerSaidKind, read: () => void | Promise<void>): void | Promise<void> {\n const held = this.peerSaid[kind];\n if (!held.timer && held.window.take()) return read();\n held.read = read;\n if (held.timer) return;\n const due = () => {\n held.timer = null;\n if (this.channel !== channel || !held.read) { held.read = null; return; }\n if (!held.window.take()) { held.timer = setTimeout(due, held.window.wait()); return; }\n const next = held.read;\n held.read = null;\n void Promise.resolve(next()).catch(() => {});\n };\n held.timer = setTimeout(due, held.window.wait());\n }\n /** What the contact said of itself and was still waiting goes with the session: the next one says it again. */\n private dropPeerSaid(): void {\n for (const said of Object.values(this.peerSaid)) {\n if (said.timer) clearTimeout(said.timer);\n said.timer = null; said.read = null;\n }\n }\n\n /** A ping on the session right after a wake, with `PONG_WAIT_MS` for its answer: none, and the session is dead. */\n private probeAfterWake(channel: FrameChannel): void {\n if (!this.peerAnswersPings || this.paired?.state.status !== \"ready\") return;\n this.unansweredPings++;\n try { this.sendPing(channel, true); } catch { this.dropDeadSession(channel); return; }\n if (this.pongWait) clearTimeout(this.pongWait);\n this.pongWait = setTimeout(() => {\n this.pongWait = null;\n if (this.channel !== channel || this.stopped) return;\n traceLink(this.myPubKeyZ32, \"wake-unanswered\", {});\n this.dropDeadSession(channel);\n }, PONG_WAIT_MS);\n }\n\n private detach(): void {\n if (this.channel && this.paired?.state.status === \"ready\") this.lastLiveOn = this.activeBinding?.transport ?? \"webrtc/1\";\n this.stopLiveness();\n const wasNative = !!this.activeBinding;\n this.applicationOpen = false;\n this.dht?.setLive(false);\n // A replacement still authenticating may yet carry the chat. Without one, the session a plan meant to move is\n // gone, and so is the plan: its dial must not go on and open a session of its own, or settle the next one. Its\n // target goes too, or the chat's native listeners are held (`canReleaseEndpoint`) until the contact is back.\n // With no change under way, a WebRTC attempt beside the native session is the contact's offer answered over the\n // session it held (`rtcOverHeld`), back after a crash: it carries the chat once open. Closed with the dead session,\n // the contact's app waited out its offer's 90 s.\n if (!this.candidate) { this.cancelCandidate(!!this.switcher.pending || !!this.rtcCandidateWaiter); this.switcher.stop(); this.transitionTarget = this.transitionError = undefined; }\n this.activeBinding = undefined;\n this.paired?.stop();\n this.paired = null;\n this.pairedPending.clear();\n this.httpHost?.closeAll();\n this.httpClient?.close();\n this.files?.closeAll();\n this.pairedFiles?.closeAll();\n this.pairedFiles = null;\n this.pairedHttp?.close();\n this.pairedHttp = null;\n this.channel = this.httpHost = this.httpClient = this.files = null;\n this.leaveHangUp();\n this.peerServicesOverride = null;\n this.peerNickOverride = null;\n this.dropPeerSaid();\n this.sessionCapabilities.reset();\n this.typingSender.reset(); this.typingReceiver.clear();\n this.endStatusSession();\n this.appsSuspended();\n this.emitFilesSession();\n this.peerGroupsWereOn = false;\n if (this.peerGroupVersions) { this.peerGroupVersions = null; this.options.events?.onGroupsSupport?.(false); }\n this.session.setDataLinkOpen(false);\n if (wasNative) this.options.events?.onDataLinkState?.(\"idle\");\n this.options.events?.onPresence?.(this.presence);\n }\n\n private rejectWaiters(error: Error): void {\n for (const waiter of this.openWaiters.splice(0)) waiter.reject(error);\n }\n\n private handleFrame(data: string | Uint8Array): void {\n if (typeof data !== \"string\") {\n const chunk = decodeChunk(data);\n if (!chunk) return;\n if (chunk.kind === CHUNK_KIND.requestBody) this.httpHost?.handleChunk(chunk);\n else if (chunk.kind === CHUNK_KIND.responseBody) this.httpClient?.handleChunk(chunk);\n else this.files?.handleChunk(chunk);\n return;\n }\n\n const frame = decodeControl(data);\n if (!frame) return;\n switch (frame.t) {\n case \"hello\":\n case \"svc\": {\n const services = servicesFromWire(frame.svc);\n if (services) {\n this.peerServicesOverride = services;\n this.options.events?.onPresence?.(this.presence);\n }\n break;\n }\n case \"m\":\n if (!this.takeMessage()) break;\n this.options.events?.onMessage?.({ text: frame.m, timestamp: frame.ts, via: \"datalink\" });\n break;\n case \"call\": {\n // Counted before it is read and none handed on twice, as on a paired session (`paired-call`).\n if (!this.callsReceived.take()) break;\n const signal = heardCallSignal(frame.s, Date.now());\n if (this.pairedCalls.heard(signal)) this.options.events?.onCallSignal?.(signal);\n break;\n }\n case \"req\":\n this.httpHost?.handleRequest(frame);\n break;\n case \"res\":\n this.httpClient?.handleResponse(frame);\n break;\n case \"file\":\n this.files?.handleFile(frame);\n break;\n case \"pay-req\":\n this.options.events?.onPaymentRequest?.({\n id: frame.id,\n timestamp: frame.ts,\n amount: { value: frame.v, asset: frame.u },\n memo: frame.memo,\n endpoints: frame.e,\n });\n break;\n case \"pay\":\n this.options.events?.onPayment?.({\n id: frame.id,\n timestamp: frame.ts,\n requestId: frame.rid,\n amount: { value: frame.v, asset: frame.u },\n memo: frame.memo,\n endpoint: frame.e,\n });\n break;\n case \"pay-res\":\n this.options.events?.onPaymentResult?.({ id: frame.id, ok: frame.ok, credited: frame.v, error: frame.err, ...(frame.c ? { closed: true } : {}) });\n break;\n case \"rst\":\n if (frame.d === \"q\") this.httpHost?.handleReset(frame);\n else if (frame.d === \"s\") this.httpClient?.handleReset(frame);\n else this.files?.handleReset(frame);\n break;\n case \"ping\":\n try {\n this.channel?.send(encodeControl({ t: \"pong\", ts: frame.ts }));\n } catch {\n // channel closing\n }\n break;\n case \"pong\":\n break;\n }\n }\n}\n","import { fromBase64Url, toBase64Url, utf8Encode } from \"./bytes\";\nimport { sanitizeAvatar } from \"./avatar\";\nimport { decryptText, encryptText, sha256Hex } from \"./groupCrypto\";\nimport { GROUP_ID, MEMBER_KEY } from \"./groupCommits\";\nimport { parseHubPolicy, wireHubPolicy, type MeshHubPolicy } from \"./groupHubs\";\nimport { publicKeyFromZ32, sign, verify } from \"./identity\";\nimport { sanitizeDisplayText } from \"./text\";\n\n/**\n * A group's metadata (WISP 902 § Metadata): what the group looks like, beside who is in it: its\n * name and its picture. It is not in the membership chain, so apps that know nothing of it keep\n * verifying the chain as before and drop the frame that carries it.\n *\n * The admin signs a **statement**: the group, a commit of the chain (`e`, `h`) the admin was the\n * admin of, a revision `r`, and the SHA-256 of the **body**, the metadata itself as JSON. The body\n * is the whole metadata: a field left out is unset, so `{}` removes the picture and gives the group\n * back the name it had when this member got in (`groupDisplayName`). It travels in a\n * `group-meta` frame, encrypted under the message key of an epoch the recipient holds (`k`), so\n * someone taken out of the group cannot read what comes after, and any member can hand it on under\n * a later epoch without the admin: the signature covers the body's hash, not its box.\n *\n * Which statement a member keeps is the rule of each profile (the signer is the current admin; a\n * later commit wins, then a higher revision), in `GroupSession` and `CommunitySession`.\n */\n\n/**\n * Longest picture (data URL) a group may have: less than a profile picture may be (`MAX_AVATAR_LENGTH`),\n * so the frame that carries it, sealed and in base64url, stays within the 60 KiB an edge takes.\n * What Ghostly makes (128×128) is a few kilobytes.\n */\nexport const MAX_GROUP_PICTURE_LENGTH = 40_000;\n/** Longest name the admin may give a group, in characters (code points), as a nickname (`MAX_NICK_LENGTH`). */\nexport const MAX_GROUP_NAME_LENGTH = 64;\n/** And in UTF-8 bytes. */\nexport const MAX_GROUP_NAME_BYTES = 256;\n/** Longest body, in UTF-8 bytes: a picture and room for little else. */\nexport const MAX_GROUP_META_BODY = 42_000;\nconst MAX_META_BOX = Math.ceil((MAX_GROUP_META_BODY + 16) * 4 / 3) + 4;\nconst HASH = /^[a-f0-9]{64}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst B64 = /^[A-Za-z0-9_-]*$/;\n\n/** What the body may say. Every field is optional; one left out is unset. */\nexport interface GroupMetaBody {\n /** The group's name, as `groupName` accepts it. Left out: the name the group had when this member got in. */\n name?: string;\n /** The group's picture: a square JPEG data URL, as `sanitizeAvatar` accepts it. */\n pic?: string;\n /** Private groups: members the admin pins as hubs, and excludes (WISP 902 · Group Mesh § Hubs). Apps from before ignore it. */\n hubs?: MeshHubPolicy;\n /**\n * Community groups: the node that forwards the group's calls (WISP 602 § The group names its node), and `e2ee: 1` when\n * the admin turned on sealed call media (WISP 602 § End-to-end encryption). Apps from before ignore it.\n */\n call?: { sfu: string; e2ee?: 1 };\n}\n\n/** Longest call node origin a group may name, in characters (WISP 602). */\nexport const MAX_GROUP_CALL_SFU = 200;\n\n/**\n * Whether a `call`'s `e2ee` turns sealed call media on (WISP 602 § End-to-end encryption): `1`, as every writer writes\n * it, or `true`, read as on so a body that says it as a JSON flag never leaves a call unsealed. Anything else is off.\n * Read either way, it is kept and written again as `1`.\n */\nexport const groupCallE2ee = (raw: unknown): boolean => raw === 1 || raw === true;\n\n/**\n * A group's call node as WISP 602 takes it: an `https` origin in its one spelling (`new URL(sfu).origin`: lower-case\n * host, no default port, path, query, fragment, userinfo or trailing `/`), at most `MAX_GROUP_CALL_SFU` characters.\n * Undefined otherwise: it is signed into every token request, so a second spelling is no call node.\n */\nexport function groupCallSfu(raw: unknown): string | undefined {\n if (typeof raw !== \"string\" || raw.length > MAX_GROUP_CALL_SFU) return undefined;\n try {\n const url = new URL(raw);\n return url.protocol === \"https:\" && url.origin === raw ? raw : undefined;\n } catch { return undefined; }\n}\n\nexport interface GroupMetaStatement {\n g: string;\n /** The commit the admin signs under: its epoch (index in the chain) and hash. */\n e: number;\n h: string;\n /** Revision: higher wins under the same commit. */\n r: number;\n by: string;\n ts: number;\n /** SHA-256 (hex) of the body's UTF-8 bytes. */\n d: string;\n sig: string;\n}\n\n/** A statement with its body, as a member keeps it. */\nexport interface GroupMeta extends GroupMetaStatement {\n /** The body, exactly as signed (JSON). */\n body: string;\n}\n\n/**\n * `group-meta` on an edge. `k` names the epoch whose message key seals the body: an epoch\n * number in `group-mesh/1`, a commit hash in `group-community/1` (whose frames also carry `v: 2`).\n */\nexport interface GroupMetaFrame extends GroupMetaStatement {\n t: \"group-meta\";\n v?: 2;\n k: number | string;\n nn: string;\n c: string;\n}\n\nconst statementBytes = (s: Omit<GroupMetaStatement, \"sig\">) =>\n utf8Encode(JSON.stringify([\"ghostly-group meta\", s.g, s.e, s.h, s.r, s.by, s.ts, s.d]));\nconst boxAad = (g: string, k: number | string, d: string) => JSON.stringify([\"ghostly-group meta\", g, k, d]);\n\n/**\n * A group's name as the admin gives it and every member shows it: any run of whitespace (a newline,\n * a tab) one space, invisible and direction-changing characters dropped, trimmed. Undefined when it\n * is not a string, nothing visible is left, or it is longer than `MAX_GROUP_NAME_LENGTH` characters\n * or `MAX_GROUP_NAME_BYTES` bytes: a name that does not hold is refused, never cut into another one.\n */\nexport function groupName(raw: unknown): string | undefined {\n if (typeof raw !== \"string\" || raw.length > 4 * MAX_GROUP_NAME_BYTES) return undefined;\n const clean = sanitizeDisplayText(raw.replace(/\\s+/gu, \" \"), Infinity)?.replace(/ {2,}/g, \" \");\n if (!clean || [...clean].length > MAX_GROUP_NAME_LENGTH || utf8Encode(clean).length > MAX_GROUP_NAME_BYTES) return undefined;\n return clean;\n}\n\n/** The body for a name and a picture (or neither). Throws on a name or picture Ghostly would not show. */\nexport function encodeGroupMetaBody(body: GroupMetaBody): string {\n const out: GroupMetaBody = {};\n if (body.name !== undefined) {\n const name = groupName(body.name);\n if (!name) throw new Error(`A group's name is 1 to ${MAX_GROUP_NAME_LENGTH} characters`);\n out.name = name;\n }\n if (body.pic) {\n if (body.pic.length > MAX_GROUP_PICTURE_LENGTH || typeof sanitizeAvatar(body.pic) !== \"string\") throw new Error(\"This picture cannot be used\");\n out.pic = body.pic;\n }\n const hubs = body.hubs && parseHubPolicy(body.hubs);\n if (body.hubs && !hubs) throw new Error(\"This hub setting cannot be used\");\n const wire = hubs && wireHubPolicy(hubs);\n if (wire) out.hubs = wire;\n if (body.call) {\n const sfu = groupCallSfu(body.call.sfu);\n if (!sfu) throw new Error(\"A group's call node is an https origin\");\n out.call = groupCallE2ee(body.call.e2ee) ? { sfu, e2ee: 1 } : { sfu };\n }\n return JSON.stringify(out);\n}\n\n/**\n * A body as received: null when it is not JSON, too large, or its picture is not one Ghostly shows. Unknown fields\n * are ignored, and so is a name that does not hold (`groupName`): the group keeps its first name, the picture shows.\n */\nexport function parseGroupMetaBody(body: string): GroupMetaBody | null {\n if (utf8Encode(body).length > MAX_GROUP_META_BODY) return null;\n let parsed: unknown;\n try { parsed = JSON.parse(body); } catch { return null; }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const out: GroupMetaBody = {};\n const name = groupName((parsed as Record<string, unknown>).name);\n if (name) out.name = name;\n const pic = (parsed as Record<string, unknown>).pic;\n if (pic !== undefined) {\n const clean = sanitizeAvatar(pic);\n if (clean === undefined || (clean && clean.length > MAX_GROUP_PICTURE_LENGTH)) return null;\n if (clean) out.pic = clean;\n }\n // A policy that does not hold is no policy: the picture beside it still shows.\n const hubs = parseHubPolicy((parsed as Record<string, unknown>).hubs), wire = hubs && wireHubPolicy(hubs);\n if (wire) out.hubs = wire;\n // A `call` that does not hold is no `call` (WISP 602): the group has no calls, its name and picture still show.\n const call = (parsed as Record<string, unknown>).call;\n const sfu = call && typeof call === \"object\" ? groupCallSfu((call as Record<string, unknown>).sfu) : undefined;\n // Sealing is on for `1` or `true`, kept as `1`; any other value is off (WISP 602 § End-to-end encryption), kept as off.\n if (sfu) out.call = groupCallE2ee((call as Record<string, unknown>).e2ee) ? { sfu, e2ee: 1 } : { sfu };\n return out;\n}\n\n/** The admin's signature on a body under commit `h` (epoch `e`). */\nexport function signGroupMeta(fields: { g: string; e: number; h: string; r: number; ts: number }, body: string, seed: Uint8Array, by: string): GroupMeta {\n const unsigned = { ...fields, by, d: sha256Hex(utf8Encode(body)) };\n return { ...unsigned, sig: toBase64Url(sign(statementBytes(unsigned), seed)), body };\n}\n\n/** The statement's shape, from a frame or storage; null when anything is off. */\nexport function parseGroupMetaStatement(raw: unknown): GroupMetaStatement | null {\n if (!raw || typeof raw !== \"object\") return null;\n const f = raw as Record<string, unknown>;\n if (typeof f.g !== \"string\" || !GROUP_ID.test(f.g) || !Number.isSafeInteger(f.e) || (f.e as number) < 0 || typeof f.h !== \"string\" || !HASH.test(f.h) ||\n !Number.isSafeInteger(f.r) || (f.r as number) < 1 || typeof f.by !== \"string\" || !MEMBER_KEY.test(f.by) || !Number.isSafeInteger(f.ts) || (f.ts as number) <= 0 ||\n typeof f.d !== \"string\" || !HASH.test(f.d) || typeof f.sig !== \"string\" || !SIG.test(f.sig)) return null;\n return { g: f.g, e: f.e as number, h: f.h, r: f.r as number, by: f.by, ts: f.ts as number, d: f.d, sig: f.sig };\n}\n\n/** Whether `by` signed this statement. */\nexport function verifyGroupMetaSignature(s: GroupMetaStatement): boolean {\n try { return verify(fromBase64Url(s.sig), statementBytes(s), publicKeyFromZ32(s.by)); } catch { return false; }\n}\n\n/** The frame that carries a statement and its body, sealed under the message key of epoch `k`. */\nexport function wrapGroupMeta(meta: GroupMeta, k: number | string, messageKey: Uint8Array, community = false): GroupMetaFrame {\n const { body, ...statement } = meta;\n const { n, c } = encryptText(messageKey, boxAad(meta.g, k, meta.d), body);\n return { t: \"group-meta\", ...(community ? { v: 2 as const } : {}), ...statement, k, nn: n, c };\n}\n\n/** The frame's statement and its key reference, before anything is opened; null when malformed. */\nexport function parseGroupMetaFrame(raw: unknown): { statement: GroupMetaStatement; k: number | string; nn: string; c: string } | null {\n if (!raw || typeof raw !== \"object\") return null;\n const f = raw as Record<string, unknown>;\n const statement = parseGroupMetaStatement(raw);\n if (f.t !== \"group-meta\" || !statement) return null;\n if (!((Number.isSafeInteger(f.k) && (f.k as number) >= 0) || (typeof f.k === \"string\" && HASH.test(f.k)))) return null;\n if (typeof f.nn !== \"string\" || f.nn.length !== 32 || !B64.test(f.nn) || typeof f.c !== \"string\" || f.c.length > MAX_META_BOX || !B64.test(f.c)) return null;\n return { statement, k: f.k as number | string, nn: f.nn, c: f.c };\n}\n\n/**\n * The body of a parsed frame, with the key of its epoch `k`: it must open, hash to what was signed\n * and be metadata Ghostly accepts. The signature is checked separately (`verifyGroupMetaSignature`).\n */\nexport function openGroupMeta(frame: { statement: GroupMetaStatement; k: number | string; nn: string; c: string }, messageKey: Uint8Array): { meta: GroupMeta; body: GroupMetaBody } | null {\n const body = decryptText(messageKey, boxAad(frame.statement.g, frame.k, frame.statement.d), frame.nn, frame.c);\n if (body === null || sha256Hex(utf8Encode(body)) !== frame.statement.d) return null;\n const parsed = parseGroupMetaBody(body);\n if (!parsed) return null;\n const meta: GroupMeta = { ...frame.statement, body };\n // The member keeps this statement as it is: its name and picture are read from here on without a second check.\n parsedBodies.set(meta, { body, parsed });\n return { meta, body: copyBody(parsed) };\n}\n\n/** Is `a` later than `b`: signed under a later commit, or a higher revision under the same one. */\nexport function groupMetaNewer(a: { e: number; r: number }, b: { e: number; r: number } | undefined): boolean {\n return !b || a.e > b.e || (a.e === b.e && a.r > b.r);\n}\n\n/**\n * The revision of the next statement signed under `epoch`: one past the held statement's under the same epoch, else 1.\n * Counting on from a statement of an earlier epoch would let a former admin who signed the highest safe revision leave\n * every later admin with a revision no member accepts. Never under `floor` (WISP 06 § Raised counters): a copy started\n * from older state signs above every revision the device it replaced may have signed under the same commit.\n */\nexport function nextGroupMetaRevision(before: { e: number; r: number } | undefined, epoch: number, floor = 0): number {\n return Math.max(before && before.e === epoch ? before.r + 1 : 1, Number.isSafeInteger(floor) ? floor : 0);\n}\n\n/**\n * Statements a member keeps from before the one it holds, oldest first, so it can hand a member back from away each\n * change it missed where it was made, not only the latest (two renames read as one, 2026-10-14). A few, and their\n * bodies within `GROUP_META_PAST_CHARS` together (a picture is ASCII): one with a large picture is not kept.\n */\nexport const GROUP_META_PAST = 4;\nexport const GROUP_META_PAST_CHARS = 48_000;\n\n/** The statements kept from before, once `before` gives way to `after`; none for the same body signed again. */\nexport function keepPastGroupMeta(past: readonly GroupMeta[] | undefined, before: GroupMeta | undefined, after: GroupMeta): GroupMeta[] | undefined {\n const kept = before && before.body !== after.body ? [...past ?? [], before] : [...past ?? []];\n let chars = kept.reduce((n, m) => n + m.body.length, 0);\n while (kept.length && (kept.length > GROUP_META_PAST || chars > GROUP_META_PAST_CHARS)) chars -= kept.shift()!.body.length;\n return kept.length ? kept : undefined;\n}\n\n/**\n * What to hand a member whose sync says it holds `theirs` (or none): the statements newer than theirs, oldest first, the\n * one I hold last. Those from before only when `wasIn` says it was a member under their commit: one let in since takes\n * the latest, as the group looked when it got in, and no line for what was changed before. And only those of the latest\n * one's signer: a member takes no statement but the current admin's.\n */\nexport function groupMetaToHand(past: readonly GroupMeta[] | undefined, meta: GroupMeta, theirs: { e: number; r: number } | undefined, wasIn: (m: GroupMeta) => boolean): GroupMeta[] {\n const before = (past ?? []).filter(m => m.by === meta.by && groupMetaNewer(m, theirs) && groupMetaNewer(meta, m) && wasIn(m));\n return groupMetaNewer(meta, theirs) ? [...before, meta] : [];\n}\n\n/** What a sync frame says of the metadata a member holds (`e.r`, \"\" for none): old apps send nothing, and get nothing. */\nexport const groupMetaTag = (meta: { e: number; r: number } | undefined): string => meta ? `${meta.e}.${meta.r}` : \"\";\nexport function parseGroupMetaTag(tag: unknown): { e: number; r: number } | undefined | null {\n if (tag === \"\") return undefined;\n if (typeof tag !== \"string\" || !/^\\d{1,15}\\.\\d{1,15}$/.test(tag)) return null;\n const [e, r] = tag.split(\".\").map(Number);\n return { e, r };\n}\n\n/**\n * Each kept statement's body as `parseGroupMetaBody` reads it, worked out once per statement: the sessions' `name` and\n * `picture` read it on every engine state, and checking a picture (`sanitizeAvatar`) costs ~0.2 ms at 40 KB. Keyed by\n * the statement object, so an entry goes with the statement it was made for; the body it was made from is kept beside\n * it, and a statement whose body was swapped in place is read again.\n */\nconst parsedBodies = new WeakMap<GroupMeta, { body: string; parsed: GroupMetaBody | null }>();\n\nfunction parsedBody(meta: GroupMeta): GroupMetaBody | null {\n const hit = parsedBodies.get(meta);\n if (hit && hit.body === meta.body) return hit.parsed;\n const parsed = parseGroupMetaBody(meta.body);\n parsedBodies.set(meta, { body: meta.body, parsed });\n return parsed;\n}\n\n/** A body the caller may change without changing the one kept for its statement. */\nfunction copyBody(parsed: GroupMetaBody): GroupMetaBody {\n const copy: GroupMetaBody = { ...parsed };\n if (parsed.hubs) copy.hubs = { pin: [...parsed.hubs.pin], no: [...parsed.hubs.no] };\n if (parsed.call) copy.call = { ...parsed.call };\n return copy;\n}\n\n/** What a kept statement's body says, `{}` for none. */\nexport function groupMetaBody(meta: GroupMeta | undefined): GroupMetaBody {\n const parsed = meta && parsedBody(meta);\n return parsed ? copyBody(parsed) : {};\n}\n\n/** The picture a kept statement's body names, if it is one Ghostly shows. */\nexport function groupMetaPicture(meta: GroupMeta | undefined): string | undefined {\n return (meta && parsedBody(meta))?.pic;\n}\n\n/**\n * The name members see: the one the admin's statement gives, else the name the group had when this member got in\n * (its creation, or the invitation and welcome that let them in). That first name is also what apps from before\n * names show, and what a member shows until the statement reaches them.\n */\nexport function groupDisplayName(meta: GroupMeta | undefined, first: string): string {\n return (meta && parsedBody(meta))?.name ?? first;\n}\n\n/** What a new statement changed that members see (a line in the history); `null` for a field now unset. */\nexport interface GroupMetaChange { name?: string | null; picture?: string | null }\n\n/**\n * The name and picture that differ between two statements; null when neither does (hubs alone, or the same body signed\n * again). With `first` (the name the group had when this member got in), a name is a change only when the name shown\n * changes: a joiner's welcome already gave the name the statement then brings, and a new admin signs it again.\n */\nexport function groupMetaChange(before: GroupMeta | undefined, after: GroupMeta, first?: string): GroupMetaChange | null {\n const a = groupMetaBody(before), b = groupMetaBody(after), change: GroupMetaChange = {};\n if ((a.name ?? first) !== (b.name ?? first)) change.name = b.name ?? null;\n if (a.pic !== b.pic) change.picture = b.pic ?? null;\n return \"name\" in change || \"picture\" in change ? change : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0BA,IAAM,OAAO,WAAW,mBAAmB;;;;;AAM3C,IAAa,2BAAuC,YAAY,EAAE;;AAGlE,SAAS,YAAY,GAAe,GAAuB;CACzD,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,IAAI,EAAE,OAAO,EAAE,IAAI,OAAO,EAAE,KAAK,EAAE,KAAK,KAAK;CAChF,OAAO;AACT;AAEA,SAAS,UAAU,GAAe,GAAe,GAAqB;CACpE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