@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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as describeProvider, c as offeredIn, i as PROVIDER_PLATFORMS, l as providerDescriptorProblems, n as PROVIDER_ID, o as isNothingSpentError, r as PROVIDER_NETWORKS, s as networkMode, t as NothingSpentError, u as redact } from "./types-DbgC491n.js";
2
- import { i as verifyIdentity, n as boundedIdentityFetch, r as descriptorProblems, t as availableSigners } from "./verify-CSo7-43-.js";
3
- import { A as newIdentityBinding, D as identityStatement, f as IDENTITY_MAX_VALIDITY, l as IDENTITY_MAX_EVIDENCE, n as isBitcoinAddress } from "./bitcoinAddress-C2MAmcDT.js";
4
- import { i as TRANSPORTS } from "./pairedTransports-CkYMAoYN.js";
2
+ import { i as verifyIdentity, n as boundedIdentityFetch, r as descriptorProblems, t as availableSigners } from "./verify-BoVhjvc_.js";
3
+ import { A as newIdentityBinding, D as identityStatement, f as IDENTITY_MAX_VALIDITY, l as IDENTITY_MAX_EVIDENCE, n as isBitcoinAddress } from "./bitcoinAddress-BbPG0DF7.js";
4
+ import { i as TRANSPORTS } from "./pairedTransports-C0I24YFz.js";
5
5
  import { n as decodeBolt11 } from "./bolt11-CRiQrma3.js";
6
6
  // ../browser/src/proofs/contract.ts
