@ghostlytools/sdk 1.11.4 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/app.js +1 -2
  2. package/dist/bitcoinAddress-C2MAmcDT.js +1225 -0
  3. package/dist/bitcoinAddress-C2MAmcDT.js.map +1 -0
  4. package/dist/bolt11-CRiQrma3.js +266 -0
  5. package/dist/bolt11-CRiQrma3.js.map +1 -0
  6. package/dist/core.js +41852 -336
  7. package/dist/core.js.map +1 -1
  8. package/dist/{fakes-CXeeyI4Z.js → fakes-Cgl1w4Nv.js} +6 -9
  9. package/dist/{fakes-CXeeyI4Z.js.map → fakes-Cgl1w4Nv.js.map} +1 -1
  10. package/dist/fakes.js +1 -2
  11. package/dist/index.js +8 -9
  12. package/dist/index.js.map +1 -1
  13. package/dist/{keet-identity-key-DLXTTFZH.js → keet-identity-key-LuoCuz1t.js} +648 -324
  14. package/dist/keet-identity-key-LuoCuz1t.js.map +1 -0
  15. package/dist/pairedTransports-CkYMAoYN.js +1149 -0
  16. package/dist/pairedTransports-CkYMAoYN.js.map +1 -0
  17. package/dist/rolldown-runtime-DpEnGzO4.js +45 -0
  18. package/dist/testing.js +7 -8
  19. package/dist/testing.js.map +1 -1
  20. package/dist/types/browser/src/proofs/contract.d.ts +10 -0
  21. package/dist/types/browser/src/shared/mints.d.ts +3 -1
  22. package/dist/types/core/src/chatFiles.d.ts +3 -1
  23. package/dist/types/core/src/communityRendezvous.d.ts +4 -0
  24. package/dist/types/core/src/dhtDelivery.d.ts +16 -0
  25. package/dist/types/core/src/engineErrors.d.ts +7 -0
  26. package/dist/types/core/src/ghostlink.d.ts +12 -2
  27. package/dist/types/core/src/groupCalls.d.ts +56 -0
  28. package/dist/types/core/src/groupCommunity.d.ts +59 -1
  29. package/dist/types/core/src/groupCrypto.d.ts +6 -0
  30. package/dist/types/core/src/groupMeta.d.ts +22 -0
  31. package/dist/types/core/src/groupSession.d.ts +42 -2
  32. package/dist/types/core/src/handoff.d.ts +0 -2
  33. package/dist/types/core/src/http.d.ts +2 -1
  34. package/dist/types/core/src/index.d.ts +1 -0
  35. package/dist/types/core/src/pairedTransports.d.ts +5 -0
  36. package/dist/types/core/src/relayBreaker.d.ts +5 -1
  37. package/dist/types/core/src/services.d.ts +6 -0
  38. package/dist/types/core/src/text.d.ts +2 -0
  39. package/dist/types/core/src/transport.d.ts +1 -1
  40. package/dist/{types-DYLIIkU8.js → types-DbgC491n.js} +2 -3
  41. package/dist/{types-DYLIIkU8.js.map → types-DbgC491n.js.map} +1 -1
  42. package/dist/{verify-B9s82dbd.js → verify-CSo7-43-.js} +3 -4
  43. package/dist/{verify-B9s82dbd.js.map → verify-CSo7-43-.js.map} +1 -1
  44. package/package.json +3 -3
  45. package/dist/keet-identity-key-DLXTTFZH.js.map +0 -1
  46. package/dist/src-CqAqFhh9.js +0 -43635
  47. package/dist/src-CqAqFhh9.js.map +0 -1
