@ghostlytools/sdk 1.11.4 → 1.12.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.
Files changed (45) hide show
  1. package/dist/app.js +1 -2
  2. package/dist/bitcoinAddress-C2MAmcDT.js +1225 -0
  3. package/dist/bitcoinAddress-C2MAmcDT.js.map +1 -0
  4. package/dist/bolt11-CRiQrma3.js +266 -0
  5. package/dist/bolt11-CRiQrma3.js.map +1 -0
  6. package/dist/core.js +41538 -336
  7. package/dist/core.js.map +1 -1
  8. package/dist/{fakes-CXeeyI4Z.js → fakes-Cgl1w4Nv.js} +6 -9
  9. package/dist/{fakes-CXeeyI4Z.js.map → fakes-Cgl1w4Nv.js.map} +1 -1
  10. package/dist/fakes.js +1 -2
  11. package/dist/index.js +8 -9
  12. package/dist/index.js.map +1 -1
  13. package/dist/{keet-identity-key-DLXTTFZH.js → keet-identity-key-LuoCuz1t.js} +648 -324
  14. package/dist/keet-identity-key-LuoCuz1t.js.map +1 -0
  15. package/dist/pairedTransports-CkYMAoYN.js +1149 -0
  16. package/dist/pairedTransports-CkYMAoYN.js.map +1 -0
  17. package/dist/rolldown-runtime-DpEnGzO4.js +45 -0
  18. package/dist/testing.js +7 -8
  19. package/dist/testing.js.map +1 -1
  20. package/dist/types/browser/src/shared/mints.d.ts +3 -1
  21. package/dist/types/core/src/chatFiles.d.ts +3 -1
  22. package/dist/types/core/src/communityRendezvous.d.ts +4 -0
  23. package/dist/types/core/src/dhtDelivery.d.ts +9 -0
  24. package/dist/types/core/src/engineErrors.d.ts +7 -0
  25. package/dist/types/core/src/ghostlink.d.ts +12 -0
  26. package/dist/types/core/src/groupCalls.d.ts +56 -0
  27. package/dist/types/core/src/groupCommunity.d.ts +16 -0
  28. package/dist/types/core/src/groupCrypto.d.ts +6 -0
  29. package/dist/types/core/src/groupMeta.d.ts +22 -0
  30. package/dist/types/core/src/groupSession.d.ts +14 -1
  31. package/dist/types/core/src/handoff.d.ts +0 -2
  32. package/dist/types/core/src/index.d.ts +1 -0
  33. package/dist/types/core/src/pairedTransports.d.ts +5 -0
  34. package/dist/types/core/src/relayBreaker.d.ts +5 -1
  35. package/dist/types/core/src/services.d.ts +6 -0
  36. package/dist/types/core/src/text.d.ts +2 -0
  37. package/dist/types/core/src/transport.d.ts +1 -1
  38. package/dist/{types-DYLIIkU8.js → types-DbgC491n.js} +2 -3
  39. package/dist/{types-DYLIIkU8.js.map → types-DbgC491n.js.map} +1 -1
  40. package/dist/{verify-B9s82dbd.js → verify-CSo7-43-.js} +3 -4
  41. package/dist/{verify-B9s82dbd.js.map → verify-CSo7-43-.js.map} +1 -1
  42. package/package.json +3 -3
  43. package/dist/keet-identity-key-DLXTTFZH.js.map +0 -1
  44. package/dist/src-CqAqFhh9.js +0 -43635
  45. package/dist/src-CqAqFhh9.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { Pa as decodeBolt11, SE as toBase64Url, TE as utf8Encode, _E as fromBase64Url, wE as utf8Decode } from "./src-CqAqFhh9.js";
2
- import { t as NothingSpentError } from "./types-DYLIIkU8.js";
1
+ import { f as toBase64Url, h as utf8Encode, m as utf8Decode, n as decodeBolt11, s as fromBase64Url } from "./bolt11-CRiQrma3.js";
2
+ import { t as NothingSpentError } from "./types-DbgC491n.js";
3
3
  import { ed25519 } from "@noble/curves/ed25519.js";
4
4
  import { sha256 } from "@noble/hashes/sha2.js";
5
5
  import { bech32 } from "@scure/base";
