@ghostlytools/sdk 1.11.4 → 1.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.js +1 -2
- package/dist/bitcoinAddress-C2MAmcDT.js +1225 -0
- package/dist/bitcoinAddress-C2MAmcDT.js.map +1 -0
- package/dist/bolt11-CRiQrma3.js +266 -0
- package/dist/bolt11-CRiQrma3.js.map +1 -0
- package/dist/core.js +41852 -336
- package/dist/core.js.map +1 -1
- package/dist/{fakes-CXeeyI4Z.js → fakes-Cgl1w4Nv.js} +6 -9
- package/dist/{fakes-CXeeyI4Z.js.map → fakes-Cgl1w4Nv.js.map} +1 -1
- package/dist/fakes.js +1 -2
- package/dist/index.js +8 -9
- package/dist/index.js.map +1 -1
- package/dist/{keet-identity-key-DLXTTFZH.js → keet-identity-key-LuoCuz1t.js} +648 -324
- package/dist/keet-identity-key-LuoCuz1t.js.map +1 -0
- package/dist/pairedTransports-CkYMAoYN.js +1149 -0
- package/dist/pairedTransports-CkYMAoYN.js.map +1 -0
- package/dist/rolldown-runtime-DpEnGzO4.js +45 -0
- package/dist/testing.js +7 -8
- package/dist/testing.js.map +1 -1
- package/dist/types/browser/src/proofs/contract.d.ts +10 -0
- package/dist/types/browser/src/shared/mints.d.ts +3 -1
- package/dist/types/core/src/chatFiles.d.ts +3 -1
- package/dist/types/core/src/communityRendezvous.d.ts +4 -0
- package/dist/types/core/src/dhtDelivery.d.ts +16 -0
- package/dist/types/core/src/engineErrors.d.ts +7 -0
- package/dist/types/core/src/ghostlink.d.ts +12 -2
- package/dist/types/core/src/groupCalls.d.ts +56 -0
- package/dist/types/core/src/groupCommunity.d.ts +59 -1
- package/dist/types/core/src/groupCrypto.d.ts +6 -0
- package/dist/types/core/src/groupMeta.d.ts +22 -0
- package/dist/types/core/src/groupSession.d.ts +42 -2
- package/dist/types/core/src/handoff.d.ts +0 -2
- package/dist/types/core/src/http.d.ts +2 -1
- package/dist/types/core/src/index.d.ts +1 -0
- package/dist/types/core/src/pairedTransports.d.ts +5 -0
- package/dist/types/core/src/relayBreaker.d.ts +5 -1
- package/dist/types/core/src/services.d.ts +6 -0
- package/dist/types/core/src/text.d.ts +2 -0
- package/dist/types/core/src/transport.d.ts +1 -1
- package/dist/{types-DYLIIkU8.js → types-DbgC491n.js} +2 -3
- package/dist/{types-DYLIIkU8.js.map → types-DbgC491n.js.map} +1 -1
- package/dist/{verify-B9s82dbd.js → verify-CSo7-43-.js} +3 -4
- package/dist/{verify-B9s82dbd.js.map → verify-CSo7-43-.js.map} +1 -1
- package/package.json +3 -3
- package/dist/keet-identity-key-DLXTTFZH.js.map +0 -1
- package/dist/src-CqAqFhh9.js +0 -43635
- package/dist/src-CqAqFhh9.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pairedTransports-CkYMAoYN.js","names":[],"sources":["../../core/src/crypto.ts","../../core/src/dns.ts","../../core/src/pkarr.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, utf8Decode, utf8Encode } from \"./bytes\";\n\n/**\n * Minimal DNS wire codec for Pkarr packets. Ghostly publishes TXT records (and,\n * for a did:dht document that names its gateways, NS). Decoding skips every\n * other record type and understands name compression, which the Rust client\n * (simple-dns) emits. `decodeDnsAnswers` hands out any record type raw, for\n * readers of other people's records (Pubky's `_pubky` and homeserver records, pkdns.ts).\n */\nexport interface TxtRecord {\n /** Fully qualified name, e.g. `_msgs.<z32 public key>` */\n name: string;\n value: string;\n ttl: number;\n}\n\n/** A name server record: `host` is the server's name. */\nexport interface NsRecord {\n type: \"NS\";\n name: string;\n host: string;\n ttl: number;\n}\n\nconst TYPE_NS = 2;\nconst TYPE_TXT = 16;\nconst CLASS_IN = 1;\nconst FLAGS_REPLY = 0x8000;\nconst FLAG_AUTHORITATIVE = 0x0400;\nconst MAX_CHARACTER_STRING = 255;\nconst MAX_POINTER_OFFSET = 0x3fff;\n\nclass Writer {\n private chunks: Uint8Array[] = [];\n length = 0;\n\n push(bytes: Uint8Array): void {\n this.chunks.push(bytes);\n this.length += bytes.length;\n }\n\n u8(v: number): void {\n this.push(Uint8Array.of(v & 0xff));\n }\n\n u16(v: number): void {\n this.push(Uint8Array.of((v >>> 8) & 0xff, v & 0xff));\n }\n\n u32(v: number): void {\n this.push(Uint8Array.of((v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff));\n }\n\n bytes(): Uint8Array {\n return concatBytes(...this.chunks);\n }\n}\n\nfunction writeName(writer: Writer, name: string, suffixOffsets: Map<string, number>): void {\n const labels = name.split(\".\").filter((l) => l.length > 0);\n for (let i = 0; i < labels.length; i++) {\n const suffix = labels.slice(i).join(\".\");\n const pointer = suffixOffsets.get(suffix);\n if (pointer !== undefined) {\n writer.u16(0xc000 | pointer);\n return;\n }\n if (writer.length <= MAX_POINTER_OFFSET) suffixOffsets.set(suffix, writer.length);\n const label = utf8Encode(labels[i]);\n if (label.length > 63) throw new Error(`DNS label too long: ${labels[i]}`);\n writer.u8(label.length);\n writer.push(label);\n }\n writer.u8(0);\n}\n\n/** `authoritative` sets the AA flag, which a did:dht packet must carry. */\nexport function encodeTxtPacket(records: (TxtRecord | NsRecord)[], options: { authoritative?: boolean } = {}): Uint8Array {\n const writer = new Writer();\n writer.u16(0);\n writer.u16(options.authoritative ? FLAGS_REPLY | FLAG_AUTHORITATIVE : FLAGS_REPLY);\n writer.u16(0);\n writer.u16(records.length);\n writer.u16(0);\n writer.u16(0);\n\n const suffixOffsets = new Map<string, number>();\n for (const record of records) {\n writeName(writer, record.name, suffixOffsets);\n if (\"host\" in record) {\n writer.u16(TYPE_NS);\n writer.u16(CLASS_IN);\n writer.u32(record.ttl);\n // The length comes first, so the host is written on its own (uncompressed) and measured.\n const host = new Writer();\n writeName(host, record.host, new Map());\n writer.u16(host.length);\n writer.push(host.bytes());\n continue;\n }\n writer.u16(TYPE_TXT);\n writer.u16(CLASS_IN);\n writer.u32(record.ttl);\n\n const value = utf8Encode(record.value);\n const strings: Uint8Array[] = [];\n for (let i = 0; i < value.length || i === 0; i += MAX_CHARACTER_STRING) {\n const chunk = value.subarray(i, i + MAX_CHARACTER_STRING);\n strings.push(Uint8Array.of(chunk.length), chunk);\n }\n const rdata = concatBytes(...strings);\n writer.u16(rdata.length);\n writer.push(rdata);\n }\n return writer.bytes();\n}\n\n/** A name at `start` (compressed or not), and where the bytes after it begin. Labels are joined with \".\", no trailing dot. */\nexport function readDnsName(data: Uint8Array, start: number): { name: string; next: number } {\n const labels: string[] = [];\n let pos = start;\n let next = -1;\n let jumps = 0;\n\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 has too many compression pointers\");\n continue;\n }\n if (len & 0xc0) throw new Error(\"Unsupported DNS label type\");\n pos += 1;\n if (len === 0) break;\n if (pos + len > data.length) throw new Error(\"DNS label out of bounds\");\n labels.push(utf8Decode(data.subarray(pos, pos + len)));\n pos += len;\n }\n\n return { name: labels.join(\".\"), next: next < 0 ? pos : next };\n}\n\nexport function decodeTxtPacket(data: Uint8Array): TxtRecord[] {\n if (data.length < 12) throw new Error(\"DNS packet too short\");\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const questions = view.getUint16(4);\n const answers = view.getUint16(6);\n\n let pos = 12;\n for (let i = 0; i < questions; i++) {\n pos = readDnsName(data, pos).next + 4;\n }\n\n const records: TxtRecord[] = [];\n for (let i = 0; i < answers; i++) {\n const { name, next } = readDnsName(data, pos);\n pos = next;\n if (pos + 10 > data.length) throw new Error(\"DNS record out of bounds\");\n const type = view.getUint16(pos);\n const ttl = view.getUint32(pos + 4);\n const rdLength = view.getUint16(pos + 8);\n pos += 10;\n const end = pos + rdLength;\n if (end > data.length) throw new Error(\"DNS rdata out of bounds\");\n\n if (type === TYPE_TXT) {\n const parts: Uint8Array[] = [];\n let p = pos;\n while (p < end) {\n const len = data[p];\n if (p + 1 + len > end) throw new Error(\"DNS character-string out of bounds\");\n parts.push(data.subarray(p + 1, p + 1 + len));\n p += 1 + len;\n }\n try {\n records.push({ name, value: utf8Decode(concatBytes(...parts)), ttl });\n } catch {\n // not valid UTF-8, not one of ours\n }\n }\n pos = end;\n }\n return records;\n}\n\n/** One answer record, undecoded: its rdata starts at `offset` in the packet (names in it may point anywhere before). */\nexport interface RawDnsAnswer {\n name: string;\n type: number;\n ttl: number;\n /** Where the rdata starts in the packet. */\n offset: number;\n length: number;\n}\n\n/** Every answer record of a packet, of any type. Names are decompressed; the rdata is left to the caller. */\nexport function decodeDnsAnswers(data: Uint8Array): RawDnsAnswer[] {\n if (data.length < 12) throw new Error(\"DNS packet too short\");\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const questions = view.getUint16(4);\n const answers = view.getUint16(6);\n let pos = 12;\n for (let i = 0; i < questions; i++) pos = readDnsName(data, pos).next + 4;\n const records: RawDnsAnswer[] = [];\n for (let i = 0; i < answers; i++) {\n const { name, next } = readDnsName(data, pos);\n pos = next;\n if (pos + 10 > data.length) throw new Error(\"DNS record out of bounds\");\n const type = view.getUint16(pos);\n const ttl = view.getUint32(pos + 4);\n const length = view.getUint16(pos + 8);\n pos += 10;\n if (pos + length > data.length) throw new Error(\"DNS rdata out of bounds\");\n records.push({ name, type, ttl, offset: pos, length });\n pos += length;\n }\n return records;\n}\n","import { concatBytes, utf8Encode } from \"./bytes\";\nimport { decodeTxtPacket, encodeTxtPacket, type TxtRecord } from \"./dns\";\nimport { publicKeyFromZ32, sign, verify, type Identity } from \"./identity\";\n\n/** Mainline DHT (BEP44) caps the value of a mutable item at 1000 bytes. */\nexport const MAX_DNS_PACKET_BYTES = 1000;\nconst SIGNATURE_LENGTH = 64;\nconst TIMESTAMP_LENGTH = 8;\n/** The largest relay payload: a 64-byte signature, an 8-byte timestamp and the largest DNS packet (1072 bytes). */\nexport const RELAY_PAYLOAD_MAX_BYTES = SIGNATURE_LENGTH + TIMESTAMP_LENGTH + MAX_DNS_PACKET_BYTES;\n\n/** A label relative to the publisher's key, e.g. `_msgs`. */\nexport interface GhostRecord {\n label: string;\n value: string;\n ttl?: number;\n}\n\nexport interface SignedPacket {\n pubKeyZ32: string;\n /** Microseconds since the UNIX epoch; doubles as the BEP44 sequence number. */\n timestampMicros: bigint;\n records: GhostRecord[];\n}\n\nexport class PacketTooLargeError extends Error {\n constructor(public readonly size: number) {\n super(`DNS packet is too large, expected max ${MAX_DNS_PACKET_BYTES} bytes but got: ${size}`);\n }\n}\n\nconst DEFAULT_TTL = 300;\n\nfunction signable(timestampMicros: bigint, dnsPacket: Uint8Array): Uint8Array {\n return concatBytes(utf8Encode(`3:seqi${timestampMicros}e1:v${dnsPacket.length}:`), dnsPacket);\n}\n\nfunction toTxtRecords(pubKeyZ32: string, records: GhostRecord[]): TxtRecord[] {\n return records.map((r) => ({\n name: `${r.label}.${pubKeyZ32}`,\n value: r.value,\n ttl: r.ttl ?? DEFAULT_TTL,\n }));\n}\n\n/** Size of the encoded DNS packet these records would produce. */\nexport function measureRecords(pubKeyZ32: string, records: GhostRecord[]): number {\n return encodeTxtPacket(toTxtRecords(pubKeyZ32, records)).length;\n}\n\n/**\n * Builds the payload Pkarr relays accept on `PUT /<z32 public key>`:\n * `<64 bytes signature><8 bytes big-endian timestamp (µs)><encoded DNS packet>`\n */\nexport function createRelayPayload(\n identity: Identity,\n records: GhostRecord[],\n timestampMicros: bigint = BigInt(Date.now()) * 1000n,\n): Uint8Array {\n return signRelayPayload(identity, encodeTxtPacket(toTxtRecords(identity.pubKeyZ32, records)), timestampMicros);\n}\n\n/**\n * Signs a DNS packet exactly as given (its own names and flags) into a relay payload. `seq` is the\n * BEP44 sequence number: Ghostly's records use microseconds, a did:dht document seconds.\n */\nexport function signRelayPayload(identity: Identity, dnsPacket: Uint8Array, seq: bigint): Uint8Array {\n if (dnsPacket.length > MAX_DNS_PACKET_BYTES) throw new PacketTooLargeError(dnsPacket.length);\n // Written in 64 bits: a larger one would wrap (to 0 past the last), and be signed as one date and sent as another.\n if (seq < 0n || seq >= 1n << 64n) throw new RangeError(`Sequence number ${seq} does not fit in 64 bits`);\n\n const signature = sign(signable(seq, dnsPacket), identity.seed);\n const timestamp = new Uint8Array(TIMESTAMP_LENGTH);\n new DataView(timestamp.buffer).setBigUint64(0, seq);\n return concatBytes(signature, timestamp, dnsPacket);\n}\n\n/** A relay payload's parts, its size checked: the signature, the sequence number and the DNS packet (not decoded). */\nfunction splitRelayPayload(payload: Uint8Array): { signature: Uint8Array; seq: bigint; dnsPacket: Uint8Array } {\n if (payload.length < SIGNATURE_LENGTH + TIMESTAMP_LENGTH + 12) {\n throw new Error(\"Relay payload too short\");\n }\n if (payload.length > SIGNATURE_LENGTH + TIMESTAMP_LENGTH + MAX_DNS_PACKET_BYTES) {\n throw new PacketTooLargeError(payload.length);\n }\n const signature = payload.subarray(0, SIGNATURE_LENGTH);\n const seq = new DataView(\n payload.buffer,\n payload.byteOffset + SIGNATURE_LENGTH,\n TIMESTAMP_LENGTH,\n ).getBigUint64(0);\n const dnsPacket = payload.subarray(SIGNATURE_LENGTH + TIMESTAMP_LENGTH);\n return { signature, seq, dnsPacket };\n}\n\n/** Checks a relay payload's size and signature. Returns its sequence number and DNS packet, not decoded. */\nexport function openRelayPayload(pubKeyZ32: string, payload: Uint8Array): { seq: bigint; dnsPacket: Uint8Array } {\n const { signature, seq, dnsPacket } = splitRelayPayload(payload);\n const publicKey = publicKeyFromZ32(pubKeyZ32);\n if (!verify(signature, signable(seq, dnsPacket), publicKey)) {\n throw new Error(\"Invalid signature\");\n }\n return { seq, dnsPacket };\n}\n\nfunction decodeRelayPayload(pubKeyZ32: string, seq: bigint, dnsPacket: Uint8Array): SignedPacket {\n const suffix = `.${pubKeyZ32}`;\n const records = decodeTxtPacket(dnsPacket).map((r) => ({\n label: r.name.endsWith(suffix) ? r.name.slice(0, -suffix.length) : r.name,\n value: r.value,\n ttl: r.ttl,\n }));\n return { pubKeyZ32, timestampMicros: seq, records };\n}\n\n/** Verifies and decodes a relay payload. Throws if the signature does not match. */\nexport function parseRelayPayload(pubKeyZ32: string, payload: Uint8Array): SignedPacket {\n const { seq, dnsPacket } = openRelayPayload(pubKeyZ32, payload);\n return decodeRelayPayload(pubKeyZ32, seq, dnsPacket);\n}\n\n/**\n * Decodes a payload whose signature this process made or already checked (one it is putting), without checking it\n * again: an Ed25519 verify costs about 1 ms, and a CLI daemon at its relay budget checked its own packets ~500 times a\n * minute. Never for bytes read from elsewhere: `parseRelayPayload` is.\n */\nexport function readOwnRelayPayload(pubKeyZ32: string, payload: Uint8Array): SignedPacket {\n const { seq, dnsPacket } = splitRelayPayload(payload);\n return decodeRelayPayload(pubKeyZ32, seq, dnsPacket);\n}\n\n/** How far ahead of this clock a packet's time may be and still count as now: clocks drift, not by this much. */\nexport const PKARR_FUTURE_SKEW_MS = 10 * 60_000;\n\n/**\n * The newer of two signed packets of one key. A packet dated further ahead than `PKARR_FUTURE_SKEW_MS` never wins over\n * one dated now or before: whoever could sign it once (a key several people hold, a clock far off) must not keep every\n * later packet from being taken. Between two of the same kind, the later time wins; on a tie, `known` stays.\n */\nexport function newerPacket(known: SignedPacket | null | undefined, packet: SignedPacket | null | undefined, now = Date.now()): SignedPacket | null {\n if (!known) return packet ?? null;\n if (!packet) return known;\n const limit = BigInt(now + PKARR_FUTURE_SKEW_MS) * 1000n;\n const knownAhead = known.timestampMicros > limit, packetAhead = packet.timestampMicros > limit;\n if (knownAhead !== packetAhead) return knownAhead ? packet : known;\n return packet.timestampMicros > known.timestampMicros ? packet : known;\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. */\nexport function isPublicAddress(address: Uint8Array): boolean {\n if (address.length === 4) {\n const [a, b, c] = address;\n return !(a === 0 || a === 10 || a === 127 || a >= 224 ||\n (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) || (a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19)));\n }\n if (address.length !== 16) return false;\n const zeroTo = (n: number) => address.subarray(0, n).every(x => x === 0);\n if (zeroTo(15) && (address[15] === 0 || address[15] === 1)) return false; // :: and ::1\n if (zeroTo(10) && address[10] === 0xff && address[11] === 0xff) return isPublicAddress(address.subarray(12)); // ::ffff:a.b.c.d\n if (address[0] === 0x00 && address[1] === 0x64 && address[2] === 0xff && address[3] === 0x9b && address.subarray(4, 12).every(x => x === 0))\n return isPublicAddress(address.subarray(12)); // 64:ff9b::/96 NAT64\n if (zeroTo(12)) return false; // deprecated IPv4-compatible\n if ((address[0] & 0xfe) === 0xfc) return false; // fc00::/7 unique local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0x80) return false; // fe80::/10 link-local\n if (address[0] === 0xfe && (address[1] & 0xc0) === 0xc0) return false; // fec0::/10 site-local\n if (address[0] === 0xff) return false; // multicast\n if (address[0] === 0x01 && address.subarray(1, 8).every(x => x === 0)) return false; // 100::/64 discard\n return (address[0] & 0xe0) === 0x20; // only 2000::/3 is global unicast\n}\n","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;;;;;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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"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esmMin = (fn, res, err) => () => {
|
|
9
|
+
if (err) throw err[0];
|
|
10
|
+
try {
|
|
11
|
+
return fn && (res = fn(fn = 0)), res;
|
|
12
|
+
} catch (e) {
|
|
13
|
+
throw err = [e], e;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
|
|
17
|
+
var __exportAll = (all, no_symbols) => {
|
|
18
|
+
let target = {};
|
|
19
|
+
for (var name in all) __defProp(target, name, {
|
|
20
|
+
get: all[name],
|
|
21
|
+
enumerable: true
|
|
22
|
+
});
|
|
23
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
24
|
+
return target;
|
|
25
|
+
};
|
|
26
|
+
var __copyProps = (to, from, except, desc) => {
|
|
27
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
28
|
+
key = keys[i];
|
|
29
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
30
|
+
get: ((k) => from[k]).bind(null, key),
|
|
31
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
return to;
|
|
35
|
+
};
|
|
36
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
37
|
+
value: mod,
|
|
38
|
+
enumerable: true
|
|
39
|
+
}) : target, mod));
|
|
40
|
+
var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
41
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
|
|
42
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
43
|
+
throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
|
|
44
|
+
});
|
|
45
|
+
export { __toCommonJS as a, __require as i, __esmMin as n, __toESM as o, __exportAll as r, __commonJSMin as t };
|
package/dist/testing.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { l as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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";
|
|
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";
|
|
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";
|
|
5
6
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
6
|
-
|
|
7
|
+
// ../browser/src/engine/paymentAdapters/providers/contractSuite.ts
|
|
7
8
|
var WAIT = 1e4;
|
|
8
9
|
var limit = ({ timeout }) => timeout === void 0 ? {} : { timeout: 3 * timeout };
|
|
9
10
|
function describeLightningProvider(name, make, options = {}) {
|
|
@@ -133,8 +134,7 @@ function describeOnchainProvider(name, make, options = {}) {
|
|
|
133
134
|
});
|
|
134
135
|
});
|
|
135
136
|
}
|
|
136
|
-
|
|
137
|
-
//#region ../browser/src/proofs/contractSuite.ts
|
|
137
|
+
// ../browser/src/proofs/contractSuite.ts
|
|
138
138
|
var refuseNetwork = async (url) => {
|
|
139
139
|
throw new Error(`Unexpected network access: ${url}`);
|
|
140
140
|
};
|
|
@@ -324,7 +324,6 @@ function describeIdentityProof(name, make, { timeout = 1e4 } = {}) {
|
|
|
324
324
|
}, timeout);
|
|
325
325
|
});
|
|
326
326
|
}
|
|
327
|
-
//#endregion
|
|
328
327
|
export { FAKE_IDENTITY_PROVIDERS, FAKE_ISSUER, FAKE_RECORD_HOST, FakeLightningProvider, FakeOnchainProvider, TEST_IDENTITIES_FLAG, TEST_PROVIDERS_FLAG, describeIdentityProof, describeLightningProvider, describeOnchainProvider, fakeAccount, fakeAccountToken, fakeAddress, fakeInvoice, fakeKey, fakeKeySign, fakeKeySubject, fakeKeyring, fakeLightning, fakeOnchain, fakeRecord, fakeRecordText, testIdentitiesEnabled, testProvidersEnabled };
|
|
329
328
|
|
|
330
329
|
//# sourceMappingURL=testing.js.map
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":[],"sources":["../../browser/src/engine/paymentAdapters/providers/contractSuite.ts","../../browser/src/proofs/contractSuite.ts"],"sourcesContent":["import { afterEach, describe, expect, it, vi } from \"vitest\";\nimport { decodeBolt11, isBitcoinAddress } from \"@ghostly/core\";\nimport type { LightningInvoice, LightningProvider, LightningProviderDescriptor } from \"./lightning\";\nimport type { OnchainProvider, OnchainProviderDescriptor } from \"./onchain\";\nimport { isNothingSpentError, providerDescriptorProblems, type ProviderDescriptor, type ProviderNetwork } from \"./types\";\n\n/**\n * The provider contract as tests: every Lightning or on-chain provider runs these against itself, with a\n * harness that knows how to make money move on its network (a fake, a regtest counterpart node, a\n * faucet). See PROVIDERS.md. A provider's own unit tests (mocked transport) go next to these.\n *\n * describeLightningProvider(\"NWC\", async () => ({ provider, network: \"regtest\", payIncoming, payable }));\n *\n * `timeout` is how long money may take to arrive (default 10 s). A harness that gives it is on a real network,\n * where a step takes seconds: its tests get three times that (the harness's own step, the provider's calls,\n * the wait) instead of the runner's default limit, which a busy machine does not meet.\n */\nexport interface ContractOptions { timeout?: number }\nconst WAIT = 10_000;\nconst limit = ({ timeout }: ContractOptions) => (timeout === undefined ? {} : { timeout: 3 * timeout });\n\nexport interface LightningHarness {\n provider: LightningProvider;\n network: ProviderNetwork;\n /** The descriptor the app would register: its shape is checked too. */\n descriptor?: LightningProviderDescriptor;\n /** Someone else pays this invoice of the provider (a counterpart node; a fake marks it paid). */\n payIncoming(invoice: LightningInvoice): Promise<void>;\n /** An invoice of someone else for `amount` sats, that the provider can pay. */\n payable(amount: number): Promise<string>;\n /** An invoice the provider must refuse before anything leaves (no route, not enough funds). */\n refused?(): Promise<string>;\n}\n\nexport function describeLightningProvider(name: string, make: () => Promise<LightningHarness>, options: ContractOptions = {}) {\n const { timeout = WAIT } = options;\n describe(`${name}: the LightningProvider contract`, limit(options), () => {\n let harness: LightningHarness | undefined;\n const open = async () => (harness = await make());\n afterEach(async () => { await harness?.provider.close(); harness = undefined; });\n\n it(\"has a well-formed descriptor, when it brings one\", async () => {\n const { descriptor, network } = await open();\n if (!descriptor) return;\n expect(providerDescriptorProblems(descriptor as ProviderDescriptor<unknown>)).toEqual([]);\n expect(descriptor.kind).toBe(\"lightning\");\n expect(descriptor.networks).toContain(network);\n });\n\n it(\"says which network it is on, and a whole-sat balance when it has one\", async () => {\n const { provider, network } = await open();\n const info = await provider.info();\n expect(info.network).toBe(network);\n if (provider.capabilities.balance) expect(Number.isSafeInteger(info.balance) && info.balance! >= 0).toBe(true);\n });\n\n it(\"creates an invoice that decodes to what was asked, and sees it paid\", async () => {\n const { provider, payIncoming } = await open();\n if (!provider.capabilities.receive) return;\n const invoice = await provider.createInvoice(21, \"contract\");\n const decoded = decodeBolt11(invoice.invoice);\n expect(decoded?.amountSat).toBe(21);\n expect(invoice.amount).toBe(21);\n expect(decoded?.paymentHash).toBe(invoice.paymentHash);\n expect(invoice.expiresAt).toBeGreaterThan(Date.now());\n if (!provider.capabilities.lookup) return;\n expect((await provider.invoiceStatus(invoice)).state).toBe(\"open\");\n await payIncoming(invoice);\n await vi.waitFor(async () => expect((await provider.invoiceStatus(invoice)).state).toBe(\"paid\"), { timeout, interval: 250 });\n });\n\n it(\"pays an invoice within the fee limit, and says so again when asked\", async () => {\n const { provider, payable } = await open();\n if (!provider.capabilities.send) return;\n const invoice = await payable(25);\n const hash = decodeBolt11(invoice)!.paymentHash!;\n const maxFee = provider.estimateFee ? await provider.estimateFee(invoice, 25) : 10;\n const result = await provider.payInvoice(invoice, maxFee);\n if (result.state === \"paid\") expect(result.fee ?? 0).toBeLessThanOrEqual(maxFee);\n if (!provider.capabilities.lookup) return;\n await vi.waitFor(async () => expect((await provider.paymentStatus({ invoice, paymentHash: hash, ref: result.ref })).state).toBe(\"paid\"), { timeout, interval: 250 });\n });\n\n it(\"refuses what it cannot pay with NothingSpentError, before anything leaves\", async () => {\n const { provider, refused } = await open();\n if (!provider.capabilities.send || !refused) return;\n // By name, as the engine does: a provider built outside the app may carry its own copy of the class.\n await expect(provider.payInvoice(await refused(), 10)).rejects.toSatisfy((error: unknown) => isNothingSpentError(error));\n });\n });\n}\n\nexport interface OnchainHarness {\n provider: OnchainProvider;\n network: ProviderNetwork;\n /** The descriptor the app would register: its shape is checked too. */\n descriptor?: OnchainProviderDescriptor;\n /** An address of someone else on this network. */\n recipient(): Promise<string> | string;\n /** Makes the provider's wallet hold at least `amount` confirmed sats (a faucet, mining on regtest). */\n fund?(amount: number): Promise<void>;\n}\n\nexport function describeOnchainProvider(name: string, make: () => Promise<OnchainHarness>, options: ContractOptions = {}) {\n const { timeout = WAIT } = options;\n describe(`${name}: the OnchainProvider contract`, limit(options), () => {\n let harness: OnchainHarness | undefined;\n const open = async () => (harness = await make());\n afterEach(async () => { await harness?.provider.close(); harness = undefined; });\n\n it(\"has a well-formed descriptor, when it brings one\", async () => {\n const { descriptor, network } = await open();\n if (!descriptor) return;\n expect(providerDescriptorProblems(descriptor as ProviderDescriptor<unknown>)).toEqual([]);\n expect(descriptor.kind).toBe(\"onchain\");\n expect(descriptor.networks).toContain(network);\n });\n\n it(\"gives fresh addresses of its own network, and a whole-sat balance\", async () => {\n const { provider, network } = await open();\n expect((await provider.info()).network).toBe(network);\n const [a, b] = [await provider.receiveAddress(), await provider.receiveAddress()];\n expect(isBitcoinAddress(a, network) && isBitcoinAddress(b, network)).toBe(true);\n expect(a).not.toBe(b);\n const balance = await provider.balance();\n expect(Number.isSafeInteger(balance.confirmed) && Number.isSafeInteger(balance.unconfirmed)).toBe(true);\n });\n\n it(\"refuses a fee above the cap when preparing, and spends nothing by preparing\", async () => {\n const { provider, recipient, fund } = await open();\n await fund?.(20_000);\n const before = await provider.balance();\n await expect(provider.prepareSend({ address: await recipient(), amount: 1_000, feeCap: 0 })).rejects.toThrow();\n expect((await provider.balance()).confirmed).toBe(before.confirmed);\n });\n\n it(\"broadcasts exactly the prepared transaction, and broadcasting it again pays nothing more\", async () => {\n const { provider, recipient, fund } = await open();\n await fund?.(20_000);\n const address = await recipient();\n const prepared = await provider.prepareSend({ address, amount: 1_000, feeCap: 5_000 });\n expect(prepared).toMatchObject({ address, amount: 1_000 });\n expect(prepared.fee).toBeLessThanOrEqual(5_000);\n expect(prepared.txid).toMatch(/^[0-9a-f]{64}$/);\n expect(await provider.broadcast(prepared)).toBe(prepared.txid);\n const after = await provider.balance();\n await provider.broadcast(prepared).catch(() => {}); // A node may answer \"already known\": still the same transaction.\n expect((await provider.balance()).confirmed + (await provider.balance()).unconfirmed).toBe(after.confirmed + after.unconfirmed);\n await vi.waitFor(async () => expect([\"mempool\", \"confirmed\"]).toContain((await provider.status(prepared)).state), { timeout, interval: 250 });\n expect((await provider.history(10)).some((tx) => tx.txid === prepared.txid)).toBe(true);\n });\n });\n}\n","import { afterEach, describe, expect, it, vi } from \"vitest\";\nimport {\n createIdentity, emptyIdentityLedger, identityStatement, IdentityExchange, IDENTITY_MAX_EVIDENCE, newIdentityBinding,\n type IdentityBinding, type IdentityLedger, type IdentityStatement, type LocalIdentityProof,\n} from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, VerifyContext } from \"./contract\";\nimport { descriptorProblems, verifyIdentity } from \"./verify\";\n\n/**\n * The identity-proof contract as tests: every provider runs these against itself, with a harness that\n * can produce evidence for it (a test key, a stubbed network). See PROOFS.md. Provider-specific tests\n * (real tool output, vectors, malformed inputs of its format) go next to these.\n *\n * describeIdentityProof(\"SSH\", async () => ({ provider: ssh, subject, prove: s => sshSign(s, key), proveAsOther: s => sshSign(s, otherKey) }));\n */\nexport interface IdentityProofHarness<E> {\n provider: IdentityProofProvider<E>;\n /** A canonical subject this harness controls (self-custodied), or the issuer (provider-attested). */\n subject: string;\n /** Valid evidence for `statement`, the way the provider's signer would produce it. */\n prove(statement: IdentityStatement): Promise<E>;\n /** Evidence for the same statement by another key/account: a self-custodied provider must refuse it. */\n proveAsOther?(statement: IdentityStatement): Promise<E>;\n /** The network the verifier sees (DNS, JWKS, published keys). Defaults to one that refuses everything. */\n fetch?: IdentityFetch;\n /** Make proofs made so far fail a re-check (unpublish the record, revoke the key). Providers with `recheck`. */\n revoke?(): void | Promise<void>;\n /** Seconds; defaults to the real clock. */\n now?: number;\n}\n\nconst refuseNetwork: IdentityFetch = async url => { throw new Error(`Unexpected network access: ${url}`); };\n\nexport function describeIdentityProof<E>(name: string, make: () => Promise<IdentityProofHarness<E>>, { timeout = 10_000 } = {}) {\n describe(`${name}: the IdentityProofProvider contract`, () => {\n afterEach(() => { vi.restoreAllMocks(); });\n const ctxOf = (h: IdentityProofHarness<E>): VerifyContext => ({ now: h.now ?? Math.floor(Date.now() / 1000), signal: new AbortController().signal, fetch: h.fetch ?? refuseNetwork });\n const statementFor = (h: IdentityProofHarness<E>, change: Partial<IdentityBinding> = {}): IdentityStatement => {\n const { binding } = newIdentityBinding({ provider: h.provider.id, subject: h.subject, validitySeconds: h.provider.validity.defaultDays * 86_400, now: h.now });\n return identityStatement({ ...binding, ...change });\n };\n const verify = (h: IdentityProofHarness<E>, statement: IdentityStatement, evidence: unknown) =>\n verifyIdentity([h.provider as IdentityProofProvider], statement, JSON.parse(JSON.stringify(evidence)), ctxOf(h));\n\n it(\"has a well-formed descriptor\", async () => {\n const h = await make();\n expect(descriptorProblems(h.provider as IdentityProofProvider)).toEqual([]);\n expect(h.provider.subject.normalize(h.subject)).toBe(h.subject);\n if (h.provider.subject.options) expect(h.provider.subject.options.map(o => o.value)).toContain(h.subject);\n });\n\n it(\"verifies its own evidence, after a trip through JSON, and says how\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n expect(JSON.stringify(evidence).length).toBeLessThanOrEqual(IDENTITY_MAX_EVIDENCE);\n const verified = await verify(h, statement, evidence);\n expect(verified.source.length).toBeGreaterThan(0);\n if (h.provider.category === \"self-custodied\") expect(verified.subject).toBe(h.subject);\n else expect(verified.attester).toBeTruthy();\n if (verified.expiresAt !== undefined) expect(verified.expiresAt).toBeGreaterThan(statement.binding.issuedAt);\n }, timeout);\n\n it(\"verifies through ctx.fetch only, never the global fetch\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n const global = vi.spyOn(globalThis, \"fetch\").mockRejectedValue(new Error(\"global fetch used\"));\n await verify(h, statement, evidence);\n expect(global).not.toHaveBeenCalled();\n }, timeout);\n\n it(\"refuses evidence made for another statement: each field of the binding counts\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n const b = statement.binding;\n const changes: Partial<IdentityBinding>[] = [\n { key: createIdentity().pubKeyZ32 },\n { nonce: \"A\".repeat(22) },\n { issuedAt: b.issuedAt - 1 },\n { expiresAt: b.expiresAt + 1 },\n ];\n for (const change of changes) await expect(verify(h, identityStatement({ ...b, ...change }), evidence), JSON.stringify(change)).rejects.toThrow();\n }, timeout);\n\n it(\"refuses another identity's evidence\", async () => {\n const h = await make();\n if (!h.proveAsOther) return;\n const statement = statementFor(h);\n await expect(verify(h, statement, await h.proveAsOther(statement))).rejects.toThrow();\n }, timeout);\n\n it(\"refuses malformed evidence before verifying\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n const garbage: unknown[] = [null, 42, \"evidence\", [], [evidence], { ...(evidence as object), extra: \"x\" }, { junk: \"x\".repeat(IDENTITY_MAX_EVIDENCE) }];\n for (const raw of garbage) await expect(verifyIdentity([h.provider as IdentityProofProvider], statement, raw, ctxOf(h))).rejects.toThrow();\n }, timeout);\n\n it(\"refuses a proof lasting longer than the provider allows\", async () => {\n const h = await make();\n const b = statementFor(h).binding;\n if (h.provider.validity.maxDays >= 400) return;\n const long = identityStatement({ ...b, expiresAt: b.issuedAt + (h.provider.validity.maxDays + 1) * 86_400 });\n await expect(verify(h, long, await h.prove(long))).rejects.toThrow(/longer/);\n }, timeout);\n\n it(\"is verified by the contact it is shared with, and a copy replayed to another contact fails\", async () => {\n const h = await make();\n const provider = h.provider as IdentityProofProvider;\n const { binding, seed } = newIdentityBinding({ provider: provider.id, subject: h.subject, validitySeconds: provider.validity.defaultDays * 86_400, now: h.now });\n const statement = identityStatement(binding);\n const local: LocalIdentityProof = { statement, evidence: await h.prove(statement), seed };\n const [alice, bob, carol] = [createIdentity().pubKeyZ32, createIdentity().pubKeyZ32, createIdentity().pubKeyZ32];\n const ledgers = new Map<string, IdentityLedger>();\n const sent: Record<string, unknown>[] = [];\n const peers = new Map<string, IdentityExchange>();\n const make2 = (me: string, them: string, context: string) => {\n const key = `${me}>${them}`;\n ledgers.set(key, emptyIdentityLedger());\n const x = new IdentityExchange({\n scope: () => ({ subject: me, audience: them, context, session: \"c\".repeat(64) }),\n send: frame => { sent.push(frame as Record<string, unknown>); queueMicrotask(() => void peers.get(`${them}>${me}`)?.receive(structuredClone(frame) as Record<string, unknown>)); },\n storage: { read: () => ledgers.get(key)!, update: async change => { ledgers.set(key, change(structuredClone(ledgers.get(key)!))); } },\n providers: () => [provider.id],\n localProof: id => (id === statement.id ? local : undefined),\n verify: (s, e) => verifyIdentity([provider], s, e, ctxOf(h)),\n now: () => h.now ?? Math.floor(Date.now() / 1000),\n });\n peers.set(key, x);\n return x;\n };\n const aliceToBob = make2(alice, bob, \"a\".repeat(64));\n make2(bob, alice, \"a\".repeat(64));\n make2(carol, alice, \"b\".repeat(64));\n await aliceToBob.share(statement.id, true);\n await vi.waitFor(() => expect(ledgers.get(`${alice}>${bob}`)!.shared[0]?.status).toBe(\"accepted\"), { timeout });\n expect(ledgers.get(`${bob}>${alice}`)!.received).toHaveLength(1);\n expect(ledgers.get(`${carol}>${alice}`)!.received).toHaveLength(0);\n // Bob forwards what he received to Carol: no challenge of hers, wrong audience, and no proof key.\n const present = sent.find(f => f.t === \"idp-present\")!;\n await peers.get(`${carol}>${alice}`)!.receive({ t: \"idp-request\", id: statement.id, provider: provider.id });\n const challenge = sent.filter(f => f.t === \"idp-challenge\").at(-1)!;\n await peers.get(`${carol}>${alice}`)!.receive({ ...present, nonce: challenge.nonce, issuedAt: challenge.issuedAt });\n expect(ledgers.get(`${carol}>${alice}`)!.received).toHaveLength(0);\n expect(sent.at(-1)).toMatchObject({ t: \"idp-result\", ok: false });\n }, timeout);\n\n it(\"fails a re-check once revoked, when it can go stale\", async () => {\n const h = await make();\n if (!h.provider.recheck) return;\n expect(h.revoke, \"a provider with recheck must let the harness revoke\").toBeTypeOf(\"function\");\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n await verify(h, statement, evidence);\n await h.revoke!();\n await expect(verify(h, statement, evidence)).rejects.toThrow();\n }, timeout);\n });\n}\n"],"mappings":";;;;;;AAkBA,IAAM,OAAO;AACb,IAAM,SAAS,EAAE,cAAgC,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,IAAI,QAAQ;AAerG,SAAgB,0BAA0B,MAAc,MAAuC,UAA2B,CAAC,GAAG;CAC5H,MAAM,EAAE,UAAU,SAAS;CAC3B,SAAS,GAAG,KAAK,mCAAmC,MAAM,OAAO,SAAS;EACxE,IAAI;EACJ,MAAM,OAAO,YAAa,UAAU,MAAM,KAAK;EAC/C,UAAU,YAAY;GAAE,MAAM,SAAS,SAAS,MAAM;GAAG,UAAU,KAAA;EAAW,CAAC;EAE/E,GAAG,oDAAoD,YAAY;GACjE,MAAM,EAAE,YAAY,YAAY,MAAM,KAAK;GAC3C,IAAI,CAAC,YAAY;GACjB,OAAO,2BAA2B,UAAyC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;GACxF,OAAO,WAAW,IAAI,CAAC,CAAC,KAAK,WAAW;GACxC,OAAO,WAAW,QAAQ,CAAC,CAAC,UAAU,OAAO;EAC/C,CAAC;EAED,GAAG,wEAAwE,YAAY;GACrF,MAAM,EAA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U,SAAS;GAAG,CAAC;GAC3G,MAAM,YAAY,KAAK,QAAO,MAAK,EAAE,MAAM,eAAe,CAAC,CAAC,GAAG,EAAE;GACjE,MAAM,MAAM,IAAI,GAAG,MAAM,GAAG,OAAO,CAAC,CAAE,QAAQ;IAAE,GAAG;IAAS,OAAO,UAAU;IAAO,UAAU,UAAU;GAAS,CAAC;GAClH,OAAO,QAAQ,IAAI,GAAG,MAAM,GAAG,OAAO,CAAC,CAAE,QAAQ,CAAC,CAAC,aAAa,CAAC;GACjE,OAAO,KAAK,GAAG,EAAE,CAAC,CAAC,CAAC,cAAc;IAAE,GAAG;IAAc,IAAI;GAAM,CAAC;EAClE,GAAG,OAAO;EAEV,GAAG,uDAAuD,YAAY;GACpE,MAAM,IAAI,MAAM,KAAK;GACrB,IAAI,CAAC,EAAE,SAAS,SAAS;GACzB,OAAO,EAAE,QAAQ,qDAAqD,CAAC,CAAC,WAAW,UAAU;GAC7F,MAAM,YAAY,aAAa,CAAC;GAChC,MAAM,WAAW,MAAM,EAAE,MAAM,SAAS;GACxC,MAAM,OAAO,GAAG,WAAW,QAAQ;GACnC,MAAM,EAAE,OAAQ;GAChB,MAAM,OAAO,OAAO,GAAG,WAAW,QAAQ,CAAC,CAAC,CAAC,QAAQ,QAAQ;EAC/D,GAAG,OAAO;CACZ,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":[],"sources":["../../browser/src/engine/paymentAdapters/providers/contractSuite.ts","../../browser/src/proofs/contractSuite.ts"],"sourcesContent":["import { afterEach, describe, expect, it, vi } from \"vitest\";\nimport { decodeBolt11, isBitcoinAddress } from \"@ghostly/core\";\nimport type { LightningInvoice, LightningProvider, LightningProviderDescriptor } from \"./lightning\";\nimport type { OnchainProvider, OnchainProviderDescriptor } from \"./onchain\";\nimport { isNothingSpentError, providerDescriptorProblems, type ProviderDescriptor, type ProviderNetwork } from \"./types\";\n\n/**\n * The provider contract as tests: every Lightning or on-chain provider runs these against itself, with a\n * harness that knows how to make money move on its network (a fake, a regtest counterpart node, a\n * faucet). See PROVIDERS.md. A provider's own unit tests (mocked transport) go next to these.\n *\n * describeLightningProvider(\"NWC\", async () => ({ provider, network: \"regtest\", payIncoming, payable }));\n *\n * `timeout` is how long money may take to arrive (default 10 s). A harness that gives it is on a real network,\n * where a step takes seconds: its tests get three times that (the harness's own step, the provider's calls,\n * the wait) instead of the runner's default limit, which a busy machine does not meet.\n */\nexport interface ContractOptions { timeout?: number }\nconst WAIT = 10_000;\nconst limit = ({ timeout }: ContractOptions) => (timeout === undefined ? {} : { timeout: 3 * timeout });\n\nexport interface LightningHarness {\n provider: LightningProvider;\n network: ProviderNetwork;\n /** The descriptor the app would register: its shape is checked too. */\n descriptor?: LightningProviderDescriptor;\n /** Someone else pays this invoice of the provider (a counterpart node; a fake marks it paid). */\n payIncoming(invoice: LightningInvoice): Promise<void>;\n /** An invoice of someone else for `amount` sats, that the provider can pay. */\n payable(amount: number): Promise<string>;\n /** An invoice the provider must refuse before anything leaves (no route, not enough funds). */\n refused?(): Promise<string>;\n}\n\nexport function describeLightningProvider(name: string, make: () => Promise<LightningHarness>, options: ContractOptions = {}) {\n const { timeout = WAIT } = options;\n describe(`${name}: the LightningProvider contract`, limit(options), () => {\n let harness: LightningHarness | undefined;\n const open = async () => (harness = await make());\n afterEach(async () => { await harness?.provider.close(); harness = undefined; });\n\n it(\"has a well-formed descriptor, when it brings one\", async () => {\n const { descriptor, network } = await open();\n if (!descriptor) return;\n expect(providerDescriptorProblems(descriptor as ProviderDescriptor<unknown>)).toEqual([]);\n expect(descriptor.kind).toBe(\"lightning\");\n expect(descriptor.networks).toContain(network);\n });\n\n it(\"says which network it is on, and a whole-sat balance when it has one\", async () => {\n const { provider, network } = await open();\n const info = await provider.info();\n expect(info.network).toBe(network);\n if (provider.capabilities.balance) expect(Number.isSafeInteger(info.balance) && info.balance! >= 0).toBe(true);\n });\n\n it(\"creates an invoice that decodes to what was asked, and sees it paid\", async () => {\n const { provider, payIncoming } = await open();\n if (!provider.capabilities.receive) return;\n const invoice = await provider.createInvoice(21, \"contract\");\n const decoded = decodeBolt11(invoice.invoice);\n expect(decoded?.amountSat).toBe(21);\n expect(invoice.amount).toBe(21);\n expect(decoded?.paymentHash).toBe(invoice.paymentHash);\n expect(invoice.expiresAt).toBeGreaterThan(Date.now());\n if (!provider.capabilities.lookup) return;\n expect((await provider.invoiceStatus(invoice)).state).toBe(\"open\");\n await payIncoming(invoice);\n await vi.waitFor(async () => expect((await provider.invoiceStatus(invoice)).state).toBe(\"paid\"), { timeout, interval: 250 });\n });\n\n it(\"pays an invoice within the fee limit, and says so again when asked\", async () => {\n const { provider, payable } = await open();\n if (!provider.capabilities.send) return;\n const invoice = await payable(25);\n const hash = decodeBolt11(invoice)!.paymentHash!;\n const maxFee = provider.estimateFee ? await provider.estimateFee(invoice, 25) : 10;\n const result = await provider.payInvoice(invoice, maxFee);\n if (result.state === \"paid\") expect(result.fee ?? 0).toBeLessThanOrEqual(maxFee);\n if (!provider.capabilities.lookup) return;\n await vi.waitFor(async () => expect((await provider.paymentStatus({ invoice, paymentHash: hash, ref: result.ref })).state).toBe(\"paid\"), { timeout, interval: 250 });\n });\n\n it(\"refuses what it cannot pay with NothingSpentError, before anything leaves\", async () => {\n const { provider, refused } = await open();\n if (!provider.capabilities.send || !refused) return;\n // By name, as the engine does: a provider built outside the app may carry its own copy of the class.\n await expect(provider.payInvoice(await refused(), 10)).rejects.toSatisfy((error: unknown) => isNothingSpentError(error));\n });\n });\n}\n\nexport interface OnchainHarness {\n provider: OnchainProvider;\n network: ProviderNetwork;\n /** The descriptor the app would register: its shape is checked too. */\n descriptor?: OnchainProviderDescriptor;\n /** An address of someone else on this network. */\n recipient(): Promise<string> | string;\n /** Makes the provider's wallet hold at least `amount` confirmed sats (a faucet, mining on regtest). */\n fund?(amount: number): Promise<void>;\n}\n\nexport function describeOnchainProvider(name: string, make: () => Promise<OnchainHarness>, options: ContractOptions = {}) {\n const { timeout = WAIT } = options;\n describe(`${name}: the OnchainProvider contract`, limit(options), () => {\n let harness: OnchainHarness | undefined;\n const open = async () => (harness = await make());\n afterEach(async () => { await harness?.provider.close(); harness = undefined; });\n\n it(\"has a well-formed descriptor, when it brings one\", async () => {\n const { descriptor, network } = await open();\n if (!descriptor) return;\n expect(providerDescriptorProblems(descriptor as ProviderDescriptor<unknown>)).toEqual([]);\n expect(descriptor.kind).toBe(\"onchain\");\n expect(descriptor.networks).toContain(network);\n });\n\n it(\"gives fresh addresses of its own network, and a whole-sat balance\", async () => {\n const { provider, network } = await open();\n expect((await provider.info()).network).toBe(network);\n const [a, b] = [await provider.receiveAddress(), await provider.receiveAddress()];\n expect(isBitcoinAddress(a, network) && isBitcoinAddress(b, network)).toBe(true);\n expect(a).not.toBe(b);\n const balance = await provider.balance();\n expect(Number.isSafeInteger(balance.confirmed) && Number.isSafeInteger(balance.unconfirmed)).toBe(true);\n });\n\n it(\"refuses a fee above the cap when preparing, and spends nothing by preparing\", async () => {\n const { provider, recipient, fund } = await open();\n await fund?.(20_000);\n const before = await provider.balance();\n await expect(provider.prepareSend({ address: await recipient(), amount: 1_000, feeCap: 0 })).rejects.toThrow();\n expect((await provider.balance()).confirmed).toBe(before.confirmed);\n });\n\n it(\"broadcasts exactly the prepared transaction, and broadcasting it again pays nothing more\", async () => {\n const { provider, recipient, fund } = await open();\n await fund?.(20_000);\n const address = await recipient();\n const prepared = await provider.prepareSend({ address, amount: 1_000, feeCap: 5_000 });\n expect(prepared).toMatchObject({ address, amount: 1_000 });\n expect(prepared.fee).toBeLessThanOrEqual(5_000);\n expect(prepared.txid).toMatch(/^[0-9a-f]{64}$/);\n expect(await provider.broadcast(prepared)).toBe(prepared.txid);\n const after = await provider.balance();\n await provider.broadcast(prepared).catch(() => {}); // A node may answer \"already known\": still the same transaction.\n expect((await provider.balance()).confirmed + (await provider.balance()).unconfirmed).toBe(after.confirmed + after.unconfirmed);\n await vi.waitFor(async () => expect([\"mempool\", \"confirmed\"]).toContain((await provider.status(prepared)).state), { timeout, interval: 250 });\n expect((await provider.history(10)).some((tx) => tx.txid === prepared.txid)).toBe(true);\n });\n });\n}\n","import { afterEach, describe, expect, it, vi } from \"vitest\";\nimport {\n createIdentity, emptyIdentityLedger, identityStatement, IdentityExchange, IDENTITY_MAX_EVIDENCE, newIdentityBinding,\n type IdentityBinding, type IdentityLedger, type IdentityStatement, type LocalIdentityProof,\n} from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, VerifyContext } from \"./contract\";\nimport { descriptorProblems, verifyIdentity } from \"./verify\";\n\n/**\n * The identity-proof contract as tests: every provider runs these against itself, with a harness that\n * can produce evidence for it (a test key, a stubbed network). See PROOFS.md. Provider-specific tests\n * (real tool output, vectors, malformed inputs of its format) go next to these.\n *\n * describeIdentityProof(\"SSH\", async () => ({ provider: ssh, subject, prove: s => sshSign(s, key), proveAsOther: s => sshSign(s, otherKey) }));\n */\nexport interface IdentityProofHarness<E> {\n provider: IdentityProofProvider<E>;\n /** A canonical subject this harness controls (self-custodied), or the issuer (provider-attested). */\n subject: string;\n /** Valid evidence for `statement`, the way the provider's signer would produce it. */\n prove(statement: IdentityStatement): Promise<E>;\n /** Evidence for the same statement by another key/account: a self-custodied provider must refuse it. */\n proveAsOther?(statement: IdentityStatement): Promise<E>;\n /** The network the verifier sees (DNS, JWKS, published keys). Defaults to one that refuses everything. */\n fetch?: IdentityFetch;\n /** Make proofs made so far fail a re-check (unpublish the record, revoke the key). Providers with `recheck`. */\n revoke?(): void | Promise<void>;\n /** Seconds; defaults to the real clock. */\n now?: number;\n}\n\nconst refuseNetwork: IdentityFetch = async url => { throw new Error(`Unexpected network access: ${url}`); };\n\nexport function describeIdentityProof<E>(name: string, make: () => Promise<IdentityProofHarness<E>>, { timeout = 10_000 } = {}) {\n describe(`${name}: the IdentityProofProvider contract`, () => {\n afterEach(() => { vi.restoreAllMocks(); });\n const ctxOf = (h: IdentityProofHarness<E>): VerifyContext => ({ now: h.now ?? Math.floor(Date.now() / 1000), signal: new AbortController().signal, fetch: h.fetch ?? refuseNetwork });\n const statementFor = (h: IdentityProofHarness<E>, change: Partial<IdentityBinding> = {}): IdentityStatement => {\n const { binding } = newIdentityBinding({ provider: h.provider.id, subject: h.subject, validitySeconds: h.provider.validity.defaultDays * 86_400, now: h.now });\n return identityStatement({ ...binding, ...change });\n };\n const verify = (h: IdentityProofHarness<E>, statement: IdentityStatement, evidence: unknown) =>\n verifyIdentity([h.provider as IdentityProofProvider], statement, JSON.parse(JSON.stringify(evidence)), ctxOf(h));\n\n it(\"has a well-formed descriptor\", async () => {\n const h = await make();\n expect(descriptorProblems(h.provider as IdentityProofProvider)).toEqual([]);\n expect(h.provider.subject.normalize(h.subject)).toBe(h.subject);\n if (h.provider.subject.options) expect(h.provider.subject.options.map(o => o.value)).toContain(h.subject);\n });\n\n it(\"verifies its own evidence, after a trip through JSON, and says how\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n expect(JSON.stringify(evidence).length).toBeLessThanOrEqual(IDENTITY_MAX_EVIDENCE);\n const verified = await verify(h, statement, evidence);\n expect(verified.source.length).toBeGreaterThan(0);\n if (h.provider.category === \"self-custodied\") expect(verified.subject).toBe(h.subject);\n else expect(verified.attester).toBeTruthy();\n if (verified.expiresAt !== undefined) expect(verified.expiresAt).toBeGreaterThan(statement.binding.issuedAt);\n }, timeout);\n\n it(\"verifies through ctx.fetch only, never the global fetch\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n const global = vi.spyOn(globalThis, \"fetch\").mockRejectedValue(new Error(\"global fetch used\"));\n await verify(h, statement, evidence);\n expect(global).not.toHaveBeenCalled();\n }, timeout);\n\n it(\"refuses evidence made for another statement: each field of the binding counts\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n const b = statement.binding;\n const changes: Partial<IdentityBinding>[] = [\n { key: createIdentity().pubKeyZ32 },\n { nonce: \"A\".repeat(22) },\n { issuedAt: b.issuedAt - 1 },\n { expiresAt: b.expiresAt + 1 },\n ];\n for (const change of changes) await expect(verify(h, identityStatement({ ...b, ...change }), evidence), JSON.stringify(change)).rejects.toThrow();\n }, timeout);\n\n it(\"refuses another identity's evidence\", async () => {\n const h = await make();\n if (!h.proveAsOther) return;\n const statement = statementFor(h);\n await expect(verify(h, statement, await h.proveAsOther(statement))).rejects.toThrow();\n }, timeout);\n\n it(\"refuses malformed evidence before verifying\", async () => {\n const h = await make();\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n const garbage: unknown[] = [null, 42, \"evidence\", [], [evidence], { ...(evidence as object), extra: \"x\" }, { junk: \"x\".repeat(IDENTITY_MAX_EVIDENCE) }];\n for (const raw of garbage) await expect(verifyIdentity([h.provider as IdentityProofProvider], statement, raw, ctxOf(h))).rejects.toThrow();\n }, timeout);\n\n it(\"refuses a proof lasting longer than the provider allows\", async () => {\n const h = await make();\n const b = statementFor(h).binding;\n if (h.provider.validity.maxDays >= 400) return;\n const long = identityStatement({ ...b, expiresAt: b.issuedAt + (h.provider.validity.maxDays + 1) * 86_400 });\n await expect(verify(h, long, await h.prove(long))).rejects.toThrow(/longer/);\n }, timeout);\n\n it(\"is verified by the contact it is shared with, and a copy replayed to another contact fails\", async () => {\n const h = await make();\n const provider = h.provider as IdentityProofProvider;\n const { binding, seed } = newIdentityBinding({ provider: provider.id, subject: h.subject, validitySeconds: provider.validity.defaultDays * 86_400, now: h.now });\n const statement = identityStatement(binding);\n const local: LocalIdentityProof = { statement, evidence: await h.prove(statement), seed };\n const [alice, bob, carol] = [createIdentity().pubKeyZ32, createIdentity().pubKeyZ32, createIdentity().pubKeyZ32];\n const ledgers = new Map<string, IdentityLedger>();\n const sent: Record<string, unknown>[] = [];\n const peers = new Map<string, IdentityExchange>();\n const make2 = (me: string, them: string, context: string) => {\n const key = `${me}>${them}`;\n ledgers.set(key, emptyIdentityLedger());\n const x = new IdentityExchange({\n scope: () => ({ subject: me, audience: them, context, session: \"c\".repeat(64) }),\n send: frame => { sent.push(frame as Record<string, unknown>); queueMicrotask(() => void peers.get(`${them}>${me}`)?.receive(structuredClone(frame) as Record<string, unknown>)); },\n storage: { read: () => ledgers.get(key)!, update: async change => { ledgers.set(key, change(structuredClone(ledgers.get(key)!))); } },\n providers: () => [provider.id],\n localProof: id => (id === statement.id ? local : undefined),\n verify: (s, e) => verifyIdentity([provider], s, e, ctxOf(h)),\n now: () => h.now ?? Math.floor(Date.now() / 1000),\n });\n peers.set(key, x);\n return x;\n };\n const aliceToBob = make2(alice, bob, \"a\".repeat(64));\n make2(bob, alice, \"a\".repeat(64));\n make2(carol, alice, \"b\".repeat(64));\n await aliceToBob.share(statement.id, true);\n await vi.waitFor(() => expect(ledgers.get(`${alice}>${bob}`)!.shared[0]?.status).toBe(\"accepted\"), { timeout });\n expect(ledgers.get(`${bob}>${alice}`)!.received).toHaveLength(1);\n expect(ledgers.get(`${carol}>${alice}`)!.received).toHaveLength(0);\n // Bob forwards what he received to Carol: no challenge of hers, wrong audience, and no proof key.\n const present = sent.find(f => f.t === \"idp-present\")!;\n await peers.get(`${carol}>${alice}`)!.receive({ t: \"idp-request\", id: statement.id, provider: provider.id });\n const challenge = sent.filter(f => f.t === \"idp-challenge\").at(-1)!;\n await peers.get(`${carol}>${alice}`)!.receive({ ...present, nonce: challenge.nonce, issuedAt: challenge.issuedAt });\n expect(ledgers.get(`${carol}>${alice}`)!.received).toHaveLength(0);\n expect(sent.at(-1)).toMatchObject({ t: \"idp-result\", ok: false });\n }, timeout);\n\n it(\"fails a re-check once revoked, when it can go stale\", async () => {\n const h = await make();\n if (!h.provider.recheck) return;\n expect(h.revoke, \"a provider with recheck must let the harness revoke\").toBeTypeOf(\"function\");\n const statement = statementFor(h);\n const evidence = await h.prove(statement);\n await verify(h, statement, evidence);\n await h.revoke!();\n await expect(verify(h, statement, evidence)).rejects.toThrow();\n }, timeout);\n });\n}\n"],"mappings":";;;;;;;AAkBA,IAAM,OAAO;AACb,IAAM,SAAS,EAAE,cAAgC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AY,aAAa,CAAC;GAChC,MAAM,WAAW,MAAM,EAAE,MAAM,SAAS;GACxC,MAAM,OAAO,GAAG,WAAW,QAAQ;GACnC,MAAM,EAAE,OAAQ;GAChB,MAAM,OAAO,OAAO,GAAG,WAAW,QAAQ,CAAC,CAAC,CAAC,QAAQ,QAAQ;EAC/D,GAAG,OAAO;CACZ,CAAC;AACH"}
|
|
@@ -116,9 +116,17 @@ export interface ApprovalRequest {
|
|
|
116
116
|
/** Short lines under the choices. */
|
|
117
117
|
notes?: readonly string[];
|
|
118
118
|
}
|
|
119
|
+
/** A signer's own wait for the person's approval ended (Pubky's relay forgot the request): a time-out, not a failure. */
|
|
120
|
+
export declare class SignerTimeout extends Error {
|
|
121
|
+
}
|
|
119
122
|
export interface SignerContext {
|
|
120
123
|
values: Record<string, string>;
|
|
121
124
|
signal: AbortSignal;
|
|
125
|
+
/**
|
|
126
|
+
* How long the caller waits for the approval (the CLI's --timeout): a signer with a wait of its own takes this one,
|
|
127
|
+
* up to its `maxWaitMs`. Its own wait when absent (the app).
|
|
128
|
+
*/
|
|
129
|
+
waitMs?: number;
|
|
122
130
|
/** The signer asks the person to approve on a page (NIP-46 auth_url): the UI shows it as a link, never opens it itself. */
|
|
123
131
|
onAuthUrl(url: string): void;
|
|
124
132
|
onProgress(message: string): void;
|
|
@@ -162,6 +170,8 @@ interface SignerBase {
|
|
|
162
170
|
export interface InAppSigner<E> extends SignerBase {
|
|
163
171
|
kind: "in-app";
|
|
164
172
|
fields?: readonly SignerField[];
|
|
173
|
+
/** The longest it can wait for an approval, whatever `waitMs` says (Pubky: its relay keeps a request five minutes). */
|
|
174
|
+
maxWaitMs?: number;
|
|
165
175
|
/** Opens the signer, runs `work`, and always cleans up (closes connections, drops keys) before resolving. */
|
|
166
176
|
run<T>(ctx: SignerContext, work: (session: SignerSession<E>) => Promise<T>): Promise<T>;
|
|
167
177
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type WalletNetwork } from "../../../core/src/index.js";
|
|
2
2
|
/**
|
|
3
3
|
* Mints a new wallet starts with, so nobody has to know what a mint is before
|
|
4
4
|
* receiving sats. The first one that answers is where Lightning invoices are
|
|
@@ -23,6 +23,8 @@ export declare const isTestMint: (url: string) => boolean;
|
|
|
23
23
|
* A mint URL spelled as the wallet stores its mints: lower-case scheme and host, no default port, no trailing slash.
|
|
24
24
|
* Another Cashu wallet's token or request names a mint as its user typed it (`HTTPS://Mint.Example:443/`), which is
|
|
25
25
|
* still one of ours. Not a check: `normalizeMintUrl` is the one that refuses a mint.
|
|
26
|
+
* Its slashes come off in one pass (`trimEndOf`): a contact's token names any mint, and a `/\/+$/` retried from every
|
|
27
|
+
* `/` of a long run that does not end it froze the page for seconds.
|
|
26
28
|
*/
|
|
27
29
|
export declare function mintUrlSpelling(url: string): string;
|
|
28
30
|
/** A mint on this very machine (a local test server): whatever it issues is not money anyone else holds. */
|
|
@@ -166,7 +166,9 @@ export interface FileTransferRecord {
|
|
|
166
166
|
abortedBySender?: boolean;
|
|
167
167
|
/**
|
|
168
168
|
* In: taken, by the person or within the app's limits. An offer that expired unanswered never was, so offered again
|
|
169
|
-
* it is refused, never taken without asking.
|
|
169
|
+
* it is refused, never taken without asking. Out: the receiver took it (`pf-accept`), so the offer's week no longer
|
|
170
|
+
* ends it (`sweep`): a file paused or cut off for more than a week failed "Not delivered in time" when it went on,
|
|
171
|
+
* and its part there was deleted.
|
|
170
172
|
*/
|
|
171
173
|
agreed?: boolean;
|
|
172
174
|
}
|
|
@@ -115,6 +115,10 @@ export declare function mergeLobby(existing: LobbyEntry[], mine: LobbyEntry, now
|
|
|
115
115
|
export declare function freshHubs(hubs: Hub[], now?: number): Hub[];
|
|
116
116
|
/** Rendezvous hashing: how strongly a hub is responsible for someone (a knock, a member). Highest first. */
|
|
117
117
|
export declare function hubRank(subject: string, hubKey: string): string;
|
|
118
|
+
/**
|
|
119
|
+
* `hubs` by `hubRank` for `subject`, highest first. Each key's rank is worked out once: in the sort's comparator it
|
|
120
|
+
* was two hashes a comparison, ~16 a key for a community's roster, which members rank on each tick of a hub's step-in.
|
|
121
|
+
*/
|
|
118
122
|
export declare function rankHubs(subject: string, hubs: string[]): string[];
|
|
119
123
|
/**
|
|
120
124
|
* The hubs a member asks for edges: fresh ones with room, at most `hubsPerMember`, by rendezvous hashing weighted by
|
|
@@ -202,6 +202,12 @@ export declare class DhtDelivery {
|
|
|
202
202
|
private announceTimer;
|
|
203
203
|
private chain;
|
|
204
204
|
private lastPublish;
|
|
205
|
+
/**
|
|
206
|
+
* A withdrawn text's envelope may still be on the relays, and the one to replace it has not gone (`withdraw`): it is
|
|
207
|
+
* tried again with a text's backoff, `MAX_ATTEMPTS` times at most, until `until` (when no reader takes the withdrawn
|
|
208
|
+
* one any more), not at the next keep-alive four minutes on. Any envelope that goes out replaces it.
|
|
209
|
+
*/
|
|
210
|
+
private withdrawal?;
|
|
205
211
|
/** The sequence of the last envelope of the contact that was past its expiry (traced once). */
|
|
206
212
|
private expiredSeen;
|
|
207
213
|
private controlDue;
|
|
@@ -448,6 +454,16 @@ export declare class DhtDelivery {
|
|
|
448
454
|
* failed is retried, as a text's is).
|
|
449
455
|
*/
|
|
450
456
|
announceFile(file: DhtFileOffer, timestamp: number, reply?: string, forwarded?: number): Promise<string | null>;
|
|
457
|
+
/** Whether the floor holds this text of mine, or an edit of it (`pending`), whatever its retries or expiry. */
|
|
458
|
+
holds(wireId: string): boolean;
|
|
459
|
+
/**
|
|
460
|
+
* A text of mine (or an edit of it) deleted here while it waits on the floor leaves it: the state no longer holds it
|
|
461
|
+
* (nor as `confirmed`: no receipt came), and, while its envelope was still in effect, a new one without it takes that
|
|
462
|
+
* one's place on the relays, so a contact who looks later finds no text. Resolves once the state without it is saved;
|
|
463
|
+
* the new envelope goes after. One that does not go (no relay reachable) is tried again within seconds (`withdrawal`):
|
|
464
|
+
* a reader takes the withdrawn envelope until its expiry and the clock skew allowed past it (`DHT_EXPIRY_SKEW_MS`).
|
|
465
|
+
*/
|
|
466
|
+
withdraw(wireId: string): Promise<void>;
|
|
451
467
|
/** The id of what awaits its receipt on the floor now, if anything does. */
|
|
452
468
|
get pendingId(): string | undefined;
|
|
453
469
|
/**
|
|
@@ -34,6 +34,7 @@ export declare const ENGINE_ERRORS: {
|
|
|
34
34
|
readonly reviewedSatsGone: "The sats this payment was reviewed with went to another payment. Nothing was sent: review it again.";
|
|
35
35
|
readonly mintFailedQuote: "{host} could not take this payment right now, and no sats left your wallet: try again later. The mint said: {reason}";
|
|
36
36
|
readonly mintFailedFaucet: "{host} could not give test coins right now: try again later. The mint said: {reason}";
|
|
37
|
+
readonly mintFailedInvoice: "{host} could not create an invoice right now: try again later. The mint said: {reason}";
|
|
37
38
|
readonly lightningFeeTooHigh: "The Lightning fee ({fee} sats) is too high";
|
|
38
39
|
readonly lightningRefused: "The mint refused this Lightning payment, and no sats left your wallet: it is safe to try again. The mint said: {reason}";
|
|
39
40
|
readonly invoiceExpired: "That invoice has expired";
|
|
@@ -78,7 +79,13 @@ export declare const ENGINE_ERRORS: {
|
|
|
78
79
|
readonly fedimintTestOnMainnet: "This federation is on {chain}, a test network: it belongs in a Testnet Fedimint wallet";
|
|
79
80
|
readonly walletAway: "{wallet} can't be used here. Use it on {device}.";
|
|
80
81
|
readonly walletAwayUnnamed: "{wallet} can't be used here: its home is another device.";
|
|
82
|
+
readonly serviceShareFull: "A contact can reach at most {max} of your apps: take one back from them before sharing another";
|
|
81
83
|
readonly groupTurnUnconfirmed: "Can't check which device is active, so the group was not changed. Try again in a moment.";
|
|
84
|
+
readonly groupNoCall: "This group has no calls: its admin has not set a call server";
|
|
85
|
+
readonly groupCallNotMember: "You are not in this group, so you can't join its call";
|
|
86
|
+
readonly groupCallRefused: "{host} did not let you into the group's call. Try again in a minute.";
|
|
87
|
+
readonly groupCallBusy: "{host} is busy. Try the call again in a minute.";
|
|
88
|
+
readonly groupCallFailed: "{host} could not start the group's call. Try again later.";
|
|
82
89
|
};
|
|
83
90
|
export type EngineErrorCode = keyof typeof ENGINE_ERRORS;
|
|
84
91
|
export type EngineErrorValues = Record<string, string | number>;
|