@@ -0,0 +1 @@
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;;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AAI;EACJ,IAAI;GAAE,UAAU,MAAM,UAAU,QAAQ,MAAM,MAAM,CAAC,CAAC;EAAG,QAAQ;GAAE,OAAO;EAAO;EACjF,IAAI,YAAY,GAAG,OAAO,QAAQ,WAAW,MAAM,QAAQ,WAAW;EACtE,OAAO,QAAQ,UAAU,KAAK,QAAQ,UAAU;CAClD;CACA,OAAO;AACT;;AAGA,SAAgB,iBAAiB,SAAkB,SAAkC;CACnF,IAAI,OAAO,YAAY,YAAY,CAAC,iBAAiB,SAAS,OAAO,KAAK,QAAQ,SAAS,MAAM,QAAQ,SAAS,IAAI,OAAO;CAC7H,IAAI,OAAO,SAAS,WAAW,QAAQ,GAAG,OAAO;CACjD,IAAI;CACJ,IAAI;EAAE,UAAU,YAAY,OAAO,OAAO;CAAG,QAAQ;EAAE,OAAO;CAAO;CACrE,OAAO,QAAQ,WAAW,MAAM,gBAAgB,QAAQ,CAAC,SAAS,QAAQ,EAAE;AAC9E"}
@@ -0,0 +1,266 @@
1
+ // ../core/src/bytes.ts
2
+ var textEncoder = new TextEncoder();
3
+ var textDecoder = new TextDecoder("utf-8", { fatal: true });
4
+ function utf8Encode(str) {
5
+ return textEncoder.encode(str);
6
+ }
7
+ function utf8Decode(bytes) {
8
+ return textDecoder.decode(bytes);
9
+ }
10
+ function concatBytes(...parts) {
11
+ let length = 0;
12
+ for (const p of parts) length += p.length;
13
+ const out = new Uint8Array(length);
14
+ let offset = 0;
15
+ for (const p of parts) {
16
+ out.set(p, offset);
17
+ offset += p.length;
18
+ }
19
+ return out;
20
+ }
21
+ function bytesEqual(a, b) {
22
+ if (a.length !== b.length) return false;
23
+ let diff = 0;
24
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
25
+ return diff === 0;
26
+ }
27
+ /** `Uint8Array.prototype.toBase64` (Node 25+, Chrome 140+, Firefox 133+, Safari 18.2+): ~200x the JS below. */
28
+ var nativeToBase64 = Uint8Array.prototype.toBase64;
29
+ var tableOf = (chars) => Uint8Array.from(chars, (c) => c.charCodeAt(0));
30
+ var BASE64_TABLE = tableOf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
31
+ var BASE64URL_TABLE = tableOf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
32
+ /**
33
+ * Base64 where the runtime has no native encoder (Node 22 and 24, older WebViews): the characters go into bytes and
34
+ * become one string at the end. Every file chunk is encoded (files/3 `pf-data`), so this is on a transfer's path.
35
+ */
36
+ function encodeBase64(bytes, table, pad) {
37
+ const out = new Uint8Array(Math.ceil(bytes.length / 3) * 4);
38
+ let o = 0, i = 0;
39
+ for (; i + 2 < bytes.length; i += 3) {
40
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
41
+ out[o++] = table[n >>> 18];
42
+ out[o++] = table[n >>> 12 & 63];
43
+ out[o++] = table[n >>> 6 & 63];
44
+ out[o++] = table[n & 63];
45
+ }
46
+ const rest = bytes.length - i;
47
+ if (rest) {
48
+ const n = bytes[i] << 16 | (rest === 2 ? bytes[i + 1] << 8 : 0);
49
+ out[o++] = table[n >>> 18];
50
+ out[o++] = table[n >>> 12 & 63];
51
+ if (rest === 2) out[o++] = table[n >>> 6 & 63];
52
+ else if (pad) out[o++] = 61;
53
+ if (pad) out[o++] = 61;
54
+ }
55
+ return textDecoder.decode(out.subarray(0, o));
56
+ }
57
+ function toBase64(bytes) {
58
+ return nativeToBase64 ? nativeToBase64.call(bytes) : encodeBase64(bytes, BASE64_TABLE, true);
59
+ }
60
+ function fromBase64(str) {
61
+ const binary = atob(str);
62
+ const bytes = new Uint8Array(binary.length);
63
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
64
+ return bytes;
65
+ }
66
+ function toBase64Url(bytes) {
67
+ return nativeToBase64 ? nativeToBase64.call(bytes, {
68
+ alphabet: "base64url",
69
+ omitPadding: true
70
+ }) : encodeBase64(bytes, BASE64URL_TABLE, false);
71
+ }
72
+ function fromBase64Url(str) {
73
+ let b = str.replace(/-/g, "+").replace(/_/g, "/");
74
+ while (b.length % 4) b += "=";
75
+ return fromBase64(b);
76
+ }
77
+ var Z32_ALPHABET = "ybndrfg8ejkmcpqxot1uwisza345h769";
78
+ function toZ32(bytes) {
79
+ let out = "";
80
+ let bits = 0;
81
+ let value = 0;
82
+ for (const byte of bytes) {
83
+ value = value << 8 | byte;
84
+ bits += 8;
85
+ while (bits >= 5) {
86
+ out += Z32_ALPHABET[value >>> bits - 5 & 31];
87
+ bits -= 5;
88
+ }
89
+ value &= (1 << bits) - 1;
90
+ }
91
+ if (bits > 0) out += Z32_ALPHABET[value << 5 - bits & 31];
92
+ return out;
93
+ }
94
+ function fromZ32(str) {
95
+ const out = new Uint8Array(Math.floor(str.length * 5 / 8));
96
+ let bits = 0;
97
+ let value = 0;
98
+ let index = 0;
99
+ for (const char of str) {
100
+ const v = Z32_ALPHABET.indexOf(char);
101
+ if (v < 0) throw new Error(`Invalid z-base-32 character: ${char}`);
102
+ value = value << 5 | v;
103
+ bits += 5;
104
+ if (bits >= 8) {
105
+ out[index++] = value >>> bits - 8 & 255;
106
+ bits -= 8;
107
+ }
108
+ value &= (1 << bits) - 1;
109
+ }
110
+ return out;
111
+ }
112
+ /**
113
+ * A 32-byte key written as the one z-base-32 spelling `toZ32` produces: 52 characters that decode to 32 bytes and
114
+ * encode back to the same string. The last character carries four zero padding bits, so each key has exactly one
115
+ * spelling and keys may be compared as strings (WISP 02). Any other spelling is not a key here.
116
+ */
117
+ function isZ32Key(value) {
118
+ if (typeof value !== "string" || value.length !== 52) return false;
119
+ try {
120
+ return toZ32(fromZ32(value)) === value;
121
+ } catch {
122
+ return false;
123
+ }
124
+ }
125
+ function randomBytes(length) {
126
+ const bytes = new Uint8Array(length);
127
+ crypto.getRandomValues(bytes);
128
+ return bytes;
129
+ }
130
+ // ../core/src/bolt11.ts
131
+ var CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
132
+ var GENERATOR = [
133
+ 996825010,
134
+ 642813549,
135
+ 513874426,
136
+ 1027748829,
137
+ 705979059
138
+ ];
139
+ var NETWORKS = {
140
+ bc: "bitcoin",
141
+ tb: "testnet",
142
+ tbs: "signet",
143
+ bcrt: "regtest"
144
+ };
145
+ var MSAT_PER_UNIT = {
146
+ "": 100000000000n,
147
+ m: 100000000n,
148
+ u: 100000n,
149
+ n: 100n
150
+ };
151
+ var TIMESTAMP_WORDS = 7;
152
+ var DEFAULT_EXPIRY = 3600;
153
+ var MAX_LENGTH = 7089;
154
+ /** Finds an invoice inside free text. The match still has to pass `decodeBolt11`. */
155
+ var BOLT11_PATTERN = /(?:lightning:)?(ln(?:bcrt|tbs|bc|tb)[0-9]*[munp]?1[02-9ac-hj-np-z]{100,})/i;
156
+ function polymod(values) {
157
+ let chk = 1;
158
+ for (const value of values) {
159
+ const top = chk >>> 25;
160
+ chk = (chk & 33554431) << 5 ^ value;
161
+ for (let i = 0; i < 5; i++) if (top >>> i & 1) chk ^= GENERATOR[i];
162
+ }
163
+ return chk >>> 0;
164
+ }
165
+ function expandHrp(hrp) {
166
+ const high = [];
167
+ const low = [];
168
+ for (const char of hrp) {
169
+ high.push(char.charCodeAt(0) >>> 5);
170
+ low.push(char.charCodeAt(0) & 31);
171
+ }
172
+ return [
173
+ ...high,
174
+ 0,
175
+ ...low
176
+ ];
177
+ }
178
+ function wordsToInt(words) {
179
+ return words.reduce((value, word) => value * 32 + word, 0);
180
+ }
181
+ /** Regroups 5-bit words into bytes, dropping the padding bits at the end. */
182
+ function wordsToBytes(words) {
183
+ const bytes = [];
184
+ let buffer = 0;
185
+ let bits = 0;
186
+ for (const word of words) {
187
+ buffer = buffer << 5 | word;
188
+ bits += 5;
189
+ if (bits >= 8) {
190
+ bits -= 8;
191
+ bytes.push(buffer >>> bits & 255);
192
+ }
193
+ }
194
+ return new Uint8Array(bytes);
195
+ }
196
+ function decodeBolt11(text) {
197
+ const invoice = text.trim().toLowerCase().replace(/^lightning:/, "");
198
+ if (invoice.length > MAX_LENGTH) return null;
199
+ const separator = invoice.lastIndexOf("1");
200
+ if (separator < 4) return null;
201
+ const hrp = invoice.slice(0, separator);
202
+ const prefix = /^ln(bcrt|tbs|bc|tb)(?:([0-9]+)([munp]?))?$/.exec(hrp);
203
+ if (!prefix) return null;
204
+ const words = [];
205
+ for (const char of invoice.slice(separator + 1)) {
206
+ const word = CHARSET.indexOf(char);
207
+ if (word < 0) return null;
208
+ words.push(word);
209
+ }
210
+ if (words.length < 117) return null;
211
+ if (polymod([...expandHrp(hrp), ...words]) !== 1) return null;
212
+ let amountMsat = null;
213
+ if (prefix[2] !== void 0) {
214
+ const digits = BigInt(prefix[2]);
215
+ if (prefix[3] === "p") {
216
+ if (digits % 10n !== 0n) return null;
217
+ amountMsat = digits / 10n;
218
+ } else amountMsat = digits * MSAT_PER_UNIT[prefix[3]];
219
+ }
220
+ const data = words.slice(0, -110);
221
+ const createdAt = wordsToInt(data.slice(0, TIMESTAMP_WORDS));
222
+ let expiry = DEFAULT_EXPIRY;
223
+ let description;
224
+ let paymentHash;
225
+ let descriptionHash;
226
+ const seen = /* @__PURE__ */ new Set();
227
+ for (let at = TIMESTAMP_WORDS; at + 3 <= data.length;) {
228
+ const tag = CHARSET[data[at]];
229
+ const length = data[at + 1] * 32 + data[at + 2];
230
+ const field = data.slice(at + 3, at + 3 + length);
231
+ if (field.length < length) return null;
232
+ at += 3 + length;
233
+ const counted = tag === "d" || tag === "x" || (tag === "p" || tag === "h") && length === 52;
234
+ if (counted && seen.has(tag)) return null;
235
+ if (counted) seen.add(tag);
236
+ if (tag === "d") description = new TextDecoder().decode(wordsToBytes(field)).trim() || void 0;
237
+ else if (tag === "x") expiry = wordsToInt(field);
238
+ else if (tag === "p" && length === 52) paymentHash = [...wordsToBytes(field)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
239
+ else if (tag === "h" && length === 52) descriptionHash = [...wordsToBytes(field)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
240
+ }
241
+ return {
242
+ invoice,
243
+ network: NETWORKS[prefix[1]],
244
+ amountMsat,
245
+ amountSat: amountMsat === null ? null : Number((amountMsat + 999n) / 1000n),
246
+ createdAt,
247
+ expiresAt: createdAt + expiry,
248
+ description,
249
+ descriptionHash,
250
+ paymentHash
251
+ };
252
+ }
253
+ /** The first valid invoice in a chat message, with whatever else the message says. */
254
+ function findBolt11(text) {
255
+ const match = BOLT11_PATTERN.exec(text);
256
+ if (!match) return null;
257
+ const invoice = decodeBolt11(match[1]);
258
+ if (!invoice) return null;
259
+ return {
260
+ invoice,
261
+ rest: (text.slice(0, match.index) + text.slice(match.index + match[0].length)).trim()
262
+ };
263
+ }
264
+ export { concatBytes as a, fromZ32 as c, toBase64 as d, toBase64Url as f, utf8Encode as h, bytesEqual as i, isZ32Key as l, utf8Decode as m, decodeBolt11 as n, fromBase64 as o, toZ32 as p, findBolt11 as r, fromBase64Url as s, BOLT11_PATTERN as t, randomBytes as u };
265
+
266
+ //# sourceMappingURL=bolt11-CRiQrma3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bolt11-CRiQrma3.js","names":[],"sources":["../../core/src/bytes.ts","../../core/src/bolt11.ts"],"sourcesContent":["const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nexport function utf8Encode(str: string): Uint8Array {\n return textEncoder.encode(str);\n}\n\nexport function utf8Decode(bytes: Uint8Array): string {\n return textDecoder.decode(bytes);\n}\n\nexport function concatBytes(...parts: Uint8Array[]): Uint8Array {\n let length = 0;\n for (const p of parts) length += p.length;\n const out = new Uint8Array(length);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\ntype NativeToBase64 = (this: Uint8Array, options?: { alphabet?: \"base64\" | \"base64url\"; omitPadding?: boolean }) => string;\n/** `Uint8Array.prototype.toBase64` (Node 25+, Chrome 140+, Firefox 133+, Safari 18.2+): ~200x the JS below. */\nconst nativeToBase64 = (Uint8Array.prototype as { toBase64?: NativeToBase64 }).toBase64;\n\nconst tableOf = (chars: string) => Uint8Array.from(chars, (c) => c.charCodeAt(0));\nconst BASE64_TABLE = tableOf(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\");\nconst BASE64URL_TABLE = tableOf(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\");\n\n/**\n * Base64 where the runtime has no native encoder (Node 22 and 24, older WebViews): the characters go into bytes and\n * become one string at the end. Every file chunk is encoded (files/3 `pf-data`), so this is on a transfer's path.\n */\nfunction encodeBase64(bytes: Uint8Array, table: Uint8Array, pad: boolean): string {\n const out = new Uint8Array(Math.ceil(bytes.length / 3) * 4);\n let o = 0, i = 0;\n for (; i + 2 < bytes.length; i += 3) {\n const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n out[o++] = table[n >>> 18];\n out[o++] = table[(n >>> 12) & 63];\n out[o++] = table[(n >>> 6) & 63];\n out[o++] = table[n & 63];\n }\n const rest = bytes.length - i;\n if (rest) {\n const n = (bytes[i] << 16) | (rest === 2 ? bytes[i + 1] << 8 : 0);\n out[o++] = table[n >>> 18];\n out[o++] = table[(n >>> 12) & 63];\n if (rest === 2) out[o++] = table[(n >>> 6) & 63];\n else if (pad) out[o++] = 61; // \"=\"\n if (pad) out[o++] = 61;\n }\n return textDecoder.decode(out.subarray(0, o));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n return nativeToBase64 ? nativeToBase64.call(bytes) : encodeBase64(bytes, BASE64_TABLE, true);\n}\n\nexport function fromBase64(str: string): Uint8Array {\n const binary = atob(str);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\nexport function toBase64Url(bytes: Uint8Array): string {\n return nativeToBase64 ? nativeToBase64.call(bytes, { alphabet: \"base64url\", omitPadding: true }) : encodeBase64(bytes, BASE64URL_TABLE, false);\n}\n\nexport function fromBase64Url(str: string): Uint8Array {\n let b = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n while (b.length % 4) b += \"=\";\n return fromBase64(b);\n}\n\nconst Z32_ALPHABET = \"ybndrfg8ejkmcpqxot1uwisza345h769\";\n\nexport function toZ32(bytes: Uint8Array): string {\n let out = \"\";\n let bits = 0;\n let value = 0;\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n out += Z32_ALPHABET[(value >>> (bits - 5)) & 31];\n bits -= 5;\n }\n value &= (1 << bits) - 1;\n }\n if (bits > 0) out += Z32_ALPHABET[(value << (5 - bits)) & 31];\n return out;\n}\n\nexport function fromZ32(str: string): Uint8Array {\n const out = new Uint8Array(Math.floor((str.length * 5) / 8));\n let bits = 0;\n let value = 0;\n let index = 0;\n for (const char of str) {\n const v = Z32_ALPHABET.indexOf(char);\n if (v < 0) throw new Error(`Invalid z-base-32 character: ${char}`);\n value = (value << 5) | v;\n bits += 5;\n if (bits >= 8) {\n out[index++] = (value >>> (bits - 8)) & 0xff;\n bits -= 8;\n }\n value &= (1 << bits) - 1;\n }\n return out;\n}\n\n/**\n * A 32-byte key written as the one z-base-32 spelling `toZ32` produces: 52 characters that decode to 32 bytes and\n * encode back to the same string. The last character carries four zero padding bits, so each key has exactly one\n * spelling and keys may be compared as strings (WISP 02). Any other spelling is not a key here.\n */\nexport function isZ32Key(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length !== 52) return false;\n try { return toZ32(fromZ32(value)) === value; } catch { return false; }\n}\n\nexport function randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n","/**\n * Reads what a Lightning invoice (BOLT11) asks for, so a pasted invoice can be\n * shown as an amount and a description instead of a wall of characters. It\n * checks the bech32 checksum but not the signature: this is for display, the\n * wallet that pays is the one that must verify.\n */\nexport interface Bolt11Invoice {\n /** The invoice as it should be handed to a wallet: lower case, no `lightning:` prefix. */\n invoice: string;\n network: \"bitcoin\" | \"testnet\" | \"signet\" | \"regtest\";\n /** Null for an invoice that lets the payer choose the amount. */\n amountMsat: bigint | null;\n /** Rounded up to whole sats; null when the payer chooses. */\n amountSat: number | null;\n /** Seconds since the UNIX epoch. */\n createdAt: number;\n expiresAt: number;\n description?: string;\n /** The `h` tag: sha256 of a description the invoice does not carry (LNURL-pay invoices commit to their metadata this way). */\n descriptionHash?: string;\n paymentHash?: string;\n}\n\nconst CHARSET = \"qpzry9x8gf2tvdw0s3jn54khce6mua7l\";\nconst GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\nconst NETWORKS = { bc: \"bitcoin\", tb: \"testnet\", tbs: \"signet\", bcrt: \"regtest\" } as const;\nconst MSAT_PER_UNIT: Record<string, bigint> = { \"\": 100_000_000_000n, m: 100_000_000n, u: 100_000n, n: 100n };\nconst SIGNATURE_WORDS = 104;\nconst CHECKSUM_WORDS = 6;\nconst TIMESTAMP_WORDS = 7;\nconst DEFAULT_EXPIRY = 3600;\nconst MAX_LENGTH = 7089;\n\n/** Finds an invoice inside free text. The match still has to pass `decodeBolt11`. */\nexport const BOLT11_PATTERN = /(?:lightning:)?(ln(?:bcrt|tbs|bc|tb)[0-9]*[munp]?1[02-9ac-hj-np-z]{100,})/i;\n\nfunction polymod(values: number[]): number {\n let chk = 1;\n for (const value of values) {\n const top = chk >>> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ value;\n for (let i = 0; i < 5; i++) if ((top >>> i) & 1) chk ^= GENERATOR[i];\n }\n return chk >>> 0;\n}\n\nfunction expandHrp(hrp: string): number[] {\n const high: number[] = [];\n const low: number[] = [];\n for (const char of hrp) {\n high.push(char.charCodeAt(0) >>> 5);\n low.push(char.charCodeAt(0) & 31);\n }\n return [...high, 0, ...low];\n}\n\nfunction wordsToInt(words: number[]): number {\n return words.reduce((value, word) => value * 32 + word, 0);\n}\n\n/** Regroups 5-bit words into bytes, dropping the padding bits at the end. */\nfunction wordsToBytes(words: number[]): Uint8Array {\n const bytes: number[] = [];\n let buffer = 0;\n let bits = 0;\n for (const word of words) {\n buffer = (buffer << 5) | word;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n bytes.push((buffer >>> bits) & 0xff);\n }\n }\n return new Uint8Array(bytes);\n}\n\nexport function decodeBolt11(text: string): Bolt11Invoice | null {\n const invoice = text.trim().toLowerCase().replace(/^lightning:/, \"\");\n if (invoice.length > MAX_LENGTH) return null;\n const separator = invoice.lastIndexOf(\"1\");\n if (separator < 4) return null;\n\n const hrp = invoice.slice(0, separator);\n const prefix = /^ln(bcrt|tbs|bc|tb)(?:([0-9]+)([munp]?))?$/.exec(hrp);\n if (!prefix) return null;\n\n const words: number[] = [];\n for (const char of invoice.slice(separator + 1)) {\n const word = CHARSET.indexOf(char);\n if (word < 0) return null;\n words.push(word);\n }\n if (words.length < TIMESTAMP_WORDS + SIGNATURE_WORDS + CHECKSUM_WORDS) return null;\n if (polymod([...expandHrp(hrp), ...words]) !== 1) return null;\n\n let amountMsat: bigint | null = null;\n if (prefix[2] !== undefined) {\n const digits = BigInt(prefix[2]);\n if (prefix[3] === \"p\") {\n // A pico-bitcoin is a tenth of a millisatoshi, so only multiples of ten exist.\n if (digits % 10n !== 0n) return null;\n amountMsat = digits / 10n;\n } else {\n amountMsat = digits * MSAT_PER_UNIT[prefix[3]];\n }\n }\n\n const data = words.slice(0, -(SIGNATURE_WORDS + CHECKSUM_WORDS));\n const createdAt = wordsToInt(data.slice(0, TIMESTAMP_WORDS));\n let expiry = DEFAULT_EXPIRY;\n let description: string | undefined;\n let paymentHash: string | undefined;\n let descriptionHash: string | undefined;\n const seen = new Set<string>();\n\n for (let at = TIMESTAMP_WORDS; at + 3 <= data.length; ) {\n const tag = CHARSET[data[at]];\n const length = data[at + 1] * 32 + data[at + 2];\n const field = data.slice(at + 3, at + 3 + length);\n if (field.length < length) return null;\n at += 3 + length;\n\n // A second `p`, `h`, `d` or `x` is malformed (LDK refuses it too): the wallet that pays may read the\n // other one, so the hash journaled and the text shown would not be what is paid.\n const counted = tag === \"d\" || tag === \"x\" || ((tag === \"p\" || tag === \"h\") && length === 52);\n if (counted && seen.has(tag)) return null;\n if (counted) seen.add(tag);\n\n if (tag === \"d\") {\n description = new TextDecoder().decode(wordsToBytes(field)).trim() || undefined;\n } else if (tag === \"x\") {\n expiry = wordsToInt(field);\n } else if (tag === \"p\" && length === 52) {\n paymentHash = [...wordsToBytes(field)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n } else if (tag === \"h\" && length === 52) {\n descriptionHash = [...wordsToBytes(field)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n }\n }\n\n return {\n invoice,\n network: NETWORKS[prefix[1] as keyof typeof NETWORKS],\n amountMsat,\n amountSat: amountMsat === null ? null : Number((amountMsat + 999n) / 1000n),\n createdAt,\n expiresAt: createdAt + expiry,\n description,\n descriptionHash,\n paymentHash,\n };\n}\n\n/** The first valid invoice in a chat message, with whatever else the message says. */\nexport function findBolt11(text: string): { invoice: Bolt11Invoice; rest: string } | null {\n const match = BOLT11_PATTERN.exec(text);\n if (!match) return null;\n const invoice = decodeBolt11(match[1]);\n if (!invoice) return null;\n return { invoice, rest: (text.slice(0, match.index) + text.slice(match.index + match[0].length)).trim() };\n}\n"],"mappings":";AAAA,IAAM,cAAc,IAAI,YAAY;AACpC,IAAM,cAAc,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAE5D,SAAgB,WAAW,KAAyB;CAClD,OAAO,YAAY,OAAO,GAAG;AAC/B;AAEA,SAAgB,WAAW,OAA2B;CACpD,OAAO,YAAY,OAAO,KAAK;AACjC;AAEA,SAAgB,YAAY,GAA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