7
7
  var IDENTITY_PLATFORMS = [
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../browser/src/proofs/contract.ts","../../browser/src/plugins/bundled.ts","../../browser/src/plugins/registry.ts"],"sourcesContent":["import type { IdentityDisplay, IdentityStatement, VerifiedIdentity } from \"@ghostly/core\";\n\n/**\n * The identity-proof provider contract. A provider is one way to prove control of an external\n * identity (a Nostr key, a domain, a Bitcoin address, an SSH or PGP key, an OpenID Connect account):\n * how the person produces evidence over the shared statement (`signers`), and how any Ghostly app\n * checks it (`verify`). Everything else — the statement bytes, the proof key, sharing per contact,\n * replay protection, storage, expiry, the UI — is shared. See PROOFS.md.\n */\n\n/**\n * Who vouches for the identity. The UI shows the difference:\n * - self-custodied: the person holds the key (Nostr, SSH, PGP, Bitcoin, a domain they control);\n * only they can have produced the evidence.\n * - provider-attested: a company signs that the person logged in to an account (OpenID Connect);\n * the evidence is only as trustworthy as that company.\n */\nexport type IdentityCategory = \"self-custodied\" | \"provider-attested\";\n/** Where Ghostly runs: the web app, the browser extension (engine in an offscreen document), the Tauri app. */\nexport type IdentityPlatform = \"web\" | \"extension\" | \"desktop\";\nexport const IDENTITY_PLATFORMS: readonly IdentityPlatform[] = [\"web\", \"extension\", \"desktop\"];\n\n/**\n * A bounded HTTPS GET through the engine: time-out, size cap (`maxBytes`, default 64 KiB), no credentials,\n * no referrer, refused offline. `redirect` defaults to \"error\": a record that redirects does not count\n * unless the provider says so. `text` is the body as UTF-8; `bytes` is the same body raw (binary\n * answers such as DNS-over-HTTPS `application/dns-message`).\n */\nexport interface IdentityFetchOptions { headers?: Record<string, string>; maxBytes?: number; signal?: AbortSignal; redirect?: \"follow\" | \"error\" }\nexport interface IdentityFetchResponse { status: number; contentType: string; text: string; bytes: Uint8Array }\nexport type IdentityFetch = (url: string, options?: IdentityFetchOptions) => Promise<IdentityFetchResponse>;\n\n/**\n * How a provider says a line it works out when it runs (a step naming the person's domain, a progress line) in the\n * app's language: `key` names the line within the provider, `english` is the line itself with `{{name}}` for each of\n * `values`. The UI reads a built-in provider's line under `identities.providers.<provider id>.<key>`, with `english`\n * when its language has none; a provider written outside the app (a plugin) always gets its `english` back, filled in.\n * Its fixed words (`label`, `summary`, a signer's `description`…) need no call: the UI reads them by the same rule,\n * under their own path (`subject.help`, `signers.<signer id>.label`, `signers.<signer id>.fields.<name>.help`).\n */\nexport type ProviderSay = (key: string, english: string, values?: Readonly<Record<string, string | number>>) => string;\n\n/** `english` with its `{{name}}`s filled in: what `ProviderSay` returns where no app language is at hand (the CLI, tests). */\nexport const englishSay: ProviderSay = (_key, english, values) =>\n values ? english.replace(/\\{\\{(\\w+)\\}\\}/g, (all, name: string) => (name in values ? String(values[name]) : all)) : english;\n\nexport interface VerifyContext {\n /** Seconds. Use this, never `Date.now()`, so tests and re-checks agree on time. */\n now: number;\n signal: AbortSignal;\n /** The only way `verify` may reach the network. Never call the global `fetch`. */\n fetch: IdentityFetch;\n}\n\nexport interface SubjectSpec {\n /** \"Public key\", \"Domain\", \"Bitcoin address\", \"Account\". */\n label: string;\n placeholder?: string;\n help?: string;\n /** Choices instead of a text field (an OpenID Connect provider's issuer). */\n options?: readonly { value: string; label: string }[];\n /** The canonical subject for what the person typed (or a signer returned). Throw a message they can act on. */\n normalize(input: string): string;\n /** Short form for badges and lists (\"npub1x…4f2\"). Defaults to the subject. */\n short?(subject: string): string;\n /**\n * What the (normalized) subject turns out to be, shown under the field before anything is signed: a DID's\n * method, its keys and its domain. Runs in the UI on the person's input; may reach the network (the\n * person's own identity). Throw a message they can act on.\n */\n preview?(subject: string, options: { signal: AbortSignal; say?: ProviderSay }): Promise<SubjectPreview>;\n}\n\nexport interface SubjectPreview {\n /** Short facts, in order: \"Method\" → \"did:web\", \"Keys\" → \"#key-1 (Ed25519)\". */\n facts: readonly { label: string; value: string }[];\n /** The ids of the signers that apply to this subject; every signer when omitted. */\n signers?: readonly string[];\n}\n\n/** A field an in-app signer needs (a NIP-46 connection link). `secret` values are never stored or logged. */\nexport interface SignerField {\n name: string;\n label: string;\n kind: \"text\" | \"secret\";\n placeholder?: string;\n help?: string;\n optional?: boolean;\n}\n\n/**\n * A request waiting for the person's approval elsewhere, in one of two ways (Pubky: Passport in a browser window, or\n * Ring by scanning a QR code). The UI shows both on one screen; whichever approves first wins. Its values are secrets\n * (the QR carries a relay key): never logged, never stored.\n */\nexport interface ApprovalRequest {\n /** The primary button. `run` is called synchronously from its click, so a popup it opens keeps the user activation. */\n open?: { label: string; description?: string; run(): void };\n /** A QR code for a phone app, with its caption. */\n qr?: { value: string; label: string };\n /** Short lines under the choices. */\n notes?: readonly string[];\n}\n\n/** A signer's own wait for the person's approval ended (Pubky's relay forgot the request): a time-out, not a failure. */\nexport class SignerTimeout extends Error {}\n\nexport interface SignerContext {\n values: Record<string, string>;\n signal: AbortSignal;\n /**\n * How long the caller waits for the approval (the CLI's --timeout): a signer with a wait of its own takes this one,\n * up to its `maxWaitMs`. Its own wait when absent (the app).\n */\n waitMs?: number;\n /** The signer asks the person to approve on a page (NIP-46 auth_url): the UI shows it as a link, never opens it itself. */\n onAuthUrl(url: string): void;\n onProgress(message: string): void;\n /** The signer waits for an approval elsewhere (`null`: it no longer does). The UI renders it; see `ApprovalRequest`. */\n onApproval?(request: ApprovalRequest | null): void;\n /** Says the signer's progress lines and approval words in the app's language; `englishSay` when absent. */\n say?: ProviderSay;\n}\n\nexport interface SignerSession<E> {\n /** The identity the signer controls, canonical (as `subject.normalize` returns it). */\n subject(): Promise<string>;\n sign(statement: IdentityStatement): Promise<E>;\n}\n\nexport interface InstructionStep {\n text: string;\n /** Shown in a copyable block (a command, a DNS record). */\n copy?: string;\n}\nexport interface SignerInstructions {\n steps: readonly InstructionStep[];\n /** external-tool: the field the output is pasted into. */\n paste?: { label: string; placeholder?: string; multiline?: boolean };\n}\n\ninterface SignerBase {\n /** Unique within the provider: \"nip07\", \"nip46\", \"ssh-keygen\". */\n id: string;\n label: string;\n description?: string;\n /** Defaults to the provider's. */\n platforms?: readonly IdentityPlatform[];\n /** False hides it (no NIP-07 extension in this window). Runs in the UI. */\n available?(): boolean;\n /** The button that starts it (\"Continue on your server\"). Default: \"Sign with <label>\" in-app, \"Continue\" otherwise. */\n action?: string;\n}\n\n/** Signs inside Ghostly through something the person already uses (NIP-07, NIP-46, a wallet API). */\nexport interface InAppSigner<E> extends SignerBase {\n kind: \"in-app\";\n fields?: readonly SignerField[];\n /** The longest it can wait for an approval, whatever `waitMs` says (Pubky: its relay keeps a request five minutes). */\n maxWaitMs?: number;\n /** Opens the signer, runs `work`, and always cleans up (closes connections, drops keys) before resolving. */\n run<T>(ctx: SignerContext, work: (session: SignerSession<E>) => Promise<T>): Promise<T>;\n}\n\n/** The person runs a tool (ssh-keygen, gpg, a Bitcoin wallet) on the statement and pastes the output back. */\nexport interface ExternalToolSigner<E> extends SignerBase {\n kind: \"external-tool\";\n /** `say`: the steps in the app's language (`englishSay` when absent). */\n instructions(statement: IdentityStatement, say?: ProviderSay): SignerInstructions;\n /** What was pasted, as evidence. Throw a message the person can act on (\"That is not an SSH signature\"). */\n parse(pasted: string, statement: IdentityStatement): E | Promise<E>;\n}\n\n/** A popup to the provider's login page (OpenID Connect); the subject comes out of `verify`. */\nexport interface RedirectSigner<E> extends SignerBase {\n kind: \"redirect\";\n start(statement: IdentityStatement, ctx: SignerContext): Promise<E>;\n}\n\n/** The person publishes something the verifier fetches (a DNS TXT record, a /.well-known file). */\nexport interface PublishSigner<E> extends SignerBase {\n kind: \"publish\";\n /** `say`: the steps in the app's language (`englishSay` when absent). */\n instructions(statement: IdentityStatement, say?: ProviderSay): SignerInstructions;\n /** Usually small or empty: the verifier looks the record up itself. */\n evidence(statement: IdentityStatement): E | Promise<E>;\n}\n\nexport type IdentitySigner<E> = InAppSigner<E> | ExternalToolSigner<E> | RedirectSigner<E> | PublishSigner<E>;\n\n/**\n * A provider module's export. Registering it is adding the module under `proofs/providers/` and ONE\n * line in `proofs/registry.ts`.\n */\nexport interface IdentityProofProvider<E = unknown> {\n /** Stable: it is in the statement, on the wire and in storage. `^[a-z][a-z0-9-]{0,31}$`. */\n id: string;\n label: string;\n category: IdentityCategory;\n /**\n * One short line for the picker card, how you make it: \"Sign once with your Nostr signer\". About 40\n * characters at most; the card shows nothing else beside the name and the category.\n */\n summary: string;\n /** The details view (opened from the card, shown again above the form): what is proven and how, a sentence or two. */\n description: string;\n /**\n * What the proof does NOT show, when a contact could easily assume more (\"Does not prove a balance, a past\n * payment, or that you would pay.\"). Shown with the description, never hidden behind a hover.\n */\n limits?: string;\n platforms: readonly IdentityPlatform[];\n subject: SubjectSpec;\n /** How long one proof may last. The person picks up to `maxDays` (never above 400). */\n validity: { defaultDays: number; maxDays: number };\n /**\n * When a verifier's check can go stale (the DNS record may be removed later): the contact's app offers\n * \"Check again\" after this many seconds and shows the last check time. Omit when the evidence is a\n * signature that stays valid until expiry. `perHour`: the most checks the app runs on its own in an hour, for a\n * server that limits lookups per IP (the rest wait for later); well under that limit, so a check a person starts\n * (a new contact's proof, \"Check again\") still gets an answer.\n */\n recheck?: { afterSeconds: number; perHour?: number };\n /** One sentence for people: what `verify` contacts and who learns what. \"Nothing: checked on this device.\" */\n privacy: string;\n /** Mark providers whose flows are not proven against real-world tools yet. */\n experimental?: boolean;\n /** Listed under \"Advanced\" in the picker, for people who know what it is (DIDs), so it does not crowd newcomers. */\n advanced?: boolean;\n signers: readonly IdentitySigner<E>[];\n /**\n * Untrusted evidence off the wire → typed evidence. Strict: exact shape, bounded sizes, no extra keys.\n * The serialized evidence is already capped at 16 KiB before this runs.\n */\n parseEvidence(raw: unknown): E;\n /**\n * Checks `evidence` against exactly `statement.bytes` / `statement.text` and returns what it proves.\n * Throws when it does not. Must:\n * - self-custodied: return `subject === statement.binding.subject`;\n * - provider-attested: return the attested subject and set `attester`;\n * - reach the network only through `ctx.fetch`, and use `ctx.now` for time.\n */\n verify(statement: IdentityStatement, evidence: E, ctx: VerifyContext): Promise<VerifiedIdentity>;\n /**\n * Optional public name/picture for a verified subject (Nostr kind-0). Called ONLY when the person asks,\n * never automatically. Sanitize like avatars: plain-text name, bounded raster re-encoded to a data URL.\n */\n lookupDisplay?(subject: string, options: { signal: AbortSignal }): Promise<IdentityDisplay | undefined>;\n /** The button that runs `lookupDisplay`. Default: \"Show public profile\". */\n lookupLabel?: string;\n /**\n * The verified subject as a URI a public DID document may list in `alsoKnownAs` (the profile's\n * did:dht, and only for identities the person chooses to list there). Omit when the identity has no\n * URI of its own. No comma: did:dht separates the list with commas.\n */\n publicUri?(subject: string): string | undefined;\n /**\n * Takes down what a signer published when the person removes the proof (an AT Protocol record, a Pubky proof file). Runs in\n * the UI, called synchronously from the confirming click (it may open a window first). The shared Pkarr\n * revocation is published either way; if this fails, the person may remove the proof without it.\n */\n unpublish?: {\n /** What the removal adds, for the confirmation: \"Also deletes the record on your server.\" */\n description: string;\n /** `evidence` is what `parseEvidence` accepted when the proof was made (Pubky: the proof file's folder). */\n run(proof: { id: string; subject: string; key: string; evidence: E }, ctx: SignerContext): Promise<void>;\n };\n}\n","import type { GhostlyAdapterPlugin } from \"./registry\";\n\n/**\n * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`\n * names their modules (comma-separated paths from the repository root, each default-exporting a\n * `GhostlyAdapterPlugin`), and the Vite plugin in `packages/browser/vite-plugin.ts` swaps this module\n * for one that imports them. Release builds never set it; the e2e build carries the SDK example.\n */\nexport const BUNDLED_PLUGINS: readonly GhostlyAdapterPlugin[] = [];\n","import type { LightningProviderDescriptor } from \"../engine/paymentAdapters/providers/lightning\";\nimport type { OnchainProviderDescriptor } from \"../engine/paymentAdapters/providers/onchain\";\nimport { providerDescriptorProblems, type ProviderDescriptor, type ProviderKind } from \"../engine/paymentAdapters/providers/types\";\nimport type { IdentityProofProvider } from \"../proofs/contract\";\nimport { descriptorProblems } from \"../proofs/verify\";\nimport { BUNDLED_PLUGINS } from \"./bundled\";\n\n/**\n * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers\n * that register here instead of being added to the built-in lists. A plugin is a plain object naming\n * its adapters; the registries (`providers/registry.ts`, `proofs/registry.ts`) list what is registered\n * after the built-ins and before the test fakes, and the same platform and mode rules apply to all.\n *\n * Two ways in:\n * - at build time: `GHOSTLY_PLUGINS` lists the modules and `bundled.ts` is swapped for them;\n * - at run time: code already running in the engine's realm calls `registerAdapters` before the\n * pickers are shown (or after: the engine re-reads the lists when something registers).\n *\n * Trust: a plugin runs with the app's privileges, in the app's own JavaScript realm. There is no\n * sandbox, no permission prompt and no store; whoever builds a plugin in, or loads one, trusts its\n * author with everything the app can do, keys and sats included. A manifest with permissions and an\n * isolated runtime are a later phase (docs/wisps/ADAPTER-ROADMAP.md, \"Plugins, apps, catalogs\").\n *\n * The state lives on `globalThis` under a well-known symbol, so a plugin bundled with its own copy of\n * the SDK (a second copy of this module) still registers into the same lists the app reads.\n */\n\n/** The generation of the adapter contracts. A plugin says which one it was written against. */\nexport const SDK_API = 1;\nexport const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;\n\nexport interface GhostlyAdapterPlugin {\n /** Stable, unique among plugins: `^[a-z][a-z0-9-]{0,63}$`. */\n id: string;\n /** The plugin's own version, for people. */\n version?: string;\n /** The contract generation it was written against: `SDK_API`. Another one is refused. */\n sdk: number;\n lightning?: readonly LightningProviderDescriptor[];\n onchain?: readonly OnchainProviderDescriptor[];\n identities?: readonly IdentityProofProvider[];\n}\n\nexport type AdapterKind = ProviderKind | \"identity\";\n\ninterface Store {\n plugins: Map<string, GhostlyAdapterPlugin>;\n /** Ids the built-in registries own, per kind: a plugin cannot take one. */\n reserved: Record<AdapterKind, Set<string>>;\n listeners: Set<() => void>;\n seeded: boolean;\n}\n\nconst KEY = Symbol.for(\"ghostly.adapters/1\");\nfunction store(): Store {\n const g = globalThis as unknown as Record<symbol, Store | undefined>;\n return (g[KEY] ??= { plugins: new Map(), reserved: { lightning: new Set(), onchain: new Set(), identity: new Set() }, listeners: new Set(), seeded: false });\n}\n\nconst ids = (kind: AdapterKind, plugin: GhostlyAdapterPlugin): string[] => {\n // Not trusted to be well formed: pluginProblems reads it before saying what is wrong with it.\n const list: unknown = kind === \"identity\" ? plugin.identities : kind === \"lightning\" ? plugin.lightning : plugin.onchain;\n return Array.isArray(list) ? list.map((a: { id?: string } | null) => a?.id as string) : [];\n};\nconst KINDS: readonly AdapterKind[] = [\"lightning\", \"onchain\", \"identity\"];\n\n/** Problems with a plugin, empty when it can be registered. Does not look at what is already registered. */\nexport function pluginProblems(plugin: GhostlyAdapterPlugin): string[] {\n const problems: string[] = [];\n if (!plugin || typeof plugin !== \"object\") return [\"not a plugin object\"];\n if (!PLUGIN_ID.test(plugin.id ?? \"\")) problems.push(\"plugin id must match ^[a-z][a-z0-9-]{0,63}$\");\n if (plugin.sdk !== SDK_API) problems.push(`plugin was written for SDK API ${String(plugin.sdk)}; this app speaks ${SDK_API}`);\n if (plugin.version !== undefined && (typeof plugin.version !== \"string\" || plugin.version.length > 64)) problems.push(\"version must be a short string\");\n for (const kind of [\"lightning\", \"onchain\"] as const) {\n const list = plugin[kind];\n if (list === undefined) continue;\n if (!Array.isArray(list)) { problems.push(`${kind} must be a list of descriptors`); continue; }\n for (const d of list as ProviderDescriptor<unknown>[]) {\n if (!d || typeof d !== \"object\") { problems.push(`${kind} ${String(d)}: not a descriptor`); continue; }\n const own = providerDescriptorProblems(d);\n if (d?.kind && d.kind !== kind) own.push(`is listed under ${kind} but says kind ${String(d.kind)}`);\n problems.push(...own.map((p) => `${kind} ${String(d?.id)}: ${p}`));\n }\n }\n if (plugin.identities !== undefined) {\n if (!Array.isArray(plugin.identities)) problems.push(\"identities must be a list of providers\");\n else for (const p of plugin.identities) {\n if (!p || typeof p !== \"object\") problems.push(`identity ${String(p)}: not a provider`);\n else problems.push(...descriptorProblems(p).map((m) => `identity ${String(p.id)}: ${m}`));\n }\n }\n for (const kind of KINDS) {\n const list = ids(kind, plugin);\n if (new Set(list).size !== list.length) problems.push(`${kind} ids are not unique within the plugin`);\n }\n if (!KINDS.some((kind) => ids(kind, plugin).length)) problems.push(\"the plugin brings no adapter\");\n return problems;\n}\n\n/** The built-in registries say which ids are theirs. A plugin using one is refused. */\nexport function reserveAdapterIds(kind: AdapterKind, list: readonly string[]): void {\n const s = store();\n for (const id of list) s.reserved[kind].add(id);\n}\n\n/**\n * Registers a plugin's adapters. Throws, registering nothing, when the plugin is malformed, its id or\n * one of its adapters' ids is taken (by a built-in or by another plugin), or its contract generation\n * is another one. Returns the function that unregisters it.\n */\nexport function registerAdapters(plugin: GhostlyAdapterPlugin): () => void {\n const problems = pluginProblems(plugin);\n const s = store();\n if (!problems.length) {\n if (s.plugins.has(plugin.id)) problems.push(`a plugin with id ${plugin.id} is already registered`);\n for (const kind of KINDS) for (const id of ids(kind, plugin)) {\n if (s.reserved[kind].has(id)) problems.push(`${kind} ${id} is a built-in of this app`);\n for (const other of s.plugins.values()) if (ids(kind, other).includes(id)) problems.push(`${kind} ${id} is already registered by plugin ${other.id}`);\n }\n }\n if (problems.length) throw new Error(`Cannot register plugin ${String(plugin?.id)}: ${problems.join(\"; \")}`);\n s.plugins.set(plugin.id, plugin);\n notify(s);\n return () => { if (s.plugins.get(plugin.id) === plugin) { s.plugins.delete(plugin.id); notify(s); } };\n}\n\nfunction notify(s: Store) { for (const listener of s.listeners) { try { listener(); } catch { /* a listener's problem */ } } }\n\n/** Called when a plugin registers or unregisters: the engine re-reads the lists. */\nexport function onAdaptersChanged(listener: () => void): () => void {\n const s = store();\n s.listeners.add(listener);\n return () => { s.listeners.delete(listener); };\n}\n\n/** Every registered plugin, in registration order (bundled ones first). */\nexport function registeredPlugins(): readonly GhostlyAdapterPlugin[] { seed(); return [...store().plugins.values()]; }\nexport function registeredLightningProviders(): readonly LightningProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.lightning ?? []); }\nexport function registeredOnchainProviders(): readonly OnchainProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.onchain ?? []); }\nexport function registeredIdentityProviders(): readonly IdentityProofProvider[] { return registeredPlugins().flatMap((p) => p.identities ?? []); }\n\n/**\n * The plugins compiled into this build register once, when they are first asked for. A broken one is\n * reported and skipped rather than taking the app down with it; the e2e that expects it fails instead.\n */\nfunction seed() {\n const s = store();\n if (s.seeded) return;\n s.seeded = true;\n for (const plugin of BUNDLED_PLUGINS) {\n try { registerAdapters(plugin); }\n catch (error) { console.error(`[ghostly] a bundled adapter plugin was not loaded: ${error instanceof Error ? error.message : String(error)}`); }\n }\n}\n\n/** Tests only: forget every registration, including the bundled ones. */\nexport function resetAdapter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CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,CAAC,CAAC;AAAG;AACjJ,SAAgB,8BAAgE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,cAAc,CAAC,CAAC;AAAG;;;;;AAMjJ,SAAS,OAAO;CACd,MAAM,IAAI,MAAM;CAChB,IAAI,EAAE,QAAQ;CACd,EAAE,SAAS;CACX,KAAK,MAAM,UAAU,iBACnB,IAAI;EAAE,iBAAiB,MAAM;CAAG,SACzB,OAAO;EAAE,QAAQ,MAAM,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAAG;AAEnJ;;AAGA,SAAgB,uBAA6B;CAC3C,MAAM,IAAI,MAAM;CAChB,EAAE,QAAQ,MAAM;CAAG,EAAE,SAAS;CAC9B,KAAK,MAAM,QAAQ,OAAO,EAAE,SAAS,KAAK,CAAC,MAAM;CACjD,OAAO,CAAC;AACV"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../browser/src/proofs/contract.ts","../../browser/src/plugins/bundled.ts","../../browser/src/plugins/registry.ts"],"sourcesContent":["import type { IdentityDisplay, IdentityStatement, VerifiedIdentity } from \"@ghostly/core\";\n\n/**\n * The identity-proof provider contract. A provider is one way to prove control of an external\n * identity (a Nostr key, a domain, a Bitcoin address, an SSH or PGP key, an OpenID Connect account):\n * how the person produces evidence over the shared statement (`signers`), and how any Ghostly app\n * checks it (`verify`). Everything else — the statement bytes, the proof key, sharing per contact,\n * replay protection, storage, expiry, the UI — is shared. See PROOFS.md.\n */\n\n/**\n * Who vouches for the identity. The UI shows the difference:\n * - self-custodied: the person holds the key (Nostr, SSH, PGP, Bitcoin, a domain they control);\n * only they can have produced the evidence.\n * - provider-attested: a company signs that the person logged in to an account (OpenID Connect);\n * the evidence is only as trustworthy as that company.\n */\nexport type IdentityCategory = \"self-custodied\" | \"provider-attested\";\n/** Where Ghostly runs: the web app, the browser extension (engine in an offscreen document), the Tauri app. */\nexport type IdentityPlatform = \"web\" | \"extension\" | \"desktop\";\nexport const IDENTITY_PLATFORMS: readonly IdentityPlatform[] = [\"web\", \"extension\", \"desktop\"];\n\n/**\n * A bounded HTTPS GET through the engine: time-out, size cap (`maxBytes`, default 64 KiB), no credentials,\n * no referrer, refused offline. `redirect` defaults to \"error\": a record that redirects does not count\n * unless the provider says so. `text` is the body as UTF-8; `bytes` is the same body raw (binary\n * answers such as DNS-over-HTTPS `application/dns-message`).\n */\nexport interface IdentityFetchOptions {\n headers?: Record<string, string>; maxBytes?: number; signal?: AbortSignal; redirect?: \"follow\" | \"error\";\n /**\n * A read of one of the profile's own Pkarr relays (a did:dht): read as the chats read them, http:// and a private\n * address included, since the person chose them. Ignored for any other URL.\n */\n ownPkarrRelay?: boolean;\n}\nexport interface IdentityFetchResponse { status: number; contentType: string; text: string; bytes: Uint8Array }\nexport type IdentityFetch = (url: string, options?: IdentityFetchOptions) => Promise<IdentityFetchResponse>;\n\n/**\n * How a provider says a line it works out when it runs (a step naming the person's domain, a progress line) in the\n * app's language: `key` names the line within the provider, `english` is the line itself with `{{name}}` for each of\n * `values`. The UI reads a built-in provider's line under `identities.providers.<provider id>.<key>`, with `english`\n * when its language has none; a provider written outside the app (a plugin) always gets its `english` back, filled in.\n * Its fixed words (`label`, `summary`, a signer's `description`…) need no call: the UI reads them by the same rule,\n * under their own path (`subject.help`, `signers.<signer id>.label`, `signers.<signer id>.fields.<name>.help`).\n */\nexport type ProviderSay = (key: string, english: string, values?: Readonly<Record<string, string | number>>) => string;\n\n/** `english` with its `{{name}}`s filled in: what `ProviderSay` returns where no app language is at hand (the CLI, tests). */\nexport const englishSay: ProviderSay = (_key, english, values) =>\n values ? english.replace(/\\{\\{(\\w+)\\}\\}/g, (all, name: string) => (name in values ? String(values[name]) : all)) : english;\n\nexport interface VerifyContext {\n /** Seconds. Use this, never `Date.now()`, so tests and re-checks agree on time. */\n now: number;\n signal: AbortSignal;\n /** The only way `verify` may reach the network. Never call the global `fetch`. */\n fetch: IdentityFetch;\n}\n\nexport interface SubjectSpec {\n /** \"Public key\", \"Domain\", \"Bitcoin address\", \"Account\". */\n label: string;\n placeholder?: string;\n help?: string;\n /** Choices instead of a text field (an OpenID Connect provider's issuer). */\n options?: readonly { value: string; label: string }[];\n /** The canonical subject for what the person typed (or a signer returned). Throw a message they can act on. */\n normalize(input: string): string;\n /** Short form for badges and lists (\"npub1x…4f2\"). Defaults to the subject. */\n short?(subject: string): string;\n /**\n * What the (normalized) subject turns out to be, shown under the field before anything is signed: a DID's\n * method, its keys and its domain. Runs in the UI on the person's input; may reach the network (the\n * person's own identity). Throw a message they can act on.\n */\n preview?(subject: string, options: { signal: AbortSignal; say?: ProviderSay }): Promise<SubjectPreview>;\n}\n\nexport interface SubjectPreview {\n /** Short facts, in order: \"Method\" → \"did:web\", \"Keys\" → \"#key-1 (Ed25519)\". */\n facts: readonly { label: string; value: string }[];\n /** The ids of the signers that apply to this subject; every signer when omitted. */\n signers?: readonly string[];\n}\n\n/** A field an in-app signer needs (a NIP-46 connection link). `secret` values are never stored or logged. */\nexport interface SignerField {\n name: string;\n label: string;\n kind: \"text\" | \"secret\";\n placeholder?: string;\n help?: string;\n optional?: boolean;\n}\n\n/**\n * A request waiting for the person's approval elsewhere, in one of two ways (Pubky: Passport in a browser window, or\n * Ring by scanning a QR code). The UI shows both on one screen; whichever approves first wins. Its values are secrets\n * (the QR carries a relay key): never logged, never stored.\n */\nexport interface ApprovalRequest {\n /** The primary button. `run` is called synchronously from its click, so a popup it opens keeps the user activation. */\n open?: { label: string; description?: string; run(): void };\n /** A QR code for a phone app, with its caption. */\n qr?: { value: string; label: string };\n /** Short lines under the choices. */\n notes?: readonly string[];\n}\n\n/** A signer's own wait for the person's approval ended (Pubky's relay forgot the request): a time-out, not a failure. */\nexport class SignerTimeout extends Error {}\n\nexport interface SignerContext {\n values: Record<string, string>;\n signal: AbortSignal;\n /**\n * How long the caller waits for the approval (the CLI's --timeout): a signer with a wait of its own takes this one,\n * up to its `maxWaitMs`. Its own wait when absent (the app).\n */\n waitMs?: number;\n /** The signer asks the person to approve on a page (NIP-46 auth_url): the UI shows it as a link, never opens it itself. */\n onAuthUrl(url: string): void;\n onProgress(message: string): void;\n /** The signer waits for an approval elsewhere (`null`: it no longer does). The UI renders it; see `ApprovalRequest`. */\n onApproval?(request: ApprovalRequest | null): void;\n /** Says the signer's progress lines and approval words in the app's language; `englishSay` when absent. */\n say?: ProviderSay;\n}\n\nexport interface SignerSession<E> {\n /** The identity the signer controls, canonical (as `subject.normalize` returns it). */\n subject(): Promise<string>;\n sign(statement: IdentityStatement): Promise<E>;\n}\n\nexport interface InstructionStep {\n text: string;\n /** Shown in a copyable block (a command, a DNS record). */\n copy?: string;\n}\nexport interface SignerInstructions {\n steps: readonly InstructionStep[];\n /** external-tool: the field the output is pasted into. */\n paste?: { label: string; placeholder?: string; multiline?: boolean };\n}\n\ninterface SignerBase {\n /** Unique within the provider: \"nip07\", \"nip46\", \"ssh-keygen\". */\n id: string;\n label: string;\n description?: string;\n /** Defaults to the provider's. */\n platforms?: readonly IdentityPlatform[];\n /** False hides it (no NIP-07 extension in this window). Runs in the UI. */\n available?(): boolean;\n /** The button that starts it (\"Continue on your server\"). Default: \"Sign with <label>\" in-app, \"Continue\" otherwise. */\n action?: string;\n}\n\n/** Signs inside Ghostly through something the person already uses (NIP-07, NIP-46, a wallet API). */\nexport interface InAppSigner<E> extends SignerBase {\n kind: \"in-app\";\n fields?: readonly SignerField[];\n /** The longest it can wait for an approval, whatever `waitMs` says (Pubky: its relay keeps a request five minutes). */\n maxWaitMs?: number;\n /** Opens the signer, runs `work`, and always cleans up (closes connections, drops keys) before resolving. */\n run<T>(ctx: SignerContext, work: (session: SignerSession<E>) => Promise<T>): Promise<T>;\n}\n\n/** The person runs a tool (ssh-keygen, gpg, a Bitcoin wallet) on the statement and pastes the output back. */\nexport interface ExternalToolSigner<E> extends SignerBase {\n kind: \"external-tool\";\n /** `say`: the steps in the app's language (`englishSay` when absent). */\n instructions(statement: IdentityStatement, say?: ProviderSay): SignerInstructions;\n /** What was pasted, as evidence. Throw a message the person can act on (\"That is not an SSH signature\"). */\n parse(pasted: string, statement: IdentityStatement): E | Promise<E>;\n}\n\n/** A popup to the provider's login page (OpenID Connect); the subject comes out of `verify`. */\nexport interface RedirectSigner<E> extends SignerBase {\n kind: \"redirect\";\n start(statement: IdentityStatement, ctx: SignerContext): Promise<E>;\n}\n\n/** The person publishes something the verifier fetches (a DNS TXT record, a /.well-known file). */\nexport interface PublishSigner<E> extends SignerBase {\n kind: \"publish\";\n /** `say`: the steps in the app's language (`englishSay` when absent). */\n instructions(statement: IdentityStatement, say?: ProviderSay): SignerInstructions;\n /** Usually small or empty: the verifier looks the record up itself. */\n evidence(statement: IdentityStatement): E | Promise<E>;\n}\n\nexport type IdentitySigner<E> = InAppSigner<E> | ExternalToolSigner<E> | RedirectSigner<E> | PublishSigner<E>;\n\n/**\n * A provider module's export. Registering it is adding the module under `proofs/providers/` and ONE\n * line in `proofs/registry.ts`.\n */\nexport interface IdentityProofProvider<E = unknown> {\n /** Stable: it is in the statement, on the wire and in storage. `^[a-z][a-z0-9-]{0,31}$`. */\n id: string;\n label: string;\n category: IdentityCategory;\n /**\n * One short line for the picker card, how you make it: \"Sign once with your Nostr signer\". About 40\n * characters at most; the card shows nothing else beside the name and the category.\n */\n summary: string;\n /** The details view (opened from the card, shown again above the form): what is proven and how, a sentence or two. */\n description: string;\n /**\n * What the proof does NOT show, when a contact could easily assume more (\"Does not prove a balance, a past\n * payment, or that you would pay.\"). Shown with the description, never hidden behind a hover.\n */\n limits?: string;\n platforms: readonly IdentityPlatform[];\n subject: SubjectSpec;\n /** How long one proof may last. The person picks up to `maxDays` (never above 400). */\n validity: { defaultDays: number; maxDays: number };\n /**\n * When a verifier's check can go stale (the DNS record may be removed later): the contact's app offers\n * \"Check again\" after this many seconds and shows the last check time. Omit when the evidence is a\n * signature that stays valid until expiry. `perHour`: the most checks the app runs on its own in an hour, for a\n * server that limits lookups per IP (the rest wait for later); well under that limit, so a check a person starts\n * (a new contact's proof, \"Check again\") still gets an answer.\n */\n recheck?: { afterSeconds: number; perHour?: number };\n /** One sentence for people: what `verify` contacts and who learns what. \"Nothing: checked on this device.\" */\n privacy: string;\n /** Mark providers whose flows are not proven against real-world tools yet. */\n experimental?: boolean;\n /** Listed under \"Advanced\" in the picker, for people who know what it is (DIDs), so it does not crowd newcomers. */\n advanced?: boolean;\n signers: readonly IdentitySigner<E>[];\n /**\n * Untrusted evidence off the wire → typed evidence. Strict: exact shape, bounded sizes, no extra keys.\n * The serialized evidence is already capped at 16 KiB before this runs.\n */\n parseEvidence(raw: unknown): E;\n /**\n * Checks `evidence` against exactly `statement.bytes` / `statement.text` and returns what it proves.\n * Throws when it does not. Must:\n * - self-custodied: return `subject === statement.binding.subject`;\n * - provider-attested: return the attested subject and set `attester`;\n * - reach the network only through `ctx.fetch`, and use `ctx.now` for time.\n */\n verify(statement: IdentityStatement, evidence: E, ctx: VerifyContext): Promise<VerifiedIdentity>;\n /**\n * Optional public name/picture for a verified subject (Nostr kind-0). Called ONLY when the person asks,\n * never automatically. Sanitize like avatars: plain-text name, bounded raster re-encoded to a data URL.\n */\n lookupDisplay?(subject: string, options: { signal: AbortSignal }): Promise<IdentityDisplay | undefined>;\n /** The button that runs `lookupDisplay`. Default: \"Show public profile\". */\n lookupLabel?: string;\n /**\n * The verified subject as a URI a public DID document may list in `alsoKnownAs` (the profile's\n * did:dht, and only for identities the person chooses to list there). Omit when the identity has no\n * URI of its own. No comma: did:dht separates the list with commas.\n */\n publicUri?(subject: string): string | undefined;\n /**\n * Takes down what a signer published when the person removes the proof (an AT Protocol record, a Pubky proof file). Runs in\n * the UI, called synchronously from the confirming click (it may open a window first). The shared Pkarr\n * revocation is published either way; if this fails, the person may remove the proof without it.\n */\n unpublish?: {\n /** What the removal adds, for the confirmation: \"Also deletes the record on your server.\" */\n description: string;\n /** `evidence` is what `parseEvidence` accepted when the proof was made (Pubky: the proof file's folder). */\n run(proof: { id: string; subject: string; key: string; evidence: E }, ctx: SignerContext): Promise<void>;\n };\n}\n","import type { GhostlyAdapterPlugin } from \"./registry\";\n\n/**\n * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`\n * names their modules (comma-separated paths from the repository root, each default-exporting a\n * `GhostlyAdapterPlugin`), and the Vite plugin in `packages/browser/vite-plugin.ts` swaps this module\n * for one that imports them. Release builds never set it; the e2e build carries the SDK example.\n */\nexport const BUNDLED_PLUGINS: readonly GhostlyAdapterPlugin[] = [];\n","import type { LightningProviderDescriptor } from \"../engine/paymentAdapters/providers/lightning\";\nimport type { OnchainProviderDescriptor } from \"../engine/paymentAdapters/providers/onchain\";\nimport { providerDescriptorProblems, type ProviderDescriptor, type ProviderKind } from \"../engine/paymentAdapters/providers/types\";\nimport type { IdentityProofProvider } from \"../proofs/contract\";\nimport { descriptorProblems } from \"../proofs/verify\";\nimport { BUNDLED_PLUGINS } from \"./bundled\";\n\n/**\n * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers\n * that register here instead of being added to the built-in lists. A plugin is a plain object naming\n * its adapters; the registries (`providers/registry.ts`, `proofs/registry.ts`) list what is registered\n * after the built-ins and before the test fakes, and the same platform and mode rules apply to all.\n *\n * Two ways in:\n * - at build time: `GHOSTLY_PLUGINS` lists the modules and `bundled.ts` is swapped for them;\n * - at run time: code already running in the engine's realm calls `registerAdapters` before the\n * pickers are shown (or after: the engine re-reads the lists when something registers).\n *\n * Trust: a plugin runs with the app's privileges, in the app's own JavaScript realm. There is no\n * sandbox, no permission prompt and no store; whoever builds a plugin in, or loads one, trusts its\n * author with everything the app can do, keys and sats included. A manifest with permissions and an\n * isolated runtime are a later phase (docs/wisps/ADAPTER-ROADMAP.md, \"Plugins, apps, catalogs\").\n *\n * The state lives on `globalThis` under a well-known symbol, so a plugin bundled with its own copy of\n * the SDK (a second copy of this module) still registers into the same lists the app reads.\n */\n\n/** The generation of the adapter contracts. A plugin says which one it was written against. */\nexport const SDK_API = 1;\nexport const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;\n\nexport interface GhostlyAdapterPlugin {\n /** Stable, unique among plugins: `^[a-z][a-z0-9-]{0,63}$`. */\n id: string;\n /** The plugin's own version, for people. */\n version?: string;\n /** The contract generation it was written against: `SDK_API`. Another one is refused. */\n sdk: number;\n lightning?: readonly LightningProviderDescriptor[];\n onchain?: readonly OnchainProviderDescriptor[];\n identities?: readonly IdentityProofProvider[];\n}\n\nexport type AdapterKind = ProviderKind | \"identity\";\n\ninterface Store {\n plugins: Map<string, GhostlyAdapterPlugin>;\n /** Ids the built-in registries own, per kind: a plugin cannot take one. */\n reserved: Record<AdapterKind, Set<string>>;\n listeners: Set<() => void>;\n seeded: boolean;\n}\n\nconst KEY = Symbol.for(\"ghostly.adapters/1\");\nfunction store(): Store {\n const g = globalThis as unknown as Record<symbol, Store | undefined>;\n return (g[KEY] ??= { plugins: new Map(), reserved: { lightning: new Set(), onchain: new Set(), identity: new Set() }, listeners: new Set(), seeded: false });\n}\n\nconst ids = (kind: AdapterKind, plugin: GhostlyAdapterPlugin): string[] => {\n // Not trusted to be well formed: pluginProblems reads it before saying what is wrong with it.\n const list: unknown = kind === \"identity\" ? plugin.identities : kind === \"lightning\" ? plugin.lightning : plugin.onchain;\n return Array.isArray(list) ? list.map((a: { id?: string } | null) => a?.id as string) : [];\n};\nconst KINDS: readonly AdapterKind[] = [\"lightning\", \"onchain\", \"identity\"];\n\n/** Problems with a plugin, empty when it can be registered. Does not look at what is already registered. */\nexport function pluginProblems(plugin: GhostlyAdapterPlugin): string[] {\n const problems: string[] = [];\n if (!plugin || typeof plugin !== \"object\") return [\"not a plugin object\"];\n if (!PLUGIN_ID.test(plugin.id ?? \"\")) problems.push(\"plugin id must match ^[a-z][a-z0-9-]{0,63}$\");\n if (plugin.sdk !== SDK_API) problems.push(`plugin was written for SDK API ${String(plugin.sdk)}; this app speaks ${SDK_API}`);\n if (plugin.version !== undefined && (typeof plugin.version !== \"string\" || plugin.version.length > 64)) problems.push(\"version must be a short string\");\n for (const kind of [\"lightning\", \"onchain\"] as const) {\n const list = plugin[kind];\n if (list === undefined) continue;\n if (!Array.isArray(list)) { problems.push(`${kind} must be a list of descriptors`); continue; }\n for (const d of list as ProviderDescriptor<unknown>[]) {\n if (!d || typeof d !== \"object\") { problems.push(`${kind} ${String(d)}: not a descriptor`); continue; }\n const own = providerDescriptorProblems(d);\n if (d?.kind && d.kind !== kind) own.push(`is listed under ${kind} but says kind ${String(d.kind)}`);\n problems.push(...own.map((p) => `${kind} ${String(d?.id)}: ${p}`));\n }\n }\n if (plugin.identities !== undefined) {\n if (!Array.isArray(plugin.identities)) problems.push(\"identities must be a list of providers\");\n else for (const p of plugin.identities) {\n if (!p || typeof p !== \"object\") problems.push(`identity ${String(p)}: not a provider`);\n else problems.push(...descriptorProblems(p).map((m) => `identity ${String(p.id)}: ${m}`));\n }\n }\n for (const kind of KINDS) {\n const list = ids(kind, plugin);\n if (new Set(list).size !== list.length) problems.push(`${kind} ids are not unique within the plugin`);\n }\n if (!KINDS.some((kind) => ids(kind, plugin).length)) problems.push(\"the plugin brings no adapter\");\n return problems;\n}\n\n/** The built-in registries say which ids are theirs. A plugin using one is refused. */\nexport function reserveAdapterIds(kind: AdapterKind, list: readonly string[]): void {\n const s = store();\n for (const id of list) s.reserved[kind].add(id);\n}\n\n/**\n * Registers a plugin's adapters. Throws, registering nothing, when the plugin is malformed, its id or\n * one of its adapters' ids is taken (by a built-in or by another plugin), or its contract generation\n * is another one. Returns the function that unregisters it.\n */\nexport function registerAdapters(plugin: GhostlyAdapterPlugin): () => void {\n const problems = pluginProblems(plugin);\n const s = store();\n if (!problems.length) {\n if (s.plugins.has(plugin.id)) problems.push(`a plugin with id ${plugin.id} is already registered`);\n for (const kind of KINDS) for (const id of ids(kind, plugin)) {\n if (s.reserved[kind].has(id)) problems.push(`${kind} ${id} is a built-in of this app`);\n for (const other of s.plugins.values()) if (ids(kind, other).includes(id)) problems.push(`${kind} ${id} is already registered by plugin ${other.id}`);\n }\n }\n if (problems.length) throw new Error(`Cannot register plugin ${String(plugin?.id)}: ${problems.join(\"; \")}`);\n s.plugins.set(plugin.id, plugin);\n notify(s);\n return () => { if (s.plugins.get(plugin.id) === plugin) { s.plugins.delete(plugin.id); notify(s); } };\n}\n\nfunction notify(s: Store) { for (const listener of s.listeners) { try { listener(); } catch { /* a listener's problem */ } } }\n\n/** Called when a plugin registers or unregisters: the engine re-reads the lists. */\nexport function onAdaptersChanged(listener: () => void): () => void {\n const s = store();\n s.listeners.add(listener);\n return () => { s.listeners.delete(listener); };\n}\n\n/** Every registered plugin, in registration order (bundled ones first). */\nexport function registeredPlugins(): readonly GhostlyAdapterPlugin[] { seed(); return [...store().plugins.values()]; }\nexport function registeredLightningProviders(): readonly LightningProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.lightning ?? []); }\nexport function registeredOnchainProviders(): readonly OnchainProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.onchain ?? []); }\nexport function registeredIdentityProviders(): readonly IdentityProofProvider[] { return registeredPlugins().flatMap((p) => p.identities ?? []); }\n\n/**\n * The plugins compiled into this build register once, when they are first asked for. A broken one is\n * reported and skipped rather than taking the app down with it; the e2e that expects it fails instead.\n */\nfunction seed() {\n const s = store();\n if (s.seeded) return;\n s.seeded = true;\n for (const plugin of BUNDLED_PLUGINS) {\n try { registerAdapters(plugin); }\n catch (error) { console.error(`[ghostly] a bundled adapter plugin was not loaded: ${error instanceof Error ? error.message : String(error)}`); }\n }\n}\n\n/** Tests only: forget every registration, including the bundled ones. */\nexport function resetAdapterRegistry(): void {\n const s = store();\n s.plugins.clear(); s.seeded = false;\n for (const kind of KINDS) s.reserved[kind].clear();\n notify(s);\n}\n"],"mappings":";;;;;;AAoBA,IAAa,qBAAkD;CAAC;CAAO;CAAa;AAAS;;;;;;;;ACZ7F,IAAa,kBAAmD,CAAC;;;;;;;;;;;;;;;;;;;;;;AC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,MAAM;CAChB,IAAI,EAAE,QAAQ;CACd,EAAE,SAAS;CACX,KAAK,MAAM,UAAU,iBACnB,IAAI;EAAE,iBAAiB,MAAM;CAAG,SACzB,OAAO;EAAE,QAAQ,MAAM,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAAG;AAEnJ;;AAGA,SAAgB,uBAA6B;CAC3C,MAAM,IAAI,MAAM;CAChB,EAAE,QAAQ,MAAM;CAAG,EAAE,SAAS;CAC9B,KAAK,MAAM,QAAQ,OAAO,EAAE,SAAS,KAAK,CAAC,MAAM;CACjD,OAAO,CAAC;AACV"}
@@ -1,5 +1,5 @@
1
1
  import { a as concatBytes, c as fromZ32, d as toBase64, f as toBase64Url, h as utf8Encode, m as utf8Decode, o as fromBase64, p as toZ32, s as fromBase64Url, u as randomBytes } from "./bolt11-CRiQrma3.js";