6
- //#region ../browser/src/shared/features.ts
6
+ // ../browser/src/shared/features.ts
7
7
  /**
8
8
  * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the
9
9
  * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is
@@ -17,8 +17,7 @@ var testBuild = () => {
17
17
  return false;
18
18
  }
19
19
  };
20
- //#endregion
21
- //#region ../browser/src/engine/paymentAdapters/providers/testing.ts
20
+ // ../browser/src/engine/paymentAdapters/providers/testing.ts
22
21
  var TEST_PROVIDERS_FLAG = "ghostly-test-providers";
23
22
  var hex$1 = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
24
23
  var random = (n) => crypto.getRandomValues(new Uint8Array(n));
@@ -296,8 +295,7 @@ function testProvidersEnabled() {
296
295
  return false;
297
296
  }
298
297
  }
299
- //#endregion
300
- //#region ../browser/src/proofs/testing.ts
298
+ // ../browser/src/proofs/testing.ts
301
299
  /**
302
300
  * Fake identity providers, for unit tests and e2e. No network, no real accounts. They are in the
303
301
  * registry only in a dev or e2e build (`testBuild`) that has `localStorage["ghostly-test-identities"] === "1"`
@@ -534,7 +532,6 @@ var FAKE_IDENTITY_PROVIDERS = [
534
532
  fakeAccount,
535
533
  fakeRecord
536
534
  ];
537
- //#endregion
538
535
  export { fakeAddress as _, fakeAccount as a, fakeOnchain as b, fakeKeySign as c, fakeRecord as d, fakeRecordText as f, TEST_PROVIDERS_FLAG as g, FakeOnchainProvider as h, TEST_IDENTITIES_FLAG as i, fakeKeySubject as l, FakeLightningProvider as m, FAKE_ISSUER as n, fakeAccountToken as o, testIdentitiesEnabled as p, FAKE_RECORD_HOST as r, fakeKey as s, FAKE_IDENTITY_PROVIDERS as t, fakeKeyring as u, fakeInvoice as v, testProvidersEnabled as x, fakeLightning as y };
539
536
 
540
- //# sourceMappingURL=fakes-CXeeyI4Z.js.map
537
+ //# sourceMappingURL=fakes-Cgl1w4Nv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"fakes-CXeeyI4Z.js","names":["hex"],"sources":["../../browser/src/shared/features.ts","../../browser/src/engine/paymentAdapters/providers/testing.ts","../../browser/src/proofs/testing.ts"],"sourcesContent":["/** Release policy: external identity experiments are retained for future work,\n * but must not advertise capabilities, start network lookups, or expose cached\n * external profiles. This does not gate Ghostly participation authentication. */\nexport const EXTERNAL_IDENTITIES_ENABLED: boolean = false;\n\n/** Mini-apps (WISP 1200): `apps/1` on paired sessions and the engine's `app*` calls. On from release 1.2 (a version\n * before 1.2.0 is never cut with it on: `RELEASE_GUARDS` in tools/scripts/changes.mjs). Off, nothing is offered to\n * contacts and every call is refused; a host that runs no apps pins its engine off (`NodeOptions.apps`). */\nexport const APPS_ENABLED: boolean = true;\n\n/**\n * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the\n * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is\n * neither: Vite folds this to `false` there, so the storage flags the test fakes answer to are ignored. The fakes\n * themselves are still in the bundle (the registries import them); plugins may still pass fakes to the registry.\n */\nexport const testBuild = (): boolean => { try { return !!import.meta.env?.DEV || import.meta.env?.VITE_APPS_TEST === \"1\"; } catch { return false; } };\n\n/**\n * A suite's switch in the page's storage (`localStorage[\"ghostly-test-…\"]`), read only in a test build (`testBuild`): a\n * release build reads none, so a leftover or pasted key changes nothing there. Null when unset, unreadable or released.\n */\nexport const testSwitch = (key: string): string | null => {\n if (!testBuild()) return null;\n try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; }\n};\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32 } from \"@scure/base\";\nimport { decodeBolt11 } from \"@ghostly/core\";\nimport type { InvoiceStatus, LightningInvoice, LightningPayResult, LightningPaymentRef, LightningPaymentStatus, LightningProvider, LightningProviderDescriptor } from \"./lightning\";\nimport type { OnchainBalance, OnchainPrepared, OnchainProvider, OnchainProviderDescriptor, OnchainSendRequest, OnchainTx, OnchainTxStatus } from \"./onchain\";\nimport { NothingSpentError, type ProviderField, type ProviderSettings } from \"./types\";\nimport { testBuild } from \"../../../shared/features\";\n\n/**\n * Fake providers, for unit tests and e2e: they hold regtest \"sats\" in memory, so they only ever show up in\n * the Testnet mode, and only in a dev or e2e build (`testBuild`) that has `localStorage[\"ghostly-test-providers\"]\n * === \"1\"` (or a test passes them to the registry itself); a release build ignores the key. No network, no money.\n *\n * `behaviour` drives the outcome of a spend:\n * - settle: invoices are paid by themselves after `settleMs`; payments and broadcasts succeed.\n * - refuse: a spend fails, provably before anything left (`NothingSpentError`).\n * - hang: a spend throws an unknown error, and the lookup later says it went through (a lost answer).\n */\nexport type FakeBehaviour = \"settle\" | \"refuse\" | \"hang\";\nexport const TEST_PROVIDERS_FLAG = \"ghostly-test-providers\";\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst random = (n: number) => crypto.getRandomValues(new Uint8Array(n));\nconst uint = (value: number, length = 1) => {\n const out: number[] = [];\n for (let v = value; v > 0; v = Math.floor(v / 32)) out.unshift(v % 32);\n while (out.length < length) out.unshift(0);\n return out;\n};\n\n/** A BOLT 11 invoice on regtest with a real checksum and a blank signature: it decodes, nobody can pay it. */\nexport function fakeInvoice(amount: number, paymentHash: Uint8Array, memo = \"\", expirySeconds = 3600): string {\n const words = uint(Math.floor(Date.now() / 1000), 7);\n const field = (tag: number, data: number[]) => words.push(tag, data.length >> 5, data.length & 31, ...data);\n field(1, bech32.toWords(paymentHash));\n if (memo) field(13, bech32.toWords(new TextEncoder().encode(memo.slice(0, 100))));\n field(6, uint(expirySeconds));\n return bech32.encode(`lnbcrt${amount * 10}n`, [...words, ...new Array<number>(104).fill(0)], false);\n}\n\n/** A valid regtest P2WPKH address of nobody's. */\nexport const fakeAddress = () => bech32.encode(\"bcrt\", [0, ...bech32.toWords(random(20))]);\n\nconst FIELDS: ProviderField[] = [\n { name: \"alias\", label: \"Name\", kind: \"text\", optional: true, placeholder: \"Fake node\" },\n { name: \"token\", label: \"Access token\", kind: \"secret\", placeholder: \"anything\", help: \"Sealed like a real provider's secret; the fake only checks it is there.\" },\n { name: \"behaviour\", label: \"Spends\", kind: \"select\", optional: true, options: [{ value: \"settle\", label: \"Go through\" }, { value: \"refuse\", label: \"Are refused\" }, { value: \"hang\", label: \"Lose their answer\" }], defaults: { testnet: \"settle\" } },\n];\nconst validate = ({ secrets, config }: ProviderSettings) => {\n if (!secrets.token?.trim()) throw new Error(\"Enter an access token\");\n if (config.behaviour && ![\"settle\", \"refuse\", \"hang\"].includes(config.behaviour)) throw new Error(\"Unknown behaviour\");\n};\n\ninterface FakeOptions { alias?: string; behaviour?: FakeBehaviour; balance?: number; settleMs?: number; token?: string }\n\nexport class FakeLightningProvider implements LightningProvider {\n readonly capabilities = { receive: true, send: true, balance: true, lookup: true };\n readonly invoices = new Map<string, { invoice: LightningInvoice; paid: boolean }>();\n readonly payments = new Map<string, LightningPaymentStatus>();\n readonly paid: string[] = [];\n balance: number;\n behaviour: FakeBehaviour;\n closed = false;\n private timers: ReturnType<typeof setTimeout>[] = [];\n constructor(readonly options: FakeOptions = {}) { this.balance = options.balance ?? 100_000; this.behaviour = options.behaviour ?? \"settle\"; }\n async info() { return { network: \"regtest\" as const, alias: this.options.alias || \"Fake Lightning\", balance: this.balance }; }\n async createInvoice(amount: number, memo?: string): Promise<LightningInvoice> {\n const preimage = random(32), hash = sha256(preimage);\n const invoice: LightningInvoice = { invoice: fakeInvoice(amount, hash, memo), paymentHash: hex(hash), amount, expiresAt: Date.now() + 3600_000, ref: hex(preimage) };\n this.invoices.set(invoice.paymentHash, { invoice, paid: false });\n if (this.behaviour === \"settle\") this.timers.push(setTimeout(() => this.markPaid(invoice.paymentHash), this.options.settleMs ?? 1500));\n return invoice;\n }\n /** Someone paid this invoice. */\n markPaid(paymentHash: string) {\n const entry = this.invoices.get(paymentHash);\n if (!entry || entry.paid || this.closed) return;\n entry.paid = true; this.balance += entry.invoice.amount;\n }\n async invoiceStatus(invoice: LightningInvoice): Promise<InvoiceStatus> {\n const entry = this.invoices.get(invoice.paymentHash);\n if (entry?.paid) return { state: \"paid\", amount: entry.invoice.amount };\n return { state: invoice.expiresAt < Date.now() ? \"expired\" : \"open\" };\n }\n async estimateFee(_invoice: string, amount: number) { return Math.max(1, Math.ceil(amount / 100)); }\n async payInvoice(invoice: string, maxFee: number): Promise<LightningPayResult> {\n const decoded = decodeBolt11(invoice);\n if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError(\"Not an invoice this fake can pay\");\n const fee = Math.min(maxFee, Math.max(1, Math.ceil(decoded.amountSat / 100)));\n if (this.behaviour === \"refuse\") throw new NothingSpentError(\"No route (fake)\");\n if (this.balance < decoded.amountSat + fee) throw new NothingSpentError(\"Not enough sats in the fake wallet\");\n this.balance -= decoded.amountSat + fee;\n this.paid.push(decoded.paymentHash);\n this.payments.set(decoded.paymentHash, { state: \"paid\", fee, preimage: hex(random(32)) });\n if (this.behaviour === \"hang\") throw new Error(\"Connection lost (fake)\");\n return { state: \"paid\", fee, preimage: this.payments.get(decoded.paymentHash)!.preimage };\n }\n async paymentStatus(payment: LightningPaymentRef): Promise<LightningPaymentStatus> {\n return this.payments.get(payment.paymentHash) ?? { state: \"failed\" };\n }\n async close() { this.closed = true; for (const t of this.timers) clearTimeout(t); }\n}\n\nexport class FakeOnchainProvider implements OnchainProvider {\n readonly addresses: string[] = [];\n readonly broadcasts: string[] = [];\n readonly released: string[] = [];\n readonly txs = new Map<string, { prepared: OnchainPrepared; confirmations: number }>();\n confirmed: number;\n behaviour: FakeBehaviour;\n closed = false;\n constructor(readonly options: FakeOptions = {}) { this.confirmed = options.balance ?? 100_000; this.behaviour = options.behaviour ?? \"settle\"; }\n async info() { return { network: \"regtest\" as const, alias: this.options.alias || \"Fake Bitcoin wallet\" }; }\n async receiveAddress() { const address = fakeAddress(); this.addresses.push(address); return address; }\n async balance(): Promise<OnchainBalance> { return { confirmed: this.confirmed, unconfirmed: 0 }; }\n async prepareSend(request: OnchainSendRequest): Promise<OnchainPrepared> {\n const feeRate = request.feeRate ?? 2, fee = feeRate * 141;\n if (fee > request.feeCap) throw new Error(`The fee (${fee} sats) is above your limit`);\n if (this.confirmed < request.amount + fee) throw new Error(\"Not enough confirmed sats\");\n return { txid: hex(random(32)), address: request.address, amount: request.amount, fee, feeRate, signed: hex(random(64)) };\n }\n async broadcast(prepared: OnchainPrepared) {\n if (this.behaviour === \"refuse\") throw new NothingSpentError(\"Rejected by the node (fake)\");\n if (!this.txs.has(prepared.txid)) { this.confirmed -= prepared.amount + prepared.fee; this.txs.set(prepared.txid, { prepared, confirmations: 1 }); }\n this.broadcasts.push(prepared.txid);\n if (this.behaviour === \"hang\") throw new Error(\"Connection lost (fake)\");\n return prepared.txid;\n }\n async status(prepared: OnchainPrepared): Promise<OnchainTxStatus> {\n const tx = this.txs.get(prepared.txid);\n return tx ? { state: \"confirmed\", confirmations: tx.confirmations } : { state: \"missing\", confirmations: 0 };\n }\n async release(prepared: OnchainPrepared) { this.released.push(prepared.txid); }\n async history(limit: number): Promise<OnchainTx[]> {\n return [...this.txs.values()].reverse().slice(0, limit).map(({ prepared, confirmations }) => ({ txid: prepared.txid, amount: -prepared.amount, fee: prepared.fee, confirmations }));\n }\n async close() { this.closed = true; }\n}\n\nconst options = ({ config, secrets }: ProviderSettings): FakeOptions => ({ alias: config.alias, behaviour: (config.behaviour as FakeBehaviour) || \"settle\", token: secrets.token });\n\nexport const fakeLightning: LightningProviderDescriptor = {\n id: \"fake-lightning\",\n label: \"Fake Lightning (test)\",\n kind: \"lightning\",\n description: \"In-memory regtest node for tests. Holds nothing.\",\n networks: [\"regtest\"],\n platforms: [\"web\", \"desktop\"],\n fields: FIELDS,\n experimental: true,\n validate,\n async create(settings) { return new FakeLightningProvider(options(settings)); },\n};\n\nexport const fakeOnchain: OnchainProviderDescriptor = {\n id: \"fake-onchain\",\n label: \"Fake Bitcoin wallet (test)\",\n kind: \"onchain\",\n description: \"In-memory regtest wallet for tests. Holds nothing.\",\n networks: [\"regtest\"],\n platforms: [\"web\", \"desktop\"],\n fields: FIELDS,\n experimental: true,\n validate,\n async create(settings) { return new FakeOnchainProvider(options(settings)); },\n};\n\n/** Whether this browser asked for the fake providers (an e2e run sets it before the app starts). */\nexport function testProvidersEnabled(): boolean {\n try { return testBuild() && globalThis.localStorage?.getItem(TEST_PROVIDERS_FLAG) === \"1\"; } catch { return false; }\n}\n","import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { fromBase64Url, toBase64Url, utf8Decode, utf8Encode, type IdentityStatement } from \"@ghostly/core\";\nimport { testBuild } from \"../shared/features\";\nimport type { IdentityProofProvider } from \"./contract\";\n\n/**\n * Fake identity providers, for unit tests and e2e. No network, no real accounts. They are in the\n * registry only in a dev or e2e build (`testBuild`) that has `localStorage[\"ghostly-test-identities\"] === \"1\"`\n * (or a test passes them itself); a release build ignores the key.\n *\n * - fake-key self-custodied: an Ed25519 key held by a fake in-app signer, or signed \"outside\" and pasted.\n * - fake-account provider-attested: a fake issuer signs a token whose nonce is the statement id (like OIDC).\n * - fake-record self-custodied, published: a record the verifier fetches through `ctx.fetch` (like DNS).\n */\nexport const TEST_IDENTITIES_FLAG = \"ghostly-test-identities\";\nexport const testIdentitiesEnabled = () => { try { return testBuild() && globalThis.localStorage?.getItem(TEST_IDENTITIES_FLAG) === \"1\"; } catch { return false; } };\n\nconst HEX64 = /^[a-f0-9]{64}$/;\nconst hex = (b: Uint8Array) => Array.from(b, x => x.toString(16).padStart(2, \"0\")).join(\"\");\nconst unhex = (s: string) => Uint8Array.from(s.match(/../g)!, x => parseInt(x, 16));\nconst normalizeHexKey = (input: string) => { const v = input.trim().toLowerCase(); if (!HEX64.test(v)) throw new Error(\"Enter 64 hex characters\"); return v; };\nconst exactKeys = (raw: unknown, keys: string) => !!raw && typeof raw === \"object\" && !Array.isArray(raw) && Object.keys(raw).sort().join(\",\") === keys;\n\n/** The key behind the fake in-app signer, made on first use so a release start draws no key. Tests may replace it. */\nlet fakeSeed: Uint8Array | undefined;\nexport const fakeKeyring = { get seed() { return fakeSeed ??= ed25519.utils.randomSecretKey(); }, set seed(value: Uint8Array) { fakeSeed = value; } };\nexport const fakeKeySubject = (seed = fakeKeyring.seed) => hex(ed25519.getPublicKey(seed));\nexport const fakeKeySign = (statement: IdentityStatement, seed = fakeKeyring.seed) => ({ sig: toBase64Url(ed25519.sign(statement.bytes, seed)) });\n\nexport interface FakeKeyEvidence { sig: string }\nexport const fakeKey: IdentityProofProvider<FakeKeyEvidence> = {\n id: \"fake-key\", label: \"Test key\", category: \"self-custodied\",\n summary: \"Sign with the test key\", description: \"A test identity: an Ed25519 key held by this page. For tests only.\",\n platforms: [\"web\", \"desktop\"],\n subject: { label: \"Public key\", placeholder: \"64 hex characters\", normalize: normalizeHexKey, short: k => `${k.slice(0, 8)}…${k.slice(-4)}` },\n publicUri: k => `urn:ghostly-test:${k}`,\n validity: { defaultDays: 30, maxDays: 365 },\n privacy: \"Nothing: checked on this device.\",\n signers: [\n { id: \"fake-signer\", kind: \"in-app\", label: \"Test signer\", fields: [{ name: \"refuse\", label: \"Refuse\", kind: \"text\", optional: true }],\n run: async (ctx, work) => {\n ctx.signal.throwIfAborted();\n if (ctx.values.refuse) throw new Error(\"The test signer refused\");\n return work({ subject: async () => fakeKeySubject(), sign: async statement => fakeKeySign(statement) });\n } },\n { id: \"fake-tool\", kind: \"external-tool\", label: \"Sign outside Ghostly\",\n instructions: statement => ({ steps: [{ text: \"Sign this statement with your test key:\", copy: statement.text }], paste: { label: \"Signature (base64url)\" } }),\n parse: pasted => { const sig = pasted.trim(); if (!/^[A-Za-z0-9_-]{86}$/.test(sig)) throw new Error(\"That is not a test signature\"); return { sig }; } },\n ],\n parseEvidence(raw) {\n const e = raw as FakeKeyEvidence;\n if (!exactKeys(raw, \"sig\") || typeof e.sig !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(e.sig)) throw new Error(\"Invalid test evidence\");\n return { sig: e.sig };\n },\n async verify(statement, evidence) {\n let ok: boolean;\n try { ok = ed25519.verify(fromBase64Url(evidence.sig), statement.bytes, unhex(statement.binding.subject)); } catch { ok = false; }\n if (!ok) throw new Error(\"Invalid test signature\");\n return { subject: statement.binding.subject, source: \"Test signature (Ed25519)\" };\n },\n};\n\n/** The fake issuer's key. Its public half is what fake-account trusts, like a provider's JWKS. */\nconst ISSUER_SEED = unhex(\"7a\".repeat(32));\nexport const FAKE_ISSUER = \"https://issuer.ghostly.test\";\nexport interface FakeAccountEvidence { token: string }\n/** What the fake login page signs: iss, sub, nonce (= statement id), iat. */\nexport function fakeAccountToken(statement: IdentityStatement, account = \"alice\", seed = ISSUER_SEED, iat = statement.binding.issuedAt): FakeAccountEvidence {\n const payload = toBase64Url(utf8Encode(JSON.stringify({ iss: FAKE_ISSUER, sub: account, nonce: statement.id, iat })));\n return { token: `${payload}.${toBase64Url(ed25519.sign(utf8Encode(payload), seed))}` };\n}\nexport const fakeAccount: IdentityProofProvider<FakeAccountEvidence> = {\n id: \"fake-account\", label: \"Test account\", category: \"provider-attested\",\n summary: \"Log in to the test issuer\", description: \"A test login provider that vouches for an account. For tests only.\",\n platforms: [\"web\", \"desktop\"],\n subject: { label: \"Provider\", options: [{ value: FAKE_ISSUER, label: \"Test issuer\" }],\n normalize: input => { if (input.trim() !== FAKE_ISSUER) throw new Error(\"Unknown test issuer\"); return FAKE_ISSUER; } },\n validity: { defaultDays: 30, maxDays: 90 },\n privacy: \"Nothing: the issuer's signature is checked on this device.\",\n signers: [{ id: \"fake-login\", kind: \"redirect\", label: \"Log in to the test issuer\",\n start: async (statement, ctx) => { ctx.signal.throwIfAborted(); return fakeAccountToken(statement, ctx.values.account || \"alice\"); } }],\n parseEvidence(raw) {\n const e = raw as FakeAccountEvidence;\n if (!exactKeys(raw, \"token\") || typeof e.token !== \"string\" || e.token.length > 2048 || !/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{86}$/.test(e.token)) throw new Error(\"Invalid test token\");\n return { token: e.token };\n },\n async verify(statement, { token }) {\n const [payload, sig] = token.split(\".\");\n if (!ed25519.verify(fromBase64Url(sig), utf8Encode(payload), ed25519.getPublicKey(ISSUER_SEED))) throw new Error(\"Not signed by the test issuer\");\n const claims = JSON.parse(utf8Decode(fromBase64Url(payload))) as { iss: string; sub: string; nonce: string };\n if (claims.iss !== statement.binding.subject) throw new Error(\"Token from another issuer\");\n if (claims.nonce !== statement.id) throw new Error(\"Token for another statement\");\n if (typeof claims.sub !== \"string\" || !/^[a-z0-9]{1,64}$/.test(claims.sub)) throw new Error(\"Invalid account\");\n return { subject: `${claims.iss}#${claims.sub}`, attester: \"issuer.ghostly.test\", source: \"Token signed by the test issuer\",\n display: { name: claims.sub, source: \"Test issuer profile\", fetchedAt: statement.binding.issuedAt } };\n },\n};\n\n/** fake-record's records: subject → published text. The verifier reads `https://records.ghostly.test/<subject>`. */\nexport const FAKE_RECORD_HOST = \"https://records.ghostly.test/\";\nexport const fakeRecordText = (statement: IdentityStatement) => `ghostly-proof=${statement.id}`;\nexport const fakeRecord: IdentityProofProvider<Record<string, never>> = {\n id: \"fake-record\", label: \"Test record\", category: \"self-custodied\",\n summary: \"Publish a test record\", description: \"A test record published where the verifier looks it up, like DNS. For tests only.\",\n platforms: [\"web\", \"desktop\"],\n subject: { label: \"Name\", placeholder: \"alice\", normalize: input => { const v = input.trim().toLowerCase(); if (!/^[a-z0-9-]{1,63}$/.test(v)) throw new Error(\"Letters, digits and dashes\"); return v; } },\n validity: { defaultDays: 30, maxDays: 365 },\n recheck: { afterSeconds: 3600 },\n privacy: \"The verifier asks records.ghostly.test for the record: that server learns the name was checked.\",\n signers: [{ id: \"fake-publish\", kind: \"publish\", label: \"Publish a record\",\n instructions: statement => ({ steps: [{ text: `Publish this record for ${statement.binding.subject}:`, copy: fakeRecordText(statement) }] }),\n evidence: () => ({}) }],\n parseEvidence(raw) { if (!exactKeys(raw, \"\")) throw new Error(\"Invalid test evidence\"); return {}; },\n async verify(statement, _evidence, ctx) {\n const response = await ctx.fetch(`${FAKE_RECORD_HOST}${statement.binding.subject}`, { maxBytes: 4096, signal: ctx.signal });\n if (response.status !== 200 || !response.text.split(\"\\n\").includes(fakeRecordText(statement))) throw new Error(\"The record is not published\");\n return { subject: statement.binding.subject, source: \"Record published at records.ghostly.test\" };\n },\n};\n\nexport const FAKE_IDENTITY_PROVIDERS: readonly IdentityProofProvider[] = [fakeKey, fakeAccount, fakeRecord];\n"],"mappings":";;;;;;;;;;;;AAgBA,IAAa,kBAA2B;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ACnD,SAAS;CAAyB,aAAa;CAC/C,WAAW,CAAC,OAAO,SAAS;CAC5B,SAAS;EAAE,OAAO;EAAQ,aAAa;EAAS,YAAW,UAAS;GAAE,MAAM,IAAI,MAAM,KAAK,CAAC,CAAC,YAAY;GAAG,IAAI,CAAC,oBAAoB,KAAK,CAAC,GAAG,MAAM,IAAI,MAAM,4BAA4B;GAAG,OAAO;EAAG;CAAE;CACzM,UAAU;EAAE,aAAa;EAAI,SAAS;CAAI;CAC1C,SAAS,EAAE,cAAc,KAAK;CAC9B,SAAS;CACT,SAAS,CAAC;EAAE,IAAI;EAAgB,MAAM;EAAW,OAAO;EACtD,eAAc,eAAc,EAAE,OAAO,CAAC;GAAE,MAAM,2BAA2B,UAAU,QAAQ,QAAQ;GAAI,MAAM,eAAe,SAAS;EAAE,CAAC,EAAE;EAC1I,iBAAiB,CAAC;CAAG,CAAC;CACxB,cAAc,KAAK;EAAE,IAAI,CAAC,UAAU,KAAK,EAAE,GAAG,MAAM,IAAI,MAAM,uBAAuB;EAAG,OAAO,CAAC;CAAG;CACnG,MAAM,OAAO,WAAW,WAAW,KAAK;EACtC,MAAM,WAAW,MAAM,IAAI,MAAM,GAAG,mBAAmB,UAAU,QAAQ,WAAW;GAAE,UAAU;GAAM,QAAQ,IAAI;EAAO,CAAC;EAC1H,IAAI,SAAS,WAAW,OAAO,CAAC,SAAS,KAAK,MAAM,IAAI,CAAC,CAAC,SAAS,eAAe,SAAS,CAAC,GAAG,MAAM,IAAI,MAAM,6BAA6B;EAC5I,OAAO;GAAE,SAAS,UAAU,QAAQ;GAAS,QAAQ;EAA2C;CAClG;AACF;AAEA,IAAa,0BAA4D;CAAC;CAAS;CAAa;AAAU"}
1
+ {"version":3,"file":"fakes-Cgl1w4Nv.js","names":["hex"],"sources":["../../browser/src/shared/features.ts","../../browser/src/engine/paymentAdapters/providers/testing.ts","../../browser/src/proofs/testing.ts"],"sourcesContent":["/** Release policy: external identity experiments are retained for future work,\n * but must not advertise capabilities, start network lookups, or expose cached\n * external profiles. This does not gate Ghostly participation authentication. */\nexport const EXTERNAL_IDENTITIES_ENABLED: boolean = false;\n\n/** Mini-apps (WISP 1200): `apps/1` on paired sessions and the engine's `app*` calls. On from release 1.2 (a version\n * before 1.2.0 is never cut with it on: `RELEASE_GUARDS` in tools/scripts/changes.mjs). Off, nothing is offered to\n * contacts and every call is refused; a host that runs no apps pins its engine off (`NodeOptions.apps`). */\nexport const APPS_ENABLED: boolean = true;\n\n/**\n * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the\n * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is\n * neither: Vite folds this to `false` there, so the storage flags the test fakes answer to are ignored. The fakes\n * themselves are still in the bundle (the registries import them); plugins may still pass fakes to the registry.\n */\nexport const testBuild = (): boolean => { try { return !!import.meta.env?.DEV || import.meta.env?.VITE_APPS_TEST === \"1\"; } catch { return false; } };\n\n/**\n * A suite's switch in the page's storage (`localStorage[\"ghostly-test-…\"]`), read only in a test build (`testBuild`): a\n * release build reads none, so a leftover or pasted key changes nothing there. Null when unset, unreadable or released.\n */\nexport const testSwitch = (key: string): string | null => {\n if (!testBuild()) return null;\n try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; }\n};\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32 } from \"@scure/base\";\nimport { decodeBolt11 } from \"@ghostly/core\";\nimport type { InvoiceStatus, LightningInvoice, LightningPayResult, LightningPaymentRef, LightningPaymentStatus, LightningProvider, LightningProviderDescriptor } from \"./lightning\";\nimport type { OnchainBalance, OnchainPrepared, OnchainProvider, OnchainProviderDescriptor, OnchainSendRequest, OnchainTx, OnchainTxStatus } from \"./onchain\";\nimport { NothingSpentError, type ProviderField, type ProviderSettings } from \"./types\";\nimport { testBuild } from \"../../../shared/features\";\n\n/**\n * Fake providers, for unit tests and e2e: they hold regtest \"sats\" in memory, so they only ever show up in\n * the Testnet mode, and only in a dev or e2e build (`testBuild`) that has `localStorage[\"ghostly-test-providers\"]\n * === \"1\"` (or a test passes them to the registry itself); a release build ignores the key. No network, no money.\n *\n * `behaviour` drives the outcome of a spend:\n * - settle: invoices are paid by themselves after `settleMs`; payments and broadcasts succeed.\n * - refuse: a spend fails, provably before anything left (`NothingSpentError`).\n * - hang: a spend throws an unknown error, and the lookup later says it went through (a lost answer).\n */\nexport type FakeBehaviour = \"settle\" | \"refuse\" | \"hang\";\nexport const TEST_PROVIDERS_FLAG = \"ghostly-test-providers\";\n\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst random = (n: number) => crypto.getRandomValues(new Uint8Array(n));\nconst uint = (value: number, length = 1) => {\n const out: number[] = [];\n for (let v = value; v > 0; v = Math.floor(v / 32)) out.unshift(v % 32);\n while (out.length < length) out.unshift(0);\n return out;\n};\n\n/** A BOLT 11 invoice on regtest with a real checksum and a blank signature: it decodes, nobody can pay it. */\nexport function fakeInvoice(amount: number, paymentHash: Uint8Array, memo = \"\", expirySeconds = 3600): string {\n const words = uint(Math.floor(Date.now() / 1000), 7);\n const field = (tag: number, data: number[]) => words.push(tag, data.length >> 5, data.length & 31, ...data);\n field(1, bech32.toWords(paymentHash));\n if (memo) field(13, bech32.toWords(new TextEncoder().encode(memo.slice(0, 100))));\n field(6, uint(expirySeconds));\n return bech32.encode(`lnbcrt${amount * 10}n`, [...words, ...new Array<number>(104).fill(0)], false);\n}\n\n/** A valid regtest P2WPKH address of nobody's. */\nexport const fakeAddress = () => bech32.encode(\"bcrt\", [0, ...bech32.toWords(random(20))]);\n\nconst FIELDS: ProviderField[] = [\n { name: \"alias\", label: \"Name\", kind: \"text\", optional: true, placeholder: \"Fake node\" },\n { name: \"token\", label: \"Access token\", kind: \"secret\", placeholder: \"anything\", help: \"Sealed like a real provider's secret; the fake only checks it is there.\" },\n { name: \"behaviour\", label: \"Spends\", kind: \"select\", optional: true, options: [{ value: \"settle\", label: \"Go through\" }, { value: \"refuse\", label: \"Are refused\" }, { value: \"hang\", label: \"Lose their answer\" }], defaults: { testnet: \"settle\" } },\n];\nconst validate = ({ secrets, config }: ProviderSettings) => {\n if (!secrets.token?.trim()) throw new Error(\"Enter an access token\");\n if (config.behaviour && ![\"settle\", \"refuse\", \"hang\"].includes(config.behaviour)) throw new Error(\"Unknown behaviour\");\n};\n\ninterface FakeOptions { alias?: string; behaviour?: FakeBehaviour; balance?: number; settleMs?: number; token?: string }\n\nexport class FakeLightningProvider implements LightningProvider {\n readonly capabilities = { receive: true, send: true, balance: true, lookup: true };\n readonly invoices = new Map<string, { invoice: LightningInvoice; paid: boolean }>();\n readonly payments = new Map<string, LightningPaymentStatus>();\n readonly paid: string[] = [];\n balance: number;\n behaviour: FakeBehaviour;\n closed = false;\n private timers: ReturnType<typeof setTimeout>[] = [];\n constructor(readonly options: FakeOptions = {}) { this.balance = options.balance ?? 100_000; this.behaviour = options.behaviour ?? \"settle\"; }\n async info() { return { network: \"regtest\" as const, alias: this.options.alias || \"Fake Lightning\", balance: this.balance }; }\n async createInvoice(amount: number, memo?: string): Promise<LightningInvoice> {\n const preimage = random(32), hash = sha256(preimage);\n const invoice: LightningInvoice = { invoice: fakeInvoice(amount, hash, memo), paymentHash: hex(hash), amount, expiresAt: Date.now() + 3600_000, ref: hex(preimage) };\n this.invoices.set(invoice.paymentHash, { invoice, paid: false });\n if (this.behaviour === \"settle\") this.timers.push(setTimeout(() => this.markPaid(invoice.paymentHash), this.options.settleMs ?? 1500));\n return invoice;\n }\n /** Someone paid this invoice. */\n markPaid(paymentHash: string) {\n const entry = this.invoices.get(paymentHash);\n if (!entry || entry.paid || this.closed) return;\n entry.paid = true; this.balance += entry.invoice.amount;\n }\n async invoiceStatus(invoice: LightningInvoice): Promise<InvoiceStatus> {\n const entry = this.invoices.get(invoice.paymentHash);\n if (entry?.paid) return { state: \"paid\", amount: entry.invoice.amount };\n return { state: invoice.expiresAt < Date.now() ? \"expired\" : \"open\" };\n }\n async estimateFee(_invoice: string, amount: number) { return Math.max(1, Math.ceil(amount / 100)); }\n async payInvoice(invoice: string, maxFee: number): Promise<LightningPayResult> {\n const decoded = decodeBolt11(invoice);\n if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError(\"Not an invoice this fake can pay\");\n const fee = Math.min(maxFee, Math.max(1, Math.ceil(decoded.amountSat / 100)));\n if (this.behaviour === \"refuse\") throw new NothingSpentError(\"No route (fake)\");\n if (this.balance < decoded.amountSat + fee) throw new NothingSpentError(\"Not enough sats in the fake wallet\");\n this.balance -= decoded.amountSat + fee;\n this.paid.push(decoded.paymentHash);\n this.payments.set(decoded.paymentHash, { state: \"paid\", fee, preimage: hex(random(32)) });\n if (this.behaviour === \"hang\") throw new Error(\"Connection lost (fake)\");\n return { state: \"paid\", fee, preimage: this.payments.get(decoded.paymentHash)!.preimage };\n }\n async paymentStatus(payment: LightningPaymentRef): Promise<LightningPaymentStatus> {\n return this.payments.get(payment.paymentHash) ?? { state: \"failed\" };\n }\n async close() { this.closed = true; for (const t of this.timers) clearTimeout(t); }\n}\n\nexport class FakeOnchainProvider implements OnchainProvider {\n readonly addresses: string[] = [];\n readonly broadcasts: string[] = [];\n readonly released: string[] = [];\n readonly txs = new Map<string, { prepared: OnchainPrepared; confirmations: number }>();\n confirmed: number;\n behaviour: FakeBehaviour;\n closed = false;\n constructor(readonly options: FakeOptions = {}) { this.confirmed = options.balance ?? 100_000; this.behaviour = options.behaviour ?? \"settle\"; }\n async info() { return { network: \"regtest\" as const, alias: this.options.alias || \"Fake Bitcoin wallet\" }; }\n async receiveAddress() { const address = fakeAddress(); this.addresses.push(address); return address; }\n async balance(): Promise<OnchainBalance> { return { confirmed: this.confirmed, unconfirmed: 0 }; }\n async prepareSend(request: OnchainSendRequest): Promise<OnchainPrepared> {\n const feeRate = request.feeRate ?? 2, fee = feeRate * 141;\n if (fee > request.feeCap) throw new Error(`The fee (${fee} sats) is above your limit`);\n if (this.confirmed < request.amount + fee) throw new Error(\"Not enough confirmed sats\");\n return { txid: hex(random(32)), address: request.address, amount: request.amount, fee, feeRate, signed: hex(random(64)) };\n }\n async broadcast(prepared: OnchainPrepared) {\n if (this.behaviour === \"refuse\") throw new NothingSpentError(\"Rejected by the node (fake)\");\n if (!this.txs.has(prepared.txid)) { this.confirmed -= prepared.amount + prepared.fee; this.txs.set(prepared.txid, { prepared, confirmations: 1 }); }\n this.broadcasts.push(prepared.txid);\n if (this.behaviour === \"hang\") throw new Error(\"Connection lost (fake)\");\n return prepared.txid;\n }\n async status(prepared: OnchainPrepared): Promise<OnchainTxStatus> {\n const tx = this.txs.get(prepared.txid);\n return tx ? { state: \"confirmed\", confirmations: tx.confirmations } : { state: \"missing\", confirmations: 0 };\n }\n async release(prepared: OnchainPrepared) { this.released.push(prepared.txid); }\n async history(limit: number): Promise<OnchainTx[]> {\n return [...this.txs.values()].reverse().slice(0, limit).map(({ prepared, confirmations }) => ({ txid: prepared.txid, amount: -prepared.amount, fee: prepared.fee, confirmations }));\n }\n async close() { this.closed = true; }\n}\n\nconst options = ({ config, secrets }: ProviderSettings): FakeOptions => ({ alias: config.alias, behaviour: (config.behaviour as FakeBehaviour) || \"settle\", token: secrets.token });\n\nexport const fakeLightning: LightningProviderDescriptor = {\n id: \"fake-lightning\",\n label: \"Fake Lightning (test)\",\n kind: \"lightning\",\n description: \"In-memory regtest node for tests. Holds nothing.\",\n networks: [\"regtest\"],\n platforms: [\"web\", \"desktop\"],\n fields: FIELDS,\n experimental: true,\n validate,\n async create(settings) { return new FakeLightningProvider(options(settings)); },\n};\n\nexport const fakeOnchain: OnchainProviderDescriptor = {\n id: \"fake-onchain\",\n label: \"Fake Bitcoin wallet (test)\",\n kind: \"onchain\",\n description: \"In-memory regtest wallet for tests. Holds nothing.\",\n networks: [\"regtest\"],\n platforms: [\"web\", \"desktop\"],\n fields: FIELDS,\n experimental: true,\n validate,\n async create(settings) { return new FakeOnchainProvider(options(settings)); },\n};\n\n/** Whether this browser asked for the fake providers (an e2e run sets it before the app starts). */\nexport function testProvidersEnabled(): boolean {\n try { return testBuild() && globalThis.localStorage?.getItem(TEST_PROVIDERS_FLAG) === \"1\"; } catch { return false; }\n}\n","import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { fromBase64Url, toBase64Url, utf8Decode, utf8Encode, type IdentityStatement } from \"@ghostly/core\";\nimport { testBuild } from \"../shared/features\";\nimport type { IdentityProofProvider } from \"./contract\";\n\n/**\n * Fake identity providers, for unit tests and e2e. No network, no real accounts. They are in the\n * registry only in a dev or e2e build (`testBuild`) that has `localStorage[\"ghostly-test-identities\"] === \"1\"`\n * (or a test passes them itself); a release build ignores the key.\n *\n * - fake-key self-custodied: an Ed25519 key held by a fake in-app signer, or signed \"outside\" and pasted.\n * - fake-account provider-attested: a fake issuer signs a token whose nonce is the statement id (like OIDC).\n * - fake-record self-custodied, published: a record the verifier fetches through `ctx.fetch` (like DNS).\n */\nexport const TEST_IDENTITIES_FLAG = \"ghostly-test-identities\";\nexport const testIdentitiesEnabled = () => { try { return testBuild() && globalThis.localStorage?.getItem(TEST_IDENTITIES_FLAG) === \"1\"; } catch { return false; } };\n\nconst HEX64 = /^[a-f0-9]{64}$/;\nconst hex = (b: Uint8Array) => Array.from(b, x => x.toString(16).padStart(2, \"0\")).join(\"\");\nconst unhex = (s: string) => Uint8Array.from(s.match(/../g)!, x => parseInt(x, 16));\nconst normalizeHexKey = (input: string) => { const v = input.trim().toLowerCase(); if (!HEX64.test(v)) throw new Error(\"Enter 64 hex characters\"); return v; };\nconst exactKeys = (raw: unknown, keys: string) => !!raw && typeof raw === \"object\" && !Array.isArray(raw) && Object.keys(raw).sort().join(\",\") === keys;\n\n/** The key behind the fake in-app signer, made on first use so a release start draws no key. Tests may replace it. */\nlet fakeSeed: Uint8Array | undefined;\nexport const fakeKeyring = { get seed() { return fakeSeed ??= ed25519.utils.randomSecretKey(); }, set seed(value: Uint8Array) { fakeSeed = value; } };\nexport const fakeKeySubject = (seed = fakeKeyring.seed) => hex(ed25519.getPublicKey(seed));\nexport const fakeKeySign = (statement: IdentityStatement, seed = fakeKeyring.seed) => ({ sig: toBase64Url(ed25519.sign(statement.bytes, seed)) });\n\nexport interface FakeKeyEvidence { sig: string }\nexport const fakeKey: IdentityProofProvider<FakeKeyEvidence> = {\n id: \"fake-key\", label: \"Test key\", category: \"self-custodied\",\n summary: \"Sign with the test key\", description: \"A test identity: an Ed25519 key held by this page. For tests only.\",\n platforms: [\"web\", \"desktop\"],\n subject: { label: \"Public key\", placeholder: \"64 hex characters\", normalize: normalizeHexKey, short: k => `${k.slice(0, 8)}…${k.slice(-4)}` },\n publicUri: k => `urn:ghostly-test:${k}`,\n validity: { defaultDays: 30, maxDays: 365 },\n privacy: \"Nothing: checked on this device.\",\n signers: [\n { id: \"fake-signer\", kind: \"in-app\", label: \"Test signer\", fields: [{ name: \"refuse\", label: \"Refuse\", kind: \"text\", optional: true }],\n run: async (ctx, work) => {\n ctx.signal.throwIfAborted();\n if (ctx.values.refuse) throw new Error(\"The test signer refused\");\n return work({ subject: async () => fakeKeySubject(), sign: async statement => fakeKeySign(statement) });\n } },\n { id: \"fake-tool\", kind: \"external-tool\", label: \"Sign outside Ghostly\",\n instructions: statement => ({ steps: [{ text: \"Sign this statement with your test key:\", copy: statement.text }], paste: { label: \"Signature (base64url)\" } }),\n parse: pasted => { const sig = pasted.trim(); if (!/^[A-Za-z0-9_-]{86}$/.test(sig)) throw new Error(\"That is not a test signature\"); return { sig }; } },\n ],\n parseEvidence(raw) {\n const e = raw as FakeKeyEvidence;\n if (!exactKeys(raw, \"sig\") || typeof e.sig !== \"string\" || !/^[A-Za-z0-9_-]{86}$/.test(e.sig)) throw new Error(\"Invalid test evidence\");\n return { sig: e.sig };\n },\n async verify(statement, evidence) {\n let ok: boolean;\n try { ok = ed25519.verify(fromBase64Url(evidence.sig), statement.bytes, unhex(statement.binding.subject)); } catch { ok = false; }\n if (!ok) throw new Error(\"Invalid test signature\");\n return { subject: statement.binding.subject, source: \"Test signature (Ed25519)\" };\n },\n};\n\n/** The fake issuer's key. Its public half is what fake-account trusts, like a provider's JWKS. */\nconst ISSUER_SEED = unhex(\"7a\".repeat(32));\nexport const FAKE_ISSUER = \"https://issuer.ghostly.test\";\nexport interface FakeAccountEvidence { token: string }\n/** What the fake login page signs: iss, sub, nonce (= statement id), iat. */\nexport function fakeAccountToken(statement: IdentityStatement, account = \"alice\", seed = ISSUER_SEED, iat = statement.binding.issuedAt): FakeAccountEvidence {\n const payload = toBase64Url(utf8Encode(JSON.stringify({ iss: FAKE_ISSUER, sub: account, nonce: statement.id, iat })));\n return { token: `${payload}.${toBase64Url(ed25519.sign(utf8Encode(payload), seed))}` };\n}\nexport const fakeAccount: IdentityProofProvider<FakeAccountEvidence> = {\n id: \"fake-account\", label: \"Test account\", category: \"provider-attested\",\n summary: \"Log in to the test issuer\", description: \"A test login provider that vouches for an account. For tests only.\",\n platforms: [\"web\", \"desktop\"],\n subject: { label: \"Provider\", options: [{ value: FAKE_ISSUER, label: \"Test issuer\" }],\n normalize: input => { if (input.trim() !== FAKE_ISSUER) throw new Error(\"Unknown test issuer\"); return FAKE_ISSUER; } },\n validity: { defaultDays: 30, maxDays: 90 },\n privacy: \"Nothing: the issuer's signature is checked on this device.\",\n signers: [{ id: \"fake-login\", kind: \"redirect\", label: \"Log in to the test issuer\",\n start: async (statement, ctx) => { ctx.signal.throwIfAborted(); return fakeAccountToken(statement, ctx.values.account || \"alice\"); } }],\n parseEvidence(raw) {\n const e = raw as FakeAccountEvidence;\n if (!exactKeys(raw, \"token\") || typeof e.token !== \"string\" || e.token.length > 2048 || !/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{86}$/.test(e.token)) throw new Error(\"Invalid test token\");\n return { token: e.token };\n },\n async verify(statement, { token }) {\n const [payload, sig] = token.split(\".\");\n if (!ed25519.verify(fromBase64Url(sig), utf8Encode(payload), ed25519.getPublicKey(ISSUER_SEED))) throw new Error(\"Not signed by the test issuer\");\n const claims = JSON.parse(utf8Decode(fromBase64Url(payload))) as { iss: string; sub: string; nonce: string };\n if (claims.iss !== statement.binding.subject) throw new Error(\"Token from another issuer\");\n if (claims.nonce !== statement.id) throw new Error(\"Token for another statement\");\n if (typeof claims.sub !== \"string\" || !/^[a-z0-9]{1,64}$/.test(claims.sub)) throw new Error(\"Invalid account\");\n return { subject: `${claims.iss}#${claims.sub}`, attester: \"issuer.ghostly.test\", source: \"Token signed by the test issuer\",\n display: { name: claims.sub, source: \"Test issuer profile\", fetchedAt: statement.binding.issuedAt } };\n },\n};\n\n/** fake-record's records: subject → published text. The verifier reads `https://records.ghostly.test/<subject>`. */\nexport const FAKE_RECORD_HOST = \"https://records.ghostly.test/\";\nexport const fakeRecordText = (statement: IdentityStatement) => `ghostly-proof=${statement.id}`;\nexport const fakeRecord: IdentityProofProvider<Record<string, never>> = {\n id: \"fake-record\", label: \"Test record\", category: \"self-custodied\",\n summary: \"Publish a test record\", description: \"A test record published where the verifier looks it up, like DNS. For tests only.\",\n platforms: [\"web\", \"desktop\"],\n subject: { label: \"Name\", placeholder: \"alice\", normalize: input => { const v = input.trim().toLowerCase(); if (!/^[a-z0-9-]{1,63}$/.test(v)) throw new Error(\"Letters, digits and dashes\"); return v; } },\n validity: { defaultDays: 30, maxDays: 365 },\n recheck: { afterSeconds: 3600 },\n privacy: \"The verifier asks records.ghostly.test for the record: that server learns the name was checked.\",\n signers: [{ id: \"fake-publish\", kind: \"publish\", label: \"Publish a record\",\n instructions: statement => ({ steps: [{ text: `Publish this record for ${statement.binding.subject}:`, copy: fakeRecordText(statement) }] }),\n evidence: () => ({}) }],\n parseEvidence(raw) { if (!exactKeys(raw, \"\")) throw new Error(\"Invalid test evidence\"); return {}; },\n async verify(statement, _evidence, ctx) {\n const response = await ctx.fetch(`${FAKE_RECORD_HOST}${statement.binding.subject}`, { maxBytes: 4096, signal: ctx.signal });\n if (response.status !== 200 || !response.text.split(\"\\n\").includes(fakeRecordText(statement))) throw new Error(\"The record is not published\");\n return { subject: statement.binding.subject, source: \"Record published at records.ghostly.test\" };\n },\n};\n\nexport const FAKE_IDENTITY_PROVIDERS: readonly IdentityProofProvider[] = [fakeKey, fakeAccount, fakeRecord];\n"],"mappings":";;;;;;;;;;;;AAgBA,IAAa,kBAA2B;CAAE,IAAI;EAAE,OAAiC;CAAyC,QAAQ;EAAE,OAAO;CAAO;AAAE;;ACGpJ,IAAa,sBAAsB;AAEnC,IAAMA,SAAO,UAAsB,MAAM,KAAK,QAAQ,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AACpG,IAAM,UAAU,MAAc,OAAO,gBAAgB,IAAI,WAAW,CAAC,CAAC;AACtE,IAAM,QAAQ,OAAe,SAAS,MAAM;CAC1C,MAAM,MAAgB,CAAC;CACvB,KAAK,IAAI,IAAI,OAAO,IAAI,GAAG,IAAI,KAAK,MAAM,IAAI,EAAE,GAAG,IAAI,QAAQ,IAAI,EAAE;CACrE,OAAO,IAAI,SAAS,QAAQ,IAAI,QAAQ,CAAC;CACzC,OAAO;AACT;;AAGA,SAAgB,YAAY,QAAgB,aAAyB,OAAO,IAAI,gBAAgB,MAAc;CAC5G,MAAM,QAAQ,KAAK,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,GAAG,CAAC;CACnD,MAAM,SAAS,KAAa,SAAmB,MAAM,KAAK,KAAK,KAAK,UAAU,GAAG,KAAK,SAAS,IAAI,GAAG,IAAI;CAC1G,MAAM,GAAG,OAAO,QAAQ,WAAW,CAAC;CACpC,IAAI,MAAM,MAAM,IAAI,OAAO,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC;CAChF,MAAM,GAAG,KAAK,aAAa,CAAC;CAC5B,OAAO,OAAO,OAAO,SAAS,SAAS,GAAG,IAAI,CAAC,GAAG,OAAO,GAAG,IAAI,MAAc,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,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@ -1,2 +1 @@
1
- import { _ as fakeAddress, a as fakeAccount, b as fakeOnchain, c as fakeKeySign, d as fakeRecord, f as fakeRecordText, g as TEST_PROVIDERS_FLAG, h as FakeOnchainProvider, i as TEST_IDENTITIES_FLAG, l as fakeKeySubject, m as FakeLightningProvider, n as FAKE_ISSUER, o as fakeAccountToken, p as testIdentitiesEnabled, r as FAKE_RECORD_HOST, s as fakeKey, t as FAKE_IDENTITY_PROVIDERS, u as fakeKeyring, v as fakeInvoice, x as testProvidersEnabled, y as fakeLightning } from "./fakes-CXeeyI4Z.js";
2
- export { FAKE_IDENTITY_PROVIDERS, FAKE_ISSUER, FAKE_RECORD_HOST, FakeLightningProvider, FakeOnchainProvider, TEST_IDENTITIES_FLAG, TEST_PROVIDERS_FLAG, fakeAccount, fakeAccountToken, fakeAddress, fakeInvoice, fakeKey, fakeKeySign, fakeKeySubject, fakeKeyring, fakeLightning, fakeOnchain, fakeRecord, fakeRecordText, testIdentitiesEnabled, testProvidersEnabled };
1
+ export { t as FAKE_IDENTITY_PROVIDERS, n as FAKE_ISSUER, r as FAKE_RECORD_HOST, m as FakeLightningProvider, h as FakeOnchainProvider, i as TEST_IDENTITIES_FLAG, g as TEST_PROVIDERS_FLAG, a as fakeAccount, o as fakeAccountToken, _ as fakeAddress, v as fakeInvoice, s as fakeKey, c as fakeKeySign, l as fakeKeySubject, u as fakeKeyring, y as fakeLightning, b as fakeOnchain, d as fakeRecord, f as fakeRecordText, p as testIdentitiesEnabled, x as testProvidersEnabled } from "./fakes-Cgl1w4Nv.js";
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
1
- import { Md as newIdentityBinding, Pa as decodeBolt11, dd as IDENTITY_MAX_EVIDENCE, kd as identityStatement, la as isBitcoinAddress, md as IDENTITY_MAX_VALIDITY, mf as TRANSPORTS } from "./src-CqAqFhh9.js";
2
- import { a as describeProvider, c as offeredIn, i as PROVIDER_PLATFORMS, l as providerDescriptorProblems, n as PROVIDER_ID, o as isNothingSpentError, r as PROVIDER_NETWORKS, s as networkMode, t as NothingSpentError, u as redact } from "./types-DYLIIkU8.js";
3
- import { i as verifyIdentity, n as boundedIdentityFetch, r as descriptorProblems, t as availableSigners } from "./verify-B9s82dbd.js";
4
- //#region ../browser/src/proofs/contract.ts
1
+ import { a as describeProvider, c as offeredIn, i as PROVIDER_PLATFORMS, l as providerDescriptorProblems, n as PROVIDER_ID, o as isNothingSpentError, r as PROVIDER_NETWORKS, s as networkMode, t as NothingSpentError, u as redact } from "./types-DbgC491n.js";
2
+ import { i as verifyIdentity, n as boundedIdentityFetch, r as descriptorProblems, t as availableSigners } from "./verify-CSo7-43-.js";
3
+ import { A as newIdentityBinding, D as identityStatement, f as IDENTITY_MAX_VALIDITY, l as IDENTITY_MAX_EVIDENCE, n as isBitcoinAddress } from "./bitcoinAddress-C2MAmcDT.js";
4
+ import { i as TRANSPORTS } from "./pairedTransports-CkYMAoYN.js";
5
+ import { n as decodeBolt11 } from "./bolt11-CRiQrma3.js";
6
+ // ../browser/src/proofs/contract.ts
5
7
  var IDENTITY_PLATFORMS = [
6
8
  "web",
7
9
  "extension",
8
10
  "desktop"
9
11
  ];
10
- //#endregion
11
- //#region ../browser/src/plugins/bundled.ts
12
+ // ../browser/src/plugins/bundled.ts
12
13
  /**
13
14
  * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`
14
15
  * names their modules (comma-separated paths from the repository root, each default-exporting a
@@ -16,8 +17,7 @@ var IDENTITY_PLATFORMS = [
16
17
  * for one that imports them. Release builds never set it; the e2e build carries the SDK example.
17
18
  */
18
19
  var BUNDLED_PLUGINS = [];
19
- //#endregion
20
- //#region ../browser/src/plugins/registry.ts
20
+ // ../browser/src/plugins/registry.ts
21
21
  /**
22
22
  * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers
23
23
  * that register here instead of being added to the built-in lists. A plugin is a plain object naming
@@ -173,7 +173,6 @@ function resetAdapterRegistry() {
173
173
  for (const kind of KINDS) s.reserved[kind].clear();
174
174
  notify(s);
175
175
  }
176
- //#endregion
177
176
  export { IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, IDENTITY_PLATFORMS, NothingSpentError, PLUGIN_ID, PROVIDER_ID, PROVIDER_NETWORKS, PROVIDER_PLATFORMS, SDK_API, TRANSPORTS, availableSigners, boundedIdentityFetch, decodeBolt11, describeProvider, descriptorProblems as identityDescriptorProblems, identityStatement, isBitcoinAddress, isNothingSpentError, networkMode, newIdentityBinding, offeredIn, onAdaptersChanged, pluginProblems, providerDescriptorProblems, redact, registerAdapters, registeredIdentityProviders, registeredLightningProviders, registeredOnchainProviders, registeredPlugins, resetAdapterRegistry, verifyIdentity };
178
177
 
179
178
  //# sourceMappingURL=index.js.map
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,M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../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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