@ghostlytools/sdk 1.12.0 → 1.13.0

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.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\nexport interface SignerContext {\n values: Record<string, string>;\n signal: AbortSignal;\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 /** 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;;;;;;;;;;;;;;;;;;;;;;ACoBjE,IAAa,UAAU;AACvB,IAAa,YAAY;AAwBzB,IAAM,MAAM,OAAO,IAAI,oBAAoB;AAC3C,SAAS,QAAe;CACtB,MAAM,IAAI;CACV,OAAQ,EAAE,SAAS;EAAE,yBAAS,IAAI,IAAI;EAAG,UAAU;GAAE,2BAAW,IAAI,IAAI;GAAG,yBAAS,IAAI,IAAI;GAAG,0BAAU,IAAI,IAAI;EAAE;EAAG,2BAAW,IAAI,IAAI;EAAG,QAAQ;CAAM;AAC5J;AAEA,IAAM,OAAO,MAAmB,WAA2C;CAEzE,MAAM,OAAgB,SAAS,aAAa,OAAO,aAAa,SAAS,cAAc,OAAO,YAAY,OAAO;CACjH,OAAO,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAK,MAA8B,GAAG,EAAY,IAAI,CAAC;AAC3F;AACA,IAAM,QAAgC;CAAC;CAAa;CAAW;AAAU;;AAGzE,SAAgB,eAAe,QAAwC;CACrE,MAAM,WAAqB,CAAC;CAC5B,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO,CAAC,qBAAqB;CACxE,IAAI,CAAC,UAAU,KAAK,OAAO,MAAM,EAAE,GAAG,SAAS,KAAK,6CAA6C;CACjG,IAAI,OAAO,QAAA,GAAiB,SAAS,KAAK,kCAAkC,OAAO,OAAO,GAAG,EAAE,oBA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D;CAAE,KAAK;CAAG,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,OAAO,CAAC;AAAG;AACrH,SAAgB,+BAAuE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,aAAa,CAAC,CAAC;AAAG;AACvJ,SAAgB,6BAAmE;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 { 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 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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,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"}
@@ -116,9 +116,17 @@ export interface ApprovalRequest {
116
116
  /** Short lines under the choices. */
117
117
  notes?: readonly string[];
118
118
  }