2
- import { H as identityFromSeed, K as sign, U as identityFromSeedB64, W as publicKeyFromZ32, q as verify } from "./bitcoinAddress-C2MAmcDT.js";
2
+ import { Vt as measureRecords, an as sign, nn as identityFromSeedB64, on as verify, rn as publicKeyFromZ32, tn as identityFromSeed } from "./bitcoinAddress-BbPG0DF7.js";
3
3
  import { xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
4
4
  import { ed25519, x25519 } from "@noble/curves/ed25519.js";
5
5
  import { sha256 } from "@noble/hashes/sha2.js";
@@ -39,292 +39,6 @@ function tryDecrypt(encoded, key) {
39
39
  return null;
40
40
  }
41
41
  }
42
- // ../core/src/dns.ts
43
- var TYPE_NS = 2;
44
- var TYPE_TXT = 16;
45
- var CLASS_IN = 1;
46
- var FLAGS_REPLY = 32768;
47
- var MAX_CHARACTER_STRING = 255;
48
- var MAX_POINTER_OFFSET = 16383;
49
- var Writer = class {
50
- chunks = [];
51
- length = 0;
52
- push(bytes) {
53
- this.chunks.push(bytes);
54
- this.length += bytes.length;
55
- }
56
- u8(v) {
57
- this.push(Uint8Array.of(v & 255));
58
- }
59
- u16(v) {
60
- this.push(Uint8Array.of(v >>> 8 & 255, v & 255));
61
- }
62
- u32(v) {
63
- this.push(Uint8Array.of(v >>> 24 & 255, v >>> 16 & 255, v >>> 8 & 255, v & 255));
64
- }
65
- bytes() {
66
- return concatBytes(...this.chunks);
67
- }
68
- };
69
- function writeName(writer, name, suffixOffsets) {
70
- const labels = name.split(".").filter((l) => l.length > 0);
71
- for (let i = 0; i < labels.length; i++) {
72
- const suffix = labels.slice(i).join(".");
73
- const pointer = suffixOffsets.get(suffix);
74
- if (pointer !== void 0) {
75
- writer.u16(49152 | pointer);
76
- return;
77
- }
78
- if (writer.length <= MAX_POINTER_OFFSET) suffixOffsets.set(suffix, writer.length);
79
- const label = utf8Encode(labels[i]);
80
- if (label.length > 63) throw new Error(`DNS label too long: ${labels[i]}`);
81
- writer.u8(label.length);
82
- writer.push(label);
83
- }
84
- writer.u8(0);
85
- }
86
- /** `authoritative` sets the AA flag, which a did:dht packet must carry. */
87
- function encodeTxtPacket(records, options = {}) {
88
- const writer = new Writer();
89
- writer.u16(0);
90
- writer.u16(options.authoritative ? 33792 : FLAGS_REPLY);
91
- writer.u16(0);
92
- writer.u16(records.length);
93
- writer.u16(0);
94
- writer.u16(0);
95
- const suffixOffsets = /* @__PURE__ */ new Map();
96
- for (const record of records) {
97
- writeName(writer, record.name, suffixOffsets);
98
- if ("host" in record) {
99
- writer.u16(TYPE_NS);
100
- writer.u16(CLASS_IN);
101
- writer.u32(record.ttl);
102
- const host = new Writer();
103
- writeName(host, record.host, /* @__PURE__ */ new Map());
104
- writer.u16(host.length);
105
- writer.push(host.bytes());
106
- continue;
107
- }
108
- writer.u16(TYPE_TXT);
109
- writer.u16(CLASS_IN);
110
- writer.u32(record.ttl);
111
- const value = utf8Encode(record.value);
112
- const strings = [];
113
- for (let i = 0; i < value.length || i === 0; i += MAX_CHARACTER_STRING) {
114
- const chunk = value.subarray(i, i + MAX_CHARACTER_STRING);
115
- strings.push(Uint8Array.of(chunk.length), chunk);
116
- }
117
- const rdata = concatBytes(...strings);
118
- writer.u16(rdata.length);
119
- writer.push(rdata);
120
- }
121
- return writer.bytes();
122
- }
123
- /** A name at `start` (compressed or not), and where the bytes after it begin. Labels are joined with ".", no trailing dot. */
124
- function readDnsName(data, start) {
125
- const labels = [];
126
- let pos = start;
127
- let next = -1;
128
- let jumps = 0;
129
- for (;;) {
130
- if (pos >= data.length) throw new Error("DNS name out of bounds");
131
- const len = data[pos];
132
- if ((len & 192) === 192) {
133
- if (pos + 1 >= data.length) throw new Error("DNS pointer out of bounds");
134
- if (next < 0) next = pos + 2;
135
- pos = (len & 63) << 8 | data[pos + 1];
136
- if (++jumps > 32) throw new Error("DNS name has too many compression pointers");
137
- continue;
138
- }
139
- if (len & 192) throw new Error("Unsupported DNS label type");
140
- pos += 1;
141
- if (len === 0) break;
142
- if (pos + len > data.length) throw new Error("DNS label out of bounds");
143
- labels.push(utf8Decode(data.subarray(pos, pos + len)));
144
- pos += len;
145
- }
146
- return {
147
- name: labels.join("."),
148
- next: next < 0 ? pos : next
149
- };
150
- }
151
- function decodeTxtPacket(data) {
152
- if (data.length < 12) throw new Error("DNS packet too short");
153
- const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
154
- const questions = view.getUint16(4);
155
- const answers = view.getUint16(6);
156
- let pos = 12;
157
- for (let i = 0; i < questions; i++) pos = readDnsName(data, pos).next + 4;
158
- const records = [];
159
- for (let i = 0; i < answers; i++) {
160
- const { name, next } = readDnsName(data, pos);
161
- pos = next;
162
- if (pos + 10 > data.length) throw new Error("DNS record out of bounds");
163
- const type = view.getUint16(pos);
164
- const ttl = view.getUint32(pos + 4);
165
- const rdLength = view.getUint16(pos + 8);
166
- pos += 10;
167
- const end = pos + rdLength;
168
- if (end > data.length) throw new Error("DNS rdata out of bounds");
169
- if (type === TYPE_TXT) {
170
- const parts = [];
171
- let p = pos;
172
- while (p < end) {
173
- const len = data[p];
174
- if (p + 1 + len > end) throw new Error("DNS character-string out of bounds");
175
- parts.push(data.subarray(p + 1, p + 1 + len));
176
- p += 1 + len;
177
- }
178
- try {
179
- records.push({
180
- name,
181
- value: utf8Decode(concatBytes(...parts)),
182
- ttl
183
- });
184
- } catch {}
185
- }
186
- pos = end;
187
- }
188
- return records;
189
- }
190
- /** Every answer record of a packet, of any type. Names are decompressed; the rdata is left to the caller. */
191
- function decodeDnsAnswers(data) {
192
- if (data.length < 12) throw new Error("DNS packet too short");
193
- const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
194
- const questions = view.getUint16(4);
195
- const answers = view.getUint16(6);
196
- let pos = 12;
197
- for (let i = 0; i < questions; i++) pos = readDnsName(data, pos).next + 4;
198
- const records = [];
199
- for (let i = 0; i < answers; i++) {
200
- const { name, next } = readDnsName(data, pos);
201
- pos = next;
202
- if (pos + 10 > data.length) throw new Error("DNS record out of bounds");
203
- const type = view.getUint16(pos);
204
- const ttl = view.getUint32(pos + 4);
205
- const length = view.getUint16(pos + 8);
206
- pos += 10;
207
- if (pos + length > data.length) throw new Error("DNS rdata out of bounds");
208
- records.push({
209
- name,
210
- type,
211
- ttl,
212
- offset: pos,
213
- length
214
- });
215
- pos += length;
216
- }
217
- return records;
218
- }
219
- // ../core/src/pkarr.ts
220
- /** Mainline DHT (BEP44) caps the value of a mutable item at 1000 bytes. */
221
- var MAX_DNS_PACKET_BYTES = 1e3;
222
- var SIGNATURE_LENGTH = 64;
223
- var TIMESTAMP_LENGTH = 8;
224
- /** The largest relay payload: a 64-byte signature, an 8-byte timestamp and the largest DNS packet (1072 bytes). */
225
- var RELAY_PAYLOAD_MAX_BYTES = 1072;
226
- var PacketTooLargeError = class extends Error {
227
- size;
228
- constructor(size) {
229
- super(`DNS packet is too large, expected max ${MAX_DNS_PACKET_BYTES} bytes but got: ${size}`);
230
- this.size = size;
231
- }
232
- };
233
- var DEFAULT_TTL = 300;
234
- function signable(timestampMicros, dnsPacket) {
235
- return concatBytes(utf8Encode(`3:seqi${timestampMicros}e1:v${dnsPacket.length}:`), dnsPacket);
236
- }
237
- function toTxtRecords(pubKeyZ32, records) {
238
- return records.map((r) => ({
239
- name: `${r.label}.${pubKeyZ32}`,
240
- value: r.value,
241
- ttl: r.ttl ?? DEFAULT_TTL
242
- }));
243
- }
244
- /** Size of the encoded DNS packet these records would produce. */
245
- function measureRecords(pubKeyZ32, records) {
246
- return encodeTxtPacket(toTxtRecords(pubKeyZ32, records)).length;
247
- }
248
- /**
249
- * Builds the payload Pkarr relays accept on `PUT /<z32 public key>`:
250
- * `<64 bytes signature><8 bytes big-endian timestamp (µs)><encoded DNS packet>`
251
- */
252
- function createRelayPayload(identity, records, timestampMicros = BigInt(Date.now()) * 1000n) {
253
- return signRelayPayload(identity, encodeTxtPacket(toTxtRecords(identity.pubKeyZ32, records)), timestampMicros);
254
- }
255
- /**
256
- * Signs a DNS packet exactly as given (its own names and flags) into a relay payload. `seq` is the
257
- * BEP44 sequence number: Ghostly's records use microseconds, a did:dht document seconds.
258
- */
259
- function signRelayPayload(identity, dnsPacket, seq) {
260
- if (dnsPacket.length > 1e3) throw new PacketTooLargeError(dnsPacket.length);
261
- if (seq < 0n || seq >= 1n << 64n) throw new RangeError(`Sequence number ${seq} does not fit in 64 bits`);
262
- const signature = sign(signable(seq, dnsPacket), identity.seed);
263
- const timestamp = new Uint8Array(TIMESTAMP_LENGTH);
264
- new DataView(timestamp.buffer).setBigUint64(0, seq);
265
- return concatBytes(signature, timestamp, dnsPacket);
266
- }
267
- /** A relay payload's parts, its size checked: the signature, the sequence number and the DNS packet (not decoded). */
268
- function splitRelayPayload(payload) {
269
- if (payload.length < 84) throw new Error("Relay payload too short");
270
- if (payload.length > 1072) throw new PacketTooLargeError(payload.length);
271
- return {
272
- signature: payload.subarray(0, SIGNATURE_LENGTH),
273
- seq: new DataView(payload.buffer, payload.byteOffset + SIGNATURE_LENGTH, TIMESTAMP_LENGTH).getBigUint64(0),
274
- dnsPacket: payload.subarray(72)
275
- };
276
- }
277
- /** Checks a relay payload's size and signature. Returns its sequence number and DNS packet, not decoded. */
278
- function openRelayPayload(pubKeyZ32, payload) {
279
- const { signature, seq, dnsPacket } = splitRelayPayload(payload);
280
- const publicKey = publicKeyFromZ32(pubKeyZ32);
281
- if (!verify(signature, signable(seq, dnsPacket), publicKey)) throw new Error("Invalid signature");
282
- return {
283
- seq,
284
- dnsPacket
285
- };
286
- }
287
- function decodeRelayPayload(pubKeyZ32, seq, dnsPacket) {
288
- const suffix = `.${pubKeyZ32}`;
289
- return {
290
- pubKeyZ32,
291
- timestampMicros: seq,
292
- records: decodeTxtPacket(dnsPacket).map((r) => ({
293
- label: r.name.endsWith(suffix) ? r.name.slice(0, -suffix.length) : r.name,
294
- value: r.value,
295
- ttl: r.ttl
296
- }))
297
- };
298
- }
299
- /** Verifies and decodes a relay payload. Throws if the signature does not match. */
300
- function parseRelayPayload(pubKeyZ32, payload) {
301
- const { seq, dnsPacket } = openRelayPayload(pubKeyZ32, payload);
302
- return decodeRelayPayload(pubKeyZ32, seq, dnsPacket);
303
- }
304
- /**
305
- * Decodes a payload whose signature this process made or already checked (one it is putting), without checking it
306
- * again: an Ed25519 verify costs about 1 ms, and a CLI daemon at its relay budget checked its own packets ~500 times a
307
- * minute. Never for bytes read from elsewhere: `parseRelayPayload` is.
308
- */
309
- function readOwnRelayPayload(pubKeyZ32, payload) {
310
- const { seq, dnsPacket } = splitRelayPayload(payload);
311
- return decodeRelayPayload(pubKeyZ32, seq, dnsPacket);
312
- }
313
- /** How far ahead of this clock a packet's time may be and still count as now: clocks drift, not by this much. */
314
- var PKARR_FUTURE_SKEW_MS = 6e5;
315
- /**
316
- * The newer of two signed packets of one key. A packet dated further ahead than `PKARR_FUTURE_SKEW_MS` never wins over
317
- * one dated now or before: whoever could sign it once (a key several people hold, a clock far off) must not keep every
318
- * later packet from being taken. Between two of the same kind, the later time wins; on a tie, `known` stays.
319
- */
320
- function newerPacket(known, packet, now = Date.now()) {
321
- if (!known) return packet ?? null;
322
- if (!packet) return known;
323
- const limit = BigInt(now + PKARR_FUTURE_SKEW_MS) * 1000n;
324
- const knownAhead = known.timestampMicros > limit;
325
- if (knownAhead !== packet.timestampMicros > limit) return knownAhead ? packet : known;
326
- return packet.timestampMicros > known.timestampMicros ? packet : known;
327
- }
328
42
  // ../core/src/domainProofs.ts
