@ghostlytools/sdk 1.12.1 → 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 (31) hide show
  1. package/dist/bitcoinAddress-BbPG0DF7.js +3927 -0
  2. package/dist/bitcoinAddress-BbPG0DF7.js.map +1 -0
  3. package/dist/core.js +496 -2386
  4. package/dist/core.js.map +1 -1
  5. package/dist/index.js +3 -3
  6. package/dist/index.js.map +1 -1
  7. package/dist/{pairedTransports-CkYMAoYN.js → pairedTransports-C0I24YFz.js} +9 -291
  8. package/dist/pairedTransports-C0I24YFz.js.map +1 -0
  9. package/dist/testing.js +2 -2
  10. package/dist/types/browser/src/proofs/contract.d.ts +5 -0
  11. package/dist/types/browser/src/proofs/pkarrRelays.d.ts +4 -0
  12. package/dist/types/browser/src/proofs/verify.d.ts +3 -0
  13. package/dist/types/core/src/chatFiles.d.ts +16 -0
  14. package/dist/types/core/src/clipboardGuard.d.ts +5 -3
  15. package/dist/types/core/src/dhtDelivery.d.ts +20 -0
  16. package/dist/types/core/src/domainProofs.d.ts +2 -1
  17. package/dist/types/core/src/ghostlink.d.ts +30 -0
  18. package/dist/types/core/src/groupCalls.d.ts +56 -0
  19. package/dist/types/core/src/groupCommunity.d.ts +15 -1
  20. package/dist/types/core/src/groupSession.d.ts +15 -1
  21. package/dist/types/core/src/index.d.ts +1 -1
  22. package/dist/types/core/src/relay.d.ts +14 -1
  23. package/dist/types/core/src/statusCards.d.ts +6 -0
  24. package/dist/types/core/src/viewerGuard.d.ts +10 -3
  25. package/dist/{verify-CSo7-43-.js → verify-BoVhjvc_.js} +24 -5
  26. package/dist/verify-BoVhjvc_.js.map +1 -0
  27. package/package.json +1 -1
  28. package/dist/bitcoinAddress-C2MAmcDT.js +0 -1225
  29. package/dist/bitcoinAddress-C2MAmcDT.js.map +0 -1
  30. package/dist/pairedTransports-CkYMAoYN.js.map +0 -1
  31. package/dist/verify-CSo7-43-.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pairedTransports-C0I24YFz.js","names":[],"sources":["../../core/src/crypto.ts","../../core/src/domainProofs.ts","../../core/src/storeForward.ts","../../core/src/pairedTransports.ts"],"sourcesContent":["import { xsalsa20poly1305 } from \"@noble/ciphers/salsa.js\";\nimport { concatBytes, fromBase64, randomBytes, toBase64, utf8Decode, utf8Encode } from \"./bytes\";\n\nconst NONCE_LENGTH = 24;\nconst KEY_LENGTH = 32;\n\nexport function generateEncryptionKey(): Uint8Array {\n return randomBytes(KEY_LENGTH);\n}\n\n/**\n * NaCl secretbox (XSalsa20-Poly1305). Wire format matches the Rust\n * implementation in `apps/desktop/src/crypto.rs`: base64(nonce || box).\n */\nexport function encrypt(plaintext: string, key: Uint8Array): string {\n if (key.length !== KEY_LENGTH) throw new Error(\"Invalid key length: expected 32 bytes\");\n const nonce = randomBytes(NONCE_LENGTH);\n const box = xsalsa20poly1305(key, nonce).encrypt(utf8Encode(plaintext));\n return toBase64(concatBytes(nonce, box));\n}\n\n/** The length of what `encrypt` returns for a plaintext of this many UTF-8 bytes: base64 of nonce, box and 16-byte tag. */\nexport function sealedLength(plaintextBytes: number): number {\n return 4 * Math.ceil((NONCE_LENGTH + 16 + plaintextBytes) / 3);\n}\n\nexport function decrypt(encoded: string, key: Uint8Array): string {\n if (key.length !== KEY_LENGTH) throw new Error(\"Invalid key length: expected 32 bytes\");\n const combined = fromBase64(encoded);\n if (combined.length < NONCE_LENGTH + 1) throw new Error(\"Invalid ciphertext: too short\");\n const nonce = combined.subarray(0, NONCE_LENGTH);\n const box = combined.subarray(NONCE_LENGTH);\n return utf8Decode(xsalsa20poly1305(key, nonce).decrypt(box));\n}\n\nexport function tryDecrypt(encoded: string, key: Uint8Array): string | null {\n try {\n return decrypt(encoded, key);\n } catch {\n return null;\n }\n}\n","import { concatBytes, fromZ32, toZ32, utf8Decode, utf8Encode } from './bytes';\n\n/**\n * Domain identity proofs (draft WISP 304, docs/wisps/304-domain.md), the pure half.\n *\n * Under WISP 300 a proof authorizes a fresh Ed25519 *proof key* that only this\n * profile holds, through a statement the external identity vouches for. A\n * domain vouches by publishing: a DNS TXT record at `_ghostly.<domain>` or a\n * `/.well-known/ghostly.json` file names the proof key **and the statement id**\n * (SHA-256 of the statement), so the record commits to the exact binding —\n * subject, key, dates and nonce — not just to a key. Sharing with a contact is\n * then the contract's per-contact presentation, signed by the proof key.\n *\n * People who already run NIP-05 can use `/.well-known/nostr.json` instead: its\n * root name `_` must be the very Nostr key that signed the statement.\n *\n * The record names no participation key and no contact. Fetching, DNS over\n * HTTPS and caching live in `@ghostly/browser/proofs/domain`.\n */\n\nexport type DomainMethod = 'dns' | 'https' | 'nip05';\n/** What a record says: this Ghostly proof key, for this statement. */\nexport interface DomainRecord { key: string; proof: string }\n\nexport const DOMAIN_METHODS: readonly DomainMethod[] = ['dns', 'https', 'nip05'];\nexport const DNS_LABEL = '_ghostly';\nexport const WELL_KNOWN_PATH = '/.well-known/ghostly.json';\nexport const NIP05_PATH = '/.well-known/nostr.json?name=_';\n/** Everything read from a domain is bounded; these match the fetch limits. */\nexport const DOMAIN_FILE_MAX_BYTES = 16 * 1024;\nexport const DOMAIN_TXT_MAX_BYTES = 1024;\nexport const DOMAIN_MAX_RECORDS = 8;\n\nconst z32 = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\nconst hex64 = /^[a-f0-9]{64}$/;\n\n// ---------------------------------------------------------------------------\n// Domain names\n\n/** Names that never resolve publicly (RFC 6761, 6762, 7686, 8375, 9476) or that\n * only ever mean a private network. A proof for them could only point inward. */\nconst SPECIAL_USE = ['localhost', 'local', 'internal', 'lan', 'home', 'corp', 'intranet', 'private',\n 'test', 'example', 'invalid', 'onion', 'alt', 'arpa'];\n\n/**\n * Normalizes what a person typed (\"Example.COM.\", \"https://example.com/\") into\n * a lowercase ASCII host name, or throws with a message fit for the UI.\n * Internationalized names become punycode (xn--), the form DNS carries.\n */\nexport function normalizeDomain(input: string): string {\n if (typeof input !== 'string') throw new Error('Enter a domain name, like example.com');\n let value = input.trim();\n if (!value || value.length > 300) throw new Error('Enter a domain name, like example.com');\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n let url: URL;\n try { url = new URL(value); } catch { throw new Error('Enter a domain name, like example.com'); }\n if (url.protocol !== 'https:' || url.username || url.password || url.port || (url.pathname !== '/' && url.pathname !== '') || url.search || url.hash)\n throw new Error('Enter only the domain name, without a path or port');\n value = url.hostname;\n } else {\n if (/[/:@?#\\s\\\\]/.test(value)) throw new Error('Enter only the domain name, without a path or port');\n try { value = new URL(`https://${value}`).hostname; } catch { throw new Error('That is not a valid domain name'); }\n }\n value = value.toLowerCase().replace(/\\.$/, '');\n if (value.length > 253 - DNS_LABEL.length - 1) throw new Error('That domain name is too long');\n const labels = value.split('.');\n if (labels.length < 2) throw new Error('Use a full domain name, like example.com');\n for (const label of labels) {\n if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) throw new Error('That is not a valid domain name');\n }\n const tld = labels[labels.length - 1];\n if (/^[0-9]+$/.test(tld) || /^\\[/.test(value)) throw new Error('Use a domain name, not an IP address');\n if (SPECIAL_USE.includes(tld) || (labels.length >= 2 && labels.slice(-2).join('.') === 'home.arpa'))\n throw new Error('That name only works on private networks');\n return value;\n}\n\nexport const dnsProofName = (domain: string) => `${DNS_LABEL}.${normalizeDomain(domain)}`;\nexport const wellKnownUrl = (domain: string, method: 'https' | 'nip05' = 'https') =>\n `https://${normalizeDomain(domain)}${method === 'nip05' ? NIP05_PATH : WELL_KNOWN_PATH}`;\n\n// ---------------------------------------------------------------------------\n// Records\n\nexport function validDomainRecord(r: DomainRecord): boolean {\n if (!r || typeof r.key !== 'string' || typeof r.proof !== 'string' || !z32.test(r.key) || !hex64.test(r.proof)) return false;\n try { return toZ32(fromZ32(r.key)) === r.key; } catch { return false; }\n}\n\n/** The TXT record value, in the `tag=value; …` style people know from DKIM. */\nexport function domainTxtRecord(r: DomainRecord): string {\n if (!validDomainRecord(r)) throw new Error('Invalid domain record');\n return `v=ghostly1; key=${r.key}; proof=${r.proof}`;\n}\n\n/** Parses one TXT string. Undefined for anything that is not ours or not exactly\n * well-formed; unknown extra tags are ignored for forward compatibility. */\nexport function parseDomainTxt(value: string): DomainRecord | undefined {\n if (typeof value !== 'string' || utf8Encode(value).length > DOMAIN_TXT_MAX_BYTES) return;\n const tags = new Map<string, string>();\n const parts = value.split(';').map(p => p.trim()).filter(Boolean);\n for (const part of parts) {\n const eq = part.indexOf('=');\n if (eq < 1) return;\n const name = part.slice(0, eq).trim().toLowerCase();\n if (tags.has(name)) return;\n tags.set(name, part.slice(eq + 1).trim());\n }\n if (!parts[0]?.toLowerCase().startsWith('v=') || tags.get('v') !== 'ghostly1') return;\n const r = { key: tags.get('key'), proof: tags.get('proof') } as DomainRecord;\n return validDomainRecord(r) ? r : undefined;\n}\n\nconst addRecord = (list: DomainRecord[], r: DomainRecord) => {\n if (!list.some(x => x.key === r.key && x.proof === r.proof)) list.push(r);\n};\n\n/** All records among the first 32 TXT strings of `_ghostly.<domain>`; other strings are skipped. A TXT set has\n * no order, so every record is kept: the one a proof needs may come in any position. */\nexport function recordsFromTxt(values: string[]): DomainRecord[] {\n const out: DomainRecord[] = [];\n for (const value of values.slice(0, 32)) { const r = parseDomainTxt(value); if (r) addRecord(out, r); }\n return out;\n}\n\n/** The body of `/.well-known/ghostly.json`. */\nexport function domainWellKnownFile(records: DomainRecord[]): string {\n if (!records.length || records.length > DOMAIN_MAX_RECORDS || !records.every(validDomainRecord)) throw new Error('Invalid domain records');\n return JSON.stringify({ ghostly: 1, proofs: records.map(r => ({ key: r.key, proof: r.proof })) }, null, 2) + '\\n';\n}\n\nfunction parseJson(text: string): unknown {\n if (typeof text !== 'string' || utf8Encode(text).length > DOMAIN_FILE_MAX_BYTES) throw new Error('File too large');\n return JSON.parse(text);\n}\n\n/** Records from the first 32 entries of `ghostly.json`. Throws on a malformed file; [] when it names none. */\nexport function recordsFromWellKnown(text: string): DomainRecord[] {\n const body = parseJson(text) as { ghostly?: unknown; proofs?: unknown };\n if (!body || typeof body !== 'object' || Array.isArray(body) || body.ghostly !== 1 || !Array.isArray(body.proofs))\n throw new Error('Not a Ghostly domain file');\n const out: DomainRecord[] = [];\n for (const entry of body.proofs.slice(0, 32) as { key?: unknown; proof?: unknown }[]) {\n if (!entry || typeof entry !== 'object') continue;\n const r = { key: entry.key, proof: entry.proof } as DomainRecord;\n if (validDomainRecord(r)) addRecord(out, r);\n }\n return out;\n}\n\n/** NIP-05: only the root name `_` speaks for the domain itself. Undefined when absent. */\nexport function nip05RootKey(text: string): string | undefined {\n const body = parseJson(text) as { names?: unknown };\n if (!body || typeof body !== 'object' || !body.names || typeof body.names !== 'object' || Array.isArray(body.names))\n throw new Error('Not a NIP-05 file');\n const root = (body.names as Record<string, unknown>)['_'];\n return typeof root === 'string' && hex64.test(root) ? root : undefined;\n}\n\nexport const recordsName = (records: DomainRecord[], r: DomainRecord) => records.some(x => x.key === r.key && x.proof === r.proof);\n\n// ---------------------------------------------------------------------------\n// DNS over HTTPS (RFC 8484) wire messages\n\nexport const DNS_TYPE = { A: 1, CNAME: 5, TXT: 16, AAAA: 28 } as const;\nexport type DnsType = keyof typeof DNS_TYPE;\nexport interface DnsAnswer { name: string; type: number; ttl: number; data: Uint8Array }\nexport interface DnsResponse {\n /** 0 = NOERROR, 3 = NXDOMAIN; anything else is a failed lookup. */\n rcode: number;\n /** The resolver reports it validated the answer with DNSSEC. */\n authenticated: boolean;\n answers: DnsAnswer[];\n}\n\n/**\n * EDNS0 OPT record (RFC 6891) with one Client Subnet option of source prefix 0 (RFC 7871 §7.1.2): a resolver must\n * not add this device's subnet to its queries to the name's servers, as Google Public DNS otherwise does.\n */\nconst NO_CLIENT_SUBNET = Uint8Array.of(0, 0, 41, 1232 >> 8, 1232 & 0xff, 0, 0, 0, 0, 0, 8, 0, 8, 0, 4, 0, 1, 0, 0);\n\n/** A recursive query for one name and type. ID 0, as RFC 8484 recommends for caching;\n * the AD bit asks the resolver to report DNSSEC validation (RFC 6840 §5.7). */\nexport function encodeDnsQuery(name: string, type: DnsType): Uint8Array {\n const labels = name.replace(/\\.$/, '').split('.');\n const parts: Uint8Array[] = [Uint8Array.of(0, 0, 0x01, 0x20, 0, 1, 0, 0, 0, 0, 0, 1)];\n for (const label of labels) {\n const bytes = utf8Encode(label);\n if (!bytes.length || bytes.length > 63) throw new Error('Invalid DNS name');\n parts.push(Uint8Array.of(bytes.length), bytes);\n }\n const code = DNS_TYPE[type];\n parts.push(Uint8Array.of(0, code >> 8, code & 0xff, 0, 1), NO_CLIENT_SUBNET);\n return concatBytes(...parts);\n}\n\nfunction readName(data: Uint8Array, start: number): { name: string; next: number } {\n const labels: string[] = [];\n let pos = start, next = -1, jumps = 0, length = 0;\n for (;;) {\n if (pos >= data.length) throw new Error('DNS name out of bounds');\n const len = data[pos];\n if ((len & 0xc0) === 0xc0) {\n if (pos + 1 >= data.length) throw new Error('DNS pointer out of bounds');\n if (next < 0) next = pos + 2;\n pos = ((len & 0x3f) << 8) | data[pos + 1];\n if (++jumps > 32) throw new Error('DNS name loops');\n continue;\n }\n if (len & 0xc0) throw new Error('Unsupported DNS label');\n pos += 1;\n if (len === 0) break;\n if (pos + len > data.length) throw new Error('DNS label out of bounds');\n length += len + 1;\n if (length > 255) throw new Error('DNS name too long');\n labels.push(utf8Decode(data.subarray(pos, pos + len)).toLowerCase());\n pos += len;\n }\n return { name: labels.join('.'), next: next < 0 ? pos : next };\n}\n\n/**\n * Decodes a resolver's answer to `encodeDnsQuery(name, type)`. Refuses a reply\n * to another question or a truncated one, and keeps only records of the asked\n * type owned by the name or by the CNAME chain the answer itself follows.\n */\nexport function decodeDnsResponse(data: Uint8Array, name: string, type: DnsType): DnsResponse {\n if (data.length < 12) throw new Error('DNS response too short');\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const flags = view.getUint16(2);\n if (!(flags & 0x8000) || (flags & 0x7800) || (flags & 0x0200)) throw new Error('Unusable DNS response');\n const questions = view.getUint16(4), count = view.getUint16(6);\n const want = name.replace(/\\.$/, '').toLowerCase(), code = DNS_TYPE[type];\n if (questions !== 1) throw new Error('DNS response is for another question');\n const q = readName(data, 12);\n if (q.name !== want || q.next + 4 > data.length || view.getUint16(q.next) !== code) throw new Error('DNS response is for another question');\n let pos = q.next + 4;\n const all: DnsAnswer[] = [];\n for (let i = 0; i < count && i < 64; i++) {\n const owner = readName(data, pos);\n pos = owner.next;\n if (pos + 10 > data.length) throw new Error('DNS record out of bounds');\n const rtype = view.getUint16(pos), ttl = view.getUint32(pos + 4), len = view.getUint16(pos + 8);\n pos += 10;\n if (pos + len > data.length) throw new Error('DNS record out of bounds');\n const rdata = rtype === DNS_TYPE.CNAME ? utf8Encode(readName(data, pos).name) : data.slice(pos, pos + len);\n all.push({ name: owner.name, type: rtype, ttl, data: rdata });\n pos += len;\n }\n const owners = new Set([want]);\n for (let hop = 0; hop < 8; hop++) {\n const cname = all.find(a => a.type === DNS_TYPE.CNAME && owners.has(a.name) && !owners.has(utf8Decode(a.data)));\n if (!cname) break;\n owners.add(utf8Decode(cname.data));\n }\n return { rcode: flags & 0x000f, authenticated: !!(flags & 0x0020), answers: all.filter(a => a.type === code && owners.has(a.name)) };\n}\n\n/** The TXT character-strings of one record, joined as RFC 7208 §3.3 does. */\nexport function txtValue(rdata: Uint8Array): string {\n const parts: Uint8Array[] = [];\n for (let p = 0; p < rdata.length;) {\n const len = rdata[p];\n if (p + 1 + len > rdata.length) throw new Error('DNS text out of bounds');\n parts.push(rdata.subarray(p + 1, p + 1 + len));\n p += 1 + len;\n }\n return new TextDecoder('utf-8', { fatal: true }).decode(concatBytes(...parts));\n}\n\n// ---------------------------------------------------------------------------\n// Addresses: a proof may only make a contact's app fetch from the public Internet\n\n/** False for loopback, private, link-local, shared (CGNAT), multicast, reserved\n * and unspecified addresses, including IPv4 embedded in IPv6, and for 6to4, Teredo and documentation IPv6, as\n * Desktop's link_preview::is_public and apps/ui/src/lib/localHost.ts refuse them. */\nexport function isPublicAddress(address: Uint8Array): boolean {\n if (address.length === 4) {\n const [a, b, c] = address;\n return !(a === 0 || a === 10 || a === 127 || a >= 224 ||\n (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) || (a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19)));\n }\n if (address.length !== 16) return false;\n const zeroTo = (n: number) => address.subarray(0, n).every(x => x === 0);\n if (zeroTo(15) && (address[15] === 0 || address[15] === 1)) return false; // :: and ::1\n if (zeroTo(10) && address[10] === 0xff && address[11] === 0xff) return isPublicAddress(address.subarray(12)); // ::ffff:a.b.c.d\n if (address[0] === 0x00 && address[1] === 0x64 && address[2] === 0xff && address[3] === 0x9b && address.subarray(4, 12).every(x => x === 0))\n return isPublicAddress(address.subarray(12)); // 64:ff9b::/96 NAT64\n if (zeroTo(12)) return false; // deprecated IPv4-compatible\n if ((address[0] & 0xfe) === 0xfc) return false; // fc00::/7 unique local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0x80) return false; // fe80::/10 link-local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0xc0) return false; // fec0::/10 site-local\n if (address[0] === 0xff) return false; // multicast\n if (address[0] === 0x01 && address.subarray(1, 8).every(x => x === 0)) return false; // 100::/64 discard\n if (address[0] === 0x20 && address[1] === 0x02) return false; // 2002::/16 6to4: carries an IPv4 address a gateway may reach\n if (address[0] === 0x20 && address[1] === 0x01 && address[2] === 0x00 && address[3] === 0x00) return false; // 2001::/32 Teredo, the same\n if (address[0] === 0x20 && address[1] === 0x01 && address[2] === 0x0d && address[3] === 0xb8) return false; // 2001:db8::/32 documentation\n return (address[0] & 0xe0) === 0x20; // only 2000::/3 is global unicast\n}\n","import { ed25519, x25519 } from \"@noble/curves/ed25519.js\";\nimport { xsalsa20poly1305 } from \"@noble/ciphers/salsa.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { concatBytes, fromBase64Url, randomBytes, toBase64Url, utf8Decode, utf8Encode } from \"./bytes\";\nimport { encrypt, tryDecrypt } from \"./crypto\";\nimport { isPublicAddress } from \"./domainProofs\";\nimport { identityFromSeed, identityFromSeedB64, publicKeyFromZ32, sign, verify, type Identity } from \"./identity\";\nimport type { LinkParams } from \"./invite\";\nimport { measureRecords, MAX_DNS_PACKET_BYTES, type GhostRecord, type SignedPacket } from \"./pkarr\";\n\n/**\n * Store-and-forward for an away contact (WISP 404 draft, `hold/1`).\n *\n * What a person sends while the contact is away is sealed into a *bundle* (signed by the sender's\n * participation key, then encrypted to a key only the two of them can derive), put in the sender's\n * own storage (WISP 1000), and named in a *manifest* the storage also holds. A small signed, encrypted\n * *pointer* record on a per-link Pkarr key tells the contact where the manifest is (a URL that expires)\n * and which of the contact's own bundles have been received. Storage and relays see ciphertext, sizes\n * and timing only. Nothing here promises forward secrecy or retention beyond the bounds below.\n */\nexport const HOLD_CAPABILITY = \"hold/1\" as const;\nexport const HOLD_LIMITS = {\n /** One bundle, ciphertext and header included: a picture, not a video. */\n maxBundleBytes: 8 * 1024 * 1024,\n /** All bundles held for one contact at once. */\n maxMailboxBytes: 64 * 1024 * 1024,\n maxMailboxBundles: 64,\n /** A bundle not picked up by then is dropped by its sender. The longest a presigned URL lives, too. */\n ttlMs: 7 * 24 * 60 * 60_000,\n maxTextBytes: 16 * 1024,\n maxPaymentRequestBytes: 64 * 1024,\n maxManifestBytes: 64 * 1024,\n /**\n * How far past one lifetime from now an expiry may reach by the reader's clock: the sender's clock may be ahead, and\n * a day covers any clock that is merely wrong. Nothing else about a pointer or a bundle is held against this clock.\n */\n clockSkewMs: 24 * 60 * 60_000,\n} as const;\n/**\n * How far before its own clock a sender dates its pointer and its manifest, and ends the lifetimes it gives. A reader\n * refuses nothing for those dates: `rev` orders pointers and `seq` orders items, both kept by the reader. Apps up to\n * 1.0.2 refuse a pointer or a manifest dated more than a minute past their clock, and an expiry more than a minute\n * past one lifetime from now, each without a word: the items of a sender whose clock ran two minutes fast were never\n * fetched. Dated back, a sender up to about eleven minutes ahead is read by them.\n */\nexport const HOLD_DATED_BACK_MS = 10 * 60_000;\n\nexport type HoldKind = \"text\" | \"file\" | \"pay-req\" | \"manifest\";\nconst KINDS: readonly string[] = [\"text\", \"file\", \"pay-req\", \"manifest\"];\nconst WIRE_ID = /^[A-Za-z0-9_-]{8,64}$/;\nconst MAILBOX = /^[A-Za-z0-9_-]{22}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst MAGIC = utf8Encode(\"GHLD\");\nconst VERSION = 1;\nconst NONCE = 24;\n/** A bundle sealed by the chat's ratchet (WISP 4xx § Held items). */\nconst RATCHETED = 2;\ntype HoldItem = { mailbox: string; seq: number; id: string; ts: number; kind: HoldKind; meta?: unknown; expires: number };\n\nexport interface HoldFileMeta { name: string; size: number; mime: string }\n/** One held bundle as the manifest lists it: where to get it, and what to expect. */\nexport type HoldManifestEntry = [seq: number, id: string, kind: Exclude<HoldKind, \"manifest\">, bytes: number, url: string, expires: number];\nexport interface HoldHeader {\n v: 1;\n /** Rendezvous keys, as the sender sees the link. */\n from: string;\n to: string;\n /** Participation keys: who signed, who may open. */\n author: string;\n recipient: string;\n mailbox: string;\n seq: number;\n id: string;\n ts: number;\n kind: HoldKind;\n meta: unknown;\n /** base64url SHA-256 of the body. */\n digest: string;\n expires: number;\n}\nexport interface HoldPointer {\n rev: number;\n issued: number;\n /** When the manifest URL stops working. */\n expires: number;\n manifestUrl: string | null;\n /** Highest sequence the publisher has held for the reader. */\n top: number;\n /** Highest sequence the publisher received from the reader. */\n ack: number;\n count: number;\n bytes: number;\n /** Sequences of the reader's items this publisher refused (changed, oversized, not for it): at most the last 32. */\n refused: number[];\n}\n\n/** Why a bundle, manifest or pointer was refused. Never a reason to trust it a little. */\nexport class HoldRefusedError extends Error {\n /** The bytes the chat's ratchet opened, when it opened them before the item was refused: the caller commits them. */\n ratcheted?: Uint8Array;\n constructor(readonly reason: \"size\" | \"format\" | \"tampered\" | \"not-for-me\" | \"author\" | \"signature\" | \"digest\" | \"limits\" | \"expired\" | \"plain\", message: string) {\n super(message);\n }\n}\n\nconst bodyDigest = (body: Uint8Array) => toBase64Url(sha256(body));\nconst newMailbox = () => toBase64Url(randomBytes(16)).slice(0, 22);\nexport { newMailbox as newHoldMailbox };\n\n/**\n * Everything derived once per link for this feature: my pointer key, the contact's pointer address and\n * the key that seals bundles and pointers between the two participation keys. Needs a pinned contact.\n */\nexport class HoldKeys {\n readonly from: string;\n readonly to: string;\n readonly me: string;\n readonly peer: string;\n /** Publishes my pointer. */\n readonly identity: Identity;\n /** Where the contact publishes its pointer. */\n readonly peerAddress: string;\n private readonly seed: Uint8Array;\n private readonly sealKey: Uint8Array;\n\n constructor(params: LinkParams, participationSeedB64: string, peerKey: 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 this.peer = peerKey;\n const secret = fromBase64Url(params.encKeyB64);\n const context = JSON.stringify([\"ghostly-hold/1\", [this.from, this.to].sort()]);\n const derive = (label: string) => hkdf(sha256, secret, utf8Encode(context), utf8Encode(label), 32);\n this.identity = identityFromSeed(derive(`pointer:${this.from}`));\n this.peerAddress = identityFromSeed(derive(`pointer:${this.to}`)).pubKeyZ32;\n const shared = x25519.getSharedSecret(ed25519.utils.toMontgomerySecret(this.seed), ed25519.utils.toMontgomery(publicKeyFromZ32(peerKey)));\n this.sealKey = hkdf(sha256, shared, derive(\"envelope\"), utf8Encode(\"ghostly-hold-envelope/1\"), 32);\n }\n\n /** Seals one item for the contact: signed with my participation key, encrypted to our shared key. */\n seal(item: HoldItem, body: Uint8Array): Uint8Array {\n const nonce = randomBytes(NONCE);\n const box = xsalsa20poly1305(this.sealKey, nonce).encrypt(this.inner(item, body));\n return concatBytes(MAGIC, new Uint8Array([VERSION]), nonce, box);\n }\n /**\n * The same item as a version-2 bundle (WISP 4xx § Held items): the same plaintext, sealed by the chat's ratchet\n * (`seal`, which saves the ratchet's state before it returns), so the bundle can be uploaded once this returns.\n */\n async sealRatcheted(item: HoldItem, body: Uint8Array, seal: (plaintext: Uint8Array) => Promise<Uint8Array>): Promise<Uint8Array> {\n return concatBytes(MAGIC, new Uint8Array([RATCHETED]), await seal(this.inner(item, body)));\n }\n /** What a bundle seals: the header's length, the signed header, the body. */\n private inner(item: HoldItem, body: Uint8Array): Uint8Array {\n const fields = [VERSION, this.from, this.to, this.me, this.peer, item.mailbox, item.seq, item.id, item.ts, item.kind, item.meta ?? null, bodyDigest(body), item.expires];\n const signature = toBase64Url(sign(utf8Encode(JSON.stringify([\"ghostly-hold-bundle\", fields])), this.seed));\n const header = utf8Encode(JSON.stringify([fields, signature]));\n const length = new Uint8Array(4);\n new DataView(length.buffer).setUint32(0, header.length);\n return concatBytes(length, header, body);\n }\n\n /**\n * Opens a bundle the contact sealed for me. Everything is checked before anything is returned: the\n * authenticated encryption, the header's shape, that it names this link, this contact and me, the\n * signature, the body digest and the limits of its kind. `loopback`: see `isHoldUrl`.\n */\n /**\n * `ratchet`: opens a version-2 bundle's sealed bytes (WISP 4xx), without keeping anything; absent, one is from a newer\n * Ghostly. `refusePlain`: a ratcheted item from this contact opened here, so a version-1 item other than the manifest is\n * refused (WISP 4xx § Downgrade). `ratcheted` in the result: the bytes the ratchet opened, for the caller to commit once\n * the item is stored.\n */\n open(bytes: Uint8Array, expect: { maxBytes?: number; mailbox?: string; now?: number; loopback?: boolean; ratchet?: (sealed: Uint8Array) => Uint8Array | null; refusePlain?: boolean } = {}): { header: HoldHeader; body: Uint8Array; ratcheted?: Uint8Array } {\n const now = expect.now ?? Date.now();\n if (bytes.length > (expect.maxBytes ?? HOLD_LIMITS.maxBundleBytes)) throw new HoldRefusedError(\"size\", \"The held item is larger than allowed\");\n if (bytes.length < MAGIC.length + 1 + 16 + 4 || !MAGIC.every((b, i) => bytes[i] === b)) throw new HoldRefusedError(\"format\", \"Not a held item\");\n const version = bytes[MAGIC.length];\n if (version !== VERSION && (version !== RATCHETED || !expect.ratchet)) throw new HoldRefusedError(\"format\", \"Held item from a newer Ghostly\");\n let plain: Uint8Array | null, ratcheted: Uint8Array | undefined;\n if (version === RATCHETED) {\n ratcheted = bytes.subarray(MAGIC.length + 1);\n try { plain = expect.ratchet!(ratcheted); } catch { plain = null; }\n if (!plain) throw new HoldRefusedError(\"tampered\", \"The held item was changed, is not for this chat, or was opened already\");\n } else {\n if (bytes.length < MAGIC.length + 1 + NONCE + 16 + 4) throw new HoldRefusedError(\"format\", \"Not a held item\");\n try { plain = xsalsa20poly1305(this.sealKey, bytes.subarray(MAGIC.length + 1, MAGIC.length + 1 + NONCE)).decrypt(bytes.subarray(MAGIC.length + 1 + NONCE)); }\n catch { throw new HoldRefusedError(\"tampered\", \"The held item was changed or is not for this chat\"); }\n }\n try { return this.read(plain, ratcheted, expect, now); }\n catch (error) {\n // Opened, then refused: the ratchet's bytes go with the refusal, so the key is used up and the lane heard all the same.\n if (error instanceof HoldRefusedError && ratcheted) error.ratcheted = ratcheted;\n throw error;\n }\n }\n /** The checks of `open` once the bundle is decrypted. */\n private read(plain: Uint8Array, ratcheted: Uint8Array | undefined, expect: { mailbox?: string; loopback?: boolean; refusePlain?: boolean }, now: number): { header: HoldHeader; body: Uint8Array; ratcheted?: Uint8Array } {\n if (plain.length < 4) throw new HoldRefusedError(\"format\", \"Not a held item\");\n const headerLength = new DataView(plain.buffer, plain.byteOffset, 4).getUint32(0);\n if (headerLength > 128 * 1024 || 4 + headerLength > plain.length) throw new HoldRefusedError(\"format\", \"Not a held item\");\n let parsed: unknown;\n try { parsed = JSON.parse(utf8Decode(plain.subarray(4, 4 + headerLength))); } catch { throw new HoldRefusedError(\"format\", \"Not a held item\"); }\n if (!Array.isArray(parsed) || parsed.length !== 2 || !Array.isArray(parsed[0]) || parsed[0].length !== 13 || typeof parsed[1] !== \"string\" || !SIG.test(parsed[1])) throw new HoldRefusedError(\"format\", \"Not a held item\");\n const [fields, signature] = parsed as [unknown[], string];\n const [v, from, to, author, recipient, mailbox, seq, id, ts, kind, meta, digest, expires] = fields;\n if (v !== VERSION || typeof from !== \"string\" || typeof to !== \"string\" || typeof author !== \"string\" || typeof recipient !== \"string\" || typeof mailbox !== \"string\" || !MAILBOX.test(mailbox) ||\n !Number.isSafeInteger(seq) || (seq as number) < 0 || typeof id !== \"string\" || !WIRE_ID.test(id) || !Number.isSafeInteger(ts) || (ts as number) <= 0 ||\n typeof kind !== \"string\" || !KINDS.includes(kind) || typeof digest !== \"string\" || !Number.isSafeInteger(expires)) throw new HoldRefusedError(\"format\", \"Not a held item\");\n // Both directions of this link are sealed with the same key: the header says which one this is.\n if (from !== this.to || to !== this.from || recipient !== this.me) throw new HoldRefusedError(\"not-for-me\", \"The held item is for another chat\");\n if (author !== this.peer) throw new HoldRefusedError(\"author\", \"The held item was not signed by this contact\");\n if (expect.mailbox && mailbox !== expect.mailbox) throw new HoldRefusedError(\"not-for-me\", \"The held item is from another mailbox\");\n let valid: boolean;\n try { valid = verify(fromBase64Url(signature), utf8Encode(JSON.stringify([\"ghostly-hold-bundle\", fields])), publicKeyFromZ32(author)); } catch { valid = false; }\n if (!valid) throw new HoldRefusedError(\"signature\", \"The held item's signature does not check out\");\n const body = plain.subarray(4 + headerLength);\n if (bodyDigest(body) !== digest) throw new HoldRefusedError(\"digest\", \"The held item's content does not match its header\");\n // Its `ts` is its sender's clock, often minutes from this one: nothing is refused for it. It was, past a minute\n // ahead, and for good: the item's sequence was passed, and its sender told \"could not be verified as yours, or was\n // too large\". What stops an item from being taken twice is its sequence (the manifest's, the pointer's `rev`).\n // The item may be older than its upload (a retry, a message written offline); its expiry may not reach past one\n // lifetime from now, give or take what the sender's clock is ahead.\n if ((expires as number) <= (ts as number) || (expires as number) > now + HOLD_LIMITS.ttlMs + HOLD_LIMITS.clockSkewMs) throw new HoldRefusedError(\"limits\", \"The held item's lifetime is out of bounds\");\n const header: HoldHeader = { v: 1, from, to, author, recipient, mailbox, seq: seq as number, id, ts: ts as number, kind: kind as HoldKind, meta, digest, expires: expires as number };\n // The manifest is always sealed as before; anything else from a contact whose items come ratcheted must be ratcheted.\n if (!ratcheted && expect.refusePlain && kind !== \"manifest\") throw new HoldRefusedError(\"plain\", \"The held item was sealed without forward secrecy, which this chat no longer takes\");\n checkKind(header, body, expect.loopback);\n return { header, body, ...(ratcheted && { ratcheted }) };\n }\n\n /** My pointer, as records to publish under `identity`. Throws when it cannot fit a packet. */\n pointerRecords(pointer: HoldPointer, now = Date.now()): GhostRecord[] {\n const body = [VERSION, pointer.rev, pointer.issued, pointer.expires, pointer.manifestUrl, pointer.top, pointer.ack, pointer.count, pointer.bytes, pointer.refused.slice(-32)];\n const signature = toBase64Url(sign(utf8Encode(JSON.stringify([\"ghostly-hold-pointer\", this.from, this.to, body])), this.seed));\n const ttl = Math.min(24 * 3600, Math.max(60, Math.ceil((pointer.expires - now) / 1000)));\n const records = [{ label: \"_hold\", value: encrypt(JSON.stringify([body, signature]), this.sealKey), ttl }];\n if (measureRecords(this.identity.pubKeyZ32, records) > MAX_DNS_PACKET_BYTES) throw new Error(\"The storage address is too long for a DHT packet. Use a shorter endpoint or prefix.\");\n return records;\n }\n\n /**\n * The contact's pointer out of its packet, or null when the packet is not one of its pointers. Its `issued` is the\n * contact's clock and refuses nothing: an older pointer cannot take a newer one's place because of `rev`. The\n * manifest's address is held to what an item's is (`isHoldUrl`): it is fetched as soon as the pointer is read.\n */\n readPointer(packet: SignedPacket, loopback = false): HoldPointer | null {\n if (packet.pubKeyZ32 !== this.peerAddress || measureRecords(packet.pubKeyZ32, packet.records) > MAX_DNS_PACKET_BYTES) return null;\n const records = packet.records.filter(r => r.label === \"_hold\");\n if (records.length !== 1) return null;\n const plain = tryDecrypt(records[0].value, this.sealKey);\n if (!plain) return null;\n let parsed: unknown;\n try { parsed = JSON.parse(plain); } catch { return null; }\n if (!Array.isArray(parsed) || parsed.length !== 2 || !Array.isArray(parsed[0]) || (parsed[0].length !== 9 && parsed[0].length !== 10) || typeof parsed[1] !== \"string\" || !SIG.test(parsed[1])) return null;\n const [body, signature] = parsed as [unknown[], string];\n const [v, rev, issued, expires, manifestUrl, top, ack, count, bytes, refused = []] = body;\n if (v !== VERSION || ![rev, issued, expires, top, ack, count, bytes].every(n => Number.isSafeInteger(n) && (n as number) >= 0) ||\n (manifestUrl !== null && !isHoldUrl(manifestUrl, loopback)) ||\n !Array.isArray(refused) || refused.length > 32 || !refused.every(n => Number.isSafeInteger(n) && (n as number) > 0)) return null;\n try {\n if (!verify(fromBase64Url(signature), utf8Encode(JSON.stringify([\"ghostly-hold-pointer\", this.to, this.from, body])), publicKeyFromZ32(this.peer))) return null;\n } catch { return null; }\n return { rev: rev as number, issued: issued as number, expires: expires as number, manifestUrl: manifestUrl as string | null, top: top as number, ack: ack as number, count: count as number, bytes: bytes as number, refused: refused as number[] };\n }\n}\n\n/** Names only a local network answers (RFC 6762, RFC 8375, ICANN's .internal, and the usual router ones). */\nconst LOCAL_SUFFIXES = [\"localhost\", \"local\", \"internal\", \"lan\", \"home\", \"home.arpa\", \"localdomain\", \"intranet\", \"corp\"];\n\n/**\n * A URL a bundle or manifest may be fetched from. The contact chose it and this device fetches it on its own, so it\n * is HTTPS, without a user or password, at a public name or a public IPv4 address: never this machine or its network.\n * A name with no dot or under a local suffix is a local one. A public name may still resolve to a local address:\n * where the host can resolve, its `fetch` refuses that too (the CLI's, packages/cli/src/runtime/holdFetch.ts, and\n * Desktop's, apps/desktop/src/hold_fetch.rs).\n * `loopback` adds plain HTTP to this machine, for a test against a local server; no shipped app passes it.\n */\nexport function isHoldUrl(value: unknown, loopback = false): value is string {\n if (typeof value !== \"string\" || value.length > 2048) return false;\n let url: URL;\n try { url = new URL(value); } catch { return false; }\n if (url.username || url.password) return false;\n const host = url.hostname.toLowerCase().replace(/\\.+$/, \"\");\n if (loopback && url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(host)) return true;\n if (url.protocol !== \"https:\" || !host.includes(\".\") || host.startsWith(\"[\") || LOCAL_SUFFIXES.some(s => host === s || host.endsWith(`.${s}`))) return false;\n // A URL's IPv4 host is always written as four decimal numbers, whatever form it was given in.\n return !/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host) || isPublicAddress(Uint8Array.from(host.split(\".\"), Number));\n}\n\n/** The limits of each kind, on the way in. */\nfunction checkKind(header: HoldHeader, body: Uint8Array, loopback = false): void {\n const bad = (message: string) => new HoldRefusedError(\"limits\", message);\n switch (header.kind) {\n case \"text\":\n if (body.length > HOLD_LIMITS.maxTextBytes) throw bad(\"The held text is too long\");\n try { utf8Decode(body); } catch { throw bad(\"The held text is not text\"); }\n return;\n case \"pay-req\":\n if (body.length > HOLD_LIMITS.maxPaymentRequestBytes) throw bad(\"The held payment request is too large\");\n return;\n case \"file\": {\n const meta = header.meta as Partial<HoldFileMeta> | null;\n if (!meta || typeof meta !== \"object\" || typeof meta.name !== \"string\" || meta.name.length > 255 || typeof meta.mime !== \"string\" || meta.mime.length > 255 || meta.size !== body.length) throw bad(\"The held file does not match its description\");\n return;\n }\n case \"manifest\": {\n if (body.length !== 0) throw bad(\"A manifest carries no body\");\n readManifest(header.meta, loopback);\n return;\n }\n }\n}\n\n/** The entries of a manifest, checked: strictly increasing sequences, bounded sizes, fetchable URLs. */\nexport function readManifest(meta: unknown, loopback = false): HoldManifestEntry[] {\n const bad = (message: string) => new HoldRefusedError(\"limits\", message);\n const entries = (meta as { entries?: unknown } | null)?.entries;\n if (!Array.isArray(entries) || entries.length > HOLD_LIMITS.maxMailboxBundles) throw bad(\"The manifest lists too many items\");\n let last = 0, total = 0;\n const out: HoldManifestEntry[] = [];\n for (const entry of entries) {\n if (!Array.isArray(entry) || entry.length !== 6) throw bad(\"The manifest is malformed\");\n const [seq, id, kind, bytes, url, expires] = entry;\n if (!Number.isSafeInteger(seq) || seq <= last || typeof id !== \"string\" || !WIRE_ID.test(id) || typeof kind !== \"string\" || !KINDS.includes(kind) || kind === \"manifest\" ||\n !Number.isSafeInteger(bytes) || bytes < 0 || bytes > HOLD_LIMITS.maxBundleBytes || !isHoldUrl(url, loopback) || !Number.isSafeInteger(expires)) throw bad(\"The manifest is malformed\");\n last = seq; total += bytes;\n if (total > HOLD_LIMITS.maxMailboxBytes) throw bad(\"The manifest lists more than a mailbox may hold\");\n out.push([seq, id, kind as HoldManifestEntry[2], bytes, url, expires]);\n }\n return out;\n}\n","import type { FrameChannel } from \"./frames\";\nimport { isHoldUrl } from \"./storeForward\";\n\nexport const TRANSPORTS = [\"iroh/1\", \"hyperdht/1\", \"webrtc/1\"] as const;\nexport type PairedTransport = typeof TRANSPORTS[number];\nexport type NativeTransport = Exclude<PairedTransport, \"webrtc/1\">;\n\n/** Supplied only by the local adapter after its real cryptographic handshake.\n * Iroh uses a TLS exporter; HyperDHT uses its Noise handshake hash. */\nexport interface NativeBinding {\n transport: NativeTransport;\n context: string;\n identities: [string, string];\n}\nexport interface BoundChannel { channel: FrameChannel; binding: NativeBinding }\nexport interface NativeEndpoint {\n transport: NativeTransport;\n descriptor: unknown;\n connect(descriptor: unknown): Promise<BoundChannel>;\n close(): Promise<void>;\n onConnection: ((connection: BoundChannel) => void) | null;\n onDescriptor: (() => void) | null;\n onUnavailable?: (() => void) | null;\n /** The endpoint is connected to its relay again after it lost it (the native Iroh's home relay; nothing else says it). */\n onRelayBack?: (() => void) | null;\n}\nexport type TransportDescriptors = Partial<Record<NativeTransport, unknown>>;\n\n/**\n * One spelling per Iroh relay. Iroh compares relay URLs as text, and its own relays are named with the trailing dot\n * of a fully qualified name (`https://use1-1.relay.n0.iroh.link./`): the same server written without the dot is\n * another relay to it, and an endpoint dialling a contact there opens a second connection to the server it is already\n * homed on, which the server answers by setting the first one aside.\n *\n * So every relay URL is put in one spelling before it goes into an Iroh endpoint (the relays it homes on, a contact's\n * descriptor before a dial), and which one depends on the endpoint:\n * - `\"dotted\"`, n0's relays with their trailing dot: what native Iroh homes on by default (the Desktop), and the form\n * to compare two relays in. Any other relay keeps its plain name here too: a relay behind a proxy (a Cloudflare\n * tunnel) is found by its Host header, and the proxy answers the dotted name with 404.\n * - `\"plain\"`, the name without it: the only one every browser opens. WebKit (Safari, the iPhone app) refuses a\n * host name that ends in a dot, for `fetch` and for a WebSocket alike, so nothing a browser's Iroh is given has one.\n *\n * An IP address and a single-label name (a search domain may complete it) stay as written; `localhost.` loses its dot\n * in both, the form the relay settings accept. What does not parse comes back untouched, for the caller's own check.\n */\nexport type IrohRelaySpelling = \"dotted\" | \"plain\";\nexport function irohRelayUrl(value: string, spelling: IrohRelaySpelling = \"dotted\"): string {\n let url: URL;\n try { url = new URL(value); } catch { return value; }\n const host = url.hostname, name = host.replace(/\\.$/, \"\");\n if (!name.includes(\".\") && name !== \"localhost\") return value;\n if (name.startsWith(\"[\") || /^\\d+(\\.\\d+){3}$/.test(name)) return value;\n const wanted = spelling === \"dotted\" && /(^|\\.)iroh\\.link$/.test(name) ? `${name}.` : name;\n if (wanted === host) return value;\n url.hostname = wanted;\n return url.href;\n}\n\n/** An Iroh descriptor with its relay in one spelling (`irohRelayUrl`); anything else as it is. */\nexport function irohDescriptor<T>(descriptor: T, spelling: IrohRelaySpelling = \"dotted\"): T {\n const relay = (descriptor as { relay?: unknown } | null | undefined)?.relay;\n if (typeof relay !== \"string\") return descriptor;\n const canonical = irohRelayUrl(relay, spelling);\n return canonical === relay ? descriptor : { ...descriptor, relay: canonical };\n}\n\n/**\n * A relay server's URL, short: https, or wss for a browser's relay; plain http or ws only on this machine's loopback,\n * as a test relay is (the same rule as the relay settings).\n */\nexport const RELAY_URL = /^((https|wss):\\/\\/[^\\s]{1,120}|(http|ws):\\/\\/(127\\.0\\.0\\.1|localhost|\\[::1\\])(:\\d{1,5})?(\\/[^\\s]{0,100})?)$/;\n/**\n * A relay URL with more than its server's address in it: a login, a query or a fragment, which no relay setting takes\n * (irohWeb.ts `irohRelayProblem`, hyperdhtRelay.ts `hyperdhtRelayProblem`). An older app named its HyperDHT relay as\n * set, with them; such a descriptor is not dialed or kept, and the rest of what the contact told still is.\n */\nexport const RELAY_WITH_SECRETS = /^[a-z]+:\\/\\/[^/?#]*@|[?#]/i;\n/** A relay URL a descriptor may name: `RELAY_URL`, with nothing but the server's address in it. */\nexport const relayUrl = (value: unknown): value is string => typeof value === \"string\" && RELAY_URL.test(value) && !RELAY_WITH_SECRETS.test(value);\n/** `RELAY_URL` at any length. */\nconst RELAY_URL_ANY_LENGTH = /^((https|wss):\\/\\/[^\\s]+|(http|ws):\\/\\/(127\\.0\\.0\\.1|localhost|\\[::1\\])(:\\d{1,5})?(\\/[^\\s]*)?)$/;\n/**\n * A relay URL `relayUrl` refuses for its length alone (past 120 characters, a loopback path past 100): a relay setting\n * asks for a shorter one, where \"not a relay address\" sent the person looking for a typo in it.\n */\nexport const relayUrlTooLong = (value: string): boolean => !relayUrl(value) && !RELAY_WITH_SECRETS.test(value) && RELAY_URL_ANY_LENGTH.test(value);\n/**\n * Whether an Iroh endpoint may dial a contact through the relay its descriptor names (none: a direct address alone).\n * The contact chose that relay and this device opens it on its own, again on each redial, so it is held to what a held\n * item's address is (`isHoldUrl`): https at a public name or a public address, never this machine or its network.\n * One of the endpoint's own relays (`own`: the person's settings, a private network's or a test's) is dialled as well,\n * in either spelling: this device opens it anyway.\n */\nexport function dialableIrohRelay(relay: unknown, own: readonly string[]): boolean {\n if (relay === null || relay === undefined) return true;\n if (!relayUrl(relay)) return false;\n const same = (a: string, b: string) => { try { return new URL(irohRelayUrl(a, \"plain\")).href === new URL(irohRelayUrl(b, \"plain\")).href; } catch { return false; } };\n return own.some(mine => same(mine, relay)) || isHoldUrl(relay);\n}\nconst HEX_KEY = /^[0-9a-f]{64}$/;\n/** An Iroh direct address as the adapters parse it: an IPv4 or bracketed IPv6 address and its port. */\nconst SOCKET_ADDRESS = /^(\\d{1,3}(\\.\\d{1,3}){3}|\\[[0-9A-Fa-f:.]{2,45}(%[A-Za-z0-9._-]{1,16})?\\]):\\d{1,5}$/;\nconst MAX_ADDRESSES = 8;\n\n/**\n * A contact's native descriptors as it tells them on a session (`paired-policy`, `paired-adapters`) or as this app\n * kept them: only what the adapters dial, each field in the shape its adapter makes. The keys are 64 hex characters,\n * a relay passes `relayUrl` (the rule its capability record is read by), an Iroh descriptor lists at most eight\n * socket addresses. A descriptor that is anything else is left out, as one the contact never told; a field this app\n * does not know is not kept.\n */\nexport function checkedDescriptors(value: unknown): TransportDescriptors {\n const out: TransportDescriptors = {};\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return out;\n const raw = value as Record<string, unknown>;\n const relayed = (v: unknown) => v === undefined || typeof v === \"boolean\";\n const iroh = raw[\"iroh/1\"] as { id?: unknown; relay?: unknown; addresses?: unknown; relayed?: unknown } | null | undefined;\n if (iroh && typeof iroh === \"object\" && typeof iroh.id === \"string\" && HEX_KEY.test(iroh.id) &&\n (iroh.relay === undefined || iroh.relay === null || relayUrl(iroh.relay)) && relayed(iroh.relayed) &&\n Array.isArray(iroh.addresses) && iroh.addresses.length <= MAX_ADDRESSES &&\n iroh.addresses.every(a => typeof a === \"string\" && SOCKET_ADDRESS.test(a)))\n out[\"iroh/1\"] = { id: iroh.id, relay: (iroh.relay as string | null | undefined) ?? null, addresses: [...iroh.addresses] as string[],\n ...(iroh.relayed !== undefined ? { relayed: iroh.relayed } : {}) };\n const hyper = raw[\"hyperdht/1\"] as { publicKey?: unknown; relay?: unknown; relayed?: unknown } | null | undefined;\n if (hyper && typeof hyper === \"object\" && typeof hyper.publicKey === \"string\" && HEX_KEY.test(hyper.publicKey) &&\n (hyper.relay === undefined || relayUrl(hyper.relay)) && relayed(hyper.relayed))\n out[\"hyperdht/1\"] = { publicKey: hyper.publicKey, ...(hyper.relay !== undefined ? { relay: hyper.relay } : {}),\n ...(hyper.relayed !== undefined ? { relayed: hyper.relayed } : {}) };\n return out;\n}\n\n/**\n * Relay only (WISP 100, \"Relayed\"): the transport reaches this contact only through a relay server, never\n * directly. A descriptor says so with `relayed: true`, and an Iroh descriptor with no direct address is relayed\n * too (a browser's, WISP 102). Either side being relay only makes the whole path relayed. Both sides hold both\n * descriptors after the exchange, so they agree, and the rank stays symmetric.\n */\nexport function relayedTransports(local: TransportDescriptors, remote: TransportDescriptors): NativeTransport[] {\n const relayOnly = (transport: NativeTransport, descriptor: unknown): boolean => {\n if (!descriptor || typeof descriptor !== \"object\") return false;\n const d = descriptor as { relayed?: unknown; addresses?: unknown };\n return d.relayed === true || (transport === \"iroh/1\" && Array.isArray(d.addresses) && d.addresses.length === 0);\n };\n return ([\"iroh/1\", \"hyperdht/1\"] as const).filter(t => relayOnly(t, local[t]) || relayOnly(t, remote[t]));\n}\n\n/** Symmetric rank sum; the fixed order breaks ties deterministically. Neither\n * a remote list nor a preference can add an unavailable local adapter. A\n * relayed transport ranks after every direct one: it is where a failed direct\n * path goes, never ahead of one that works. Iroh through its relay is the\n * exception (WISP 100, revision 2026-11-08): it comes back almost at once after\n * the app was away, and a browser's Iroh is never anything else. */\nexport function rankTransports(local: readonly string[], remote: readonly string[], relayed: readonly string[] = []): PairedTransport[] {\n const penalty = (t: PairedTransport) => t !== \"iroh/1\" && relayed.includes(t) ? 1 : 0;\n return TRANSPORTS.filter(t => local.includes(t) && remote.includes(t))\n .sort((a, b) => penalty(a) - penalty(b)\n || (local.indexOf(a) + remote.indexOf(a)) - (local.indexOf(b) + remote.indexOf(b))\n || TRANSPORTS.indexOf(a) - TRANSPORTS.indexOf(b));\n}\n\n/**\n * What a chat prefers when nobody chose (Automatic): Iroh where the app has it, then WebRTC, then HyperDHT (WISP 100,\n * revision 2026-11-08). Every app puts Iroh first, so the rank sum of two apps that both run it puts it first on both\n * sides. With nothing at all, WebRTC, which the offer then leaves out.\n * With Fallback off the chat may use only that one transport, and nothing moves it off a relayed Iroh then: WebRTC\n * where the app has it, else the first transport it has (a Linux Desktop: WebKitGTK has no WebRTC), as before.\n */\nexport const AUTOMATIC_ORDER: readonly PairedTransport[] = [\"iroh/1\", \"webrtc/1\", \"hyperdht/1\"];\nexport function automaticTransport(available: readonly PairedTransport[], fallback = true): PairedTransport {\n if (!fallback) return available.includes(\"webrtc/1\") ? \"webrtc/1\" : TRANSPORTS.find(t => available.includes(t)) ?? \"webrtc/1\";\n return AUTOMATIC_ORDER.find(t => available.includes(t)) ?? \"webrtc/1\";\n}\n\nexport function transportOrder(available: readonly PairedTransport[], preferred: PairedTransport,\n fallback: boolean): PairedTransport[] {\n const rest = TRANSPORTS.filter(t => available.includes(t) && t !== preferred);\n return [...(available.includes(preferred) ? [preferred] : []), ...(fallback ? rest : [])];\n}\n"],"mappings":";;;;;;;AAGA,IAAM,eAAe;AACrB,IAAM,aAAa;AAEnB,SAAgB,wBAAoC;CAClD,OAAO,YAAY,UAAU;AAC/B;;;;;AAMA,SAAgB,QAAQ,WAAmB,KAAyB;CAClE,IAAI,IAAI,WAAW,YAAY,MAAM,IAAI,MAAM,uCAAuC;CACtF,MAAM,QAAQ,YAAY,YAAY;CACtC,MAAM,MAAM,iBAAiB,KAAK,KAAK,CAAC,CAAC,QAAQ,WAAW,SAAS,CAAC;CACtE,OAAO,SAAS,YAAY,OAAO,GAAG,CAAC;AACzC;;AAGA,SAAgB,aAAa,gBAAgC;CAC3D,OAAO,IAAI,KAAK,MAAM,KAAoB,kBAAkB,CAAC;AAC/D;AAEA,SAAgB,QAAQ,SAAiB,KAAyB;CAChE,IAAI,IAAI,WAAW,YAAY,MAAM,IAAI,MAAM,uCAAuC;CACtF,MAAM,WAAW,WAAW,OAAO;CACnC,IAAI,SAAS,SAAS,IAAkB,MAAM,IAAI,MAAM,+BAA+B;CACvF,MAAM,QAAQ,SAAS,SAAS,GAAG,YAAY;CAC/C,MAAM,MAAM,SAAS,SAAS,YAAY;CAC1C,OAAO,WAAW,iBAAiB,KAAK,KAAK,CAAC,CAAC,QAAQ,GAAG,CAAC;AAC7D;AAEA,SA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AAC,CAAC,CAAC,CACnE,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,QAAQ,CAAC,KAChC,MAAM,QAAQ,CAAC,IAAI,OAAO,QAAQ,CAAC,KAAM,MAAM,QAAQ,CAAC,IAAI,OAAO,QAAQ,CAAC,MAC7E,WAAW,QAAQ,CAAC,IAAI,WAAW,QAAQ,CAAC,CAAC;AACtD;;;;;;;;AASA,IAAa,kBAA8C;CAAC;CAAU;CAAY;AAAY;AAC9F,SAAgB,mBAAmB,WAAuC,WAAW,MAAuB;CAC1G,IAAI,CAAC,UAAU,OAAO,UAAU,SAAS,UAAU,IAAI,aAAa,WAAW,MAAK,MAAK,UAAU,SAAS,CAAC,CAAC,KAAK;CACnH,OAAO,gBAAgB,MAAK,MAAK,UAAU,SAAS,CAAC,CAAC,KAAK;AAC7D;AAEA,SAAgB,eAAe,WAAuC,WACpE,UAAsC;CACtC,MAAM,OAAO,WAAW,QAAO,MAAK,UAAU,SAAS,CAAC,KAAK,MAAM,SAAS;CAC5E,OAAO,CAAC,GAAI,UAAU,SAAS,SAAS,IAAI,CAAC,SAAS,IAAI,CAAC,GAAI,GAAI,WAAW,OAAO,CAAC,CAAE;AAC1F"}
