@ghostlytools/sdk 1.13.0 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"bitcoinAddress-C2MAmcDT.js","names":[],"sources":["../../core/src/text.ts","../../core/src/identity.ts","../../core/src/identityTimeline.ts","../../core/src/identityProofs.ts","../../core/src/bitcoinAddress.ts"],"sourcesContent":["/**\n * Display text a peer chooses: nicknames and service names. It is shown next\n * to the peer's messages and in the chat header, so it must not be able to\n * read as something it is not, and it must not be able to grow without bound.\n */\n\n/** Longest nickname kept from a peer. The `hello` frame has always cut here. */\nexport const MAX_NICK_LENGTH = 64;\n\n/**\n * Invisible and direction-changing characters. Unlike a file name, display\n * text may legitimately hold emoji and Indic or Arabic joiners, so the two\n * joiners stay and the rest of Cf goes: bidi overrides and isolates reorder\n * what follows them, and the others hide text or let two different names\n * render identically.\n */\nconst HIDDEN = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]/gu;\n/** Zero-width non-joiner and zero-width joiner. */\nconst KEEP = /[\\u200c\\u200d]/;\n\n/** `text` without its invisible and direction-changing characters, at any length: for display text with a cut of its own. */\nexport function stripHidden(text: string): string {\n return text.replace(HIDDEN, (char) => (KEEP.test(char) ? char : \"\"));\n}\n\n/** The variation selectors other than VS15 and VS16: a symbol's, an ideograph's, a Mongolian letter's. */\nconst SELECTOR = /[︀-︍᠋-᠍᠏\\u{e0100}-\\u{e01ef}]/u;\n/** Letters of the alphabets that neither join their letters nor make conjuncts: a joiner beside one changes nothing. */\nconst NO_JOINING = /[\\p{sc=Latin}\\p{sc=Greek}\\p{sc=Cyrillic}\\p{sc=Armenian}\\p{sc=Georgian}\\p{sc=Hebrew}\\p{sc=Han}\\p{sc=Hiragana}\\p{sc=Katakana}\\p{sc=Hangul}\\p{sc=Thai}\\p{sc=Lao}\\p{sc=Ethiopic}]/u;\nconst EUROPEAN = /[\\p{sc=Latin}\\p{sc=Greek}\\p{sc=Cyrillic}]/u;\nconst LETTER = /\\p{L}/u, MARK = /\\p{M}/u, SYMBOL = /\\p{S}/u;\nconst PICTOGRAPH = /\\p{Extended_Pictographic}/u;\n/** What an emoji sequence's joiner follows: a pictograph, a skin tone, or VS16 after a pictograph. */\nconst BEFORE_EMOJI_JOINER = /[\\p{Extended_Pictographic}\\p{Emoji_Modifier}️]/u;\nconst EMOJI = /\\p{Emoji}/u, ASCII = /^[\\0-\\x7f]$/, KEYCAP_BASE = /^[#*0-9]$/;\nconst joining = (char: string) => LETTER.test(char) && !NO_JOINING.test(char);\n\n/**\n * `text` without the joiners and variation selectors that join or select nothing, which draw nothing and could only\n * make a name look like another one, or one nobody can type. A zero-width joiner stays between two emoji (a skin tone\n * or VS16 before it) and either joiner between two letters of a script that joins its letters or makes conjuncts\n * (Persian, the Indic scripts; the marks after the first letter, a virama, don't count); VS15 and VS16 stay after an\n * emoji (an ASCII one only in a keycap), and the other selectors after a symbol or a letter that is not Latin, Greek or\n * Cyrillic.\n */\nexport function dropLoneJoiners(text: string): string {\n const chars = Array.from(text);\n let out = \"\", last = \"\", base = \"\";\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i], next = chars[i + 1] ?? \"\";\n let keep = true;\n if (char === \"‍\" || char === \"‌\") keep = (char === \"‍\" && BEFORE_EMOJI_JOINER.test(last) && PICTOGRAPH.test(next)) || (joining(base) && joining(next));\n else if (char === \"︎\" || char === \"️\") keep = (EMOJI.test(last) && !ASCII.test(last)) || (KEYCAP_BASE.test(last) && next === \"⃣\");\n else if (SELECTOR.test(char)) keep = SYMBOL.test(last) || (LETTER.test(last) && !EUROPEAN.test(last));\n if (!keep) continue;\n out += char;\n last = char;\n if (!MARK.test(char)) base = char;\n }\n return out;\n}\n\n/**\n * What draws nothing when it stands alone and `HIDDEN` leaves in, since text needs it beside something else: the\n * joiners, the fillers, the variation selectors and the other default-ignorable code points, combining marks, white\n * space and the blank Braille pattern.\n */\nconst UNSEEN = /^[\\p{Default_Ignorable_Code_Point}\\p{M}\\p{White_Space}\\u2800]*$/u;\n\n/** Whether `text` holds a character that shows by itself: a name of joiners, fillers or marks alone has none. */\nexport function hasVisible(text: string): boolean {\n return !UNSEEN.test(text);\n}\n\n/** Undefined when nothing visible is left, so callers can fall back. */\nexport function sanitizeDisplayText(text: string, max: number): string | undefined {\n const clean = [...stripHidden(text)].slice(0, max).join(\"\").trim();\n return hasVisible(clean) ? clean : undefined;\n}\n\n/** A nickname as it arrived from a peer, ready to show. */\nexport function sanitizeNick(nick: unknown): string | undefined {\n return typeof nick === \"string\" ? sanitizeDisplayText(nick, MAX_NICK_LENGTH) : undefined;\n}\n\n/**\n * `text` without the characters of `chars` it ends with, in one pass from the end. A `/[…]+$/` replace would retry\n * from every character of a run that does not reach the end.\n */\nexport function trimEndOf(text: string, chars: string): string {\n let end = text.length;\n while (end > 0 && chars.includes(text[end - 1])) end--;\n return end === text.length ? text : text.slice(0, end);\n}\n\n/** What a token is copied with before it: quotes, guillemets, brackets, a backtick. */\nconst PASTE_OPENERS = \"\\\"'“‘«‹<[({`\";\n/** What a token is copied with after it: those closed, and a sentence's marks. */\nconst PASTE_CLOSERS = \"\\\"'”’»›>])}`.,!?;:…\";\nconst PASTE_SPACES = \" \\t\\n\\r\\u00a0\\u202f\";\n\n/**\n * The token in what someone copied with the words around it: an invite, a group's link or a device code from the end\n * of \"Join us: <https://…#ghostly1…>!\", \"« ghostly1… »\" or \"code: ghostly1…\". The last word, without the quotes,\n * brackets and marks before and after it. Readers try it only once the paste itself did not read, so a bare token\n * reads as it always did and a token with a character lost is still refused as one.\n * A `/` a link ends with (typed, or added by a chat app's linkifier: `…/#/join/group2/…/`) is not the token's either,\n * as `inviteRouteCode` drops it from an invite's route; a bare address keeps its own (`https://ghostly.tools/`).\n */\nexport function unwrapPasted(text: string): string {\n const words = trimEndOf(text.trim(), PASTE_CLOSERS + PASTE_SPACES).split(/\\s+/);\n const last = words[words.length - 1] ?? \"\";\n let start = 0;\n while (start < last.length && PASTE_OPENERS.includes(last[start])) start++;\n const token = trimEndOf(last.slice(start), PASTE_CLOSERS);\n const bare = trimEndOf(token, PASTE_CLOSERS + \"/\");\n return /:\\/\\/[^/]*$/.test(bare) ? token : bare;\n}\n","import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { fromBase64Url, fromZ32, randomBytes, toBase64Url, toZ32 } from \"./bytes\";\n\n/**\n * A Ghostly identity is an Ed25519 keypair. The public key, z-base-32 encoded,\n * is the peer's Pkarr address. Today every link (chat) uses its own identity,\n * exactly like Ghostly Desktop.\n */\nexport interface Identity {\n seed: Uint8Array;\n seedB64: string;\n publicKey: Uint8Array;\n pubKeyZ32: string;\n}\n\n/** How many public keys `identityFromSeed` keeps however long ago they were used: a start with 50 chats and 20 groups derives about 400 distinct ones. */\nexport const IDENTITY_MEMO_SIZE = 1024;\n/**\n * Past `IDENTITY_MEMO_SIZE`, a key is let go only once it has not been asked for this long: a start asks for all of a\n * profile's keys within seconds (a 600-chat one, ~4,000 of them), then asks again for the running links' ones.\n */\nexport const IDENTITY_MEMO_IDLE_MS = 10 * 60_000;\n/** The most keys kept, used or not: ~410 bytes each in V8 (its id, its key and when it was used), ~6.7 MB in all. */\nexport const IDENTITY_MEMO_MAX = 16_384;\n/**\n * Public keys already derived, by the SHA-256 of their seed, the most recently used last. A chat's start derives the\n * same few seeds' keys again and again (its link, its delivery, its capability record): ~0.25 ms each in V8, ~3.4x\n * that in JSC. The seed itself is never kept, so a seed its owner zeroes leaves nothing behind here.\n */\nconst publicKeys = new Map<string, { key: Uint8Array; at: number }>();\n\n/**\n * A faster derivation of a seed's Ed25519 public key a host may give (the CLI gives node:crypto's, ~4x noble's): each\n * process starts with an empty memo, so a one-shot command derives every chat's keys again. A throw, or an answer that\n * is not 32 bytes, leaves the key to noble.\n */\nexport type PublicKeyFastPath = (seed: Uint8Array) => Uint8Array;\n\nlet publicKeyFastPath: PublicKeyFastPath | null = null;\n\n/** Gives (or, with `null`, takes back) the faster derivation of every public key `identityFromSeed` derives. */\nexport function setPublicKeyFastPath(derive: PublicKeyFastPath | null): void {\n publicKeyFastPath = derive;\n}\n\nfunction derivePublicKey(seed: Uint8Array): Uint8Array {\n if (publicKeyFastPath) {\n try {\n const key = publicKeyFastPath(seed);\n if (key.length === 32) return Uint8Array.from(key);\n } catch { /* noble's below */ }\n }\n return ed25519.getPublicKey(seed);\n}\n\nfunction publicKeyOf(seed: Uint8Array): Uint8Array {\n const id = toBase64Url(sha256(seed));\n const now = Date.now();\n let entry = publicKeys.get(id);\n if (entry) {\n publicKeys.delete(id);\n entry.at = now;\n } else {\n entry = { key: derivePublicKey(seed), at: now };\n for (const [oldest, { at }] of publicKeys) {\n if (publicKeys.size < IDENTITY_MEMO_SIZE) break;\n if (publicKeys.size < IDENTITY_MEMO_MAX && now - at < IDENTITY_MEMO_IDLE_MS) break;\n publicKeys.delete(oldest);\n }\n }\n publicKeys.set(id, entry);\n // A copy: a caller that writes over its key never changes another's.\n return entry.key.slice();\n}\n\nexport function identityFromSeed(seed: Uint8Array): Identity {\n if (seed.length !== 32) throw new Error(\"Seed must be exactly 32 bytes\");\n const publicKey = publicKeyOf(seed);\n return {\n seed,\n seedB64: toBase64Url(seed),\n publicKey,\n pubKeyZ32: toZ32(publicKey),\n };\n}\n\nexport function identityFromSeedB64(seedB64: string): Identity {\n return identityFromSeed(fromBase64Url(seedB64));\n}\n\nexport function createIdentity(): Identity {\n return identityFromSeed(randomBytes(32));\n}\n\nexport function publicKeyFromZ32(z32: string): Uint8Array {\n if (z32.length !== 52) throw new Error(\"Invalid public key: expected 52 z-base-32 characters\");\n const bytes = fromZ32(z32);\n // One key, one spelling: a 52-character string whose four padding bits are not zero decodes to the same 32 bytes\n // as the canonical one but is not it, and keys are compared as strings (WISP 02).\n if (toZ32(bytes) !== z32) throw new Error(\"Invalid public key: not canonical z-base-32\");\n return bytes;\n}\n\nexport function sign(message: Uint8Array, seed: Uint8Array): Uint8Array {\n return ed25519.sign(message, seed);\n}\n\n/**\n * Ed25519 verification as RFC 8032 writes it (`zip215: false`): canonical encodings only, and no key of small order,\n * which no secret key goes with and which \"verifies\" a constant signature of any message.\n */\nexport function verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {\n try {\n return ed25519.verify(signature, message, publicKey, { zip215: false });\n } catch {\n return false;\n }\n}\n","/**\n * What a chat's timeline shows of the identity-proof exchange (WISP 300, \"In the conversation\"): one entry when\n * an identity is shared, on both sides, turning verified or failed as the exchange settles, and one when it stops\n * (withdrawn by its owner, or found revoked). Local only: made from the exchange's own steps, stored with the\n * chat's identity ledger, never sent. Nothing new goes on the wire.\n */\n\n/** \"mine\": this side shared it. \"theirs\": the contact did. */\nexport type IdentityTimelineSide = \"mine\" | \"theirs\";\nexport type IdentityTimelineState = \"verifying\" | \"verified\" | \"failed\";\n\nexport interface IdentityTimelineEntry {\n /**\n * Unique in the chat: side, proof and one past the highest number that proof's kept entries on that side have. A\n * contact's later attempt that took the entry over keeps it (see applyIdentityEvent).\n */\n id: string;\n /** The proof's id (identityStatement().id). */\n proof: string;\n side: IdentityTimelineSide;\n kind: \"shared\" | \"stopped\";\n provider: string;\n /** The identity, once known: at once on the sharer's side, from the presentation on the contact's. */\n subject?: string;\n /** A share only: where the contact's check stands. */\n state?: IdentityTimelineState;\n /** A failed share: why, as the verifier said it. */\n error?: string;\n /** A stop only: its owner withdrew it here, or its proof key published a revocation. */\n reason?: \"withdrawn\" | \"revoked\";\n /** Milliseconds. When it happened; later steps of the same share leave it in place. */\n at: number;\n}\n\n/** One step of the exchange, as the timeline needs it. */\nexport type IdentityTimelineEvent =\n /** A share began: this side shared, or the contact asked for a challenge. `requested`: the id the request named. */\n | { type: \"shared\"; side: IdentityTimelineSide; proof: string; provider: string; subject?: string }\n /** The contact's check settled. `requested`: the id the request named, when the presented proof is another. */\n | { type: \"result\"; side: IdentityTimelineSide; proof: string; requested?: string; provider?: string; subject?: string; ok: boolean; error?: string }\n | { type: \"stopped\"; side: IdentityTimelineSide; proof: string; provider: string; subject?: string; reason: \"withdrawn\" | \"revoked\" }\n /** A share taken back before it ever left this side (queued, the contact never heard of it): its entry goes. */\n | { type: \"unsent\"; side: \"mine\"; proof: string }\n /** The contact asked for a challenge and presented nothing within its window: its entry goes, as `unsent` does. */\n | { type: \"unanswered\"; side: \"theirs\"; proof: string };\n\n/** Entries a chat keeps, newest last. */\nexport const IDENTITY_TIMELINE_MAX = 100;\n\nconst lastOf = (timeline: readonly IdentityTimelineEntry[], side: IdentityTimelineSide, proofs: readonly (string | undefined)[]) => {\n for (let i = timeline.length - 1; i >= 0; i--) if (timeline[i].side === side && proofs.includes(timeline[i].proof)) return i;\n return -1;\n};\n\n/** The contact's share of this kind still not verified (checking, or failed): the one its next attempt takes over. */\nconst unverifiedOf = (timeline: readonly IdentityTimelineEntry[], provider: string | undefined) => {\n for (let i = timeline.length - 1; i >= 0; i--) {\n const e = timeline[i];\n if (e.side === \"theirs\" && e.kind === \"shared\" && e.state !== \"verified\" && e.provider === provider) return i;\n }\n return -1;\n};\n\n/**\n * The timeline after one step. A share already on it is updated in place, never repeated: a request sent again at\n * a reconnect, a second share of a proof the contact already verified. A new attempt after a failure or a stop is\n * a new entry, except the contact's own not verified: those keep one entry per kind, which its next attempt takes\n * over in place (its id and time stay, so no new sound and the chat does not move). The ids and the kind are the\n * contact's to choose, so otherwise its requests alone could push every other entry, this side's too, out of the\n * bound. A stop is written once; a withdrawal later found revoked becomes a revocation in place.\n */\nexport function applyIdentityEvent(timeline: readonly IdentityTimelineEntry[], event: IdentityTimelineEvent, at: number): IdentityTimelineEntry[] {\n const out = [...timeline];\n const i = lastOf(out, event.side, event.type === \"result\" ? [event.proof, event.requested] : [event.proof]);\n const last = i >= 0 ? out[i] : undefined;\n /** Puts the contact's attempt on the entry of its kind still not verified, if there is one. */\n const takeOver = (entry: Omit<IdentityTimelineEntry, \"id\" | \"at\" | \"side\" | \"kind\">) => {\n const j = event.side === \"theirs\" ? unverifiedOf(out, entry.provider) : -1;\n if (j < 0) return false;\n out[j] = { id: out[j].id, proof: entry.proof, side: \"theirs\", kind: \"shared\", provider: entry.provider, ...(entry.subject ? { subject: entry.subject } : {}),\n state: entry.state, ...(entry.error ? { error: entry.error } : {}), at: out[j].at };\n return true;\n };\n const add = (entry: Omit<IdentityTimelineEntry, \"id\" | \"at\">) => {\n // One past the highest number kept, not the count: the bound may have cut this proof's earlier entries.\n const prefix = `${entry.side}:${entry.proof}:`;\n let n = 0;\n for (const e of out) if (e.id.startsWith(prefix)) n = Math.max(n, Number(e.id.slice(prefix.length)) + 1 || 0);\n out.push({ ...entry, id: `${prefix}${n}`, at });\n };\n switch (event.type) {\n case \"shared\":\n if (last?.kind === \"shared\" && last.state !== \"failed\") {\n out[i] = { ...last, provider: event.provider, subject: event.subject ?? last.subject };\n break;\n }\n if (takeOver({ proof: event.proof, provider: event.provider, subject: event.subject, state: \"verifying\" })) break;\n add({ proof: event.proof, side: event.side, kind: \"shared\", provider: event.provider, ...(event.subject ? { subject: event.subject } : {}), state: \"verifying\" });\n break;\n case \"result\": {\n const settled = { state: event.ok ? \"verified\" as const : \"failed\" as const, ...(event.ok || !event.error ? {} : { error: event.error }) };\n if (last?.kind === \"shared\") {\n const { error: _, ...rest } = last;\n out[i] = { ...rest, proof: event.proof, provider: event.provider ?? last.provider, subject: event.subject ?? last.subject, ...settled };\n break;\n }\n // Its start is no longer kept (the timeline is bounded, or a later attempt took it over): the outcome stands\n // alone, a failed one on the contact's entry of its kind still not verified.\n if (!event.ok && event.provider && takeOver({ proof: event.proof, provider: event.provider, subject: event.subject, ...settled })) break;\n if (event.provider) add({ proof: event.proof, side: event.side, kind: \"shared\", provider: event.provider, ...(event.subject ? { subject: event.subject } : {}), ...settled });\n break;\n }\n case \"stopped\":\n // A revocation found after the withdrawal (a removal is both, WISP 300) says what the stop was: the same entry.\n if (last?.kind === \"stopped\") { if (last.reason === \"withdrawn\" && event.reason === \"revoked\") out[i] = { ...last, reason: \"revoked\" }; break; }\n add({ proof: event.proof, side: event.side, kind: \"stopped\", provider: event.provider, subject: event.subject ?? last?.subject, reason: event.reason });\n break;\n case \"unsent\":\n case \"unanswered\":\n if (last?.kind === \"shared\" && last.state === \"verifying\") out.splice(i, 1);\n break;\n }\n return out.length > IDENTITY_TIMELINE_MAX ? out.slice(-IDENTITY_TIMELINE_MAX) : out;\n}\n\n/** When the contact last shared an identity here (milliseconds), for the chat list: 0 when never. */\nexport function lastSharedWithMe(timeline: readonly IdentityTimelineEntry[] | undefined): number {\n let at = 0;\n for (const e of timeline ?? []) if (e.side === \"theirs\" && e.kind === \"shared\" && e.at > at) at = e.at;\n return at;\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { fromBase64Url, isZ32Key, randomBytes, toBase64Url, utf8Encode } from \"./bytes\";\nimport { identityFromSeed, publicKeyFromZ32, sign, verify } from \"./identity\";\nimport { applyIdentityEvent, type IdentityTimelineEntry, type IdentityTimelineEvent } from \"./identityTimeline\";\nimport { hasVisible, stripHidden } from \"./text\";\n\n/**\n * Identity proofs (WISP 300), provider-agnostic half.\n *\n * A proof is made once per profile: the external identity (a Nostr key, a domain, an SSH key, an\n * OpenID Connect account…) signs or attests the canonical **statement** below, which authorizes a\n * fresh Ed25519 **proof key** that only this profile holds. Sharing it with a contact is then a\n * challenge-response on that contact's authenticated paired channel: the contact sends a fresh nonce,\n * the proof key signs a **presentation** binding the proof to both participation keys, the\n * conversation, the session and that nonce. A copy replayed to anyone else fails: wrong audience,\n * unknown nonce, and nobody else has the proof key.\n *\n * Providers (browser side, `packages/browser/src/proofs/`) only know how to produce and check the\n * evidence over the statement bytes; everything here is shared, so every provider signs the same bytes.\n */\n\nexport const IDENTITY_PROOF_CAPABILITY = \"identity-proof/1\";\n/** Domain separation: the first words of every statement. */\nexport const IDENTITY_STATEMENT_PREFIX = \"Ghostly identity proof v1\";\n/** No binding is valid for longer than this, whatever the provider allows. */\nexport const IDENTITY_MAX_VALIDITY = 400 * 86_400;\n/** A binding issued this far in the future is refused (seconds of clock disagreement tolerated). */\nexport const IDENTITY_CLOCK_SKEW = 300;\n/** A contact's challenge must be answered within this many seconds. */\nexport const IDENTITY_CHALLENGE_WINDOW = 300;\n/** Evidence, serialized as JSON, is at most this many characters. */\nexport const IDENTITY_MAX_EVIDENCE = 16 * 1024;\n/** A whole `idp-*` frame, serialized. */\nexport const IDENTITY_MAX_FRAME = 32 * 1024;\n/** Unanswered challenges a verifier keeps per conversation. */\nconst MAX_CHALLENGES = 8;\n/** A challenge still open at `now` (seconds): a presentation for it is still taken. */\nconst liveAt = (c: { issuedAt: number }, now: number) => c.issuedAt > now - IDENTITY_CHALLENGE_WINDOW;\n/**\n * Proofs a verifier keeps from one contact. A newer proof of the same identity replaces the older one, and one no longer\n * standing (withdrawn, revoked, expired) gives its place to a new one; past that a presentation is refused before it is\n * checked, so a contact cannot make this side store, re-send to its pages and look up its proofs without end.\n */\nexport const IDENTITY_MAX_RECEIVED = 16;\n/** `idp-*` frames a paired session reads from the contact per `IDENTITY_FRAME_WINDOW_MS`; the rest are dropped unread. */\nexport const IDENTITY_FRAME_LIMIT = 40;\nexport const IDENTITY_FRAME_WINDOW_MS = 60_000;\n/**\n * A proof this side holds verified, presented again with the same evidence between the same keys, is answered from that\n * check while it is younger than this (seconds): the contact chooses how often it presents, and each check costs this\n * device a provider lookup (a forge's per-IP quota, a DNS query, a contact's server) and a Pkarr read. An hour keeps an\n * answer as fresh as a re-share can expect; past it, and between, the daily re-check (or Check again) asks the provider.\n */\nexport const IDENTITY_REUSE_CHECK_S = 3600;\n/**\n * Presentations a verifier checks with their provider per contact in an hour; past it the contact is told the check\n * could not run. Room for every proof it may keep (`IDENTITY_MAX_RECEIVED`) and a few retries: a contact making fresh\n * proofs cannot spend a forge's per-IP quota (GitHub: 60 an hour) for every chat and app on this network.\n */\nexport const IDENTITY_MAX_CHECKS_PER_HOUR = 20;\n\nexport const IDENTITY_PROVIDER_ID = /^[a-z][a-z0-9-]{0,31}$/;\n/** Printable ASCII without spaces, so the statement can be built but never needs parsing. */\nexport const IDENTITY_SUBJECT = /^[\\x21-\\x7e]{1,512}$/;\nconst BINDING_NONCE = /^[A-Za-z0-9_-]{22}$/;\nconst CHALLENGE_NONCE = /^[A-Za-z0-9_-]{43}$/;\nconst HEX64 = /^[a-f0-9]{64}$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\n\n/** What the external identity signs, as fields. `key` is the proof key (z-base-32 Ed25519). */\nexport interface IdentityBinding {\n v: 1;\n provider: string;\n subject: string;\n key: string;\n issuedAt: number;\n expiresAt: number;\n nonce: string;\n}\n\n/** A binding with its exact bytes. Providers sign `text` (UTF-8 `bytes`) and never rebuild it. */\nexport interface IdentityStatement {\n binding: IdentityBinding;\n text: string;\n bytes: Uint8Array;\n /** SHA-256 of `bytes`, lowercase hex: the proof's id everywhere (storage, frames, OIDC nonce input). */\n id: string;\n}\n\n/** What a provider's `verify` established. Stored by the verifier with the evidence. */\nexport interface VerifiedIdentity {\n /** The identity that was proven, canonical. Self-custodied providers: exactly `binding.subject`. */\n subject: string;\n /** How it was checked, for people: \"Nostr signature (BIP-340)\", \"ID token signed by accounts.google.com\". */\n source: string;\n /** Provider-attested only: who vouches for `subject` (an issuer host). */\n attester?: string;\n /** Earlier than the binding's own expiry when the evidence says so (a key or certificate expiring). */\n expiresAt?: number;\n /** Optional name/picture carried by the evidence itself, with where it came from. */\n display?: IdentityDisplay;\n}\n\nexport interface IdentityDisplay {\n name?: string;\n /** A sanitized `data:image/…` URL, never a remote one. */\n avatar?: string;\n /** Where the person can see the identity (a profile page), https only. */\n url?: string;\n /** Where name/picture came from: \"Nostr kind-0 metadata (self-described)\". */\n source: string;\n fetchedAt: number;\n}\n\nexport interface IdentityScope { subject: string; audience: string; context: string; session: string }\n\n/**\n * Early revocation: the proof key publishes, under its own Pkarr key, a TXT record naming the proof it\n * revokes. Anyone holding a copy can look it up by the key in the binding; nothing else is published,\n * and the key is random, so the record says nothing about the identity or its contacts.\n */\nexport const IDENTITY_REVOCATION_LABEL = \"_ghostly-revoked\";\nexport const identityRevocationValue = (id: string, at: number) => `v=1;id=${id};at=${at}`;\n/** True when these records (resolved and signature-checked under the proof key) revoke proof `id`. */\nexport function revokesIdentity(records: { label: string; value: string }[], id: string): boolean {\n return records.some(r => r.label === IDENTITY_REVOCATION_LABEL && new RegExp(`^v=1;id=${id};at=\\\\d{1,12}$`).test(r.value));\n}\n\nconst nowSeconds = () => Math.floor(Date.now() / 1000);\nconst hex = (bytes: Uint8Array) => Array.from(bytes, b => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst iso = (seconds: number) => new Date(seconds * 1000).toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\nconst isInt = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;\n\nexport function isIdentityBinding(value: unknown): value is IdentityBinding {\n const b = value as IdentityBinding;\n return !!b && typeof b === \"object\" && !Array.isArray(b) &&\n Object.keys(b).sort().join(\",\") === \"expiresAt,issuedAt,key,nonce,provider,subject,v\" && b.v === 1 &&\n typeof b.provider === \"string\" && IDENTITY_PROVIDER_ID.test(b.provider) &&\n typeof b.subject === \"string\" && IDENTITY_SUBJECT.test(b.subject) &&\n isZ32Key(b.key) && typeof b.nonce === \"string\" && BINDING_NONCE.test(b.nonce) &&\n isInt(b.issuedAt) && isInt(b.expiresAt) && b.expiresAt > b.issuedAt && b.expiresAt - b.issuedAt <= IDENTITY_MAX_VALIDITY &&\n // ISO dates in the text need years 1970–9999.\n b.expiresAt < 253_402_300_800;\n}\n\n/**\n * The canonical statement, one line, so it survives every tool and clipboard (no line-ending\n * ambiguity). Every field is space-free and the order is fixed, so the text is injective.\n */\nexport function identityStatementText(b: IdentityBinding): string {\n if (!isIdentityBinding(b)) throw new Error(\"Invalid identity binding\");\n return `${IDENTITY_STATEMENT_PREFIX}: I control ${b.provider}:${b.subject} and authorize the Ghostly key ${b.key} ` +\n `to present it to contacts I choose, from ${iso(b.issuedAt)} until ${iso(b.expiresAt)}. Nonce: ${b.nonce}`;\n}\n\nexport function identityStatement(binding: IdentityBinding): IdentityStatement {\n const text = identityStatementText(binding);\n const bytes = utf8Encode(text);\n return { binding: { ...binding }, text, bytes, id: hex(sha256(bytes)) };\n}\n\n/** A new binding and the seed of its proof key. The seed stays in this profile; never share it. */\nexport function newIdentityBinding(options: { provider: string; subject: string; validitySeconds: number; now?: number }): { binding: IdentityBinding; seed: Uint8Array } {\n const issuedAt = options.now ?? nowSeconds();\n const seed = randomBytes(32);\n const binding: IdentityBinding = { v: 1, provider: options.provider, subject: options.subject,\n key: identityFromSeed(seed).pubKeyZ32, issuedAt, expiresAt: issuedAt + options.validitySeconds, nonce: toBase64Url(randomBytes(16)) };\n if (!isIdentityBinding(binding)) { seed.fill(0); throw new Error(\"Invalid identity provider, subject or validity\"); }\n return { binding, seed };\n}\n\n/** Bytes the proof key signs for one contact. `scope` is the presenter's view (subject = presenter). */\nexport function identityPresentationBytes(proofId: string, scope: IdentityScope, nonce: string, issuedAt: number): Uint8Array {\n return utf8Encode(JSON.stringify([\"ghostly-identity-presentation\", 1, proofId, scope.subject, scope.audience, scope.context, scope.session, nonce, issuedAt]));\n}\n\nexport function signIdentityPresentation(seed: Uint8Array, proofId: string, scope: IdentityScope, nonce: string, issuedAt: number): string {\n return toBase64Url(sign(identityPresentationBytes(proofId, scope, nonce, issuedAt), seed));\n}\n\nexport function verifyIdentityPresentation(key: string, sig: string, proofId: string, scope: IdentityScope, nonce: string, issuedAt: number): boolean {\n if (typeof sig !== \"string\" || !SIG.test(sig) || !isZ32Key(key)) return false;\n return verify(fromBase64Url(sig), identityPresentationBytes(proofId, scope, nonce, issuedAt), publicKeyFromZ32(key));\n}\n\nconst clean = (value: unknown, max: number): string | undefined => {\n if (typeof value !== \"string\") return undefined;\n // One line of plain text, as a nickname: no control, format, bidi or line-separator character from peer-supplied text.\n const text = stripHidden(value).trim();\n return text && hasVisible(text) ? text.slice(0, max) : undefined;\n};\n\n/**\n * Room for a line that names a domain (up to 253 characters) once or twice: a How line or a reason cut inside the name\n * names a record that does not exist, and the app no longer knows the reason to say it in the person's language.\n */\nconst SOURCE_MAX = 640;\nconst ERROR_MAX = 512;\n\n/** Bounds a provider's result so a buggy provider cannot store or show arbitrary data. */\nexport function boundVerifiedIdentity(v: VerifiedIdentity): VerifiedIdentity {\n if (!v || typeof v.subject !== \"string\" || !IDENTITY_SUBJECT.test(v.subject)) throw new Error(\"Provider returned an invalid subject\");\n const source = clean(v.source, SOURCE_MAX);\n if (!source) throw new Error(\"Provider did not say how it verified\");\n const out: VerifiedIdentity = { subject: v.subject, source };\n const attester = clean(v.attester, 253);\n if (attester) out.attester = attester;\n if (v.expiresAt !== undefined) { if (!isInt(v.expiresAt)) throw new Error(\"Provider returned an invalid expiry\"); out.expiresAt = v.expiresAt; }\n if (v.display) out.display = boundIdentityDisplay(v.display);\n return out;\n}\n\n/** Bounds a provider's public name/picture (from a proof or `lookupDisplay`): a name with nothing visible left is dropped. */\nexport function boundIdentityDisplay(d: IdentityDisplay): IdentityDisplay {\n const display: IdentityDisplay = { source: clean(d.source, 120) ?? \"Self-described\", fetchedAt: isInt(d.fetchedAt) ? d.fetchedAt : nowSeconds() };\n const name = clean(d.name, 64);\n if (name) display.name = name;\n if (typeof d.avatar === \"string\" && d.avatar.length <= 48 * 1024 && /^data:image\\/(png|jpeg);base64,[A-Za-z0-9+/=]+$/.test(d.avatar)) display.avatar = d.avatar;\n if (typeof d.url === \"string\" && d.url.length <= 512) { try { const u = new URL(d.url); if (u.protocol === \"https:\" && !u.username && !u.password) display.url = u.href; } catch { /* dropped */ } }\n return display;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Per-conversation exchange\n\n/** Sharer side, one per proof shared in this conversation. */\nexport interface SharedIdentity {\n id: string;\n provider: string;\n subject: string;\n /**\n * The identity the contact keeps it under (the provider's verified subject: an OIDC binding names the issuer, its\n * account is the issuer and `sub`). Absent in older ledgers.\n */\n account?: string;\n /** queued: the person chose to share, the contact is not connected yet. */\n status: \"queued\" | \"pending\" | \"accepted\" | \"rejected\" | \"withdrawal-pending\" | \"withdrawn\";\n /** Seconds. When the status last changed. */\n at: number;\n error?: string;\n}\n\n/** Verifier side: a contact's proof as this app checked it. */\nexport interface ReceivedIdentity {\n id: string;\n binding: IdentityBinding;\n evidence: unknown;\n verified: VerifiedIdentity;\n /** The participation keys it was presented between (presenter, then this side). */\n presenter: string;\n audience: string;\n context: string;\n verifiedAt: number;\n checkedAt: number;\n /**\n * unconfirmed: a re-check failed (the domain record is gone, the account cannot be confirmed).\n * revoked: its proof key published a revocation (the person removed it from their profile).\n */\n status: \"verified\" | \"withdrawn\" | \"unconfirmed\" | \"revoked\";\n error?: string;\n /** A name/picture looked up on the person's request (Nostr kind-0), with its source. */\n display?: IdentityDisplay;\n}\n\n/** `id`: the proof the request named, kept here only (never sent) so the timeline can settle its entry.\n * `withdrawn`: its owner withdrew that proof while this side was checking its presentation. */\nexport interface IdentityChallenge { nonce: string; issuedAt: number; provider: string; id?: string; withdrawn?: true }\n\nexport interface IdentityLedger {\n challenges: IdentityChallenge[];\n shared: SharedIdentity[];\n received: ReceivedIdentity[];\n /** What the chat's timeline shows of this exchange (identityTimeline.ts). Local only; absent in older ledgers. */\n timeline?: IdentityTimelineEntry[];\n}\nexport const emptyIdentityLedger = (): IdentityLedger => ({ challenges: [], shared: [], received: [] });\n\n/** `account`: the subject its provider verified (`VerifiedIdentity.subject`); the binding's subject when not given. */\nexport interface LocalIdentityProof { statement: IdentityStatement; evidence: unknown; seed: Uint8Array; account?: string }\n\nexport interface IdentityExchangeOptions {\n /** This side's view of the authenticated channel; throws when there is none. */\n scope(): IdentityScope;\n send(frame: object): void;\n storage: { read(): IdentityLedger; update(change: (ledger: IdentityLedger) => IdentityLedger): Promise<void> };\n /** Providers this app can verify. */\n providers(): readonly string[];\n /** A proof of this profile, by id; undefined once removed. */\n localProof(id: string): LocalIdentityProof | undefined | Promise<LocalIdentityProof | undefined>;\n /** Parses and checks untrusted evidence for a statement (the registry's `verifyIdentity`). */\n verify(statement: IdentityStatement, evidence: unknown): Promise<VerifiedIdentity>;\n /** Looks up the proof key's revocation record. Resolves false when there is none or it cannot be read. */\n revoked?(statement: IdentityStatement): Promise<boolean>;\n now?(): number;\n onError?(error: string): void;\n}\n\nexport type IdentityStatus = \"verified\" | \"expired\" | \"withdrawn\" | \"revoked\" | \"unconfirmed\" | \"previous-key\";\n\n/** What the verifier should show for a received proof right now. */\nexport function receivedIdentityStatus(r: ReceivedIdentity, presenter: string | undefined, audience: string | undefined, now = nowSeconds()): IdentityStatus {\n if (r.presenter !== presenter || r.audience !== audience) return \"previous-key\";\n if (r.status === \"withdrawn\") return \"withdrawn\";\n if (r.status === \"revoked\") return \"revoked\";\n if (Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity) <= now) return \"expired\";\n return r.status === \"unconfirmed\" ? \"unconfirmed\" : \"verified\";\n}\n\nconst standing = (r: ReceivedIdentity, now: number) =>\n r.status !== \"withdrawn\" && r.status !== \"revoked\" && Math.min(r.binding.expiresAt, r.verified.expiresAt ?? Infinity) > now;\n/**\n * `received` with room for one more proof: `replaced` (the older proof of the same identity) dropped, then the oldest ones\n * no longer standing; undefined when every place is still taken.\n */\nfunction receivedWithRoom(received: ReceivedIdentity[], id: string, replaced: (r: ReceivedIdentity) => boolean, now: number): ReceivedIdentity[] | undefined {\n const kept = received.filter(r => r.id !== id && !replaced(r));\n const gone = kept.filter(r => !standing(r, now)).sort((a, b) => a.verifiedAt - b.verifiedAt);\n const drop = new Set(gone.slice(0, Math.max(0, kept.length - IDENTITY_MAX_RECEIVED + 1)));\n const out = kept.filter(r => !drop.has(r));\n return out.length < IDENTITY_MAX_RECEIVED ? out : undefined;\n}\n\nconst REVOKED = \"Its owner revoked this proof\";\n/** Revoked is final: a later lookup that fails or finds nothing (the relays forgot it) does not undo it. */\nconst revokedHere = (received: ReceivedIdentity[], id: string) => received.some(r => r.id === id && r.status === \"revoked\");\n\nconst shortError = (e: unknown) => clean(e instanceof Error ? e.message : String(e), ERROR_MAX) ?? \"Invalid proof\";\n\n/**\n * A check this side could not finish because of what its own network did: a host it refused to contact, a server\n * that did not answer or answered an error. The message is for this side only. The contact is told the proof could\n * not be checked, never which host, address or status was seen, so a proof cannot make a contact's app report on\n * the network it sits in.\n */\nexport class IdentityCheckUnavailable extends Error {\n constructor(message: string) { super(message); this.name = \"IdentityCheckUnavailable\"; }\n}\n\n/** What the contact is told when the check failed with an IdentityCheckUnavailable. */\nexport const IDENTITY_CHECK_UNAVAILABLE = \"Your contact's app could not check it. Try again later.\";\n\nconst TOO_MANY_RECEIVED = \"Your contact keeps too many identities from you already\";\n\nconst NEWER_HELD = \"Your contact keeps a newer proof of this identity from you\";\n\nconst peerError = (e: unknown) => e instanceof IdentityCheckUnavailable ? IDENTITY_CHECK_UNAVAILABLE : shortError(e);\n\nconst UNSUPPORTED_KIND = \"Your contact's app cannot verify this kind of identity yet\";\nconst NOT_IN_PROFILE = \"That identity is no longer in your profile\";\nconst CONTACT_REFUSED = \"Your contact could not verify it\";\nconst EXPIRED = \"The proof has expired\";\n/** The refusals a contact's app writes itself (onRequest, onPresent): the only words of its `idp-result` kept as they came. */\nconst CONTACT_REFUSALS = new Set([UNSUPPORTED_KIND, IDENTITY_CHECK_UNAVAILABLE, TOO_MANY_RECEIVED, REVOKED, EXPIRED, NEWER_HELD]);\n\n/**\n * Why a share of mine was not accepted, as this app may say it under my identity: one of the refusals above or my own\n * app's line; else nothing past \"not verified\". Any other words came from the contact (a ledger kept before this check)\n * and would read as this app's own notice.\n */\nexport const identityRefusal = (error: unknown): string | undefined =>\n typeof error === \"string\" && (CONTACT_REFUSALS.has(error) || error === NOT_IN_PROFILE) ? error : undefined;\n\n/**\n * The `idp-*` exchange of one conversation. Frames (all JSON, additive, over the paired channel,\n * only when both offers carry `identity-proof/1`):\n *\n * idp-hello {providers} each side, when the channel is ready\n * idp-request {id, provider} sharer → verifier: \"give me a challenge for this proof\"\n * idp-challenge {id, nonce, issuedAt} verifier, after saving the nonce\n * idp-present {nonce, issuedAt, binding, evidence, sig}\n * idp-result {id, ok, error?} verifier, after saving the outcome\n * idp-withdraw {id} / idp-withdrawn {id}\n */\nexport class IdentityExchange {\n private peerProviders: readonly string[] | undefined;\n private requested = new Set<string>();\n /** The nonces of the presentations in their provider's check now. */\n private checking = new Set<string>();\n /** When the contact's presentations were checked with their provider (seconds), for `IDENTITY_MAX_CHECKS_PER_HOUR`. */\n private checks: number[] = [];\n constructor(private options: IdentityExchangeOptions) {}\n private now() { return (this.options.now ?? nowSeconds)(); }\n /** The ledger with one more step on the chat's timeline, in milliseconds (a test's clock, in seconds, when given). */\n private log(l: IdentityLedger, event: IdentityTimelineEvent): IdentityLedger {\n return { ...l, timeline: applyIdentityEvent(l.timeline ?? [], event, this.options.now ? this.now() * 1000 : Date.now()) };\n }\n private incomingScope(): IdentityScope { const s = this.options.scope(); return { ...s, subject: s.audience, audience: s.subject }; }\n private send(frame: object) {\n if (JSON.stringify(frame).length > IDENTITY_MAX_FRAME) throw new Error(\"Identity proof too large\");\n this.options.send(frame);\n }\n private shared(id: string) { return this.options.storage.read().shared.find(s => s.id === id); }\n private async setShared(entry: SharedIdentity, event?: IdentityTimelineEvent) {\n await this.options.storage.update(l => {\n const next = { ...l, shared: [...l.shared.filter(s => s.id !== entry.id), entry] };\n return event ? this.log(next, event) : next;\n });\n }\n\n /** The providers the contact said it verifies; undefined until its hello. */\n get contactProviders(): readonly string[] | undefined { return this.peerProviders; }\n\n /** The channel is ready: say what we verify, then send what the person queued while offline. */\n ready(): void {\n this.options.scope();\n this.send({ t: \"idp-hello\", providers: [...this.options.providers()] });\n for (const s of this.options.storage.read().shared) {\n if (s.status === \"queued\" || s.status === \"pending\") this.request(s);\n else if (s.status === \"withdrawal-pending\") this.send({ t: \"idp-withdraw\", id: s.id });\n }\n }\n stop(): void { this.requested.clear(); this.peerProviders = undefined; }\n\n /**\n * The challenges whose window ended unanswered go, and with them their requests' lines still verifying: a contact\n * whose app closed, or whose proof left its profile, before it presented tells this side nothing, and its line read\n * \"verifying\" for good. No write when none ended.\n */\n async expire(): Promise<void> {\n const now = this.now();\n if (!this.options.storage.read().challenges.some(c => !liveAt(c, now))) return;\n await this.options.storage.update(l => this.withoutExpired(l, now));\n }\n private withoutExpired(l: IdentityLedger, now: number): IdentityLedger {\n const live = l.challenges.filter(c => liveAt(c, now));\n if (live.length === l.challenges.length) return l;\n // A request sent again (a reconnect) has a live challenge of the same id, whose line it shares.\n const ended = new Set(l.challenges.filter(c => c.id !== undefined && !liveAt(c, now) && !live.some(x => x.id === c.id)).map(c => c.id!));\n return [...ended].reduce((out, proof) => this.log(out, { type: \"unanswered\", side: \"theirs\", proof }), { ...l, challenges: live });\n }\n\n /** Share a proof of this profile with this contact: now if connected, else when it next is. */\n async share(id: string, connected: boolean): Promise<void> {\n const local = await this.options.localProof(id);\n if (!local) throw new Error(\"That identity is no longer in your profile\");\n const { provider, subject } = local.statement.binding;\n const entry: SharedIdentity = { id, provider, subject, account: local.account ?? subject, status: \"queued\", at: this.now() };\n await this.setShared(entry, { type: \"shared\", side: \"mine\", proof: id, provider, subject });\n if (connected) this.request(entry);\n }\n private request(s: SharedIdentity) {\n this.requested.add(s.id);\n this.send({ t: \"idp-request\", id: s.id, provider: s.provider });\n }\n\n /** Stop sharing here. The contact is told (now or on reconnect); a copy it kept cannot be erased. */\n async withdraw(id: string, connected: boolean): Promise<void> {\n let s = this.shared(id);\n if (!s || s.status === \"withdrawn\") return;\n this.requested.delete(id);\n if (s.status === \"queued\") {\n // Unless its challenge was answered meanwhile: that presentation is out, so it is withdrawn as a pending one.\n let answered: SharedIdentity | undefined;\n await this.options.storage.update(l => {\n answered = l.shared.find(x => x.id === id && x.status === \"pending\");\n return answered ? l : this.log({ ...l, shared: l.shared.filter(x => x.id !== id) }, { type: \"unsent\", side: \"mine\", proof: id });\n });\n if (!answered) return;\n s = answered;\n }\n // One the contact refused, it never held: its app writes no stop, and neither does this side.\n await this.setShared({ ...s, status: \"withdrawal-pending\", at: this.now(), error: undefined },\n s.status === \"rejected\" ? undefined : { type: \"stopped\", side: \"mine\", proof: id, provider: s.provider, subject: s.subject, reason: \"withdrawn\" });\n // A link that closed during that write: the withdrawal stays pending and ready() sends it on reconnect.\n if (connected) try { this.send({ t: \"idp-withdraw\", id }); } catch { /* sent on reconnect */ }\n }\n\n /**\n * Run the checks again on a received proof: its revocation record, then (unless `revocationOnly`) the\n * provider's check (a domain record may be gone). `keepUnavailable`: a check that could not run (IdentityCheckUnavailable)\n * is thrown, and the proof is left as it was, for a check this side started on its own.\n */\n async recheck(id: string, { revocationOnly = false, keepUnavailable = false } = {}): Promise<ReceivedIdentity> {\n const r = this.options.storage.read().received.find(x => x.id === id);\n if (!r) throw new Error(\"Unknown identity\");\n if (r.status === \"revoked\") return r;\n if (await this.options.revoked?.(identityStatement(r.binding)).catch(() => false)) {\n return await this.settleRecheck(id, x => x.status === \"revoked\" ? x : { ...x, status: \"revoked\", checkedAt: this.now(), error: undefined },\n { type: \"stopped\", side: \"theirs\", proof: id, provider: r.binding.provider, subject: r.verified.subject, reason: \"revoked\" }) ?? r;\n }\n if (revocationOnly) return r;\n let outcome: (x: ReceivedIdentity) => ReceivedIdentity;\n try {\n const verified = boundVerifiedIdentity(await this.options.verify(identityStatement(r.binding), r.evidence));\n if (verified.subject !== r.verified.subject) throw new Error(\"The identity changed\");\n outcome = x => ({ ...x, verified: { ...verified, display: verified.display ?? x.verified.display }, checkedAt: this.now(), status: \"verified\", error: undefined });\n } catch (e) {\n if (keepUnavailable && e instanceof IdentityCheckUnavailable) throw e;\n const error = shortError(e);\n outcome = x => ({ ...x, checkedAt: this.now(), status: \"unconfirmed\", error });\n }\n // Applied to the record as it is once the check is back: a withdraw or revocation that landed meanwhile holds.\n return await this.settleRecheck(id, x => x.status === \"revoked\" ? x : x.status === \"withdrawn\" ? { ...outcome(x), status: \"withdrawn\" } : outcome(x)) ?? r;\n }\n private async settleRecheck(id: string, outcome: (x: ReceivedIdentity) => ReceivedIdentity, event?: IdentityTimelineEvent): Promise<ReceivedIdentity | undefined> {\n let next: ReceivedIdentity | undefined;\n await this.options.storage.update(l => {\n const x = l.received.find(y => y.id === id);\n if (!x) return l;\n next = outcome(x);\n const out = { ...l, received: l.received.map(y => y.id === id ? next! : y) };\n return event && x.status !== \"revoked\" ? this.log(out, event) : out;\n });\n return next;\n }\n\n async receive(frame: Record<string, unknown>): Promise<void> {\n try {\n if (JSON.stringify(frame).length > IDENTITY_MAX_FRAME) throw new Error(\"Identity proof too large\");\n const id = typeof frame.id === \"string\" && HEX64.test(frame.id) ? frame.id : undefined;\n switch (frame.t) {\n case \"idp-hello\":\n if (Array.isArray(frame.providers) && frame.providers.length <= 64)\n this.peerProviders = frame.providers.filter((p): p is string => typeof p === \"string\" && IDENTITY_PROVIDER_ID.test(p));\n return;\n case \"idp-request\": return await this.onRequest(id, frame.provider);\n case \"idp-challenge\": return await this.onChallenge(id, frame.nonce, frame.issuedAt);\n case \"idp-present\": {\n // The engine checks a presentation beside the chat's other frames, not before them: a copy of one still in\n // its check is refused here, so it never reaches the provider twice.\n const nonce = typeof frame.nonce === \"string\" ? frame.nonce : \"\";\n if (this.checking.has(nonce)) throw new Error(\"Unknown or reused identity challenge\");\n this.checking.add(nonce);\n try { return await this.onPresent(frame); } finally { this.checking.delete(nonce); }\n }\n case \"idp-result\": {\n const s = id ? this.shared(id) : undefined;\n if (!s || s.status !== \"pending\") return;\n const ok = frame.ok === true;\n // Only a refusal its app writes: any other text is the contact's own, never shown as this app's line.\n const error = ok ? undefined : typeof frame.error === \"string\" && CONTACT_REFUSALS.has(frame.error) ? frame.error : CONTACT_REFUSED;\n const entry: SharedIdentity = { ...s, status: ok ? \"accepted\" : \"rejected\", at: this.now(), error };\n // The contact keeps one proof per identity (onPresent): the one it accepted replaced any other of the same\n // provider and verified identity it held from here, so that one is no longer shared in this chat. Matched on\n // the account, not the binding's subject (two OIDC accounts at one issuer are two identities there); one whose\n // account this side does not know stays shared, so Stop sharing still reaches it.\n // Its share stops on the timeline too, as the contact's does (onPresent).\n const replaced = (x: SharedIdentity) => ok && x.status === \"accepted\" && x.provider === s.provider &&\n x.account !== undefined && x.account === s.account;\n await this.options.storage.update(l => l.shared.filter(x => x.id !== s.id && replaced(x)).reduce(\n (out, x) => this.log(out, { type: \"stopped\", side: \"mine\", proof: x.id, provider: x.provider, subject: x.subject, reason: \"withdrawn\" }),\n this.log({ ...l, shared: [\n ...l.shared.filter(x => x.id !== s.id).map(x => replaced(x) ? { ...x, status: \"withdrawn\" as const, at: entry.at } : x), entry,\n ] }, { type: \"result\", side: \"mine\", proof: s.id, ok, error })));\n return;\n }\n case \"idp-withdraw\": {\n if (!id) return;\n // A durable write only for a proof this side actually received and still holds: a withdraw naming an\n // unknown (or already-withdrawn) id is only acknowledged, never written, so it cannot be repeated for a\n // durable write each time. The ack is always sent (a share the contact refused is withdrawn this way too).\n // A revoked one stays revoked: the owner revoked it everywhere, which says more than a withdraw from here.\n const r = this.options.storage.read().received.find(x => x.id === id);\n if (r && r.status !== \"withdrawn\" && r.status !== \"revoked\")\n await this.options.storage.update(l => this.log(\n { ...l, received: l.received.map(x => x.id === id ? { ...x, status: \"withdrawn\" as const } : x) },\n { type: \"stopped\", side: \"theirs\", proof: id, provider: r.binding.provider, subject: r.verified.subject, reason: \"withdrawn\" }));\n // A presentation of it may still be in its check (a withdraw on a new session after a reconnect): noted on\n // the challenge, so the check's outcome is stored withdrawn. Once per challenge, and challenges are bounded.\n if (this.options.storage.read().challenges.some(c => c.id === id && !c.withdrawn))\n await this.options.storage.update(l => ({ ...l, challenges: l.challenges.map(c => c.id === id ? { ...c, withdrawn: true as const } : c) }));\n this.send({ t: \"idp-withdrawn\", id });\n return;\n }\n case \"idp-withdrawn\": {\n const s = id ? this.shared(id) : undefined;\n if (s?.status === \"withdrawal-pending\") await this.setShared({ ...s, status: \"withdrawn\", at: this.now() });\n return;\n }\n }\n } catch (e) { this.options.onError?.(shortError(e)); }\n }\n\n private async onRequest(id: string | undefined, provider: unknown) {\n if (!id) return;\n if (typeof provider !== \"string\" || !this.options.providers().includes(provider)) {\n // A kind this app does not verify: told so at once (`idp-result`), no durable write. The provider is the\n // contact's to choose, so a write here would let it fill the timeline (one entry per fresh id, the real\n // verified line pushed out) and ring the identity cue, with no limit.\n const error = UNSUPPORTED_KIND;\n this.send({ t: \"idp-result\", id, ok: false, error });\n return;\n }\n this.options.scope();\n const now = this.now();\n const challenge: IdentityChallenge = { nonce: toBase64Url(randomBytes(32)), issuedAt: now, provider, id };\n // Saved before it is sent: a presentation for a nonce this side never saved is always refused.\n await this.options.storage.update(l => {\n if (l.challenges.filter(c => liveAt(c, now)).length >= MAX_CHALLENGES) throw new Error(\"Too many identity challenges\");\n // The request's line first, the ended challenges after: a line of this kind an ended one left verifying is\n // taken over in place (its id and time stay), and only the other ended ones' lines go.\n return this.withoutExpired(this.log({ ...l, challenges: [...l.challenges, challenge] }, { type: \"shared\", side: \"theirs\", proof: id, provider }), now);\n });\n this.send({ t: \"idp-challenge\", id, nonce: challenge.nonce, issuedAt: challenge.issuedAt });\n }\n\n private async onChallenge(id: string | undefined, nonce: unknown, issuedAt: unknown) {\n if (!id || !this.requested.has(id) || typeof nonce !== \"string\" || !CHALLENGE_NONCE.test(nonce) || !isInt(issuedAt)) return;\n const s = this.shared(id);\n if (!s || (s.status !== \"queued\" && s.status !== \"pending\")) return;\n this.requested.delete(id);\n const local = await this.options.localProof(id);\n if (!local) {\n const error = NOT_IN_PROFILE;\n await this.setShared({ ...s, status: \"rejected\", at: this.now(), error }, { type: \"result\", side: \"mine\", proof: id, ok: false, error });\n return;\n }\n const scope = this.options.scope();\n const sig = signIdentityPresentation(local.seed, id, scope, nonce, issuedAt);\n // Read again in the write: a Remove or Unshare while the proof key was opened holds, and nothing is presented.\n let stopped = false;\n await this.options.storage.update(l => {\n const x = l.shared.find(y => y.id === id);\n if (!x || (x.status !== \"queued\" && x.status !== \"pending\")) { stopped = true; return l; }\n return { ...l, shared: [...l.shared.filter(y => y.id !== id), { ...x, status: \"pending\", at: this.now(), error: undefined }] };\n });\n if (stopped) return;\n this.send({ t: \"idp-present\", nonce, issuedAt, binding: local.statement.binding, evidence: local.evidence, sig });\n }\n\n private async onPresent(frame: Record<string, unknown>) {\n const { nonce, issuedAt, binding, evidence, sig } = frame;\n if (typeof nonce !== \"string\" || !CHALLENGE_NONCE.test(nonce) || !isInt(issuedAt) || !isIdentityBinding(binding)) return;\n const statement = identityStatement(binding);\n const id = statement.id;\n const scope = this.incomingScope();\n const now = this.now();\n const challengeOf = (l: IdentityLedger) => l.challenges.find(c => c.nonce === nonce && c.issuedAt === issuedAt && c.provider === binding.provider && liveAt(c, now));\n const known = (l: IdentityLedger) => !!challengeOf(l);\n if (!known(this.options.storage.read())) throw new Error(\"Unknown or reused identity challenge\");\n let verified: VerifiedIdentity | undefined;\n // Only what the contact may know: see IdentityCheckUnavailable.\n let error: string | undefined;\n /** The same, as this side's own timeline says it. */\n let reason: string | undefined;\n /** Its owner withdrew the proof while this check ran: no result goes out (see below). */\n let withdrawn = false;\n /** The check could not run on this side (IdentityCheckUnavailable). */\n let unavailable = false;\n /** The same proof this side holds verified, checked recently: its answer is reused (`IDENTITY_REUSE_CHECK_S`). */\n let reused: ReceivedIdentity | undefined;\n try {\n // Before anything is checked or looked up: a contact past the bound costs this side nothing more.\n // The checked subject is not known yet: an identity kept under the binding's subject may be the one replaced.\n const mayReplace = (r: ReceivedIdentity) => r.binding.provider === binding.provider && (r.binding.subject === binding.subject || r.verified.subject === binding.subject);\n if (revokedHere(this.options.storage.read().received, id)) throw new Error(REVOKED);\n if (!receivedWithRoom(this.options.storage.read().received, id, mayReplace, now)) throw new Error(TOO_MANY_RECEIVED);\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n if (!verifyIdentityPresentation(binding.key, sig as string, id, scope, nonce, issuedAt)) throw new Error(\"The proof key did not sign this conversation's challenge\");\n if (binding.issuedAt > now + IDENTITY_CLOCK_SKEW) throw new Error(\"The proof is dated in the future\");\n const evidenceJson = JSON.stringify(evidence ?? null);\n reused = this.options.storage.read().received.find(r => r.id === id && r.status === \"verified\" && r.presenter === scope.subject &&\n r.audience === scope.audience && r.context === scope.context && r.checkedAt <= now && now - r.checkedAt < IDENTITY_REUSE_CHECK_S &&\n JSON.stringify(r.evidence ?? null) === evidenceJson);\n if (!reused) {\n this.checks = this.checks.filter(t => t > now - 3600 && t <= now);\n if (this.checks.length >= IDENTITY_MAX_CHECKS_PER_HOUR) throw new IdentityCheckUnavailable(\"Too many of this contact's proofs to check this hour\");\n this.checks.push(now);\n }\n const result = reused ? reused.verified : boundVerifiedIdentity(await this.options.verify(statement, evidence));\n if (Math.min(binding.expiresAt, result.expiresAt ?? Infinity) <= now) throw new Error(EXPIRED);\n // A presentation needs the proof key, so this only matters when its seed leaked: a lookup that\n // fails is not a refusal, a revocation found is. A held proof was looked up with its check.\n if (!reused && await this.options.revoked?.(statement).catch(() => false)) throw new Error(REVOKED);\n verified = result;\n } catch (e) { error = peerError(e); reason = shortError(e); unavailable = e instanceof IdentityCheckUnavailable; }\n // Consuming the nonce and recording the outcome are one transaction.\n await this.options.storage.update(l => {\n const challenge = challengeOf(l);\n if (!challenge) throw new Error(\"Unknown or reused identity challenge\");\n const challenges = l.challenges.filter(c => c.nonce !== nonce);\n withdrawn = !!challenge.withdrawn;\n // Withdrawn while it was checked, then shared again: the newer share decides, so this outcome is dropped. A withdraw\n // marks every challenge and record of that proof, so one of them still unmarked came with the newer share.\n if (withdrawn && (challenges.some(c => c.id === challenge.id && !c.withdrawn) ||\n l.received.some(r => r.id === challenge.id && r.status !== \"withdrawn\" && r.status !== \"revoked\"))) return { ...l, challenges };\n // A newer proof of the same identity replaces the older one; the bound holds for presentations checked at once.\n const subject = verified?.subject;\n // A re-check may have found it revoked while it was being checked.\n if (verified && revokedHere(l.received, id)) { verified = undefined; error = reason = REVOKED; }\n // Checked beside a newer one that is stored already: the binding's date decides, not which check ended last.\n if (verified && l.received.some(r => r.id !== id && r.binding.provider === binding.provider && r.verified.subject === subject &&\n r.binding.issuedAt > binding.issuedAt && standing(r, now))) { verified = undefined; error = reason = NEWER_HELD; }\n // A held proof's record as it is now: one a re-check found unconfirmed meanwhile is not written back verified.\n const prior = reused && l.received.find(r => r.id === id);\n if (verified && reused && prior?.status !== (withdrawn ? \"withdrawn\" : \"verified\")) {\n verified = undefined; error = IDENTITY_CHECK_UNAVAILABLE; reason = \"It was checked again while it was presented\";\n }\n const received = verified && receivedWithRoom(l.received, id, r => r.binding.provider === binding.provider && r.verified.subject === subject, now);\n if (verified && !received) { verified = undefined; error = reason = TOO_MANY_RECEIVED; }\n // This proof, held from this contact already, presented again (its result was lost, so it was asked again): the\n // check settles the held copy. One that could not run leaves a verified copy standing, and the contact is told it\n // is held; one that failed turns it unconfirmed, as a re-check does.\n const held = verified ? undefined : l.received.find(r => r.id === id && r.presenter === scope.subject && r.audience === scope.audience &&\n (r.status === \"verified\" || r.status === \"unconfirmed\"));\n const stands = held?.status === \"verified\" && unavailable;\n if (stands) { verified = held.verified; error = reason = undefined; }\n const logged = this.log(l, { type: \"result\", side: \"theirs\", proof: id, requested: challenge.id, provider: binding.provider,\n subject: verified?.subject ?? binding.subject, ok: !!verified, ...(reason ? { error: reason } : {}) });\n if (stands) return { ...logged, challenges };\n if (!verified || !received) return { ...logged, challenges, received: held && !unavailable\n ? l.received.map(r => r === held ? { ...r, checkedAt: now, status: \"unconfirmed\" as const, error: reason } : r) : l.received };\n // Its owner withdrew it while it was being checked: kept as if the withdraw had come just after.\n const record: ReceivedIdentity = { id, binding, evidence, verified, presenter: scope.subject, audience: scope.audience, context: scope.context,\n verifiedAt: prior?.verifiedAt ?? now, checkedAt: prior?.checkedAt ?? now, status: withdrawn ? \"withdrawn\" : \"verified\" };\n // The older proof it replaced is no longer held: its share stops on the timeline (one already stopped has its stop).\n const replaced = l.received.filter(r => r.id !== id && !received.includes(r) && r.binding.provider === binding.provider && r.verified.subject === subject\n && r.status !== \"withdrawn\" && r.status !== \"revoked\");\n const kept = replaced.reduce((out, r) => this.log(out, { type: \"stopped\", side: \"theirs\", proof: r.id, provider: r.binding.provider, subject: r.verified.subject, reason: \"withdrawn\" }),\n { ...logged, challenges, received: [...received, record] });\n return withdrawn ? this.log(kept, { type: \"stopped\", side: \"theirs\", proof: id, provider: binding.provider, subject: verified.subject, reason: \"withdrawn\" }) : kept;\n });\n // A withdrawn one gets no result, verified or not: the owner has it withdrawn (`idp-withdrawn` went out), and a late\n // one would settle a new share of the same proof made since.\n if (!withdrawn) this.send(verified ? { t: \"idp-result\", id, ok: true } : { t: \"idp-result\", id, ok: false, error });\n }\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32, bech32m, createBase58check } from \"@scure/base\";\n\n/** The Bitcoin networks an on-chain wallet can be on. Only `bitcoin` is real money. */\nexport type BitcoinNetwork = \"bitcoin\" | \"signet\" | \"testnet\" | \"regtest\" | \"mutinynet\";\nexport const BITCOIN_NETWORKS: readonly BitcoinNetwork[] = [\"bitcoin\", \"signet\", \"testnet\", \"regtest\", \"mutinynet\"];\n\n/** Mutinynet is a signet: it shares signet's (and testnet's) address prefixes. */\nconst SEGWIT_HRP: Record<BitcoinNetwork, string> = { bitcoin: \"bc\", signet: \"tb\", testnet: \"tb\", mutinynet: \"tb\", regtest: \"bcrt\" };\nconst BASE58_VERSIONS: Record<BitcoinNetwork, readonly number[]> = { bitcoin: [0x00, 0x05], signet: [0x6f, 0xc4], testnet: [0x6f, 0xc4], mutinynet: [0x6f, 0xc4], regtest: [0x6f, 0xc4] };\nconst base58check = createBase58check(sha256);\n\nfunction segwit(address: string, hrp: string): boolean {\n // BIP 173: one case only. The checksum is over the lower-case form.\n if (address !== address.toLowerCase() && address !== address.toUpperCase()) return false;\n const lower = address.toLowerCase();\n if (!lower.startsWith(`${hrp}1`) || lower.length > 90) return false;\n // Version 0 is bech32 (BIP 173), every later version bech32m (BIP 350); the wrong one is refused.\n for (const [coder, v0] of [[bech32, true], [bech32m, false]] as const) {\n let decoded: { prefix: string; words: number[] };\n try { decoded = coder.decode(lower as `${string}1${string}`, 90); } catch { continue; }\n if (decoded.prefix !== hrp || decoded.words.length < 1) return false;\n const version = decoded.words[0];\n if (version > 16 || (version === 0) !== v0) return false;\n let program: Uint8Array;\n try { program = coder.fromWords(decoded.words.slice(1)); } catch { return false; }\n if (version === 0) return program.length === 20 || program.length === 32;\n return program.length >= 2 && program.length <= 40;\n }\n return false;\n}\n\n/** Whether `address` is a valid address on `network`: checksums, witness versions, lengths and prefixes. */\nexport function isBitcoinAddress(address: unknown, network: BitcoinNetwork): boolean {\n if (typeof address !== \"string\" || !BITCOIN_NETWORKS.includes(network) || address.length < 14 || address.length > 90) return false;\n if (segwit(address, SEGWIT_HRP[network])) return true;\n let payload: Uint8Array;\n try { payload = base58check.decode(address); } catch { return false; }\n return payload.length === 21 && BASE58_VERSIONS[network].includes(payload[0]);\n}\n"],"mappings":";;;;;;;;;;;AAOA,IAAa,kBAAkB;;;;;;;;AAS/B,IAAM,SAAS;;AAEf,IAAM,OAAO;;AAGb,SAAgB,YAAY,MAAsB;CAChD,OAAO,KAAK,QAAQ,SAAS,SAAU,KAAK,KAAK,IAAI,IAAI,OAAO,EAAG;AACrE;;AAGA,IAAM,WAAW;;AAEjB,IAAM,aAAa;AACnB,IAAM,WAAW;AACjB,IAAM,SAAS;AAAU,IAAA,OAAO;AAAU,IAAA,SAAS;AACnD,IAAM,aAAa;;AAEnB,IAAM,sBAAsB;AAC5B,IAAM,QAAQ;AAAc,IAAA,QAAQ;AAAe,IAAA,cAAc;AACjE,IAAM,WAAW,SAAiB,OAAO,KAAK,IAAI,KAAK,CAAC,WAAW,KAAK,IAAI;;;;;;;;;AAU5E,SAAgB,gBAAgB,MAAsB;CACpD,MAAM,QAAQ,MAAM,KAAK,IAAI;CAC7B,IAAI,MAAM,IAA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AQ;EAAE,OAAO;CAAO;CACrE,OAAO,QAAQ,WAAW,MAAM,gBAAgB,QAAQ,CAAC,SAAS,QAAQ,EAAE;AAC9E"}
@@ -1 +0,0 @@
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;;;;;AAMA,SAAgB,QAAQ,WAAmB,KAAyB;CAClE,IAAI,IAAI,WAAW,YAAY,MAAM,IAAI,MAAM,uCAAuC;CACtF,MAAM,QAAQ,YAAY,YAAY;CACtC,MAAM,MAAM,iBAAiB,KAAK,KAAK,CAAC,CAAC,QAAQ,WAAW,SAAS,CAAC;CACtE,OAAO,SAAS,YAAY,OAAO,GAAG,CAAC;AACzC;;AAGA,SAAgB,aAAa,gBAAgC;CAC3D,OAAO,IAAI,KAAK,MAAM,KAAoB,kBAAkB,CAAC;AAC/D;AAEA,SAAgB,QAAQ,SAAiB,KAAyB;CAChE,IAAI,IA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entity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (p.recheck?.perHour !== undefined && !(Number.isInteger(p.recheck.perHour) && p.recheck.perHour >= 1)) problems.push(\"recheck.perHour must be a whole number, at least 1\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\" } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n if (target.protocol !== \"https:\" || target.username || target.password) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const response = await (options.fetcher ?? fetch)(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n"],"mappings":";;AAGA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C,WAA8B,UAAmB,KAA+C;CAChL,MAAM,EAAE,YAAY;CACpB,MAAM,WAAW,UAAU,MAAK,MAAK,EAAE,OAAO,QAAQ,QAAQ;CAC9D,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,8CAA8C;CAC7E,IAAI,QAAQ,YAAY,QAAQ,WAAW,KAAK,IAAI,SAAS,SAAS,UAAU,KAAA,MAA0B,GAAG,MAAM,IAAI,MAAM,0DAA0D;CACvL,IAAI,KAAK,UAAU,YAAY,IAAI,CAAC,CAAC,SAAA,OAAgC,MAAM,IAAI,MAAM,oBAAoB;CACzG,MAAM,SAA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