329
43
  var DOMAIN_METHODS = [
330
44
  "dns",
@@ -589,7 +303,8 @@ function txtValue(rdata) {
589
303
  return new TextDecoder("utf-8", { fatal: true }).decode(concatBytes(...parts));
590
304
  }
591
305
  /** False for loopback, private, link-local, shared (CGNAT), multicast, reserved
592
- * and unspecified addresses, including IPv4 embedded in IPv6. */
306
+ * and unspecified addresses, including IPv4 embedded in IPv6, and for 6to4, Teredo and documentation IPv6, as
307
+ * Desktop's link_preview::is_public and apps/ui/src/lib/localHost.ts refuse them. */
593
308
  function isPublicAddress(address) {
594
309
  if (address.length === 4) {
595
310
  const [a, b, c] = address;
@@ -606,6 +321,9 @@ function isPublicAddress(address) {
606
321
  if (address[0] === 254 && (address[1] & 192) === 192) return false;
607
322
  if (address[0] === 255) return false;
608
323
  if (address[0] === 1 && address.subarray(1, 8).every((x) => x === 0)) return false;
324
+ if (address[0] === 32 && address[1] === 2) return false;
325
+ if (address[0] === 32 && address[1] === 1 && address[2] === 0 && address[3] === 0) return false;
326
+ if (address[0] === 32 && address[1] === 1 && address[2] === 13 && address[3] === 184) return false;
609
327
  return (address[0] & 224) === 32;
610
328
  }
611
329
  // ../core/src/storeForward.ts
@@ -939,7 +657,7 @@ function isHoldUrl(value, loopback = false) {
939
657
  return false;
940
658
  }
941
659
  if (url.username || url.password) return false;
942
- const host = url.hostname.toLowerCase().replace(/\.$/, "");
660
+ const host = url.hostname.toLowerCase().replace(/\.+$/, "");
943
661
  if (loopback && url.protocol === "http:" && [
944
662
  "localhost",
945
663
  "127.0.0.1",
@@ -1144,6 +862,6 @@ function transportOrder(available, preferred, fallback) {
1144
862
  const rest = TRANSPORTS.filter((t) => available.includes(t) && t !== preferred);
1145
863
  return [...available.includes(preferred) ? [preferred] : [], ...fallback ? rest : []];
1146
864
  }
1147
- export { openRelayPayload as $, WELL_KNOWN_PATH as A, recordsFromTxt as B, DNS_LABEL as C, DOMAIN_METHODS as D, DOMAIN_MAX_RECORDS as E, encodeDnsQuery as F, wellKnownUrl as G, recordsName as H, isPublicAddress as I, PacketTooLargeError as J, MAX_DNS_PACKET_BYTES as K, nip05RootKey as L, dnsProofName as M, domainTxtRecord as N, DOMAIN_TXT_MAX_BYTES as O, domainWellKnownFile as P, newerPacket as Q, normalizeDomain as R, readManifest as S, DOMAIN_FILE_MAX_BYTES as T, txtValue as U, recordsFromWellKnown as V, validDomainRecord as W, createRelayPayload as X, RELAY_PAYLOAD_MAX_BYTES as Y, measureRecords as Z, HOLD_LIMITS as _, automaticTransport as a, encodeTxtPacket as at, isHoldUrl as b, irohDescriptor as c, encrypt as ct, relayUrl as d, tryDecrypt as dt, parseRelayPayload as et, relayUrlTooLong as f, HOLD_DATED_BACK_MS as g, HOLD_CAPABILITY as h, TRANSPORTS as i, decodeTxtPacket as it, decodeDnsResponse as j, NIP05_PATH as k, irohRelayUrl as l, generateEncryptionKey as lt, transportOrder as m, RELAY_URL as n, signRelayPayload as nt, checkedDescriptors as o, readDnsName as ot, relayedTransports as p, PKARR_FUTURE_SKEW_MS as q, RELAY_WITH_SECRETS as r, decodeDnsAnswers as rt, dialableIrohRelay as s, decrypt as st, AUTOMATIC_ORDER as t, readOwnRelayPayload as tt, rankTransports as u, sealedLength as ut, HoldKeys as v, DNS_TYPE as w, newMailbox as x, HoldRefusedError as y, parseDomainTxt as z };
865
+ export { WELL_KNOWN_PATH as A, recordsFromTxt as B, DNS_LABEL as C, DOMAIN_METHODS as D, DOMAIN_MAX_RECORDS as E, encodeDnsQuery as F, wellKnownUrl as G, recordsName as H, isPublicAddress as I, generateEncryptionKey as J, decrypt as K, nip05RootKey as L, dnsProofName as M, domainTxtRecord as N, DOMAIN_TXT_MAX_BYTES as O, domainWellKnownFile as P, normalizeDomain as R, readManifest as S, DOMAIN_FILE_MAX_BYTES as T, txtValue as U, recordsFromWellKnown as V, validDomainRecord as W, tryDecrypt as X, sealedLength as Y, HOLD_LIMITS as _, automaticTransport as a, isHoldUrl as b, irohDescriptor as c, relayUrl as d, relayUrlTooLong as f, HOLD_DATED_BACK_MS as g, HOLD_CAPABILITY as h, TRANSPORTS as i, decodeDnsResponse as j, NIP05_PATH as k, irohRelayUrl as l, transportOrder as m, RELAY_URL as n, checkedDescriptors as o, relayedTransports as p, encrypt as q, RELAY_WITH_SECRETS as r, dialableIrohRelay as s, AUTOMATIC_ORDER as t, rankTransports as u, HoldKeys as v, DNS_TYPE as w, newMailbox as x, HoldRefusedError as y, parseDomainTxt as z };
1148
866
 
1149
- //# sourceMappingURL=pairedTransports-CkYMAoYN.js.map
867
+ //# sourceMappingURL=pairedTransports-C0I24YFz.js.map