package/dist/testing.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { n as decodeBolt11 } from "./bolt11-CRiQrma3.js";
2
- import { A as newIdentityBinding, C as emptyIdentityLedger, D as identityStatement, V as createIdentity, b as IdentityExchange, l as IDENTITY_MAX_EVIDENCE, n as isBitcoinAddress } from "./bitcoinAddress-C2MAmcDT.js";
2
+ import { A as newIdentityBinding, C as emptyIdentityLedger, D as identityStatement, b as IdentityExchange, en as createIdentity, l as IDENTITY_MAX_EVIDENCE, n as isBitcoinAddress } from "./bitcoinAddress-BbPG0DF7.js";
3
3
  import { l as providerDescriptorProblems, o as isNothingSpentError } from "./types-DbgC491n.js";
4
- import { i as verifyIdentity, r as descriptorProblems } from "./verify-CSo7-43-.js";
4
+ import { i as verifyIdentity, r as descriptorProblems } from "./verify-BoVhjvc_.js";
5
5
  import { _ as fakeAddress, a as fakeAccount, b as fakeOnchain, c as fakeKeySign, d as fakeRecord, f as fakeRecordText, g as TEST_PROVIDERS_FLAG, h as FakeOnchainProvider, i as TEST_IDENTITIES_FLAG, l as fakeKeySubject, m as FakeLightningProvider, n as FAKE_ISSUER, o as fakeAccountToken, p as testIdentitiesEnabled, r as FAKE_RECORD_HOST, s as fakeKey, t as FAKE_IDENTITY_PROVIDERS, u as fakeKeyring, v as fakeInvoice, x as testProvidersEnabled, y as fakeLightning } from "./fakes-Cgl1w4Nv.js";