119
+ /** A signer's own wait for the person's approval ended (Pubky's relay forgot the request): a time-out, not a failure. */
120
+ export declare class SignerTimeout extends Error {
121
+ }
119
122
  export interface SignerContext {
120
123
  values: Record<string, string>;
121
124
  signal: AbortSignal;
125
+ /**
126
+ * How long the caller waits for the approval (the CLI's --timeout): a signer with a wait of its own takes this one,
127
+ * up to its `maxWaitMs`. Its own wait when absent (the app).
128
+ */
129
+ waitMs?: number;
122
130
  /** The signer asks the person to approve on a page (NIP-46 auth_url): the UI shows it as a link, never opens it itself. */
123
131
  onAuthUrl(url: string): void;
124
132
  onProgress(message: string): void;
@@ -162,6 +170,8 @@ interface SignerBase {
162
170
  export interface InAppSigner<E> extends SignerBase {
163
171
  kind: "in-app";
164
172
  fields?: readonly SignerField[];
173
+ /** The longest it can wait for an approval, whatever `waitMs` says (Pubky: its relay keeps a request five minutes). */
174
+ maxWaitMs?: number;
165
175
  /** Opens the signer, runs `work`, and always cleans up (closes connections, drops keys) before resolving. */
166
176
  run<T>(ctx: SignerContext, work: (session: SignerSession<E>) => Promise<T>): Promise<T>;
167
177
  }
@@ -318,6 +318,11 @@ export declare class ChatFiles {
318
318
  private readonly moving;
319
319
  /** Files that stopped sending for the chat's window alone: they go on once another's bytes are confirmed. */
320
320
  private readonly held;
321
+ /**
322
+ * The entries not ended (`track`): what is still to come or under way is read from these, not from every file the
323
+ * chat ever had, which it keeps for good. An offer read all of them, in every chat, at 100,000 files about 10 ms each.
324
+ */
325
+ private readonly unended;
321
326
  /**
322
327
  * Files this side cancelled while no session carried the cancel (`pf-abort`), said on the next one. The session also
323
328
  * goes for a moment when a move swaps it (its capabilities are agreed again): unsaid, the receiver showed the file
@@ -349,6 +354,12 @@ export declare class ChatFiles {
349
354
  /** What the contact said it can take, on this session. */
350
355
  get peerRoom(): number | null;
351
356
  records(): FileTransferRecord[];
357
+ /** Bytes still to come of the files taken here, not ended (one still asked about is not taken yet). */
358
+ stillToCome(): number;
359
+ /** A transfer under way: offered, moving, or being checked. */
360
+ underWay(): boolean;
361
+ /** Bytes of the files received here that were taken without asking and are kept (or on their way). */
362
+ takenUnasked(): number;
352
363
  get(direction: "in" | "out", id: string): FileTransferRecord | undefined;
353
364
  /** Bytes moved so far: confirmed by the receiver (sending), stored (receiving). */
354
365
  transferred(direction: "in" | "out", id: string): number;
@@ -356,6 +367,11 @@ export declare class ChatFiles {
356
367
  sent(id: string): number;
357
368
  private moved;
358
369
  private changed;
370
+ /**
371
+ * Keeps `unended` to the entries of this chat not ended. Each change of a record's state is reported (`changed`),
372
+ * so that is where a file that ended leaves it, and one taken or sent again comes back.
373
+ */
374
+ private track;
359
375
  private send;
360
376
  private sendData;
361
377
  /** A session that agreed files/3 is open: say what fits here, then offer again what is not finished. */
@@ -28,7 +28,9 @@
28
28
  * this script first, a declarative shadow root the page's script would make is refused, and with `VIEWER_GUARD_CSP`
29
29
  * a `javascript:` URL is refused (its own Trusted Types default policy; one passes every other string on as it is,
30
30
  * or, once the page made its own `default` policy, to that one's rules: the page's `createPolicy("default")` gets the
31
- * guard's policy back with them, and the copy of itself it puts in a `srcdoc` frame skips them).
31
+ * guard's policy back with them, and the copy of itself it puts in a `srcdoc` frame skips them);
32
+ * - starts a worker made from a `blob:` URL of the page's own from a script that makes a pass-through Trusted Types
33
+ * `default` policy in it first, as the WebRTC guard does (`VIEWER_GUARD_SCRIPT`, whichever of the two runs first).
32
34
  * A frame's window keeps what was run in it on its first, empty page when the page it loads is of the same origin (the
33
35
  * bridge's guard reaches the app's frame then): there this script only watches the new document. Each document it
34
36
  * watches is marked (`ghostlyClipboardGuard`, fixed in place): the bridge reads that to know the guard ran in the page
@@ -38,6 +40,6 @@
38
40
  * inside a shadow tree written in the HTML the page itself sends, is out of its sight.
39
41
  * No backslash, `${` or backtick in it.
40
42
  */
41
- export declare const CLIPBOARD_GUARD_SCRIPT = "(function noClipboardWrites(w) {\n \"use strict\";\n try {\n const apply = w.Reflect.apply;\n const describe = w.Object.getOwnPropertyDescriptor;\n const define = w.Object.defineProperty;\n const proto = w.Document.prototype;\n const home = w.document;\n const exec = describe(proto, \"execCommand\");\n const fresh = !!exec && exec.configurable === true && typeof exec.value === \"function\";\n const watched = !!describe(home, \"ghostlyClipboardGuard\");\n if (!fresh && watched) return;\n if (!watched) define(home, \"ghostlyClipboardGuard\", { value: true });\n const own = \"<script>(\" + noClipboardWrites + \")(window)<\" + \"/script>\";\n const close = \"<\" + \"/script>\";\n const webRtc = \"<script>(function noWebRtc(\";\n const text = w.String;\n const lower = text.prototype.toLowerCase;\n const slice = text.prototype.slice;\n const index = text.prototype.indexOf;\n const listen = w.EventTarget.prototype.addEventListener;\n const shut = (inner) => {\n try { if (inner && inner !== w) noClipboardWrites(inner); } catch (e) {}\n };\n const count = describe(w, \"length\").get;\n const view = describe(proto, \"defaultView\").get;\n const sweep = () => {\n try { for (let i = apply(count, w, []); i-- > 0;) shut(w[i]); } catch (e) {}\n };\n const elements = w.Element.prototype;\n const getAttribute = elements.getAttribute;\n const setAttribute = elements.setAttribute;\n const removeAttribute = elements.removeAttribute;\n const attachShadow = elements.attachShadow;\n const size = describe(w.NodeList.prototype, \"length\").get;\n let passing = false;\n const first = (frame) => {\n const doc = apply(getAttribute, frame, [\"srcdoc\"]);\n if (doc === null) return;\n let at = 0;\n if (apply(slice, doc, [0, webRtc.length]) === webRtc) {\n const end = apply(index, doc, [close]);\n if (end >= 0) at = end + close.length;\n }\n if (apply(slice, doc, [at, at + own.length]) === own) return;\n passing = true;\n try { apply(setAttribute, frame, [\"srcdoc\", own + doc]); } catch (e) { apply(removeAttribute, frame, [\"srcdoc\"]); }\n passing = false;\n };\n const Observer = w.MutationObserver;\n const observe = Observer.prototype.observe;\n const watch = (root, all) => {\n const scan = () => {\n try {\n const frames = apply(all, root, [\"iframe[srcdoc]\"]);\n for (let i = apply(size, frames, []); i-- > 0;) first(frames[i]);\n } catch (e) {}\n sweep();\n };\n apply(observe, new Observer(scan), [root, { subtree: true, childList: true, attributes: true, attributeFilter: [\"srcdoc\"] }]);\n apply(listen, root, [\"load\", sweep, true]);\n scan();\n return root;\n };\n if (fresh) {\n const run = exec.value;\n const phase = describe(w.Event.prototype, \"eventPhase\").get;\n const trust = (event) => {\n try {\n const found = describe(event, \"isTrusted\");\n if (found && found.get && apply(found.get, event, []) === true) return found.get;\n } catch (e) {}\n return null;\n };\n const dispatching = (event, trusted) => {\n try { return apply(trusted, event, []) === true && apply(phase, event, []) !== 0; } catch (e) { return false; }\n };\n const stamp = describe(w.Event.prototype, \"timeStamp\");\n const clock = w.performance;\n const tick = clock && clock.now;\n const time = () => { try { return apply(tick, clock, []); } catch (e) { return NaN; } };\n const recent = (at) => time() - at <= 1000;\n const shutters = [];\n try {\n const channel = new w.MessageChannel();\n const post = w.MessagePort.prototype.postMessage;\n const out = channel.port2;\n channel.port1.onmessage = () => settle();\n shutters[0] = () => apply(post, out, [0]);\n } catch (e) {}\n try {\n const tasks = w.scheduler;\n const postTask = tasks && tasks.postTask;\n const urgent = { __proto__: null, priority: \"user-blocking\" };\n if (typeof postTask === \"function\") shutters[shutters.length] = () => { apply(postTask, tasks, [settle, urgent]); };\n } catch (e) {}\n try {\n const frame = w.requestAnimationFrame;\n if (typeof frame === \"function\") shutters[shutters.length] = () => { apply(frame, w, [settle]); };\n } catch (e) {}\n let tap = null;\n let trusted = null;\n let tapped = NaN;\n let open = 0;\n let follows = null;\n const settle = () => { open = 0; follows = null; };\n const seen = (event) => {\n const found = trust(event);\n if (found === null) return;\n let at = time();\n try {\n const given = apply(stamp.get, event, []);\n if (given >= 0 && given < at) at = given;\n } catch (e) {}\n tap = event;\n trusted = found;\n tapped = at;\n if (shutters.length === 0) return;\n open = 1;\n for (let i = 0; i < shutters.length; i++) { try { shutters[i](); } catch (e) {} }\n };\n const taps = [\"pointerdown\", \"pointerup\", \"mousedown\", \"mouseup\", \"click\", \"auxclick\", \"dblclick\", \"contextmenu\", \"touchstart\", \"touchend\", \"keydown\", \"keypress\", \"keyup\"];\n for (let i = 0; i < taps.length; i++) apply(listen, w, [taps[i], seen, true]);\n const followed = (event) => {\n if (open === 0) return;\n const found = trust(event);\n if (found !== null) follows = { event: event, trusted: found, at: tapped, next: follows };\n };\n apply(listen, w, [\"submit\", followed, true]);\n apply(listen, w, [\"change\", followed, true]);\n const tapping = () => {\n if (tap !== null && dispatching(tap, trusted) && recent(tapped)) return true;\n for (let f = follows; f !== null; f = f.next) if (dispatching(f.event, f.trusted) && recent(f.at)) return true;\n return false;\n };\n const guarded = function execCommand(command) {\n const name = apply(lower, text(command), []);\n if (name === \"paste\" || ((name === \"copy\" || name === \"cut\") && !tapping())) return false;\n const args = [name];\n for (let i = 1; i < arguments.length; i++) args[i] = arguments[i];\n return apply(run, this, args);\n };\n define(proto, \"execCommand\", { value: guarded, writable: false, enumerable: exec.enumerable, configurable: false });\n const types = w.trustedTypes;\n if (types && !types.defaultPolicy) {\n try {\n let rules = null;\n const rule = (kind) => (input, type, sink) => {\n if (kind === \"createScript\" && sink === \"Location href\") return null;\n if (passing || rules === null) return input;\n return rules[kind] ? apply(rules[kind], undefined, [input, type, sink]) : null;\n };\n const members = [\"createHTML\", \"createScript\", \"createScriptURL\"];\n const create = types.createPolicy;\n const policy = apply(create, types, [\"default\", { createHTML: rule(members[0]), createScript: rule(members[1]), createScriptURL: rule(members[2]) }]);\n const Mistyped = w.TypeError;\n w.Object.getPrototypeOf(types).createPolicy = function createPolicy(name, options) {\n if (this !== types || rules !== null || text(name) !== \"default\") return apply(create, this, arguments);\n const given = { createHTML: null, createScript: null, createScriptURL: null };\n for (let i = 0; i < members.length; i++) {\n const found = options ? options[members[i]] : undefined;\n if (found === undefined || found === null) continue;\n if (typeof found !== \"function\") throw new Mistyped(\"The policy's \" + members[i] + \" is not a function\");\n given[members[i]] = found;\n }\n rules = given;\n return policy;\n };\n } catch (e) {}\n }\n const reopen = proto.open;\n proto.open = function () {\n const got = apply(reopen, this, arguments);\n try { if (apply(view, this, []) === w) apply(listen, this, [\"load\", sweep, true]); } catch (e) {}\n return got;\n };\n const shadowed = (html) => apply(index, apply(lower, html, []), [\"shadowrootmode\"]) >= 0;\n const Refused = w.TypeError;\n const refuse = () => { throw new Refused(\"A declarative shadow root is not allowed here\"); };\n const parsers = [[elements, \"setHTMLUnsafe\"], [w.ShadowRoot && w.ShadowRoot.prototype, \"setHTMLUnsafe\"], [w.Document, \"parseHTMLUnsafe\"]];\n for (let i = 0; i < parsers.length; i++) {\n const owner = parsers[i][0];\n const name = parsers[i][1];\n const real = owner && owner[name];\n if (typeof real !== \"function\") continue;\n owner[name] = function (html) {\n const checked = text(html);\n if (shadowed(checked)) refuse();\n return apply(real, this, arguments.length > 1 ? [checked, arguments[1]] : [checked]);\n };\n }\n let tail = \"\";\n const writes = [\"write\", \"writeln\"];\n for (let i = 0; i < writes.length; i++) {\n const real = proto[writes[i]];\n if (typeof real !== \"function\") continue;\n proto[writes[i]] = function () {\n let checked = \"\";\n for (let j = 0; j < arguments.length; j++) checked += text(arguments[j]);\n if (shadowed(tail + checked)) refuse();\n tail = apply(slice, tail + checked, [-16]);\n return apply(real, this, [checked]);\n };\n }\n const kinds = [\"HTMLIFrameElement\", \"HTMLFrameElement\", \"HTMLObjectElement\", \"HTMLEmbedElement\"];\n const reads = [\"contentWindow\", \"contentDocument\", \"getSVGDocument\"];\n for (let k = 0; k < kinds.length; k++) {\n const owner = w[kinds[k]] && w[kinds[k]].prototype;\n for (let r = 0; r < reads.length; r++) {\n const name = reads[r];\n const found = owner && describe(owner, name);\n const key = found && found.get ? \"get\" : \"value\";\n if (!found || typeof found[key] !== \"function\") continue;\n const read = found[key];\n found[key] = function () {\n const got = apply(read, this, arguments);\n try { shut(name === \"contentWindow\" ? got : apply(view, got, [])); } catch (e) {}\n return got;\n };\n try { define(owner, name, found); } catch (e) {}\n }\n }\n const inShadow = w.DocumentFragment.prototype.querySelectorAll;\n if (attachShadow) {\n elements.attachShadow = function () {\n const root = apply(attachShadow, this, arguments);\n try { watch(root, inShadow); } catch (e) {}\n return root;\n };\n }\n }\n if (!watched) watch(home, proto.querySelectorAll);\n } catch (e) {}\n})(window)";
43
+ export declare const CLIPBOARD_GUARD_SCRIPT = "(function noClipboardWrites(w) {\n \"use strict\";\n try {\n const apply = w.Reflect.apply;\n const describe = w.Object.getOwnPropertyDescriptor;\n const define = w.Object.defineProperty;\n const proto = w.Document.prototype;\n const home = w.document;\n const exec = describe(proto, \"execCommand\");\n const fresh = !!exec && exec.configurable === true && typeof exec.value === \"function\";\n const watched = !!describe(home, \"ghostlyClipboardGuard\");\n if (!fresh && watched) return;\n if (!watched) define(home, \"ghostlyClipboardGuard\", { value: true });\n const own = \"<script>(\" + noClipboardWrites + \")(window)<\" + \"/script>\";\n const close = \"<\" + \"/script>\";\n const webRtc = \"<script>(function noWebRtc(\";\n const text = w.String;\n const lower = text.prototype.toLowerCase;\n const slice = text.prototype.slice;\n const index = text.prototype.indexOf;\n const listen = w.EventTarget.prototype.addEventListener;\n const shut = (inner) => {\n try { if (inner && inner !== w) noClipboardWrites(inner); } catch (e) {}\n };\n const count = describe(w, \"length\").get;\n const view = describe(proto, \"defaultView\").get;\n const sweep = () => {\n try { for (let i = apply(count, w, []); i-- > 0;) shut(w[i]); } catch (e) {}\n };\n const elements = w.Element.prototype;\n const getAttribute = elements.getAttribute;\n const setAttribute = elements.setAttribute;\n const removeAttribute = elements.removeAttribute;\n const attachShadow = elements.attachShadow;\n const size = describe(w.NodeList.prototype, \"length\").get;\n let passing = false;\n const first = (frame) => {\n const doc = apply(getAttribute, frame, [\"srcdoc\"]);\n if (doc === null) return;\n let at = 0;\n if (apply(slice, doc, [0, webRtc.length]) === webRtc) {\n const end = apply(index, doc, [close]);\n if (end >= 0) at = end + close.length;\n }\n if (apply(slice, doc, [at, at + own.length]) === own) return;\n passing = true;\n try { apply(setAttribute, frame, [\"srcdoc\", own + doc]); } catch (e) { apply(removeAttribute, frame, [\"srcdoc\"]); }\n passing = false;\n };\n const Observer = w.MutationObserver;\n const observe = Observer.prototype.observe;\n const watch = (root, all) => {\n const scan = () => {\n try {\n const frames = apply(all, root, [\"iframe[srcdoc]\"]);\n for (let i = apply(size, frames, []); i-- > 0;) first(frames[i]);\n } catch (e) {}\n sweep();\n };\n apply(observe, new Observer(scan), [root, { subtree: true, childList: true, attributes: true, attributeFilter: [\"srcdoc\"] }]);\n apply(listen, root, [\"load\", sweep, true]);\n scan();\n return root;\n };\n if (fresh) {\n const run = exec.value;\n const phase = describe(w.Event.prototype, \"eventPhase\").get;\n const trust = (event) => {\n try {\n const found = describe(event, \"isTrusted\");\n if (found && found.get && apply(found.get, event, []) === true) return found.get;\n } catch (e) {}\n return null;\n };\n const dispatching = (event, trusted) => {\n try { return apply(trusted, event, []) === true && apply(phase, event, []) !== 0; } catch (e) { return false; }\n };\n const stamp = describe(w.Event.prototype, \"timeStamp\");\n const clock = w.performance;\n const tick = clock && clock.now;\n const time = () => { try { return apply(tick, clock, []); } catch (e) { return NaN; } };\n const recent = (at) => time() - at <= 1000;\n const shutters = [];\n try {\n const channel = new w.MessageChannel();\n const post = w.MessagePort.prototype.postMessage;\n const out = channel.port2;\n channel.port1.onmessage = () => settle();\n shutters[0] = () => apply(post, out, [0]);\n } catch (e) {}\n try {\n const tasks = w.scheduler;\n const postTask = tasks && tasks.postTask;\n const urgent = { __proto__: null, priority: \"user-blocking\" };\n if (typeof postTask === \"function\") shutters[shutters.length] = () => { apply(postTask, tasks, [settle, urgent]); };\n } catch (e) {}\n try {\n const frame = w.requestAnimationFrame;\n if (typeof frame === \"function\") shutters[shutters.length] = () => { apply(frame, w, [settle]); };\n } catch (e) {}\n let tap = null;\n let trusted = null;\n let tapped = NaN;\n let open = 0;\n let follows = null;\n const settle = () => { open = 0; follows = null; };\n const seen = (event) => {\n const found = trust(event);\n if (found === null) return;\n let at = time();\n try {\n const given = apply(stamp.get, event, []);\n if (given >= 0 && given < at) at = given;\n } catch (e) {}\n tap = event;\n trusted = found;\n tapped = at;\n if (shutters.length === 0) return;\n open = 1;\n for (let i = 0; i < shutters.length; i++) { try { shutters[i](); } catch (e) {} }\n };\n const taps = [\"pointerdown\", \"pointerup\", \"mousedown\", \"mouseup\", \"click\", \"auxclick\", \"dblclick\", \"contextmenu\", \"touchstart\", \"touchend\", \"keydown\", \"keypress\", \"keyup\"];\n for (let i = 0; i < taps.length; i++) apply(listen, w, [taps[i], seen, true]);\n const followed = (event) => {\n if (open === 0) return;\n const found = trust(event);\n if (found !== null) follows = { event: event, trusted: found, at: tapped, next: follows };\n };\n apply(listen, w, [\"submit\", followed, true]);\n apply(listen, w, [\"change\", followed, true]);\n const tapping = () => {\n if (tap !== null && dispatching(tap, trusted) && recent(tapped)) return true;\n for (let f = follows; f !== null; f = f.next) if (dispatching(f.event, f.trusted) && recent(f.at)) return true;\n return false;\n };\n const guarded = function execCommand(command) {\n const name = apply(lower, text(command), []);\n if (name === \"paste\" || ((name === \"copy\" || name === \"cut\") && !tapping())) return false;\n const args = [name];\n for (let i = 1; i < arguments.length; i++) args[i] = arguments[i];\n return apply(run, this, args);\n };\n define(proto, \"execCommand\", { value: guarded, writable: false, enumerable: exec.enumerable, configurable: false });\n const types = w.trustedTypes;\n if (types && !types.defaultPolicy) {\n try {\n let rules = null;\n const rule = (kind) => (input, type, sink) => {\n if (kind === \"createScript\" && sink === \"Location href\") return null;\n if (passing || rules === null) return input;\n return rules[kind] ? apply(rules[kind], undefined, [input, type, sink]) : null;\n };\n const members = [\"createHTML\", \"createScript\", \"createScriptURL\"];\n const create = types.createPolicy;\n const policy = apply(create, types, [\"default\", { createHTML: rule(members[0]), createScript: rule(members[1]), createScriptURL: rule(members[2]) }]);\n const Mistyped = w.TypeError;\n w.Object.getPrototypeOf(types).createPolicy = function createPolicy(name, options) {\n if (this !== types || rules !== null || text(name) !== \"default\") return apply(create, this, arguments);\n const given = { createHTML: null, createScript: null, createScriptURL: null };\n for (let i = 0; i < members.length; i++) {\n const found = options ? options[members[i]] : undefined;\n if (found === undefined || found === null) continue;\n if (typeof found !== \"function\") throw new Mistyped(\"The policy's \" + members[i] + \" is not a function\");\n given[members[i]] = found;\n }\n rules = given;\n return policy;\n };\n } catch (e) {}\n }\n if (types && w.URL && w.Blob && !describe(w, \"ghostlyWorkerGuard\")) {\n try {\n define(w, \"ghostlyWorkerGuard\", { value: true });\n const construct = w.Reflect.construct;\n const json = w.JSON.stringify;\n const later = w.setTimeout;\n const Blob = w.Blob;\n const sized = describe(Blob.prototype, \"size\").get;\n const make = w.URL.createObjectURL;\n const revoke = w.URL.revokeObjectURL;\n const policy = \"if (self.trustedTypes && !self.trustedTypes.defaultPolicy) { try { self.trustedTypes.createPolicy('default', { createHTML: (s) => s, createScript: (s) => s, createScriptURL: (s) => s }); } catch (e) {} }\";\n const script = (code) => apply(make, null, [new Blob([code], { type: \"text/javascript\" })]);\n const known = { __proto__: null };\n let first = null;\n w.URL.createObjectURL = function createObjectURL(object) {\n const made = apply(make, this, arguments);\n try { apply(sized, object, []); known[made] = { blob: object, inner: null, classic: null, module: null }; } catch (e) {}\n return made;\n };\n w.URL.revokeObjectURL = function revokeObjectURL(url) {\n try {\n const key = text(url);\n const entry = known[key];\n if (entry) {\n delete known[key];\n const ours = [entry.inner, entry.classic, entry.module];\n apply(later, w, [() => { for (let i = 0; i < 3; i++) { if (ours[i] !== null) apply(revoke, null, [ours[i]]); } }, 60000]);\n }\n } catch (e) {}\n return apply(revoke, this, arguments);\n };\n const start = (url, options) => {\n const entry = known[text(url)];\n if (!entry) return url;\n const kind = options && typeof options === \"object\" && options.type === \"module\" ? \"module\" : \"classic\";\n if (entry[kind] === null) {\n if (entry.inner === null) entry.inner = apply(make, null, [entry.blob]);\n if (kind === \"module\" && first === null) first = script(policy);\n entry[kind] = script(kind === \"module\" ? \"import \" + json(first) + \"; import \" + json(entry.inner) + \";\" : policy + \" importScripts(\" + json(entry.inner) + \");\");\n }\n return entry[kind];\n };\n const makers = [\"Worker\", \"SharedWorker\"];\n for (let i = 0; i < makers.length; i++) {\n const Real = w[makers[i]];\n if (typeof Real !== \"function\") continue;\n const started = function (url) {\n if (new.target === undefined) return apply(Real, this, arguments);\n const args = [];\n for (let j = 0; j < arguments.length; j++) args[j] = arguments[j];\n if (args.length > 0) { try { args[0] = start(url, args[1]); } catch (e) {} }\n return construct(Real, args, new.target);\n };\n define(started, \"name\", { value: makers[i] });\n started.prototype = Real.prototype;\n define(Real.prototype, \"constructor\", { value: started, writable: true, enumerable: false, configurable: true });\n w[makers[i]] = started;\n }\n } catch (e) {}\n }\n const reopen = proto.open;\n proto.open = function () {\n const got = apply(reopen, this, arguments);\n try { if (apply(view, this, []) === w) apply(listen, this, [\"load\", sweep, true]); } catch (e) {}\n return got;\n };\n const shadowed = (html) => apply(index, apply(lower, html, []), [\"shadowrootmode\"]) >= 0;\n const Refused = w.TypeError;\n const refuse = () => { throw new Refused(\"A declarative shadow root is not allowed here\"); };\n const parsers = [[elements, \"setHTMLUnsafe\"], [w.ShadowRoot && w.ShadowRoot.prototype, \"setHTMLUnsafe\"], [w.Document, \"parseHTMLUnsafe\"]];\n for (let i = 0; i < parsers.length; i++) {\n const owner = parsers[i][0];\n const name = parsers[i][1];\n const real = owner && owner[name];\n if (typeof real !== \"function\") continue;\n owner[name] = function (html) {\n const checked = text(html);\n if (shadowed(checked)) refuse();\n return apply(real, this, arguments.length > 1 ? [checked, arguments[1]] : [checked]);\n };\n }\n let tail = \"\";\n const writes = [\"write\", \"writeln\"];\n for (let i = 0; i < writes.length; i++) {\n const real = proto[writes[i]];\n if (typeof real !== \"function\") continue;\n proto[writes[i]] = function () {\n let checked = \"\";\n for (let j = 0; j < arguments.length; j++) checked += text(arguments[j]);\n if (shadowed(tail + checked)) refuse();\n tail = apply(slice, tail + checked, [-16]);\n return apply(real, this, [checked]);\n };\n }\n const kinds = [\"HTMLIFrameElement\", \"HTMLFrameElement\", \"HTMLObjectElement\", \"HTMLEmbedElement\"];\n const reads = [\"contentWindow\", \"contentDocument\", \"getSVGDocument\"];\n for (let k = 0; k < kinds.length; k++) {\n const owner = w[kinds[k]] && w[kinds[k]].prototype;\n for (let r = 0; r < reads.length; r++) {\n const name = reads[r];\n const found = owner && describe(owner, name);\n const key = found && found.get ? \"get\" : \"value\";\n if (!found || typeof found[key] !== \"function\") continue;\n const read = found[key];\n found[key] = function () {\n const got = apply(read, this, arguments);\n try { shut(name === \"contentWindow\" ? got : apply(view, got, [])); } catch (e) {}\n return got;\n };\n try { define(owner, name, found); } catch (e) {}\n }\n }\n const inShadow = w.DocumentFragment.prototype.querySelectorAll;\n if (attachShadow) {\n elements.attachShadow = function () {\n const root = apply(attachShadow, this, arguments);\n try { watch(root, inShadow); } catch (e) {}\n return root;\n };\n }\n }\n if (!watched) watch(home, proto.querySelectorAll);\n } catch (e) {}\n})(window)";
42
44
  /** `CLIPBOARD_GUARD_SCRIPT`'s hash, as a CSP source: the bridge's policy and a contact's own are given it. */
43
- export declare const CLIPBOARD_GUARD_HASH = "'sha256-ay9kpYD2BIflB8W9w+iAbo1krsFBwIJunUmXTACfhao='";
45
+ export declare const CLIPBOARD_GUARD_HASH = "'sha256-D8U3zSg1xP77RbZuV/DekRuM6nx80gIN5mh2TQAtZ40='";
@@ -202,6 +202,14 @@ export declare class DhtDelivery {
202
202
  private announceTimer;
203
203
  private chain;
204
204
  private lastPublish;
205
+ /**
206
+ * A withdrawn text's envelope may still be on the relays, and the one to replace it has not gone (`withdraw`): it is
207
+ * tried again with a text's backoff, `MAX_ATTEMPTS` times at most, until `until` (when no reader takes the withdrawn
208
+ * one any more), not at the next keep-alive four minutes on. Any envelope that goes out replaces it.
209
+ */
210
+ private withdrawal?;
211
+ /** When the last withdrawal's envelope went (its `lastPublish`), for `withdrawalWaits`. */
212
+ private withdrewAt;
205
213
  /** The sequence of the last envelope of the contact that was past its expiry (traced once). */
206
214
  private expiredSeen;
207
215
  private controlDue;
@@ -243,6 +251,8 @@ export declare class DhtDelivery {
243
251
  private namedRev?;
244
252
  /** A reaction of this side waits to ride on an envelope, or the contact's reactions wait to be said taken. */
245
253
  private reactionsDue;
254
+ /** The text on the floor whose envelope left the reactions no room (its id): they wait for the ones its backoff publishes. */
255
+ private crowdedBy?;
246
256
  constructor(options: {
247
257
  params: LinkParams;
248
258
  mode: DeliveryMode;
@@ -454,9 +464,19 @@ export declare class DhtDelivery {
454
464
  * A text of mine (or an edit of it) deleted here while it waits on the floor leaves it: the state no longer holds it
455
465
  * (nor as `confirmed`: no receipt came), and, while its envelope was still in effect, a new one without it takes that
456
466
  * one's place on the relays, so a contact who looks later finds no text. Resolves once the state without it is saved;
457
- * the new envelope goes after.
467
+ * the new envelope goes after. One that does not go (no relay reachable) is tried again within seconds (`withdrawal`):
468
+ * a reader takes the withdrawn envelope until its expiry and the clock skew allowed past it (`DHT_EXPIRY_SKEW_MS`).
469
+ * It goes at once, spacing or not: the deleted text is out of reach from then on. The text that takes the floor next
470
+ * waits out the spacing instead (`withdrawalWaits`).
458
471
  */
459
472
  withdraw(wireId: string): Promise<void>;
473
+ /**
474
+ * The last envelope was a withdrawal's, inside the publication spacing: the text that takes the floor now goes once
475
+ * the spacing allows (`schedule`), not in an envelope of its own at once. Deleted then, it never went, so it costs
476
+ * no withdrawal: deleting 10 texts queued for an away contact one after the other, each one's withdrawal and the next
477
+ * text's envelope put 10 envelopes on every relay in under 2 s, each replaced a moment later (bug hunt, 2026-11-15).
478
+ */
479
+ private withdrawalWaits;
460
480
  /** The id of what awaits its receipt on the floor now, if anything does. */
461
481
  get pendingId(): string | undefined;
462
482
  /**
@@ -481,6 +501,11 @@ export declare class DhtDelivery {
481
501
  private publish;
482
502
  /** The contact is pinned and this side's envelope in the invite's mailbox is still unsealed (`unsealedOut`). */
483
503
  private get resealDue();
504
+ /**
505
+ * Reactions due (`reactionsDue`) that force an envelope of their own: not while the text that left them no room
506
+ * (`crowdedBy`) is still retried, or each publication spends one of its attempts 4 s apart instead of at its backoff.
507
+ */
508
+ private get reactionsPress();
484
509
  /**
485
510
  * The relays' request budget held the envelope back: nothing went out, so it was no attempt (a text keeps its eight),
486
511
  * and what it carried (a text, a receipt, a new mode) goes the moment the budget frees a request: the text and the
@@ -724,8 +724,6 @@ export declare class GhostLink {
724
724
  private nativeFailures;
725
725
  private demotedUntil;
726
726
  private connectionEpoch;
727
- private switchAllowedUntil;
728
- private switchAck;
729
727
  private readonly switcher;
730
728
  /** `plan`: a switch both sides agreed; without one, a replacement the contact dialled (`attachReplacement`). */
731
729
  private candidate;
@@ -54,3 +54,59 @@ export declare function verifyGroupCallRequest(raw: unknown, sfu: string, now: n
54
54
  ok: false;
55
55
  reason: GroupCallRefusal;
56
56
  };
57
+ /**
58
+ * An admin's request to act on a member in its group's call (WISP 602 · Group Calls § Moderation): what it sends to
59
+ * `POST <sfu>/sfu/group-moderate`, signed by its group key over the node's origin as a token request is, under its own
60
+ * tag, so neither request can stand for the other.
61
+ *
62
+ * {"v":1,"g":"<group>","k":"<admin key>","room":"g_<group>","act":"mute","target":"<member key>","src":["microphone"],
63
+ * "ts":1794700800,"n":"<nonce>","sig":"…"}
64
+ *
65
+ * `mute` takes `src` away from `target`, `allow` gives it back, `remove` takes `target` out of the call and keeps it
66
+ * out, `unban` lets it back in, and `state` changes nothing (the reply says who is muted and banned). Whether `k` is
67
+ * the group's admin is the node's to say, from its roster.
68
+ */
69
+ /** What an admin can take from a member, in the sorted order a request lists them in. */
70
+ export declare const GROUP_CALL_SOURCES: readonly ["camera", "microphone", "screen_share"];
71
+ export type GroupCallSource = (typeof GROUP_CALL_SOURCES)[number];
72
+ export declare const GROUP_CALL_MODERATION_ACTS: readonly ["mute", "allow", "remove", "unban", "state"];
73
+ export type GroupCallModerationAct = (typeof GROUP_CALL_MODERATION_ACTS)[number];
74
+ export interface GroupCallModeration {
75
+ v: typeof GROUP_CALL_VERSION;
76
+ g: string;
77
+ k: string;
78
+ room: string;
79
+ act: GroupCallModerationAct;
80
+ /** The member acted on; `""` for `state`. */
81
+ target: string;
82
+ /** Non-empty, unique and sorted for `mute` and `allow`; empty for the other acts. */
83
+ src: GroupCallSource[];
84
+ ts: number;
85
+ n: string;
86
+ sig: string;
87
+ }
88
+ /** Exactly the bytes an admin signs: the array form, as the token request's. */
89
+ export declare const groupCallModerationBytes: (sfu: string, g: string, room: string, k: string, act: GroupCallModerationAct, target: string, src: readonly GroupCallSource[], ts: number, n: string) => Uint8Array<ArrayBufferLike>;
90
+ /** A moderation request for `sfu`, signed by the admin's group key `seed`; `src` is listed unique and sorted. */
91
+ export declare function signGroupCallModeration(input: {
92
+ sfu: string;
93
+ g: string;
94
+ act: GroupCallModerationAct;
95
+ target?: string;
96
+ src?: readonly GroupCallSource[];
97
+ ts?: number;
98
+ n?: string;
99
+ }, seed: Uint8Array): GroupCallModeration;
100
+ /**
101
+ * The node's checks of a moderation request but the roster, in order: the shape (a known act, a `target` that is a
102
+ * member key other than `k`, or `""` for `state`, and `src` as the act takes it), the time within `GROUP_CALL_SKEW_S`
103
+ * of `now` (ms), a nonce not in `seen`, and the signature over the node's own origin `sfu`. A request that passes has
104
+ * its nonce added to `seen`; entries older than `GROUP_CALL_NONCE_S` are dropped on the way.
105
+ */
106
+ export declare function verifyGroupCallModeration(raw: unknown, sfu: string, now: number, seen: GroupCallNonces): {
107
+ ok: true;
108
+ request: GroupCallModeration;
109
+ } | {
110
+ ok: false;
111
+ reason: GroupCallRefusal;
112
+ };
@@ -77,6 +77,8 @@ export declare const COMMUNITY_LIMITS: {
77
77
  readonly chainPiece: 100;
78
78
  /** Admissions members other than the admin may commit in a row while the admin is away (`memberAdmissions`). */
79
79
  readonly memberAdmissions: 32;
80
+ /** Commits back in which a leave of a key a member let in counts against `memberAdmissions`, the admin there or not. */
81
+ readonly memberLeaves: 256;
80
82
  readonly pendingLeaves: 64;
81
83
  /** Leaves whose mark (`group-left`) is kept, and the epochs one names. */
82
84
  readonly leftMarks: 64;
@@ -110,6 +112,11 @@ export declare const COMMUNITY_LIMITS: {
110
112
  */
111
113
  readonly liveMarkMs: number;
112
114
  };
115
+ /**
116
+ * After the admin role moved to me: how long I still take the statement of the admin I took it from (WISP 903
117
+ * § Metadata), one that was on its way while the commit reached me first. Past it, condition 4 holds as for anyone.
118
+ */
119
+ export declare const COMMUNITY_TAKEOVER_META_MS: number;
113
120
  /** What every member should know about who can read what, and what the link does, in the words the apps show. */
114
121
  export declare const GROUP_READ_NOTE_COMMUNITY: string;
115
122
  /** A community group's link: `group2/<group id>/<entry key>` (web: `#/join/group2/…`). */
@@ -123,6 +130,19 @@ export declare function decodeCommunityLink(input: string): {
123
130
  host: string;
124
131
  } | null;
125
132
  export type CommunityKind = "create" | "add" | "leave" | "remove" | "role" | "rotate" | "link";
133
+ /**
134
+ * The admissions signed by members other than `admin` on a branch (`before`: its commits, newest first) since the admin
135
+ * last let someone in, rotated, changed the link or handed the role on, or since the group began. A removal or a leave
136
+ * the admin commits does not count as the admin being there: its app commits leaves by itself, and a removal while
137
+ * the admin clears keys let in would otherwise make room for as many more each time. An admission is a member's
138
+ * right, and costs nothing: a key nobody holds is as good as anyone's, so without a bound one member could fill the
139
+ * group to its cap in seconds. `COMMUNITY_LIMITS.memberAdmissions` in a row, then the admin's turn.
140
+ * A leave among the last `COMMUNITY_LIMITS.memberLeaves` commits that ends an admission a member other than the admin
141
+ * signed counts as one more, whether or not the admin was there since: the key leaves the roster as it was, and a
142
+ * member that lets in keys it made up and commits their own leaves would otherwise fill the history with two commits
143
+ * for each one the admin lets in at the door.
144
+ */
145
+ export declare function memberAdmissions(admin: string | undefined, before: Iterable<CommunityCommit>): number;
126
146
  export interface CommunityCommit {
127
147
  v: 2;
128
148
  g: string;
@@ -570,6 +590,13 @@ export declare class CommunitySession {
570
590
  private saveTimer;
571
591
  /** Metadata frames naming a commit or a secret I do not have yet, one signed by the admin and one by anyone else (`waitMeta`): tried again when the chain or my secrets move. */
572
592
  private pendingMeta;
593
+ /** The admin as of the last `metaFollowsChain`. In memory only. */
594
+ private adminSeen;
595
+ /**
596
+ * After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
597
+ * one of theirs I signed again (what I held then, until one of theirs comes). In memory only.
598
+ */
599
+ private takeover;
573
600
  /** The store's frames the app holds with their messages (`storeKey` → message id): in memory here, not in what is saved. */
574
601
  private readonly onRows;
575
602
  /** The oldest epoch whose seen marks are kept, as of the last `pruneSeen`. In memory only. */
@@ -1105,6 +1132,8 @@ export declare class CommunitySession {
1105
1132
  * Signs a body under my current commit, keeps it and sends it to everyone (hubs relay it). Inside `serialize`. Like a
1106
1133
  * commit, only with admin work on and a good turn read (WISP 06 § Forced takeover): refused otherwise, or, `quiet`,
1107
1134
  * not made. Its revision is never under the floor (WISP 06 § Raised counters).
1135
+ * `taken`: a former admin's statement signed again (`signAgainTaken`): the line credits them, and the one held is not
1136
+ * kept to hand on when it was no change (an older statement signed again).
1108
1137
  */
1109
1138
  private publishMeta;
1110
1139
  /** A statement sealed under my current epoch, when I hold its secret. */
@@ -1118,9 +1147,22 @@ export declare class CommunitySession {
1118
1147
  * A metadata statement (from its author's edge or a hub's): kept when it is newer than mine, its
1119
1148
  * commit is on my main branch, its signer was the admin after that commit and is the admin now,
1120
1149
  * its signature holds, and it opens under the epoch it names into metadata Ghostly shows. Returns
1121
- * whether it was new, so a hub relays it. One naming what I do not have yet waits for the chain.
1150
+ * whether it was new, so a hub relays it. One naming what I do not have yet waits for the chain. Just after the admin
1151
+ * role moved to me, the former admin's is signed again as mine (`takesOver`).
1122
1152
  */
1123
1153
  private receiveMeta;
1154
+ /**
1155
+ * Whether I take a statement though its signer is no longer the admin (WISP 903 § Metadata): I am the admin since
1156
+ * moments ago, they were the admin before me, and it is later than the one of theirs I signed again. A member who had
1157
+ * not synced when the role moved to them signed again what they held (or nothing), and the statement on its way would
1158
+ * be refused for good: a rename of theirs, or a member back from away, would then lose the group's call node.
1159
+ */
1160
+ private takesOver;
1161
+ /**
1162
+ * The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
1163
+ * value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
1164
+ */
1165
+ private signAgainTaken;
1124
1166
  /**
1125
1167
  * A statement that waits for the chain: only one its signer signed, so an altered copy cannot push out the one
1126
1168
  * waiting. The admin I know has a place of their own, which another member's statement cannot take, and in each
@@ -435,6 +435,11 @@ export interface GroupSessionHooks {
435
435
  */
436
436
  removed?(id: string): boolean;
437
437
  }
438
+ /**
439
+ * After the admin role moved to me: how long I still take the statement of the admin I took it from (WISP 902
440
+ * § Metadata), one that was on its way while the commit reached me first. Past it, only the admin's is taken, as for anyone.
441
+ */
442
+ export declare const GROUP_TAKEOVER_META_MS: number;
438
443
  export declare const groupMessageId: (sender: string, epoch: number, seq: number) => string;
439
444
  /**
440
445
  * A member's reaction as a hub passes it on: signed by the member (`k`), unlike `group-react`, which the edge it comes
@@ -504,6 +509,13 @@ export declare class GroupSession {
504
509
  private queue;
505
510
  /** Metadata frames that name a commit or an epoch I do not have yet, one signed by the admin and one by anyone else (`waitMeta`): tried again when the chain moves. */
506
511
  private pendingMeta;
512
+ /** The admin as of the last `metaFollowsChain`. In memory only. */
513
+ private adminSeen;
514
+ /**
515
+ * After the admin role moved to me (`metaFollowsChain`): whom from, until when I take their statement, and the last
516
+ * one of theirs I signed again (what I held then, until one of theirs comes). In memory only.
517
+ */
518
+ private takeover;
507
519
  /** While `handle` runs: the frames it took that a hub passes on (`handle`'s result). */
508
520
  private passOn;
509
521
  /** The frames kept to hand on that the app holds with its messages, oldest first; undefined when the state holds them all. */
@@ -1024,6 +1036,8 @@ export declare class GroupSession {
1024
1036
  /**
1025
1037
  * Signs a body under my current commit, keeps it and sends it to every member. Inside `serialize`. Like a commit, only
1026
1038
  * with admin work on and a good turn read (WISP 06 § Forced takeover): refused otherwise, or, `quiet`, not made.
1039
+ * `taken`: a former admin's statement signed again (`signAgainTaken`): the line credits them, and the one held is not
1040
+ * kept to hand on when it was no change (an older statement signed again).
1027
1041
  */
1028
1042
  private publishMeta;
1029
1043
  /** My statement, to a member whose sync says it holds an older one (or none); nothing to an app that says nothing. */
@@ -1033,9 +1047,22 @@ export declare class GroupSession {
1033
1047
  /**
1034
1048
  * A metadata statement: kept when it is newer than mine, its commit is on my chain, its signer was
1035
1049
  * the admin of that commit and is the admin now, its signature holds, and it opens under the epoch
1036
- * it names into metadata Ghostly shows. One naming what I do not have yet waits for the chain.
1050
+ * it names into metadata Ghostly shows. One naming what I do not have yet waits for the chain. Just after the admin
1051
+ * role moved to me, the former admin's is signed again as mine (`takesOver`).
1037
1052
  */
1038
1053
  private receiveMeta;
1054
+ /**
1055
+ * Whether I take a statement though its signer is no longer the admin (WISP 902 § Metadata): I am the admin since
1056
+ * moments ago, they were the admin before me, and it is later than the one of theirs I signed again. A member who had
1057
+ * not synced when the role moved to them signed again what they held (or nothing), and the statement on its way would
1058
+ * be refused for good: their next rename, picture or hubs change would then be built on the older body.
1059
+ */
1060
+ private takesOver;
1061
+ /**
1062
+ * The former admin's statement, taken (`takesOver`): signed again as mine, each field I changed since keeping my
1063
+ * value. Dated as theirs, and credited to them, when I changed nothing; what I held was then no change to hand on.
1064
+ */
1065
+ private signAgainTaken;
1039
1066
  /**
1040
1067
  * A statement that waits for the chain: only one its signer signed, so an altered copy cannot push out the one
1041
1068
  * waiting. The admin I know has a place of their own, which another member's statement cannot take, and in each
@@ -63,7 +63,8 @@ export declare function viewerServicePolicy(relayOnly: boolean): string;
63
63
  * The browser features a contact's app in the extension's viewer tab may not use. Its tab is a site of its own, so
64
64
  * what the person granted it (camera, microphone, location, a device) would be a site setting of the browser's, which
65
65
  * no Delete chat, Clear all data or Delete profile reaches; denied here, the browser never asks and ignores a grant
66
- * made before. The web app's view is a frame of another site, which gets none of them, and Desktop's window grants none.
66
+ * made before. The web app's view is a frame of another site, which gets none of them, and Desktop's window grants none
67
+ * and is served the same value (`PERMISSIONS_POLICY` in `apps/desktop/src/viewer.rs`).
67
68
  */
68
69
  export declare const VIEWER_PERMISSIONS_POLICY: string;
69
70
  /**
@@ -389,6 +389,8 @@ export declare class RelayTransport implements PkarrTransport {
389
389
  private readonly lastPut;
390
390
  /** Per relay and key, the newest packet that relay held back for its budget while another relay took it (`catchUpLater`). */
391
391
  private readonly catchUp;
392
+ /** Per relay, how many packets wait in `catchUp` for it: background reads leave them their share (`heldFor`). */
393
+ private readonly catchUpWaiting;
392
394
  private catchUpTimer;
393
395
  /**
394
396
  * Per key whose reads the budget held back since its last read went out: when a request frees for it
@@ -583,11 +585,14 @@ export declare class RelayTransport implements PkarrTransport {
583
585
  /**
584
586
  * A relay whose budget (this client's, or its own rate limit) held a packet back that another relay took: it gets
585
587
  * that packet when it frees a request, as a background write (`who`: a group edge's offer or answer as its own, also
586
- * after that relay failed it). Only the newest per key and relay; a newer packet put everywhere drops it. Without this,
588
+ * after that relay failed it). Only the newest per key and relay, until that relay takes this packet or a newer one (one
589
+ * the budget holds there takes its place). Without this,
587
590
  * that relay kept the key's older packet for good, and an app that restarted and read it first found a contact's offer
588
591
  * long answered, answered it again, and waited on it (bug hunt r7a).
589
592
  */
590
593
  private catchUpLater;
594
+ private keepCatchUp;
595
+ private dropCatchUp;
591
596
  private scheduleCatchUp;
592
597
  private runCatchUp;
593
598
  /** `sent`: told, once the budget took the request, whether the relay takes the packet (a 2xx). */
@@ -643,6 +648,14 @@ export declare class RelayTransport implements PkarrTransport {
643
648
  * waiting for the chats held every chat's read back (CLI lab, 2026-10-13).
644
649
  */
645
650
  private turnAhead;
651
+ /**
652
+ * How long until a background read of `key` the budget held back is likely to have its turn: the background reads of
653
+ * keys ahead of it in turn (read longer ago, still asking; `turnAhead`), one after the other at the relays' background
654
+ * share. Told only when the budget frees the next request, every held key asked again then, and lost it to the key
655
+ * whose turn it was: a daemon whose 50 contacts were away asked about 600 times a minute for some 50 reads, and one
656
+ * with 200 three times as often after four hours as after 15 minutes (bug hunts, 2026-11-06 and 2026-11-14).
657
+ */
658
+ private backgroundTurnIn;
646
659
  /** A 1:1 chat's read of `key` the budget has held back for `READ_STARVED_MS` without a break. */
647
660
  private starved;
648
661
  /** This key's departed reads past the limit in the last minute (`DEPARTED_READS`). */