6
6
  import { afterEach, describe, expect, it, vi } from "vitest";
7
7
  // ../browser/src/engine/paymentAdapters/providers/contractSuite.ts
@@ -28,6 +28,11 @@ export interface IdentityFetchOptions {
28
28
  maxBytes?: number;
29
29
  signal?: AbortSignal;
30
30
  redirect?: "follow" | "error";
31
+ /**
32
+ * A read of one of the profile's own Pkarr relays (a did:dht): read as the chats read them, http:// and a private
33
+ * address included, since the person chose them. Ignored for any other URL.
34
+ */
35
+ ownPkarrRelay?: boolean;
31
36
  }
32
37
  export interface IdentityFetchResponse {
33
38
  status: number;
@@ -0,0 +1,4 @@
1
+ export declare function setPkarrRelaySource(read: () => readonly string[] | undefined): void;
2
+ export declare function pkarrRelays(): string[];
3
+ /** Whether `url` is under one of the profile's Pkarr relays (`<relay>/…`). */
4
+ export declare function isOwnPkarrRelayUrl(url: URL): boolean;
@@ -15,9 +15,12 @@ export declare function availableSigners<E>(p: IdentityProofProvider<E>, platfor
15
15
  * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,
16
16
  * redirects refused unless asked for.
17
17
  * `online` false refuses everything (the person turned the network off).
18
+ * A did:dht read of the profile's own Pkarr relays (`ownPkarrRelay`) may be http://, through `relayFetcher`: those are
19
+ * the relays the person chose, as the chats read them, not an address a contact named.
18
20
  */
19
21
  export declare function boundedIdentityFetch(options?: {
20
22
  online: () => boolean;
21
23
  timeoutMs?: number;
22
24
  fetcher?: typeof fetch;
25
+ relayFetcher?: typeof fetch;
23
26
  }): IdentityFetch;
@@ -318,6 +318,11 @@ export declare class ChatFiles {
318
318
  private readonly moving;
319
319
  /** Files that stopped sending for the chat's window alone: they go on once another's bytes are confirmed. */
320
320
  private readonly held;
321
+ /**
322
+ * The entries not ended (`track`): what is still to come or under way is read from these, not from every file the
323
+ * 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.
324
+ */
325
+ private readonly unended;
321
326
  /**
322
327
  * Files this side cancelled while no session carried the cancel (`pf-abort`), said on the next one. The session also
323
328
  * goes for a moment when a move swaps it (its capabilities are agreed again): unsaid, the receiver showed the file
@@ -349,6 +354,12 @@ export declare class ChatFiles {
349
354
  /** What the contact said it can take, on this session. */
350
355
  get peerRoom(): number | null;
351
356
  records(): FileTransferRecord[];
357
+ /** Bytes still to come of the files taken here, not ended (one still asked about is not taken yet). */
358
+ stillToCome(): number;
359
+ /** A transfer under way: offered, moving, or being checked. */
360
+ underWay(): boolean;
361
+ /** Bytes of the files received here that were taken without asking and are kept (or on their way). */
362
+ takenUnasked(): number;
352
363
  get(direction: "in" | "out", id: string): FileTransferRecord | undefined;
353
364
  /** Bytes moved so far: confirmed by the receiver (sending), stored (receiving). */
354
365
  transferred(direction: "in" | "out", id: string): number;
@@ -356,6 +367,11 @@ export declare class ChatFiles {
356
367
  sent(id: string): number;
357
368
  private moved;
358
369
  private changed;
370
+ /**
371
+ * Keeps `unended` to the entries of this chat not ended. Each change of a record's state is reported (`changed`),
372
+ * so that is where a file that ended leaves it, and one taken or sent again comes back.
373
+ */
374
+ private track;
359
375
  private send;
360
376
  private sendData;
361
377
  /** A session that agreed files/3 is open: say what fits here, then offer again what is not finished. */
@@ -28,7 +28,9 @@
28
28
  * this script first, a declarative shadow root the page's script would make is refused, and with `VIEWER_GUARD_CSP`
29
29
  * a `javascript:` URL is refused (its own Trusted Types default policy; one passes every other string on as it is,
30
30
  * or, once the page made its own `default` policy, to that one's rules: the page's `createPolicy("default")` gets the
31
- * guard's policy back with them, and the copy of itself it puts in a `srcdoc` frame skips them).
31
+ * guard's policy back with them, and the copy of itself it puts in a `srcdoc` frame skips them);
32
+ * - starts a worker made from a `blob:` URL of the page's own from a script that makes a pass-through Trusted Types
33
+ * `default` policy in it first, as the WebRTC guard does (`VIEWER_GUARD_SCRIPT`, whichever of the two runs first).
32
34
  * A frame's window keeps what was run in it on its first, empty page when the page it loads is of the same origin (the
33
35
  * bridge's guard reaches the app's frame then): there this script only watches the new document. Each document it
34
36
  * watches is marked (`ghostlyClipboardGuard`, fixed in place): the bridge reads that to know the guard ran in the page
@@ -38,6 +40,6 @@
38
40
  * inside a shadow tree written in the HTML the page itself sends, is out of its sight.
39
41
  * No backslash, `${` or backtick in it.
40
42
  */
41
- export declare const CLIPBOARD_GUARD_SCRIPT = "(function noClipboardWrites(w) {\n \"use strict\";\n try {\n const apply = w.Reflect.apply;\n const describe = w.Object.getOwnPropertyDescriptor;\n const define = w.Object.defineProperty;\n const proto = w.Document.prototype;\n const home = w.document;\n const exec = describe(proto, \"execCommand\");\n const fresh = !!exec && exec.configurable === true && typeof exec.value === \"function\";\n const watched = !!describe(home, \"ghostlyClipboardGuard\");\n if (!fresh && watched) return;\n if (!watched) define(home, \"ghostlyClipboardGuard\", { value: true });\n const own = \"<script>(\" + noClipboardWrites + \")(window)<\" + \"/script>\";\n const close = \"<\" + \"/script>\";\n const webRtc = \"<script>(function noWebRtc(\";\n const text = w.String;\n const lower = text.prototype.toLowerCase;\n const slice = text.prototype.slice;\n const index = text.prototype.indexOf;\n const listen = w.EventTarget.prototype.addEventListener;\n const shut = (inner) => {\n try { if (inner && inner !== w) noClipboardWrites(inner); } catch (e) {}\n };\n const count = describe(w, \"length\").get;\n const view = describe(proto, \"defaultView\").get;\n const sweep = () => {\n try { for (let i = apply(count, w, []); i-- > 0;) shut(w[i]); } catch (e) {}\n };\n const elements = w.Element.prototype;\n const getAttribute = elements.getAttribute;\n const setAttribute = elements.setAttribute;\n const removeAttribute = elements.removeAttribute;\n const attachShadow = elements.attachShadow;\n const size = describe(w.NodeList.prototype, \"length\").get;\n let passing = false;\n const first = (frame) => {\n const doc = apply(getAttribute, frame, [\"srcdoc\"]);\n if (doc === null) return;\n let at = 0;\n if (apply(slice, doc, [0, webRtc.length]) === webRtc) {\n const end = apply(index, doc, [close]);\n if (end >= 0) at = end + close.length;\n }\n if (apply(slice, doc, [at, at + own.length]) === own) return;\n passing = true;\n try { apply(setAttribute, frame, [\"srcdoc\", own + doc]); } catch (e) { apply(removeAttribute, frame, [\"srcdoc\"]); }\n passing = false;\n };\n const Observer = w.MutationObserver;\n const observe = Observer.prototype.observe;\n const watch = (root, all) => {\n const scan = () => {\n try {\n const frames = apply(all, root, [\"iframe[srcdoc]\"]);\n for (let i = apply(size, frames, []); i-- > 0;) first(frames[i]);\n } catch (e) {}\n sweep();\n };\n apply(observe, new Observer(scan), [root, { subtree: true, childList: true, attributes: true, attributeFilter: [\"srcdoc\"] }]);\n apply(listen, root, [\"load\", sweep, true]);\n scan();\n return root;\n };\n if (fresh) {\n const run = exec.value;\n const phase = describe(w.Event.prototype, \"eventPhase\").get;\n const trust = (event) => {\n try {\n const found = describe(event, \"isTrusted\");\n if (found && found.get && apply(found.get, event, []) === true) return found.get;\n } catch (e) {}\n return null;\n };\n const dispatching = (event, trusted) => {\n try { return apply(trusted, event, []) === true && apply(phase, event, []) !== 0; } catch (e) { return false; }\n };\n const stamp = describe(w.Event.prototype, \"timeStamp\");\n const clock = w.performance;\n const tick = clock && clock.now;\n const time = () => { try { return apply(tick, clock, []); } catch (e) { return NaN; } };\n const recent = (at) => time() - at <= 1000;\n const shutters = [];\n try {\n const channel = new w.MessageChannel();\n const post = w.MessagePort.prototype.postMessage;\n const out = channel.port2;\n channel.port1.onmessage = () => settle();\n shutters[0] = () => apply(post, out, [0]);\n } catch (e) {}\n try {\n const tasks = w.scheduler;\n const postTask = tasks && tasks.postTask;\n const urgent = { __proto__: null, priority: \"user-blocking\" };\n if (typeof postTask === \"function\") shutters[shutters.length] = () => { apply(postTask, tasks, [settle, urgent]); };\n } catch (e) {}\n try {\n const frame = w.requestAnimationFrame;\n if (typeof frame === \"function\") shutters[shutters.length] = () => { apply(frame, w, [settle]); };\n } catch (e) {}\n let tap = null;\n let trusted = null;\n let tapped = NaN;\n let open = 0;\n let follows = null;\n const settle = () => { open = 0; follows = null; };\n const seen = (event) => {\n const found = trust(event);\n if (found === null) return;\n let at = time();\n try {\n const given = apply(stamp.get, event, []);\n if (given >= 0 && given < at) at = given;\n } catch (e) {}\n tap = event;\n trusted = found;\n tapped = at;\n if (shutters.length === 0) return;\n open = 1;\n for (let i = 0; i < shutters.length; i++) { try { shutters[i](); } catch (e) {} }\n };\n const taps = [\"pointerdown\", \"pointerup\", \"mousedown\", \"mouseup\", \"click\", \"auxclick\", \"dblclick\", \"contextmenu\", \"touchstart\", \"touchend\", \"keydown\", \"keypress\", \"keyup\"];\n for (let i = 0; i < taps.length; i++) apply(listen, w, [taps[i], seen, true]);\n const followed = (event) => {\n if (open === 0) return;\n const found = trust(event);\n if (found !== null) follows = { event: event, trusted: found, at: tapped, next: follows };\n };\n apply(listen, w, [\"submit\", followed, true]);\n apply(listen, w, [\"change\", followed, true]);\n const tapping = () => {\n if (tap !== null && dispatching(tap, trusted) && recent(tapped)) return true;\n for (let f = follows; f !== null; f = f.next) if (dispatching(f.event, f.trusted) && recent(f.at)) return true;\n return false;\n };\n const guarded = function execCommand(command) {\n const name = apply(lower, text(command), []);\n if (name === \"paste\" || ((name === \"copy\" || name === \"cut\") && !tapping())) return false;\n const args = [name];\n for (let i = 1; i < arguments.length; i++) args[i] = arguments[i];\n return apply(run, this, args);\n };\n define(proto, \"execCommand\", { value: guarded, writable: false, enumerable: exec.enumerable, configurable: false });\n const types = w.trustedTypes;\n if (types && !types.defaultPolicy) {\n try {\n let rules = null;\n const rule = (kind) => (input, type, sink) => {\n if (kind === \"createScript\" && sink === \"Location href\") return null;\n if (passing || rules === null) return input;\n return rules[kind] ? apply(rules[kind], undefined, [input, type, sink]) : null;\n };\n const members = [\"createHTML\", \"createScript\", \"createScriptURL\"];\n const create = types.createPolicy;\n const policy = apply(create, types, [\"default\", { createHTML: rule(members[0]), createScript: rule(members[1]), createScriptURL: rule(members[2]) }]);\n const Mistyped = w.TypeError;\n w.Object.getPrototypeOf(types).createPolicy = function createPolicy(name, options) {\n if (this !== types || rules !== null || text(name) !== \"default\") return apply(create, this, arguments);\n const given = { createHTML: null, createScript: null, createScriptURL: null };\n for (let i = 0; i < members.length; i++) {\n const found = options ? options[members[i]] : undefined;\n if (found === undefined || found === null) continue;\n if (typeof found !== \"function\") throw new Mistyped(\"The policy's \" + members[i] + \" is not a function\");\n given[members[i]] = found;\n }\n rules = given;\n return policy;\n };\n } catch (e) {}\n }\n const reopen = proto.open;\n proto.open = function () {\n const got = apply(reopen, this, arguments);\n try { if (apply(view, this, []) === w) apply(listen, this, [\"load\", sweep, true]); } catch (e) {}\n return got;\n };\n const shadowed = (html) => apply(index, apply(lower, html, []), [\"shadowrootmode\"]) >= 0;\n const Refused = w.TypeError;\n const refuse = () => { throw new Refused(\"A declarative shadow root is not allowed here\"); };\n const parsers = [[elements, \"setHTMLUnsafe\"], [w.ShadowRoot && w.ShadowRoot.prototype, \"setHTMLUnsafe\"], [w.Document, \"parseHTMLUnsafe\"]];\n for (let i = 0; i < parsers.length; i++) {\n const owner = parsers[i][0];\n const name = parsers[i][1];\n const real = owner && owner[name];\n if (typeof real !== \"function\") continue;\n owner[name] = function (html) {\n const checked = text(html);\n if (shadowed(checked)) refuse();\n return apply(real, this, arguments.length > 1 ? [checked, arguments[1]] : [checked]);\n };\n }\n let tail = \"\";\n const writes = [\"write\", \"writeln\"];\n for (let i = 0; i < writes.length; i++) {\n const real = proto[writes[i]];\n if (typeof real !== \"function\") continue;\n proto[writes[i]] = function () {\n let checked = \"\";\n for (let j = 0; j < arguments.length; j++) checked += text(arguments[j]);\n if (shadowed(tail + checked)) refuse();\n tail = apply(slice, tail + checked, [-16]);\n return apply(real, this, [checked]);\n };\n }\n const kinds = [\"HTMLIFrameElement\", \"HTMLFrameElement\", \"HTMLObjectElement\", \"HTMLEmbedElement\"];\n const reads = [\"contentWindow\", \"contentDocument\", \"getSVGDocument\"];\n for (let k = 0; k < kinds.length; k++) {\n const owner = w[kinds[k]] && w[kinds[k]].prototype;\n for (let r = 0; r < reads.length; r++) {\n const name = reads[r];\n const found = owner && describe(owner, name);\n const key = found && found.get ? \"get\" : \"value\";\n if (!found || typeof found[key] !== \"function\") continue;\n const read = found[key];\n found[key] = function () {\n const got = apply(read, this, arguments);\n try { shut(name === \"contentWindow\" ? got : apply(view, got, [])); } catch (e) {}\n return got;\n };\n try { define(owner, name, found); } catch (e) {}\n }\n }\n const inShadow = w.DocumentFragment.prototype.querySelectorAll;\n if (attachShadow) {\n elements.attachShadow = function () {\n const root = apply(attachShadow, this, arguments);\n try { watch(root, inShadow); } catch (e) {}\n return root;\n };\n }\n }\n if (!watched) watch(home, proto.querySelectorAll);\n } catch (e) {}\n})(window)";
43
+ export declare const CLIPBOARD_GUARD_SCRIPT = "(function noClipboardWrites(w) {\n \"use strict\";\n try {\n const apply = w.Reflect.apply;\n const describe = w.Object.getOwnPropertyDescriptor;\n const define = w.Object.defineProperty;\n const proto = w.Document.prototype;\n const home = w.document;\n const exec = describe(proto, \"execCommand\");\n const fresh = !!exec && exec.configurable === true && typeof exec.value === \"function\";\n const watched = !!describe(home, \"ghostlyClipboardGuard\");\n if (!fresh && watched) return;\n if (!watched) define(home, \"ghostlyClipboardGuard\", { value: true });\n const own = \"<script>(\" + noClipboardWrites + \")(window)<\" + \"/script>\";\n const close = \"<\" + \"/script>\";\n const webRtc = \"<script>(function noWebRtc(\";\n const text = w.String;\n const lower = text.prototype.toLowerCase;\n const slice = text.prototype.slice;\n const index = text.prototype.indexOf;\n const listen = w.EventTarget.prototype.addEventListener;\n const shut = (inner) => {\n try { if (inner && inner !== w) noClipboardWrites(inner); } catch (e) {}\n };\n const count = describe(w, \"length\").get;\n const view = describe(proto, \"defaultView\").get;\n const sweep = () => {\n try { for (let i = apply(count, w, []); i-- > 0;) shut(w[i]); } catch (e) {}\n };\n const elements = w.Element.prototype;\n const getAttribute = elements.getAttribute;\n const setAttribute = elements.setAttribute;\n const removeAttribute = elements.removeAttribute;\n const attachShadow = elements.attachShadow;\n const size = describe(w.NodeList.prototype, \"length\").get;\n let passing = false;\n const first = (frame) => {\n const doc = apply(getAttribute, frame, [\"srcdoc\"]);\n if (doc === null) return;\n let at = 0;\n if (apply(slice, doc, [0, webRtc.length]) === webRtc) {\n const end = apply(index, doc, [close]);\n if (end >= 0) at = end + close.length;\n }\n if (apply(slice, doc, [at, at + own.length]) === own) return;\n passing = true;\n try { apply(setAttribute, frame, [\"srcdoc\", own + doc]); } catch (e) { apply(removeAttribute, frame, [\"srcdoc\"]); }\n passing = false;\n };\n const Observer = w.MutationObserver;\n const observe = Observer.prototype.observe;\n const watch = (root, all) => {\n const scan = () => {\n try {\n const frames = apply(all, root, [\"iframe[srcdoc]\"]);\n for (let i = apply(size, frames, []); i-- > 0;) first(frames[i]);\n } catch (e) {}\n sweep();\n };\n apply(observe, new Observer(scan), [root, { subtree: true, childList: true, attributes: true, attributeFilter: [\"srcdoc\"] }]);\n apply(listen, root, [\"load\", sweep, true]);\n scan();\n return root;\n };\n if (fresh) {\n const run = exec.value;\n const phase = describe(w.Event.prototype, \"eventPhase\").get;\n const trust = (event) => {\n try {\n const found = describe(event, \"isTrusted\");\n if (found && found.get && apply(found.get, event, []) === true) return found.get;\n } catch (e) {}\n return null;\n };\n const dispatching = (event, trusted) => {\n try { return apply(trusted, event, []) === true && apply(phase, event, []) !== 0; } catch (e) { return false; }\n };\n const stamp = describe(w.Event.prototype, \"timeStamp\");\n const clock = w.performance;\n const tick = clock && clock.now;\n const time = () => { try { return apply(tick, clock, []); } catch (e) { return NaN; } };\n const recent = (at) => time() - at <= 1000;\n const shutters = [];\n try {\n const channel = new w.MessageChannel();\n const post = w.MessagePort.prototype.postMessage;\n const out = channel.port2;\n channel.port1.onmessage = () => settle();\n shutters[0] = () => apply(post, out, [0]);\n } catch (e) {}\n try {\n const tasks = w.scheduler;\n const postTask = tasks && tasks.postTask;\n const urgent = { __proto__: null, priority: \"user-blocking\" };\n if (typeof postTask === \"function\") shutters[shutters.length] = () => { apply(postTask, tasks, [settle, urgent]); };\n } catch (e) {}\n try {\n const frame = w.requestAnimationFrame;\n if (typeof frame === \"function\") shutters[shutters.length] = () => { apply(frame, w, [settle]); };\n } catch (e) {}\n let tap = null;\n let trusted = null;\n let tapped = NaN;\n let open = 0;\n let follows = null;\n const settle = () => { open = 0; follows = null; };\n const seen = (event) => {\n const found = trust(event);\n if (found === null) return;\n let at = time();\n try {\n const given = apply(stamp.get, event, []);\n if (given >= 0 && given < at) at = given;\n } catch (e) {}\n tap = event;\n trusted = found;\n tapped = at;\n if (shutters.length === 0) return;\n open = 1;\n for (let i = 0; i < shutters.length; i++) { try { shutters[i](); } catch (e) {} }\n };\n const taps = [\"pointerdown\", \"pointerup\", \"mousedown\", \"mouseup\", \"click\", \"auxclick\", \"dblclick\", \"contextmenu\", \"touchstart\", \"touchend\", \"keydown\", \"keypress\", \"keyup\"];\n for (let i = 0; i < taps.length; i++) apply(listen, w, [taps[i], seen, true]);\n const followed = (event) => {\n if (open === 0) return;\n const found = trust(event);\n if (found !== null) follows = { event: event, trusted: found, at: tapped, next: follows };\n };\n apply(listen, w, [\"submit\", followed, true]);\n apply(listen, w, [\"change\", followed, true]);\n const tapping = () => {\n if (tap !== null && dispatching(tap, trusted) && recent(tapped)) return true;\n for (let f = follows; f !== null; f = f.next) if (dispatching(f.event, f.trusted) && recent(f.at)) return true;\n return false;\n };\n const guarded = function execCommand(command) {\n const name = apply(lower, text(command), []);\n if (name === \"paste\" || ((name === \"copy\" || name === \"cut\") && !tapping())) return false;\n const args = [name];\n for (let i = 1; i < arguments.length; i++) args[i] = arguments[i];\n return apply(run, this, args);\n };\n define(proto, \"execCommand\", { value: guarded, writable: false, enumerable: exec.enumerable, configurable: false });\n const types = w.trustedTypes;\n if (types && !types.defaultPolicy) {\n try {\n let rules = null;\n const rule = (kind) => (input, type, sink) => {\n if (kind === \"createScript\" && sink === \"Location href\") return null;\n if (passing || rules === null) return input;\n return rules[kind] ? apply(rules[kind], undefined, [input, type, sink]) : null;\n };\n const members = [\"createHTML\", \"createScript\", \"createScriptURL\"];\n const create = types.createPolicy;\n const policy = apply(create, types, [\"default\", { createHTML: rule(members[0]), createScript: rule(members[1]), createScriptURL: rule(members[2]) }]);\n const Mistyped = w.TypeError;\n w.Object.getPrototypeOf(types).createPolicy = function createPolicy(name, options) {\n if (this !== types || rules !== null || text(name) !== \"default\") return apply(create, this, arguments);\n const given = { createHTML: null, createScript: null, createScriptURL: null };\n for (let i = 0; i < members.length; i++) {\n const found = options ? options[members[i]] : undefined;\n if (found === undefined || found === null) continue;\n if (typeof found !== \"function\") throw new Mistyped(\"The policy's \" + members[i] + \" is not a function\");\n given[members[i]] = found;\n }\n rules = given;\n return policy;\n };\n } catch (e) {}\n }\n if (types && w.URL && w.Blob && !describe(w, \"ghostlyWorkerGuard\")) {\n try {\n define(w, \"ghostlyWorkerGuard\", { value: true });\n const construct = w.Reflect.construct;\n const json = w.JSON.stringify;\n const later = w.setTimeout;\n const Blob = w.Blob;\n const sized = describe(Blob.prototype, \"size\").get;\n const make = w.URL.createObjectURL;\n const revoke = w.URL.revokeObjectURL;\n const policy = \"if (self.trustedTypes && !self.trustedTypes.defaultPolicy) { try { self.trustedTypes.createPolicy('default', { createHTML: (s) => s, createScript: (s) => s, createScriptURL: (s) => s }); } catch (e) {} }\";\n const script = (code) => apply(make, null, [new Blob([code], { type: \"text/javascript\" })]);\n const known = { __proto__: null };\n let first = null;\n w.URL.createObjectURL = function createObjectURL(object) {\n const made = apply(make, this, arguments);\n try { apply(sized, object, []); known[made] = { blob: object, inner: null, classic: null, module: null }; } catch (e) {}\n return made;\n };\n w.URL.revokeObjectURL = function revokeObjectURL(url) {\n try {\n const key = text(url);\n const entry = known[key];\n if (entry) {\n delete known[key];\n const ours = [entry.inner, entry.classic, entry.module];\n apply(later, w, [() => { for (let i = 0; i < 3; i++) { if (ours[i] !== null) apply(revoke, null, [ours[i]]); } }, 60000]);\n }\n } catch (e) {}\n return apply(revoke, this, arguments);\n };\n const start = (url, options) => {\n const entry = known[text(url)];\n if (!entry) return url;\n const kind = options && typeof options === \"object\" && options.type === \"module\" ? \"module\" : \"classic\";\n if (entry[kind] === null) {\n if (entry.inner === null) entry.inner = apply(make, null, [entry.blob]);\n if (kind === \"module\" && first === null) first = script(policy);\n entry[kind] = script(kind === \"module\" ? \"import \" + json(first) + \"; import \" + json(entry.inner) + \";\" : policy + \" importScripts(\" + json(entry.inner) + \");\");\n }\n return entry[kind];\n };\n const makers = [\"Worker\", \"SharedWorker\"];\n for (let i = 0; i < makers.length; i++) {\n const Real = w[makers[i]];\n if (typeof Real !== \"function\") continue;\n const started = function (url) {\n if (new.target === undefined) return apply(Real, this, arguments);\n const args = [];\n for (let j = 0; j < arguments.length; j++) args[j] = arguments[j];\n if (args.length > 0) { try { args[0] = start(url, args[1]); } catch (e) {} }\n return construct(Real, args, new.target);\n };\n define(started, \"name\", { value: makers[i] });\n started.prototype = Real.prototype;\n define(Real.prototype, \"constructor\", { value: started, writable: true, enumerable: false, configurable: true });\n w[makers[i]] = started;\n }\n } catch (e) {}\n }\n const reopen = proto.open;\n proto.open = function () {\n const got = apply(reopen, this, arguments);\n try { if (apply(view, this, []) === w) apply(listen, this, [\"load\", sweep, true]); } catch (e) {}\n return got;\n };\n const shadowed = (html) => apply(index, apply(lower, html, []), [\"shadowrootmode\"]) >= 0;\n const Refused = w.TypeError;\n const refuse = () => { throw new Refused(\"A declarative shadow root is not allowed here\"); };\n const parsers = [[elements, \"setHTMLUnsafe\"], [w.ShadowRoot && w.ShadowRoot.prototype, \"setHTMLUnsafe\"], [w.Document, \"parseHTMLUnsafe\"]];\n for (let i = 0; i < parsers.length; i++) {\n const owner = parsers[i][0];\n const name = parsers[i][1];\n const real = owner && owner[name];\n if (typeof real !== \"function\") continue;\n owner[name] = function (html) {\n const checked = text(html);\n if (shadowed(checked)) refuse();\n return apply(real, this, arguments.length > 1 ? [checked, arguments[1]] : [checked]);\n };\n }\n let tail = \"\";\n const writes = [\"write\", \"writeln\"];\n for (let i = 0; i < writes.length; i++) {\n const real = proto[writes[i]];\n if (typeof real !== \"function\") continue;\n proto[writes[i]] = function () {\n let checked = \"\";\n for (let j = 0; j < arguments.length; j++) checked += text(arguments[j]);\n if (shadowed(tail + checked)) refuse();\n tail = apply(slice, tail + checked, [-16]);\n return apply(real, this, [checked]);\n };\n }\n const kinds = [\"HTMLIFrameElement\", \"HTMLFrameElement\", \"HTMLObjectElement\", \"HTMLEmbedElement\"];\n const reads = [\"contentWindow\", \"contentDocument\", \"getSVGDocument\"];\n for (let k = 0; k < kinds.length; k++) {\n const owner = w[kinds[k]] && w[kinds[k]].prototype;\n for (let r = 0; r < reads.length; r++) {\n const name = reads[r];\n const found = owner && describe(owner, name);\n const key = found && found.get ? \"get\" : \"value\";\n if (!found || typeof found[key] !== \"function\") continue;\n const read = found[key];\n found[key] = function () {\n const got = apply(read, this, arguments);\n try { shut(name === \"contentWindow\" ? got : apply(view, got, [])); } catch (e) {}\n return got;\n };\n try { define(owner, name, found); } catch (e) {}\n }\n }\n const inShadow = w.DocumentFragment.prototype.querySelectorAll;\n if (attachShadow) {\n elements.attachShadow = function () {\n const root = apply(attachShadow, this, arguments);\n try { watch(root, inShadow); } catch (e) {}\n return root;\n };\n }\n }\n if (!watched) watch(home, proto.querySelectorAll);\n } catch (e) {}\n})(window)";
42
44
  /** `CLIPBOARD_GUARD_SCRIPT`'s hash, as a CSP source: the bridge's policy and a contact's own are given it. */
43
- export declare const CLIPBOARD_GUARD_HASH = "'sha256-ay9kpYD2BIflB8W9w+iAbo1krsFBwIJunUmXTACfhao='";
45
+ export declare const CLIPBOARD_GUARD_HASH = "'sha256-D8U3zSg1xP77RbZuV/DekRuM6nx80gIN5mh2TQAtZ40='";
@@ -7,6 +7,8 @@ import { type DhtFileAnnouncement, type DhtFileElement, type DhtFileOffer } from
7
7
  export type DeliveryMode = "stream" | "dht";
8
8
  export declare const DHT_TEXT_BYTES = 256;
9
9
  export declare const DHT_MESSAGE_TTL: number;
10
+ export declare const DHT_TEXT_TOO_LONG = "DHT text is limited to 256 UTF-8 bytes. Shorten it or choose a live connection.";
11
+ export declare const DHT_PACKET_BUDGET = "Text and authentication exceed the DHT packet budget. Shorten the message.";
10
12
  /**
11
13
  * How far apart two devices' clocks may be for an envelope's expiry: a reader takes one until this long after `expires`
12
14
  * 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
@@ -208,6 +210,8 @@ export declare class DhtDelivery {
208
210
  * one any more), not at the next keep-alive four minutes on. Any envelope that goes out replaces it.
209
211
  */
210
212
  private withdrawal?;
213
+ /** When the last withdrawal's envelope went (its `lastPublish`), for `withdrawalWaits`. */
214
+ private withdrewAt;
211
215
  /** The sequence of the last envelope of the contact that was past its expiry (traced once). */
212
216
  private expiredSeen;
213
217
  private controlDue;
@@ -249,6 +253,8 @@ export declare class DhtDelivery {
249
253
  private namedRev?;
250
254
  /** A reaction of this side waits to ride on an envelope, or the contact's reactions wait to be said taken. */
251
255
  private reactionsDue;
256
+ /** The text on the floor whose envelope left the reactions no room (its id): they wait for the ones its backoff publishes. */
257
+ private crowdedBy?;
252
258
  constructor(options: {
253
259
  params: LinkParams;
254
260
  mode: DeliveryMode;
@@ -462,8 +468,17 @@ export declare class DhtDelivery {
462
468
  * one's place on the relays, so a contact who looks later finds no text. Resolves once the state without it is saved;
463
469
  * the new envelope goes after. One that does not go (no relay reachable) is tried again within seconds (`withdrawal`):
464
470
  * a reader takes the withdrawn envelope until its expiry and the clock skew allowed past it (`DHT_EXPIRY_SKEW_MS`).
471
+ * It goes at once, spacing or not: the deleted text is out of reach from then on. The text that takes the floor next
472
+ * waits out the spacing instead (`withdrawalWaits`).
465
473
  */
466
474
  withdraw(wireId: string): Promise<void>;
475
+ /**
476
+ * The last envelope was a withdrawal's, inside the publication spacing: the text that takes the floor now goes once
477
+ * the spacing allows (`schedule`), not in an envelope of its own at once. Deleted then, it never went, so it costs
478
+ * no withdrawal: deleting 10 texts queued for an away contact one after the other, each one's withdrawal and the next
479
+ * text's envelope put 10 envelopes on every relay in under 2 s, each replaced a moment later (bug hunt, 2026-11-15).
480
+ */
481
+ private withdrawalWaits;
467
482
  /** The id of what awaits its receipt on the floor now, if anything does. */
468
483
  get pendingId(): string | undefined;
469
484
  /**
@@ -488,6 +503,11 @@ export declare class DhtDelivery {
488
503
  private publish;
489
504
  /** The contact is pinned and this side's envelope in the invite's mailbox is still unsealed (`unsealedOut`). */
490
505
  private get resealDue();
506
+ /**
507
+ * Reactions due (`reactionsDue`) that force an envelope of their own: not while the text that left them no room
508
+ * (`crowdedBy`) is still retried, or each publication spends one of its attempts 4 s apart instead of at its backoff.
509
+ */
510
+ private get reactionsPress();
491
511
  /**
492
512
  * The relays' request budget held the envelope back: nothing went out, so it was no attempt (a text keeps its eight),
493
513
  * and what it carried (a text, a receipt, a new mode) goes the moment the budget frees a request: the text and the
@@ -85,5 +85,6 @@ export declare function decodeDnsResponse(data: Uint8Array, name: string, type:
85
85
  /** The TXT character-strings of one record, joined as RFC 7208 §3.3 does. */
86
86
  export declare function txtValue(rdata: Uint8Array): string;
87
87
  /** False for loopback, private, link-local, shared (CGNAT), multicast, reserved
88
- * and unspecified addresses, including IPv4 embedded in IPv6. */
88
+ * and unspecified addresses, including IPv4 embedded in IPv6, and for 6to4, Teredo and documentation IPv6, as
89
+ * Desktop's link_preview::is_public and apps/ui/src/lib/localHost.ts refuse them. */
89
90
  export declare function isPublicAddress(address: Uint8Array): boolean;
@@ -230,6 +230,25 @@ export declare const MESSAGE_RECEIVE_LIMITS: {
230
230
  readonly hourly: 1800;
231
231
  readonly hourWindowMs: 3600000;
232
232
  };
233
+ /** What `sendMessage` says of a text the contact's windows have no room for yet: it did not go (`MessagePace`). */
234
+ export declare const MESSAGE_PACED = "Your contact takes a limited number of texts at a time. It goes by itself once they can take more.";
235
+ /**
236
+ * The texts this side sent on a paired session, counted against the contact's windows (`MESSAGE_RECEIVE_LIMITS`), so
237
+ * none goes that the contact would refuse. A refused text went unconfirmed and came again with the outbox's backoff,
238
+ * after texts written later that found room meanwhile: the contact read them out of order. Past the hour's total it
239
+ * was sent until its attempts ran out, well inside the hour, and ended failed. Each counts from its receipt, the latest
240
+ * the contact can have taken it: counted from its send, a frame that sat in a queue was taken later than counted.
241
+ */
242
+ export declare class MessagePace {
243
+ private readonly now;
244
+ private sent;
245
+ constructor(now?: () => number);
246
+ /** The contact's windows have room for one more text now. */
247
+ room(): boolean;
248
+ took(id: string): void;
249
+ /** Its receipt came: the contact counted it by now. */
250
+ answered(id: string): void;
251
+ }
233
252
  /**
234
253
  * A `paired-message` frame. The preview (`pv`) is left out when the frame would pass `MAX_PAIRED_MESSAGE_FRAME`
235
254
  * with it: the text matters, the card does not. A reply (`r`, WISP 401 § Replies) is a few hundred bytes at most
@@ -818,6 +837,8 @@ export declare class GhostLink {
818
837
  private readonly editsReceived;
819
838
  /** Text frames the contact may send per window (`MESSAGE_RECEIVE_LIMITS`); the rest go unconfirmed and come again. */
820
839
  private readonly messagesReceived;
840
+ /** The texts sent to the contact, against their `messagesReceived` (`MessagePace`). */
841
+ private readonly messagesSent;
821
842
  /** Call signals the contact may send per window; the rest are dropped. */
822
843
  private readonly callsReceived;
823
844
  /** WebRTC signals the contact may send on the session (`paired-rtc`) per window; the rest are dropped. */
@@ -1082,6 +1103,8 @@ export declare class GhostLink {
1082
1103
  private get sessionBlocked();
1083
1104
  validateText(text: string, timestamp: number, id: string, reply?: WireReply): string | null;
1084
1105
  get canSendText(): boolean;
1106
+ /** A text on the live session would find room in the contact's windows now (`MessagePace`); the DHT floor has its own pace. */
1107
+ get textRoom(): boolean;
1085
1108
  get dhtDelivery(): DhtDeliveryView | undefined;
1086
1109
  /** The chat is on screen: on the DHT its mailbox is read at the signaling pace (WISP 403, poll pace). */
1087
1110
  setChatActive(active: boolean): void;
@@ -1684,6 +1707,13 @@ export declare class GhostLink {
1684
1707
  sendEdit(edit: WireEdit, { dht }?: {
1685
1708
  dht?: boolean;
1686
1709
  }): Promise<string | null>;
1710
+ /**
1711
+ * Why the DHT floor can never carry this edit, or null (WISP 403 § Edits): it goes there as a text with the edit's
1712
+ * element, which must fit the packet once sealed, as a text must (`validateText`). One past the 256 bytes never fits
1713
+ * it either, and says so with the same reason. Null off the floor, and for what only makes it wait there (a text
1714
+ * awaiting its receipt): that one goes in its turn.
1715
+ */
1716
+ dhtEditTooBig(edit: WireEdit): string | null;
1687
1717
  /** Confirms an edit of the contact's that waited for its message (`onMessageEdit` returned false). */
1688
1718
  confirmEdit(id: string, e: number): void;
1689
1719
  /**
@@ -54,3 +54,59 @@ export declare function verifyGroupCallRequest(raw: unknown, sfu: string, now: n
54
54
  ok: false;
55
55
  reason: GroupCallRefusal;
56
56
  };
57
+ /**
58
+ * An admin's request to act on a member in its group's call (WISP 602 · Group Calls § Moderation): what it sends to
59
+ * `POST <sfu>/sfu/group-moderate`, signed by its group key over the node's origin as a token request is, under its own
60
+ * tag, so neither request can stand for the other.
61
+ *
62
+ * {"v":1,"g":"<group>","k":"<admin key>","room":"g_<group>","act":"mute","target":"<member key>","src":["microphone"],
63
+ * "ts":1794700800,"n":"<nonce>","sig":"…"}
64
+ *
65
+ * `mute` takes `src` away from `target`, `allow` gives it back, `remove` takes `target` out of the call and keeps it
66
+ * out, `unban` lets it back in, and `state` changes nothing (the reply says who is muted and banned). Whether `k` is
67
+ * the group's admin is the node's to say, from its roster.
68
+ */
69
+ /** What an admin can take from a member, in the sorted order a request lists them in. */
70
+ export declare const GROUP_CALL_SOURCES: readonly ["camera", "microphone", "screen_share"];
71
+ export type GroupCallSource = (typeof GROUP_CALL_SOURCES)[number];
72
+ export declare const GROUP_CALL_MODERATION_ACTS: readonly ["mute", "allow", "remove", "unban", "state"];
73
+ export type GroupCallModerationAct = (typeof GROUP_CALL_MODERATION_ACTS)[number];
74
+ export interface GroupCallModeration {
75
+ v: typeof GROUP_CALL_VERSION;
76
+ g: string;
77
+ k: string;
78
+ room: string;
79
+ act: GroupCallModerationAct;
80
+ /** The member acted on; `""` for `state`. */
81
+ target: string;
82
+ /** Non-empty, unique and sorted for `mute` and `allow`; empty for the other acts. */
83
+ src: GroupCallSource[];
84
+ ts: number;
85
+ n: string;
86
+ sig: string;
87
+ }
88
+ /** Exactly the bytes an admin signs: the array form, as the token request's. */
89
+ export declare const groupCallModerationBytes: (sfu: string, g: string, room: string, k: string, act: GroupCallModerationAct, target: string, src: readonly GroupCallSource[], ts: number, n: string) => Uint8Array<ArrayBufferLike>;
90
+ /** A moderation request for `sfu`, signed by the admin's group key `seed`; `src` is listed unique and sorted. */
91
+ export declare function signGroupCallModeration(input: {
92
+ sfu: string;
93
+ g: string;
94
+ act: GroupCallModerationAct;
95
+ target?: string;
96
+ src?: readonly GroupCallSource[];
97
+ ts?: number;
98
+ n?: string;
99
+ }, seed: Uint8Array): GroupCallModeration;
100
+ /**
101
+ * The node's checks of a moderation request but the roster, in order: the shape (a known act, a `target` that is a
102
+ * member key other than `k`, or `""` for `state`, and `src` as the act takes it), the time within `GROUP_CALL_SKEW_S`
103
+ * of `now` (ms), a nonce not in `seen`, and the signature over the node's own origin `sfu`. A request that passes has
104
+ * its nonce added to `seen`; entries older than `GROUP_CALL_NONCE_S` are dropped on the way.
105
+ */
106
+ export declare function verifyGroupCallModeration(raw: unknown, sfu: string, now: number, seen: GroupCallNonces): {
107
+ ok: true;
108
+ request: GroupCallModeration;
109
+ } | {
110
+ ok: false;
111
+ reason: GroupCallRefusal;
112
+ };
@@ -594,7 +594,8 @@ export declare class CommunitySession {
594
594
  private adminSeen;
595
595
  /**
596
596
  * After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
597
- * one of theirs I signed again (what I held then, until one of theirs comes). In memory only.
597
+ * one of theirs I signed again (what I held then, until one of theirs comes). `vouched`: the latest of theirs another
598
+ * member's sync said it holds; `held`: the latest of theirs no other member has shown it holds yet. In memory only.
598
599
  */
599
600
  private takeover;
600
601
  /** The store's frames the app holds with their messages (`storeKey` → message id): in memory here, not in what is saved. */
@@ -1158,6 +1159,19 @@ export declare class CommunitySession {
1158
1159
  * be refused for good: a rename of theirs, or a member back from away, would then lose the group's call node.
1159
1160
  */
1160
1161
  private takesOver;
1162
+ /**
1163
+ * Whether a statement I would take (`takesOver`) was on its way when the role moved, as far as I can tell: a member
1164
+ * other than its signer handed it to me (a hub's relay included), or said in a sync it holds that one or a later one
1165
+ * under the same commit. The former admin alone could sign new ones after the hand-over, each taken for the whole group.
1166
+ */
1167
+ private vouches;
1168
+ /** The former admin's statement nobody else has shown it holds: the latest is kept until a sync does (`vouch`). */
1169
+ private holdTaken;
1170
+ /**
1171
+ * A member's sync names the statement it holds: one signed under a commit of the admin before me, by another member
1172
+ * than them, vouches for theirs up to it, and the one held is taken if it now is.
1173
+ */
1174
+ private vouch;
1161
1175
  /**
1162
1176
  * The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
1163
1177
  * value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
@@ -513,7 +513,8 @@ export declare class GroupSession {
513
513
  private adminSeen;
514
514
  /**
515
515
  * After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
516
- * one of theirs I signed again (what I held then, until one of theirs comes). In memory only.
516
+ * one of theirs I signed again (what I held then, until one of theirs comes). `vouched`: the latest of theirs another
517
+ * member's sync said it holds; `held`: the latest of theirs no other member has shown it holds yet. In memory only.
517
518
  */
518
519
  private takeover;
519
520
  /** While `handle` runs: the frames it took that a hub passes on (`handle`'s result). */
@@ -1058,6 +1059,19 @@ export declare class GroupSession {
1058
1059
  * be refused for good: their next rename, picture or hubs change would then be built on the older body.
1059
1060
  */
1060
1061
  private takesOver;
1062
+ /**
1063
+ * Whether a statement I would take (`takesOver`) was on its way when the role moved, as far as I can tell: a member
1064
+ * other than its signer handed it to me, or said in a sync it holds that one or a later one under the same commit.
1065
+ * The former admin alone could sign new ones after the hand-over, each taken for the whole group.
1066
+ */
1067
+ private vouches;
1068
+ /** The former admin's statement nobody else has shown it holds: the latest is kept until a sync does (`vouch`). */
1069
+ private holdTaken;
1070
+ /**
1071
+ * A member's sync names the statement it holds: one signed under a commit of the admin before me, by another member
1072
+ * than them, vouches for theirs up to it, and the one held is taken if it now is.
1073
+ */
1074
+ private vouch;
1061
1075
  /**
1062
1076
  * The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
1063
1077
  * value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
@@ -64,7 +64,7 @@ export * from './pkdns.js';
64
64
  export * from './pubkyProofs.js';
65
65
  export * from './pubkyRing.js';
66
66
  export * from "./capsRecord.js";
67
- export { DhtDelivery, peekDhtMailbox, DHT_TEXT_BYTES, DHT_MESSAGE_TTL, DHT_TEXT_REFUSED, DHT_FILE_REFUSED, DHT_FILE_TOO_LARGE, LIVE_POLL_MS, ACTIVE_DHT_POLL_MS, emptyDhtDeliveryState, type DeliveryMode, type DhtDeliveryState, type DhtDeliveryView, type DhtPacketFacts } from "./dhtDelivery.js";
67
+ export { DhtDelivery, peekDhtMailbox, DHT_TEXT_BYTES, DHT_PACKET_BUDGET, DHT_MESSAGE_TTL, DHT_TEXT_REFUSED, DHT_FILE_REFUSED, DHT_FILE_TOO_LARGE, LIVE_POLL_MS, ACTIVE_DHT_POLL_MS, emptyDhtDeliveryState, type DeliveryMode, type DhtDeliveryState, type DhtDeliveryView, type DhtPacketFacts } from "./dhtDelivery.js";
68
68
  export { DHT_FILE_CAPABILITY, dhtFileId, dhtFileElements, readDhtFile, type DhtFileAnnouncement, type DhtFileElement, type DhtFileMeta, type DhtFileOffer } from "./dhtFiles.js";
69
69
  export * from "./storeForward.js";
70
70
  export * from "./ratchet.js";