@ghostlytools/cli 1.13.0 → 1.13.2

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 (113) hide show
  1. package/README.md +13 -10
  2. package/dist/assets/api-DV52o7A8.js +3 -0
  3. package/dist/assets/{api-CjOaoG-v.js → api-O57SNJcb.js} +495 -99
  4. package/dist/assets/api-O57SNJcb.js.map +1 -0
  5. package/dist/assets/{apiKit-BAGvlQtm.js → apiKit-CPTFJHA7.js} +40 -8
  6. package/dist/assets/{apiKit-BAGvlQtm.js.map → apiKit-CPTFJHA7.js.map} +1 -1
  7. package/dist/assets/{appFetch-BwJd-kNq.js → appFetch-Ca9DNQQ2.js} +2 -2
  8. package/dist/assets/{appFetch-BwJd-kNq.js.map → appFetch-Ca9DNQQ2.js.map} +1 -1
  9. package/dist/assets/{apps-Cuk45sz5.js → apps-gXpGFPiv.js} +16 -14
  10. package/dist/assets/apps-gXpGFPiv.js.map +1 -0
  11. package/dist/assets/{apps-DjY095Af.js → apps-uZTu5FlR.js} +1 -1
  12. package/dist/assets/{arkade-DryM-q5n.js → arkade-B6UNf5HI.js} +2 -2
  13. package/dist/assets/{arkade-DryM-q5n.js.map → arkade-B6UNf5HI.js.map} +1 -1
  14. package/dist/assets/{backup-DekVCDWv.js → backup-CxH3auHB.js} +9 -7
  15. package/dist/assets/backup-CxH3auHB.js.map +1 -0
  16. package/dist/assets/{backup-B56sQqoQ.js → backup-Di2U6QVH.js} +1 -1
  17. package/dist/assets/bark_ffi_wasm_bg-CcafsJla.js.map +1 -1
  18. package/dist/assets/{bitcoind-B2bbVSzh.js → bitcoind-BpZn3bRN.js} +2 -2
  19. package/dist/assets/{bitcoind-B2bbVSzh.js.map → bitcoind-BpZn3bRN.js.map} +1 -1
  20. package/dist/assets/bitcoindevkit_bg-BWQHx7vd.js.map +1 -1
  21. package/dist/assets/{buttons-BGxzOtrq.js → buttons-D4udKEvT.js} +8 -8
  22. package/dist/assets/buttons-D4udKEvT.js.map +1 -0
  23. package/dist/assets/buttons-YTYEqvGC.js +1 -0
  24. package/dist/assets/{client-DcQAfc3h.js → client-DGx7E8b3.js} +3 -3
  25. package/dist/assets/{client-DcQAfc3h.js.map → client-DGx7E8b3.js.map} +1 -1
  26. package/dist/assets/{domainProofs-BDNP1dIy.js → domainProofs-b3Y1Gj9g.js} +6 -2
  27. package/dist/assets/{domainProofs-BDNP1dIy.js.map → domainProofs-b3Y1Gj9g.js.map} +1 -1
  28. package/dist/assets/{engineErrors--9hfgKlK.js → engineErrors-wWlLy54D.js} +11 -3
  29. package/dist/assets/engineErrors-wWlLy54D.js.map +1 -0
  30. package/dist/assets/{errors-DDLFO4Gf.js → errors-JVJsO8Iu.js} +18 -2
  31. package/dist/assets/errors-JVJsO8Iu.js.map +1 -0
  32. package/dist/assets/{fixedHosts-C3hBliM9.js → fixedHosts-CODN2pTL.js} +3 -3
  33. package/dist/assets/{fixedHosts-C3hBliM9.js.map → fixedHosts-CODN2pTL.js.map} +1 -1
  34. package/dist/assets/{ghostly_iroh_web-DIj5xGmR.js → ghostly_iroh_web-9VOwZcJQ.js} +30 -35
  35. package/dist/assets/ghostly_iroh_web-9VOwZcJQ.js.map +1 -0
  36. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  37. package/dist/assets/{groupMeta-goASqzOt.js → groupMeta-CeZpqVVC.js} +174 -37
  38. package/dist/assets/groupMeta-CeZpqVVC.js.map +1 -0
  39. package/dist/assets/{host-C2WRKj3g.js → host-CRA7h5A2.js} +270 -64
  40. package/dist/assets/host-CRA7h5A2.js.map +1 -0
  41. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js → hyperdhtRelay-B34Zhz4P.js} +2 -2
  42. package/dist/assets/{hyperdhtRelay-DLUiwfnt.js.map → hyperdhtRelay-B34Zhz4P.js.map} +1 -1
  43. package/dist/assets/{hyperdhtRelay-bjNGacf5.js → hyperdhtRelay-DDwU5b4P.js} +2 -2
  44. package/dist/assets/{hyperdhtRelay-bjNGacf5.js.map → hyperdhtRelay-DDwU5b4P.js.map} +1 -1
  45. package/dist/assets/{identityProofs-Cksc_K7_.js → identityProofs-B8zCp5_0.js} +140 -27
  46. package/dist/assets/identityProofs-B8zCp5_0.js.map +1 -0
  47. package/dist/assets/{irohWeb-NfthOL98.js → irohWeb-mnOi2Jp7.js} +10838 -4837
  48. package/dist/assets/irohWeb-mnOi2Jp7.js.map +1 -0
  49. package/dist/assets/{linkPreview-DdMf-YAc.js → linkPreview-5kHmKUTN.js} +20 -8
  50. package/dist/assets/linkPreview-5kHmKUTN.js.map +1 -0
  51. package/dist/assets/{main-Dh7fePd8.js → main-Chc871HV.js} +119 -81
  52. package/dist/assets/main-Chc871HV.js.map +1 -0
  53. package/dist/assets/{mainline-DY95WbuK.js → mainline-CDUXtV-I.js} +2 -2
  54. package/dist/assets/{mainline-DY95WbuK.js.map → mainline-CDUXtV-I.js.map} +1 -1
  55. package/dist/assets/{networkReason-Be-hMghr.js → networkReason-DYlPZS5M.js} +2 -2
  56. package/dist/assets/{networkReason-Be-hMghr.js.map → networkReason-DYlPZS5M.js.map} +1 -1
  57. package/dist/assets/{ownDid-BErplN7N.js → ownDid-BOuSlDv-.js} +10 -6
  58. package/dist/assets/ownDid-BOuSlDv-.js.map +1 -0
  59. package/dist/assets/{ownStatus-ClrFjd7h.js → ownStatus-CLA1VPkL.js} +6 -6
  60. package/dist/assets/{ownStatus-ClrFjd7h.js.map → ownStatus-CLA1VPkL.js.map} +1 -1
  61. package/dist/assets/{pairedTransports-BKmvlKz1.js → pairedTransports-DAzupLYo.js} +23 -17
  62. package/dist/assets/pairedTransports-DAzupLYo.js.map +1 -0
  63. package/dist/assets/{paymentIntent-DySU3Ajm.js → paymentIntent-Cr3uZa_0.js} +2 -2
  64. package/dist/assets/{paymentIntent-DySU3Ajm.js.map → paymentIntent-Cr3uZa_0.js.map} +1 -1
  65. package/dist/assets/{profiles-B8xO8-oj.js → profiles-BH1bH9aE.js} +3 -3
  66. package/dist/assets/{profiles-B8xO8-oj.js.map → profiles-BH1bH9aE.js.map} +1 -1
  67. package/dist/assets/{registry--Rg2YvOH.js → registry-DAq16T-V.js} +1 -1
  68. package/dist/assets/{registry-CU8PevhI.js → registry-DP_-RA-v.js} +11 -7
  69. package/dist/assets/registry-DP_-RA-v.js.map +1 -0
  70. package/dist/assets/{relay-CHWg5hpZ.js → relay-gJTOYQJZ.js} +93 -7
  71. package/dist/assets/relay-gJTOYQJZ.js.map +1 -0
  72. package/dist/assets/{resolve-B1upovPM.js → resolve-B1eQ4dVQ.js} +10 -5
  73. package/dist/assets/resolve-B1eQ4dVQ.js.map +1 -0
  74. package/dist/assets/secretGuard-Bh11MPdI.js +1 -0
  75. package/dist/assets/{secretGuard-BrATm_gl.js → secretGuard-oz_3hBfW.js} +19 -2
  76. package/dist/assets/{secretGuard-BrATm_gl.js.map → secretGuard-oz_3hBfW.js.map} +1 -1
  77. package/dist/assets/{server-Dgxx_DaN.js → server-Bd2ofxc1.js} +1283 -6628
  78. package/dist/assets/server-Bd2ofxc1.js.map +1 -0
  79. package/dist/assets/{sshForges-BnvwmNj-.js → sshForges-As7dbGXM.js} +2 -2
  80. package/dist/assets/{sshForges-BnvwmNj-.js.map → sshForges-As7dbGXM.js.map} +1 -1
  81. package/dist/assets/{translate-BcbSWkuq.js → translate-DnuQMfj0.js} +22 -11
  82. package/dist/assets/translate-DnuQMfj0.js.map +1 -0
  83. package/dist/assets/{usdt-CBJ4Q5Ji.js → usdt-DLmtf8F9.js} +4 -4
  84. package/dist/assets/{usdt-CBJ4Q5Ji.js.map → usdt-DLmtf8F9.js.map} +1 -1
  85. package/dist/assets/{waitNotice-ylU3XwjO.js → waitNotice-BHuMofaH.js} +57 -3
  86. package/dist/assets/waitNotice-BHuMofaH.js.map +1 -0
  87. package/dist/ghostly.mjs +1 -1
  88. package/npm-shrinkwrap.json +2 -2
  89. package/package.json +1 -1
  90. package/dist/assets/api-CVtg7MpI.js +0 -3
  91. package/dist/assets/api-CjOaoG-v.js.map +0 -1
  92. package/dist/assets/apps-Cuk45sz5.js.map +0 -1
  93. package/dist/assets/backup-DekVCDWv.js.map +0 -1
  94. package/dist/assets/buttons-BGxzOtrq.js.map +0 -1
  95. package/dist/assets/buttons-CsN2WJOf.js +0 -1
  96. package/dist/assets/engineErrors--9hfgKlK.js.map +0 -1
  97. package/dist/assets/errors-DDLFO4Gf.js.map +0 -1
  98. package/dist/assets/ghostly_iroh_web-DIj5xGmR.js.map +0 -1
  99. package/dist/assets/groupMeta-goASqzOt.js.map +0 -1
  100. package/dist/assets/host-C2WRKj3g.js.map +0 -1
  101. package/dist/assets/identityProofs-Cksc_K7_.js.map +0 -1
  102. package/dist/assets/irohWeb-NfthOL98.js.map +0 -1
  103. package/dist/assets/linkPreview-DdMf-YAc.js.map +0 -1
  104. package/dist/assets/main-Dh7fePd8.js.map +0 -1
  105. package/dist/assets/ownDid-BErplN7N.js.map +0 -1
  106. package/dist/assets/pairedTransports-BKmvlKz1.js.map +0 -1
  107. package/dist/assets/registry-CU8PevhI.js.map +0 -1
  108. package/dist/assets/relay-CHWg5hpZ.js.map +0 -1
  109. package/dist/assets/resolve-B1upovPM.js.map +0 -1
  110. package/dist/assets/secretGuard-Bm6nci0I.js +0 -1
  111. package/dist/assets/server-Dgxx_DaN.js.map +0 -1
  112. package/dist/assets/translate-BcbSWkuq.js.map +0 -1
  113. package/dist/assets/waitNotice-ylU3XwjO.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry-DP_-RA-v.js","names":["SEGMENT","HEX64","holds","MAX_SIGNATURE","HEX64","hex","unhex","nip19Decode","exactKeys","ARMOR","USER_ID_SOURCE","KEYSERVER_SOURCE","scopeFor","callbackParams","currentHost","hostOf","exactKeys","hex"],"sources":["../../../core/src/pkdns.ts","../../../core/src/did.ts","../../../core/src/bitcoinScript.ts","../../../core/src/bip322.ts","../../../core/src/bitcoinMessage.ts","../../../browser/src/proofs/contract.ts","../../../browser/src/proofs/bitcoinWallets.ts","../../../browser/src/proofs/providers/bitcoin.ts","../../../browser/src/proofs/displaySource.ts","../../../browser/src/proofs/nostr.ts","../../../browser/src/proofs/providers/nostr.ts","../../../browser/src/proofs/providers/domain.ts","../../../browser/src/proofs/openpgp.ts","../../../browser/src/proofs/providers/openpgp.ts","../../../browser/src/proofs/providers/ssh.ts","../../../browser/src/host.ts","../../../browser/src/proofs/oidc/jwks.ts","../../../browser/src/proofs/oidc/verify.ts","../../../browser/src/proofs/oidc/flow.ts","../../../browser/src/proofs/providers/oidc.ts","../../../browser/src/proofs/did.ts","../../../browser/src/proofs/providers/did.ts","../../../browser/src/proofs/atproto/oauth.ts","../../../browser/src/proofs/providers/atproto.ts","../../../browser/src/proofs/pubky.ts","../../../browser/src/proofs/providers/pubky.ts","../../../browser/src/proofs/testing.ts","../../../browser/src/proofs/registry.ts"],"sourcesContent":["import { isZ32Key } from \"./bytes\";\nimport { decodeDnsAnswers, readDnsName } from \"./dns\";\nimport { normalizeDomain } from \"./domainProofs\";\n\n/**\n * Pubky's PKDNS records, read (https://pubky.org). A Pubky key's signed Pkarr packet names its homeserver in an\n * HTTPS (or SVCB) record at `_pubky` whose target is the homeserver's own key; the homeserver's packet names, in\n * HTTPS records at its root, where it answers: its Pubky TLS endpoint (target \".\", for native clients) and an ICANN\n * host name for browsers. The Pubky SDK resolves exactly this. Packets reach these functions already checked\n * against their key (`openRelayPayload`); nothing here trusts a host or URL from anywhere else.\n */\n\nconst SVCB = 64;\nconst HTTPS = 65;\n/** SvcParamKey \"port\" (RFC 9460). */\nconst PORT = 3;\nconst Z32 = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\n\nexport interface SvcbRecord {\n /** The owner name, lowercase, without a trailing dot (a Pkarr packet's names end in its key). */\n name: string;\n priority: number;\n /** The target name, lowercase; \"\" is \".\" (the owner itself). */\n target: string;\n /** SvcParams by key, raw. */\n params: Map<number, Uint8Array>;\n}\n\nconst u16 = (data: Uint8Array, at: number) => (data[at] << 8) | data[at + 1];\n\n/** Every SVCB and HTTPS record of a DNS packet, in packet order. Throws on a malformed one. */\nexport function decodeSvcbRecords(dnsPacket: Uint8Array): SvcbRecord[] {\n const records: SvcbRecord[] = [];\n for (const answer of decodeDnsAnswers(dnsPacket)) {\n if (answer.type !== SVCB && answer.type !== HTTPS) continue;\n const end = answer.offset + answer.length;\n if (answer.length < 3) throw new Error(\"SVCB record too short\");\n const priority = u16(dnsPacket, answer.offset);\n const { name: target, next } = readDnsName(dnsPacket, answer.offset + 2);\n if (next > end) throw new Error(\"SVCB target out of bounds\");\n const params = new Map<number, Uint8Array>();\n for (let at = next; at < end;) {\n if (at + 4 > end) throw new Error(\"SVCB parameter out of bounds\");\n const key = u16(dnsPacket, at), length = u16(dnsPacket, at + 2);\n at += 4;\n if (at + length > end) throw new Error(\"SVCB parameter out of bounds\");\n if (!params.has(key)) params.set(key, dnsPacket.slice(at, at + length));\n at += length;\n }\n records.push({ name: answer.name.toLowerCase(), priority, target: target.toLowerCase(), params });\n }\n return records;\n}\n\n/**\n * The homeserver a Pubky key's packet names: the z-base-32 key its `_pubky` record points at, or undefined. The target\n * is read next as a key (`pubkyRecords` checks the homeserver's packet against it), so only a canonical one names a\n * homeserver; a respelled one is none, not a lookup that fails as \"no records\".\n */\nexport function pubkyHomeserverOf(dnsPacket: Uint8Array, userZ32: string): string | undefined {\n // Like the SDK: the first `_pubky` record. Pkarr stores names with the key appended; accept the relative form too.\n const record = decodeSvcbRecords(dnsPacket).find(r => r.name === `_pubky.${userZ32}` || r.name === \"_pubky\");\n return record && isZ32Key(record.target) ? record.target : undefined;\n}\n\n/** Where a homeserver answers browsers: a public host name and, when its record says so, a port. */\nexport interface HomeserverEndpoint { host: string; port?: number }\n\n/**\n * The homeserver's web endpoint from its own packet: of the HTTPS/SVCB records at its root, the lowest priority one\n * whose target is a public ICANN host name (not \".\", not another Pkarr key, not a name that only works on private\n * networks, which would point a contact's app inward), with its port parameter. Undefined when there is none.\n */\nexport function homeserverWebEndpoint(dnsPacket: Uint8Array, homeserverZ32: string): HomeserverEndpoint | undefined {\n const records = decodeSvcbRecords(dnsPacket)\n .filter(r => (r.name === homeserverZ32 || r.name === \"\") && r.priority > 0)\n .sort((a, b) => a.priority - b.priority);\n for (const r of records) {\n if (!r.target || Z32.test(r.target.split(\".\")[0])) continue;\n let host: string;\n try { host = normalizeDomain(r.target); } catch { continue; }\n const port = r.params.get(PORT);\n if (port && port.length !== 2) continue;\n const number = port ? u16(port, 0) : undefined;\n if (number === 0) continue;\n return number === undefined || number === 443 ? { host } : { host, port: number };\n }\n return undefined;\n}\n\n/**\n * A DNS packet of SVCB/HTTPS records, the way Pkarr stores them (names with the key appended, targets\n * uncompressed). For tests and test services: Ghostly itself never publishes these.\n */\nexport function encodeSvcbPacket(records: { name: string; priority: number; target: string; port?: number; type?: 64 | 65 }[]): Uint8Array {\n const name = (value: string) => {\n const labels = value.split(\".\").filter(Boolean).map(l => new TextEncoder().encode(l));\n return Uint8Array.from([...labels.flatMap(l => [l.length, ...l]), 0]);\n };\n const be16 = (n: number) => [(n >> 8) & 0xff, n & 0xff];\n const bytes: number[] = [0, 0, 0x80, 0, 0, 0, ...be16(records.length), 0, 0, 0, 0];\n for (const r of records) {\n const rdata = [...be16(r.priority), ...name(r.target), ...(r.port === undefined ? [] : [...be16(PORT), 0, 2, ...be16(r.port)])];\n bytes.push(...name(r.name), ...be16(r.type ?? HTTPS), 0, 1, 0, 0, 0x0e, 0x10, ...be16(rdata.length), ...rdata);\n }\n return Uint8Array.from(bytes);\n}\n","import { ed25519 } from \"@noble/curves/ed25519.js\";\nimport { p256 } from \"@noble/curves/nist.js\";\nimport { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { base58 } from \"@scure/base\";\nimport { bytesEqual, concatBytes, fromZ32, toBase64Url, toZ32, utf8Decode, utf8Encode } from \"./bytes\";\nimport { normalizeDomain } from \"./domainProofs\";\n\n/**\n * Decentralized identifiers (W3C DID Core 1.0) as external identities, network-free half: DID syntax,\n * the documents did:key and did:jwk carry in the identifier itself, did:web's URLs, strict parsing of a\n * fetched DID document, and JWS / raw signatures by the keys it lists. Fetching did:web documents and\n * did:dht records is the browser's (`packages/browser/src/proofs/did.ts`).\n *\n * Only keys a document lists under `authentication` or `assertionMethod` may sign for the DID: a key\n * listed only for key agreement or capability delegation does not speak for it.\n */\n\nexport class DidError extends Error {}\n\nexport const DID_METHODS = [\"key\", \"jwk\", \"dht\", \"web\"] as const;\nexport type DidMethod = (typeof DID_METHODS)[number];\nexport type DidCurve = \"Ed25519\" | \"secp256k1\" | \"P-256\";\nexport type DidRelationship = \"authentication\" | \"assertionMethod\";\nconst RELATIONSHIPS: readonly DidRelationship[] = [\"authentication\", \"assertionMethod\"];\n\n/** Same bound as an identity proof's subject (printable ASCII, no spaces). */\nexport const DID_MAX_LENGTH = 512;\n/** A fetched did.json. */\nexport const DID_DOCUMENT_MAX_BYTES = 64 * 1024;\n/** The statement file a did:web publishes beside its did.json. */\nexport const DID_FILE_MAX_BYTES = 16 * 1024;\nexport const DID_JWS_MAX_LENGTH = 4096;\n/** Entries read from each list of a document; the rest are ignored. */\nconst MAX_ENTRIES = 64;\n/** The service type a did.json uses to vouch for a Ghostly proof. */\nexport const DID_GHOSTLY_SERVICE = \"GhostlyIdentityProof\";\n\nexport interface DidKey {\n /** The verification method's absolute id: `<did>#<fragment>`. */\n id: string;\n curve: DidCurve;\n /** Ed25519: 32 bytes. secp256k1 and P-256: 33 bytes, compressed. */\n publicKey: Uint8Array;\n /** Empty when the document lists the key but not for authentication or assertionMethod. */\n relationships: DidRelationship[];\n}\n\n/** A `GhostlyIdentityProof` service: the document names a proof key and the statement id it vouches for. */\nexport interface DidGhostlyService { id: string; key: string; proof: string }\n\n/** What a DID document says, as far as Ghostly uses it. */\nexport interface DidDocumentView {\n did: string;\n keys: DidKey[];\n /** Verification methods Ghostly cannot use (other curves, key agreement keys, other DIDs' ids). */\n skipped: number;\n services: DidGhostlyService[];\n}\n\nconst METHOD_NAME = /^[a-z0-9]+$/;\nconst Z32_KEY = /^[ybndrfg8ejkmcpqxot1uwisza345h769]{52}$/;\nconst B64URL = /^[A-Za-z0-9_-]*$/;\nconst SEGMENT = /^[A-Za-z0-9._~-]{1,64}$/;\nconst HEX64 = /^[a-f0-9]{64}$/;\n\nconst METHOD_LIST = \"did:key, did:jwk, did:dht and did:web\";\n\n/** base64url without padding, strictly: decoding and encoding again gives the same text. */\nexport function strictBase64Url(value: string): Uint8Array {\n if (typeof value !== \"string\" || !B64URL.test(value) || value.length % 4 === 1) throw new DidError(\"Not base64url\");\n const pad = \"=\".repeat((4 - (value.length % 4)) % 4);\n const bytes = Uint8Array.from(atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\") + pad), c => c.charCodeAt(0));\n if (toBase64Url(bytes) !== value) throw new DidError(\"Not canonical base64url\");\n return bytes;\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\n\n// ---------------------------------------------------------------------------------------------\n// Syntax\n\nexport interface ParsedDid { did: string; method: DidMethod; id: string }\n\n/**\n * The DID a person typed, checked and in canonical form, or a message they can act on. Methods other than\n * the four Ghostly checks are refused with \"not supported yet\"; a DID URL (a `#fragment`, `?query` or\n * `/path`) is refused, since it names something inside a DID rather than the DID.\n */\nexport function parseDid(input: string): ParsedDid {\n if (typeof input !== \"string\") throw new DidError(\"Enter a DID, like did:key:z6Mk… or did:web:example.com\");\n const value = input.trim();\n if (!/^did:/i.test(value)) throw new DidError(\"Enter a DID, like did:key:z6Mk… or did:web:example.com\");\n if (value.length > DID_MAX_LENGTH) throw new DidError(`That DID is too long (at most ${DID_MAX_LENGTH} characters)`);\n if (/[#?/]/.test(value)) throw new DidError(\"Enter the DID alone, without a #fragment, ?query or /path\");\n const rest = value.slice(4);\n const colon = rest.indexOf(\":\");\n const method = colon > 0 ? rest.slice(0, colon) : \"\";\n const id = colon > 0 ? rest.slice(colon + 1) : \"\";\n if (!METHOD_NAME.test(method.toLowerCase()) || !id) throw new DidError(\"That is not a DID: it looks like did:<method>:<identifier>\");\n if (method !== method.toLowerCase() && DID_METHODS.includes(method.toLowerCase() as DidMethod)) throw new DidError(`Write the method in lowercase: did:${method.toLowerCase()}:…`);\n if (!DID_METHODS.includes(method as DidMethod)) throw new DidError(`did:${method} is not supported yet. Ghostly checks ${METHOD_LIST}.`);\n if (!/^[\\x21-\\x7e]+$/.test(id)) throw new DidError(\"A DID has no spaces or other special characters\");\n switch (method as DidMethod) {\n case \"key\": staticKey(`did:key:${id}`); return { did: `did:key:${id}`, method: \"key\", id };\n case \"jwk\": staticKey(`did:jwk:${id}`); return { did: `did:jwk:${id}`, method: \"jwk\", id };\n case \"dht\": {\n const key = id.toLowerCase();\n if (!Z32_KEY.test(key) || toZ32(fromZ32(key)) !== key) throw new DidError(\"A did:dht identifier is 52 z-base-32 characters\");\n return { did: `did:dht:${key}`, method: \"dht\", id: key };\n }\n case \"web\": {\n const web = parseWeb(id);\n return { did: `did:web:${web.id}`, method: \"web\", id: web.id };\n }\n }\n}\n\n/** The canonical form of a DID Ghostly checks (a lowercase did:web host, a lowercase did:dht key). */\nexport const normalizeDid = (input: string) => parseDid(input).did;\n\n// ---------------------------------------------------------------------------------------------\n// did:web\n\ninterface WebDid { id: string; host: string; port?: number; path: string[] }\n\nfunction parseWeb(id: string): WebDid {\n const [hostPart, ...path] = id.split(\":\");\n const portMatch = /^(.*)%3a(\\d{1,5})$/i.exec(hostPart);\n const hostInput = portMatch ? portMatch[1] : hostPart;\n if (/%/.test(hostInput)) throw new DidError(\"A did:web domain has no percent-encoding, other than %3A before a port\");\n let host: string;\n try { host = normalizeDomain(hostInput); } catch (e) { throw new DidError(`did:web: ${(e as Error).message}`); }\n if (hostInput.toLowerCase().replace(/\\.$/, \"\") !== host) throw new DidError(\"did:web: write the domain as ASCII (punycode for international names)\");\n let port: number | undefined;\n if (portMatch) {\n port = Number(portMatch[2]);\n if (!(port >= 1 && port <= 65535) || String(port) !== portMatch[2]) throw new DidError(\"did:web: that port is not valid\");\n }\n if (path.length > 8) throw new DidError(\"did:web: at most 8 path segments\");\n for (const segment of path) {\n if (!SEGMENT.test(segment) || segment === \".\" || segment === \"..\") throw new DidError(\"did:web: each path segment is letters, digits, dots, dashes, underscores or tildes\");\n }\n return { id: [`${host}${port ? `%3A${port}` : \"\"}`, ...path].join(\":\"), host, port, path };\n}\n\n/**\n * A did:web (or one of its URLs) as `parseDid` writes it: the domain in lowercase, the port's `%3a` written `%3A`.\n * A domain and percent-encoding are case-insensitive (RFC 3986), so a document may write either, and parseDid\n * lowercased what the person typed. The path and the fragment are left as they are; one parseDid refuses too.\n */\nconst webForm = (value: string) => {\n if (!value.startsWith(\"did:web:\")) return value;\n const at = value.indexOf(\"#\");\n const part = at < 0 ? value : value.slice(0, at);\n let did: string;\n // parseDid trims what was typed: a space in a document's id stays, and so it names no key.\n try { did = /^[\\x21-\\x7e]+$/.test(part) ? parseDid(part).did : part; } catch { did = part.replace(/%3a/g, \"%3A\"); }\n return at < 0 ? did : did + value.slice(at);\n};\n\nconst web = (did: string): WebDid => {\n const parsed = parseDid(did);\n if (parsed.method !== \"web\") throw new DidError(\"Not a did:web\");\n return parseWeb(parsed.id);\n};\n\n/** The host a did:web lives on (no port): the name looked up before contacting it. */\nexport const didWebHost = (did: string) => web(did).host;\nconst origin = (w: WebDid) => `https://${w.host}${w.port ? `:${w.port}` : \"\"}`;\n/** did:web → its did.json: `/.well-known/did.json` for a bare domain, `/<path>/did.json` otherwise. */\nexport function didWebDocumentUrl(did: string): string {\n const w = web(did);\n return `${origin(w)}/${w.path.length ? w.path.join(\"/\") : \".well-known\"}/did.json`;\n}\n/** Where a did:web publishes the statement of proof `proofId`: `ghostly/<id>.json` beside its did.json. */\nexport function didWebFileUrl(did: string, proofId: string): string {\n if (!HEX64.test(proofId)) throw new DidError(\"Invalid proof id\");\n const w = web(did);\n return `${origin(w)}/${w.path.length ? w.path.join(\"/\") : \".well-known\"}/ghostly/${proofId}.json`;\n}\n\n/** The body of that file: the DID and the exact statement text. */\nexport function didWebFile(did: string, statement: string): string {\n return JSON.stringify({ ghostly: 1, did, statement }, null, 2) + \"\\n\";\n}\n/** True when `text` is a statement file for exactly this DID and statement. */\nexport function didWebFileNames(text: string, did: string, statement: string): boolean {\n if (typeof text !== \"string\" || utf8Encode(text).length > DID_FILE_MAX_BYTES) return false;\n let body: unknown;\n try { body = JSON.parse(text); } catch { return false; }\n return isObject(body) && body.ghostly === 1 && typeof body.did === \"string\" && webForm(body.did) === did && body.statement === statement;\n}\n\n/** The service entry a did.json can carry instead of the file. */\nexport function didGhostlyServiceEntry(did: string, key: string, proofId: string): Record<string, unknown> {\n return { id: `${did}#ghostly-${proofId.slice(0, 12)}`, type: DID_GHOSTLY_SERVICE, serviceEndpoint: { key, proof: proofId } };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Keys\n\n/** Multicodec prefixes (unsigned varint) of the public keys Ghostly checks, and X25519 to name it when refused. */\nconst MULTICODEC: { prefix: [number, number]; curve: DidCurve | \"X25519\"; length: number }[] = [\n { prefix: [0xed, 0x01], curve: \"Ed25519\", length: 32 },\n { prefix: [0xe7, 0x01], curve: \"secp256k1\", length: 33 },\n { prefix: [0x80, 0x24], curve: \"P-256\", length: 33 },\n { prefix: [0xec, 0x01], curve: \"X25519\", length: 32 },\n];\n\n/** A public key on its curve, validated; ECDSA keys compressed. */\nfunction curveKey(curve: DidCurve, bytes: Uint8Array): Uint8Array {\n let smallOrder: boolean;\n try {\n if (curve !== \"Ed25519\") return (curve === \"secp256k1\" ? secp256k1 : p256).Point.fromBytes(bytes).toBytes(true);\n if (bytes.length !== 32) throw new Error();\n smallOrder = ed25519.Point.fromBytes(bytes).isSmallOrder();\n } catch { throw new DidError(`That ${curve} key is not a valid point`); }\n // No secret key goes with a point of small order, and one \"verifies\" a constant signature of any text.\n if (smallOrder) throw new DidError(\"That Ed25519 key is a point of small order, which no secret key goes with\");\n return bytes;\n}\n\n/** A `z…` multibase (base58btc) multicodec key. X25519 and unknown codecs are `undefined`. */\nfunction multikey(value: string): { curve: DidCurve; publicKey: Uint8Array } | { curve: \"X25519\" } | undefined {\n if (typeof value !== \"string\" || !value.startsWith(\"z\") || value.length > 128) return undefined;\n let bytes: Uint8Array;\n try { bytes = base58.decode(value.slice(1)); } catch { return undefined; }\n const codec = MULTICODEC.find(c => bytes[0] === c.prefix[0] && bytes[1] === c.prefix[1]);\n if (!codec || bytes.length !== codec.length + 2) return undefined;\n if (codec.curve === \"X25519\") return { curve: \"X25519\" };\n return { curve: codec.curve, publicKey: curveKey(codec.curve, bytes.subarray(2)) };\n}\n\nconst JWK_CURVES: Record<string, { kty: string; curve: DidCurve }> = {\n Ed25519: { kty: \"OKP\", curve: \"Ed25519\" },\n secp256k1: { kty: \"EC\", curve: \"secp256k1\" },\n \"P-256\": { kty: \"EC\", curve: \"P-256\" },\n};\n\n/** A public JWK. Other curves are `undefined`; a malformed one throws. */\nfunction jwkKey(jwk: unknown): { curve: DidCurve; publicKey: Uint8Array } | undefined {\n if (!isObject(jwk)) throw new DidError(\"That JWK is not an object\");\n const spec = typeof jwk.crv === \"string\" ? JWK_CURVES[jwk.crv] : undefined;\n if (!spec || jwk.kty !== spec.kty) return undefined;\n const coordinate = (v: unknown) => { const b = strictBase64Url(v as string); if (b.length !== 32) throw new DidError(\"JWK coordinates are 32 bytes\"); return b; };\n try {\n if (spec.curve === \"Ed25519\") return { curve: \"Ed25519\", publicKey: curveKey(\"Ed25519\", coordinate(jwk.x)) };\n return { curve: spec.curve, publicKey: curveKey(spec.curve, concatBytes(Uint8Array.of(4), coordinate(jwk.x), coordinate(jwk.y))) };\n } catch (e) { throw e instanceof DidError && /point/.test(e.message) ? e : new DidError(`That ${spec.curve} JWK is malformed`); }\n}\n\n/**\n * The single key of a did:key or did:jwk, from the identifier itself, as the method specs build their\n * documents: did:key's `#<multibase>` and did:jwk's `#0`, both for authentication and assertionMethod\n * (a did:jwk marked `\"use\": \"enc\"` is for encryption only).\n */\nfunction staticKey(did: string): DidKey {\n if (did.startsWith(\"did:key:\")) {\n const mb = did.slice(8);\n const key = multikey(mb);\n if (!key) throw new DidError(\"That did:key is not an Ed25519, secp256k1 or P-256 key Ghostly can read\");\n if (key.curve === \"X25519\") throw new DidError(\"That did:key is an X25519 encryption key: it cannot sign\");\n return { id: `${did}#${mb}`, curve: key.curve, publicKey: key.publicKey, relationships: [...RELATIONSHIPS] };\n }\n let jwk: unknown;\n try { jwk = JSON.parse(utf8Decode(strictBase64Url(did.slice(8)))); } catch { throw new DidError(\"That did:jwk does not hold a JSON Web Key\"); }\n if (!isObject(jwk)) throw new DidError(\"That did:jwk does not hold a JSON Web Key\");\n if (\"d\" in jwk || \"p\" in jwk || \"k\" in jwk) throw new DidError(\"That did:jwk contains a private key. Never share it: make a new key\");\n const key = jwkKey(jwk);\n if (!key) throw new DidError(\"That did:jwk is not an Ed25519, secp256k1 or P-256 key\");\n return { id: `${did}#0`, curve: key.curve, publicKey: key.publicKey, relationships: jwk.use === \"enc\" ? [] : [...RELATIONSHIPS] };\n}\n\n/** The document of a did:key or did:jwk, which needs no network. */\nexport function staticDidDocument(did: string): DidDocumentView {\n const parsed = parseDid(did);\n if (parsed.method !== \"key\" && parsed.method !== \"jwk\") throw new DidError(`did:${parsed.method} is resolved over the network`);\n return { did: parsed.did, keys: [staticKey(parsed.did)], skipped: 0, services: [] };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Documents\n\n/** An id as absolute `<did>#<fragment>`, from `#frag` or the absolute form; undefined for another DID's. */\nfunction methodId(did: string, id: unknown): string | undefined {\n if (typeof id !== \"string\" || id.length > DID_MAX_LENGTH + 128) return undefined;\n const absolute = id.startsWith(\"#\") ? `${did}${id}` : webForm(id);\n return absolute.startsWith(`${did}#`) && absolute.length > did.length + 1 && /^[\\x21-\\x7e]+$/.test(absolute) ? absolute : undefined;\n}\n\n/** Key material of one verification method: `publicKeyJwk`, `publicKeyMultibase` or (Ed25519 2018) `publicKeyBase58`. */\nfunction methodKey(vm: Record<string, unknown>): { curve: DidCurve; publicKey: Uint8Array } | undefined {\n try {\n if (vm.publicKeyJwk !== undefined) return jwkKey(vm.publicKeyJwk);\n if (typeof vm.publicKeyMultibase === \"string\") {\n const key = multikey(vm.publicKeyMultibase);\n if (key && key.curve !== \"X25519\") return key;\n // Ed25519VerificationKey2020 documents written before multicodec prefixes carry the raw 32 bytes.\n if (!key && vm.type === \"Ed25519VerificationKey2020\" && vm.publicKeyMultibase.startsWith(\"z\")) {\n const raw = base58.decode(vm.publicKeyMultibase.slice(1));\n if (raw.length === 32) return { curve: \"Ed25519\", publicKey: curveKey(\"Ed25519\", raw) };\n }\n return undefined;\n }\n if (typeof vm.publicKeyBase58 === \"string\" && vm.type === \"Ed25519VerificationKey2018\" && vm.publicKeyBase58.length <= 64) {\n return { curve: \"Ed25519\", publicKey: curveKey(\"Ed25519\", base58.decode(vm.publicKeyBase58)) };\n }\n } catch { return undefined; }\n return undefined;\n}\n\nconst list = (value: unknown, name: string): unknown[] => {\n if (value === undefined) return [];\n if (!Array.isArray(value)) throw new DidError(`The DID document's ${name} is not a list`);\n return value.slice(0, MAX_ENTRIES);\n};\n\n/**\n * A fetched or resolved DID document, strictly: it must be for exactly `did`; verification methods are\n * read from `verificationMethod` and from `authentication` / `assertionMethod` (references or embedded);\n * `GhostlyIdentityProof` services are kept. Keys Ghostly cannot use are counted in `skipped`.\n */\nexport function parseDidDocument(did: string, raw: unknown): DidDocumentView {\n if (!isObject(raw)) throw new DidError(\"The DID document is not a JSON object\");\n if (typeof raw.id !== \"string\" || webForm(raw.id) !== did) throw new DidError(typeof raw.id === \"string\" ? `The DID document is for another DID (${raw.id.slice(0, 80)})` : \"The DID document has no id\");\n const keys = new Map<string, DidKey>();\n const unusable = new Set<string>();\n let skipped = 0;\n const add = (vm: unknown): string | undefined => {\n if (!isObject(vm)) { skipped++; return undefined; }\n const id = methodId(did, vm.id);\n if (!id) { skipped++; return undefined; }\n if (keys.has(id) || unusable.has(id)) return id;\n const key = methodKey(vm);\n if (!key) { unusable.add(id); skipped++; return id; }\n keys.set(id, { id, ...key, relationships: [] });\n return id;\n };\n for (const vm of list(raw.verificationMethod, \"verificationMethod\")) add(vm);\n for (const relationship of RELATIONSHIPS) {\n for (const entry of list(raw[relationship], relationship)) {\n const id = typeof entry === \"string\" ? methodId(did, entry) : add(entry);\n const key = id ? keys.get(id) : undefined;\n if (key && !key.relationships.includes(relationship)) key.relationships.push(relationship);\n }\n }\n const services: DidGhostlyService[] = [];\n for (const s of list(raw.service, \"service\")) {\n if (!isObject(s)) continue;\n const types = Array.isArray(s.type) ? s.type : [s.type];\n const endpoint = s.serviceEndpoint;\n if (!types.includes(DID_GHOSTLY_SERVICE) || !isObject(endpoint)) continue;\n if (typeof endpoint.key === \"string\" && Z32_KEY.test(endpoint.key) && typeof endpoint.proof === \"string\" && HEX64.test(endpoint.proof))\n services.push({ id: typeof s.id === \"string\" ? s.id.slice(0, 200) : \"\", key: endpoint.key, proof: endpoint.proof });\n }\n return { did, keys: [...keys.values()].slice(0, MAX_ENTRIES), skipped, services: services.slice(0, 16) };\n}\n\n/** Keys that may sign for the DID. */\nexport const signingKeys = (doc: DidDocumentView) => doc.keys.filter(k => k.relationships.length > 0);\n\n// ---------------------------------------------------------------------------------------------\n// Signatures\n\n/** JWS `alg` values Ghostly checks, and the curve each needs (RFC 8037, RFC 8812, RFC 7518, RFC 9864's Ed25519). */\nexport const DID_JWS_ALGS: Record<string, DidCurve> = { EdDSA: \"Ed25519\", Ed25519: \"Ed25519\", ES256K: \"secp256k1\", ES256: \"P-256\" };\n/** The `alg` a person's tool should write for a key on this curve. */\nexport const didJwsAlg = (curve: DidCurve) => ({ Ed25519: \"EdDSA\", secp256k1: \"ES256K\", \"P-256\": \"ES256\" } as const)[curve];\n\nexport interface DidJws {\n alg: string;\n curve: DidCurve;\n kid?: string;\n /** RFC 7797: false signs the payload as it is (detached only). */\n b64: boolean;\n /** The protected header and payload segments as they were, for the signing input. */\n header: string;\n payload: string;\n signature: Uint8Array;\n}\n\n/** A compact JWS, attached or detached (`header..signature`), checked for shape only. */\nexport function parseDidJws(input: string): DidJws {\n const jws = typeof input === \"string\" ? input.trim() : \"\";\n if (!jws || jws.length > DID_JWS_MAX_LENGTH) throw new DidError(\"That is not a compact JWS\");\n const parts = jws.split(\".\");\n if (parts.length !== 3 || !parts[0] || !parts[2]) throw new DidError(\"A compact JWS has three parts separated by dots\");\n let header: unknown;\n try {\n const bytes = strictBase64Url(parts[0]);\n if (bytes.length > 2048) throw new Error();\n header = JSON.parse(utf8Decode(bytes));\n } catch { throw new DidError(\"The JWS header is not base64url JSON\"); }\n if (!isObject(header)) throw new DidError(\"The JWS header is not a JSON object\");\n const alg = header.alg;\n // The reasons here are shown on the checking side: never a word the signer chose (alg, kid, key ids), only what is wrong.\n if (typeof alg !== \"string\" || !DID_JWS_ALGS[alg]) throw new DidError(`The JWS uses ${typeof alg === \"string\" ? \"another algorithm\" : \"no algorithm\"}: Ghostly checks EdDSA, ES256K and ES256`);\n if (header.kid !== undefined && (typeof header.kid !== \"string\" || header.kid.length > DID_MAX_LENGTH + 128)) throw new DidError(\"The JWS kid is not a key id\");\n if (header.b64 !== undefined && typeof header.b64 !== \"boolean\") throw new DidError(\"The JWS b64 header is not true or false\");\n const crit = header.crit;\n if (crit !== undefined && (!Array.isArray(crit) || !crit.length || crit.some(c => c !== \"b64\"))) throw new DidError(\"The JWS requires an extension Ghostly does not know (crit)\");\n const b64 = header.b64 !== false;\n if (!b64 && !(Array.isArray(crit) && crit.includes(\"b64\"))) throw new DidError(\"A JWS with b64 false must list it in crit\");\n if (!b64 && parts[1]) throw new DidError(\"A JWS with b64 false must be detached (header..signature)\");\n let signature: Uint8Array;\n try { signature = strictBase64Url(parts[2]); } catch { throw new DidError(\"The JWS signature is not base64url\"); }\n if (signature.length !== 64) throw new DidError(`A ${alg} signature is 64 bytes`);\n if (parts[1]) { try { strictBase64Url(parts[1]); } catch { throw new DidError(\"The JWS payload is not base64url\"); } }\n return { alg, curve: DID_JWS_ALGS[alg], kid: header.kid as string | undefined, b64, header: parts[0], payload: parts[1], signature };\n}\n\n/** What a JWS signs for one candidate message: its own payload when attached (which must be that message). */\nfunction signingInput(jws: DidJws, message: Uint8Array): Uint8Array | undefined {\n if (jws.payload) return bytesEqual(strictBase64Url(jws.payload), message) ? utf8Encode(`${jws.header}.${jws.payload}`) : undefined;\n return jws.b64 ? utf8Encode(`${jws.header}.${toBase64Url(message)}`) : concatBytes(utf8Encode(`${jws.header}.`), message);\n}\n\nfunction verifyWith(key: DidKey, signature: Uint8Array, message: Uint8Array, format: \"compact\" | \"der\" = \"compact\"): boolean {\n try {\n if (key.curve === \"Ed25519\") return format === \"compact\" && ed25519.verify(signature, message, key.publicKey, { zip215: false });\n // ECDSA over SHA-256 of the message, either half of s (JOSE does not require low S).\n return (key.curve === \"secp256k1\" ? secp256k1 : p256).verify(signature, message, key.publicKey, { prehash: true, lowS: false, format });\n } catch { return false; }\n}\n\nexport interface DidSignatureCheck { key: DidKey; alg: string }\n\nconst refusedKey = () => new DidError(\"Signed by a key the DID document does not list under authentication or assertionMethod\");\n\n/**\n * Which key of `doc` made this JWS over one of `messages` (the statement, and the statement with a\n * trailing newline some tools add). With a `kid`, only that key is tried. Refused unless the key is\n * listed for authentication or assertionMethod.\n */\nexport function checkDidJws(input: string, messages: Uint8Array[], doc: DidDocumentView): DidSignatureCheck {\n const jws = parseDidJws(input);\n let candidates = doc.keys.filter(k => k.curve === jws.curve);\n if (jws.kid !== undefined) {\n const kid = methodId(doc.did, jws.kid);\n if (!kid) throw new DidError(`The JWS names a key that is not a key of ${doc.did}`);\n candidates = candidates.filter(k => k.id === kid);\n if (!candidates.length) throw new DidError(doc.keys.some(k => k.id === kid) ? `The key the JWS names is not a ${jws.curve} key: the JWS says ${jws.alg}` : \"The DID document does not list the key the JWS names\");\n }\n if (!candidates.length) throw new DidError(`The DID document lists no ${jws.curve} key for ${jws.alg}`);\n let inputs: Uint8Array[];\n try { inputs = messages.map(m => signingInput(jws, m)).filter((m): m is Uint8Array => !!m); } catch { inputs = []; }\n if (!inputs.length) throw new DidError(\"The JWS carries another text: sign exactly the statement shown\");\n // The same key may be listed under several ids: one that may not sign does not end the search.\n let refused: DidKey | undefined;\n for (const key of candidates) {\n if (!inputs.some(m => verifyWith(key, jws.signature, m))) continue;\n if (!key.relationships.length) { refused ??= key; continue; }\n return { key, alg: jws.alg };\n }\n if (refused) throw refusedKey();\n throw new DidError(\"The JWS signature does not match: sign exactly the statement shown, with a key of this DID\");\n}\n\n/**\n * Which key of `doc` made this raw signature over one of `messages`: Ed25519 (64 bytes), or ECDSA with\n * SHA-256 on secp256k1 or P-256 (64 bytes r‖s, or DER as OpenSSL writes it). `vm` narrows it to one key.\n * Returns the signature in its canonical form (r‖s for ECDSA).\n */\nexport function checkDidSignature(signature: Uint8Array, messages: Uint8Array[], doc: DidDocumentView, vm?: string): DidSignatureCheck & { signature: Uint8Array } {\n let candidates = doc.keys;\n if (vm !== undefined) {\n const id = methodId(doc.did, vm);\n if (!id) throw new DidError(`The proof names a key that is not a key of ${doc.did}`);\n candidates = candidates.filter(k => k.id === id);\n if (!candidates.length) throw new DidError(\"The DID document does not list the key the proof names\");\n }\n const der = signature.length !== 64 && signature[0] === 0x30;\n if (signature.length !== 64 && !der) throw new DidError(\"A signature is 64 bytes (or DER, for ECDSA)\");\n let refused: DidKey | undefined;\n for (const key of candidates) {\n if (der && key.curve === \"Ed25519\") continue;\n if (!messages.some(m => verifyWith(key, signature, m, der ? \"der\" : \"compact\"))) continue;\n if (!key.relationships.length) { refused ??= key; continue; }\n const canonical = der ? (key.curve === \"secp256k1\" ? secp256k1 : p256).Signature.fromBytes(signature, \"der\").toBytes(\"compact\") : signature;\n return { key, alg: key.curve === \"Ed25519\" ? \"Ed25519\" : `ECDSA ${key.curve}`, signature: canonical };\n }\n if (refused) throw refusedKey();\n throw new DidError(\"The signature does not match: sign exactly the statement shown, with a key of this DID\");\n}\n\n/**\n * What a person pasted as a signature: a compact JWS, or a raw signature (hex, base64 or base64url),\n * optionally after the verification method id (`did:…#key-1 <signature>` or `#key-1 <signature>`).\n */\nexport type DidSignaturePaste = { kind: \"jws\"; jws: string } | { kind: \"raw\"; vm?: string; signature: Uint8Array };\n\nexport function parseDidSignaturePaste(pasted: string): DidSignaturePaste {\n const tokens = (typeof pasted === \"string\" ? pasted : \"\").trim().split(/\\s+/).filter(Boolean);\n if (!tokens.length) throw new DidError(\"Paste the signature\");\n // A JWS or signature split over several lines (base64 wrapped at 76 characters) comes back together.\n const vm = tokens.length > 1 && /^(did:|#)/.test(tokens[0]) ? tokens[0] : undefined;\n const text = (vm ? tokens.slice(1) : tokens).join(\"\");\n if (text.split(\".\").length === 3) {\n if (vm) throw new DidError(\"Paste the JWS alone: its header names the key (kid)\");\n return { kind: \"jws\", jws: text };\n }\n if (text.length > 400) throw new DidError(\"That is too long for a signature\");\n let signature: Uint8Array | undefined;\n if (/^(?:[0-9a-fA-F]{2})+$/.test(text)) signature = Uint8Array.from(text.match(/../g)!, h => parseInt(h, 16));\n else {\n const url = text.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n try { signature = strictBase64Url(url); } catch { signature = undefined; }\n }\n if (!signature) throw new DidError(\"That is not a signature: paste a JWS, or a signature in hex or base64\");\n return { kind: \"raw\", vm, signature };\n}\n\n/** The statement bytes a signature may cover: exactly the statement, or with the newline `echo` adds. */\nexport const didSignedMessages = (statement: string) => [utf8Encode(statement), utf8Encode(`${statement}\\n`)];\n","import { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32, bech32m, createBase58check } from \"@scure/base\";\nimport { concatBytes } from \"./bytes\";\n\n/**\n * The little of Bitcoin's address and transaction formats a message-signature verifier needs: decoding an\n * address to its output script, and (de)serialising the two virtual transactions of BIP-322. Nothing here\n * builds, signs or broadcasts a real transaction.\n */\n\n/** Which addresses a proof may name: the real network, or any of the test networks (testnet, signet, regtest…). */\nexport type BitcoinProofNetwork = \"mainnet\" | \"testnet\";\nexport type BitcoinScriptType = \"p2pkh\" | \"p2sh\" | \"p2wpkh\" | \"p2wsh\" | \"p2tr\" | \"witness-unknown\";\n\nexport interface BitcoinAddressInfo {\n address: string;\n type: BitcoinScriptType;\n network: BitcoinProofNetwork;\n /** The output script paying this address. */\n scriptPubKey: Uint8Array;\n /** The key/script hash of a base58 address, or the witness program of a SegWit one. */\n program: Uint8Array;\n witnessVersion?: number;\n}\n\nconst base58check = createBase58check(sha256);\nexport const sha256d = (...parts: Uint8Array[]) => sha256(sha256(concatBytes(...parts)));\nexport const hash160 = (data: Uint8Array) => ripemd160(sha256(data));\n\n/** Base58 versions: P2PKH, P2SH. Every test network (testnet3/4, signet, mutinynet, regtest) shares one pair. */\nconst BASE58 = { mainnet: [0x00, 0x05], testnet: [0x6f, 0xc4] } as const;\nconst HRP = { mainnet: [\"bc\"], testnet: [\"tb\", \"bcrt\"] } as const;\n\nfunction decodeSegwit(address: string): { hrp: string; version: number; program: Uint8Array } | undefined {\n // BIP 173: one case only; the checksum is over the lower-case form.\n if (address !== address.toLowerCase() && address !== address.toUpperCase()) return undefined;\n const lower = address.toLowerCase() as `${string}1${string}`;\n for (const [coder, v0] of [[bech32, true], [bech32m, false]] as const) {\n let decoded: { prefix: string; words: number[] };\n try { decoded = coder.decode(lower, 90); } catch { continue; }\n if (decoded.words.length < 1) return undefined;\n const version = decoded.words[0];\n // Version 0 is bech32 (BIP 173), every later version bech32m (BIP 350); the wrong one is refused.\n if (version > 16 || (version === 0) !== v0) return undefined;\n let program: Uint8Array;\n try { program = coder.fromWords(decoded.words.slice(1)); } catch { return undefined; }\n if (program.length < 2 || program.length > 40 || (version === 0 && program.length !== 20 && program.length !== 32)) return undefined;\n return { hrp: decoded.prefix, version, program };\n }\n return undefined;\n}\n\n/** An address refused, with a reason fit to show the person. */\nexport class BitcoinAddressError extends Error {}\n\n/** Decodes `address` for `network`, or throws a `BitcoinAddressError` saying what is wrong with it. */\nexport function decodeBitcoinAddress(address: string, network: BitcoinProofNetwork): BitcoinAddressInfo {\n if (typeof address !== \"string\" || address.length < 14 || address.length > 90) throw new BitcoinAddressError(\"Not a Bitcoin address\");\n const other: BitcoinProofNetwork = network === \"mainnet\" ? \"testnet\" : \"mainnet\";\n const wrongNetwork = () => new BitcoinAddressError(network === \"mainnet\"\n ? \"This is a test-network address; switch the wallets to Testnet to use it\"\n : \"This is a mainnet address; switch the wallets to Mainnet to use it\");\n const segwit = decodeSegwit(address);\n if (segwit) {\n if (!(HRP[network] as readonly string[]).includes(segwit.hrp)) {\n if ((HRP[other] as readonly string[]).includes(segwit.hrp)) throw wrongNetwork();\n throw new BitcoinAddressError(\"Not a Bitcoin address\");\n }\n const { version, program } = segwit;\n const type: BitcoinScriptType = version === 0 ? (program.length === 20 ? \"p2wpkh\" : \"p2wsh\") : version === 1 && program.length === 32 ? \"p2tr\" : \"witness-unknown\";\n const scriptPubKey = concatBytes(Uint8Array.of(version === 0 ? 0x00 : 0x50 + version, program.length), program);\n return { address, type, network, scriptPubKey, program, witnessVersion: version };\n }\n let payload: Uint8Array;\n try { payload = base58check.decode(address); } catch { throw new BitcoinAddressError(\"Not a Bitcoin address (bad checksum?)\"); }\n if (payload.length !== 21) throw new BitcoinAddressError(\"Not a Bitcoin address\");\n const [pkh, sh] = BASE58[network];\n const hash = payload.slice(1);\n if (payload[0] === pkh) return { address, type: \"p2pkh\", network, program: hash, scriptPubKey: concatBytes(Uint8Array.of(0x76, 0xa9, 0x14), hash, Uint8Array.of(0x88, 0xac)) };\n if (payload[0] === sh) return { address, type: \"p2sh\", network, program: hash, scriptPubKey: concatBytes(Uint8Array.of(0xa9, 0x14), hash, Uint8Array.of(0x87)) };\n if ((BASE58[other] as readonly number[]).includes(payload[0])) throw wrongNetwork();\n throw new BitcoinAddressError(\"Not a Bitcoin address\");\n}\n\n// ---- Transactions (consensus serialisation) ----\n\nexport interface TxInput { txid: Uint8Array; vout: number; scriptSig: Uint8Array; sequence: number; witness: Uint8Array[] }\nexport interface TxOutput { value: bigint; script: Uint8Array }\nexport interface Tx { version: number; inputs: TxInput[]; outputs: TxOutput[]; lockTime: number }\n\nexport function compactSize(n: number): Uint8Array {\n if (n < 0xfd) return Uint8Array.of(n);\n if (n <= 0xffff) return Uint8Array.of(0xfd, n & 0xff, n >>> 8);\n if (n <= 0xffffffff) { const b = new Uint8Array(5); b[0] = 0xfe; new DataView(b.buffer).setUint32(1, n, true); return b; }\n throw new Error(\"Too large\");\n}\nexport const varBytes = (b: Uint8Array) => concatBytes(compactSize(b.length), b);\nexport const u32 = (n: number) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n >>> 0, true); return b; };\nexport const u64 = (n: bigint) => { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, n, true); return b; };\n\nexport function encodeTx(tx: Tx, withWitness = tx.inputs.some(i => i.witness.length > 0)): Uint8Array {\n const parts: Uint8Array[] = [u32(tx.version)];\n if (withWitness) parts.push(Uint8Array.of(0x00, 0x01));\n parts.push(compactSize(tx.inputs.length));\n for (const i of tx.inputs) parts.push(i.txid, u32(i.vout), varBytes(i.scriptSig), u32(i.sequence));\n parts.push(compactSize(tx.outputs.length));\n for (const o of tx.outputs) parts.push(u64(o.value), varBytes(o.script));\n if (withWitness) for (const i of tx.inputs) parts.push(encodeWitness(i.witness));\n parts.push(u32(tx.lockTime));\n return concatBytes(...parts);\n}\nexport const encodeWitness = (stack: Uint8Array[]) => concatBytes(compactSize(stack.length), ...stack.map(varBytes));\n/** The id other transactions refer to it by, in internal byte order (reverse it for display). */\nexport const txHash = (tx: Tx) => sha256d(encodeTx(tx, false));\n\n/** A strict reader: canonical sizes only, and the whole input must be consumed. */\nexport class ByteReader {\n private at = 0;\n constructor(private bytes: Uint8Array) {}\n get done() { return this.at === this.bytes.length; }\n take(n: number): Uint8Array {\n if (!Number.isSafeInteger(n) || n < 0 || this.at + n > this.bytes.length) throw new Error(\"Truncated data\");\n const out = this.bytes.slice(this.at, this.at + n);\n this.at += n;\n return out;\n }\n peek(): number { if (this.done) throw new Error(\"Truncated data\"); return this.bytes[this.at]; }\n u32(): number { return new DataView(this.take(4).buffer).getUint32(0, true); }\n i32(): number { return new DataView(this.take(4).buffer).getInt32(0, true); }\n u64(): bigint { return new DataView(this.take(8).buffer).getBigUint64(0, true); }\n compactSize(): number {\n const first = this.take(1)[0];\n const [n, min] = first < 0xfd ? [first, 0] : first === 0xfd ? [new DataView(this.take(2).buffer).getUint16(0, true), 0xfd]\n : first === 0xfe ? [this.u32(), 0x10000] : [Number(this.u64()), 0x100000000];\n if (n < min || n > 0x02000000) throw new Error(\"Non-canonical size\");\n return n;\n }\n varBytes(): Uint8Array { return this.take(this.compactSize()); }\n end() { if (!this.done) throw new Error(\"Unexpected trailing data\"); }\n}\n\nexport function decodeWitness(bytes: Uint8Array): Uint8Array[] {\n const r = new ByteReader(bytes);\n const stack = readWitness(r);\n r.end();\n return stack;\n}\nfunction readWitness(r: ByteReader): Uint8Array[] {\n const n = r.compactSize();\n return Array.from({ length: n }, () => r.varBytes());\n}\n\nexport function decodeTx(bytes: Uint8Array): Tx {\n const r = new ByteReader(bytes);\n const version = r.i32();\n let segwit = false;\n if (r.peek() === 0x00) {\n r.take(1);\n if (r.take(1)[0] !== 0x01) throw new Error(\"Unknown transaction flag\");\n segwit = true;\n }\n const inputs: TxInput[] = Array.from({ length: r.compactSize() }, () => ({ txid: r.take(32), vout: r.u32(), scriptSig: r.varBytes(), sequence: r.u32(), witness: [] }));\n const outputs: TxOutput[] = Array.from({ length: r.compactSize() }, () => ({ value: r.u64(), script: r.varBytes() }));\n if (segwit) {\n for (const input of inputs) input.witness = readWitness(r);\n // A witness flag with nothing in it is a non-canonical serialisation (Bitcoin Core refuses it).\n if (inputs.every(i => i.witness.length === 0)) throw new Error(\"Superfluous witness flag\");\n }\n const lockTime = r.u32();\n r.end();\n return { version, inputs, outputs, lockTime };\n}\n\n/** The address decoded on whichever network it belongs to (mainnet first), or a `BitcoinAddressError`. */\nexport function decodeAnyBitcoinAddress(address: string): BitcoinAddressInfo {\n try { return decodeBitcoinAddress(address, \"mainnet\"); } catch (e) {\n if (!(e instanceof BitcoinAddressError) || !/test-network/.test(e.message)) throw e;\n return decodeBitcoinAddress(address, \"testnet\");\n }\n}\n","import { schnorr, secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToNumberBE } from \"@noble/curves/utils.js\";\nimport { base64 } from \"@scure/base\";\nimport { bytesEqual, concatBytes, utf8Encode } from \"./bytes\";\nimport {\n type BitcoinAddressInfo, type Tx, decodeTx, decodeWitness, encodeTx, hash160, sha256d, txHash, u32, u64, varBytes,\n} from \"./bitcoinScript\";\n\n/**\n * BIP-322 \"Generic Signed Message Format\", verification only, pinned to **version 2.0.0** of the BIP\n * (bitcoin/bips commit 4061a54418f62a5a1ae44f4604e56373329bfad3, 2026-06-05), whose official test vectors\n * are in packages/core/test/fixtures/bip322/.\n *\n * Without a full script interpreter, this verifier checks the scripts it understands and says\n * \"inconclusive\" for the rest, as the BIP allows:\n *\n * - P2WPKH (bc1q…, 42 chars) simple and full\n * - P2TR (bc1p…) key path simple and full\n * - P2SH-P2WPKH (3…) full only: the simple format is for native SegWit\n * - P2PKH (1…) full only\n *\n * Multisig and other scripts (P2WSH, bare P2SH, Taproot script path) and proofs of funds (`pof`) are\n * inconclusive, which a proof treats as not proven.\n */\nexport const BIP322_REVISION = \"2.0.0 (bitcoin/bips@4061a54418f62a5a1ae44f4604e56373329bfad3)\";\n\nexport type Bip322Format = \"bip322-simple\" | \"bip322-full\";\nexport type BitcoinProofScript = \"p2pkh\" | \"p2wpkh\" | \"p2sh-p2wpkh\" | \"p2tr\";\nexport interface Bip322Valid {\n format: Bip322Format;\n script: BitcoinProofScript;\n /** The full format's nLockTime and first nSequence, when the signer set them (BIP-322: \"valid at time T and age S\"). */\n lockTime?: number;\n sequence?: number;\n}\nexport type BitcoinMessageVerdict =\n | ({ state: \"valid\" } & (Bip322Valid | { format: \"legacy\"; script: \"p2pkh\" }))\n /** Something checked failed: wrong key, message, address or a malformed signature. */\n | { state: \"invalid\"; reason: string }\n /** Maybe valid, but not something this verifier can check (a multisig, a time lock…). Never treat as proven. */\n | { state: \"inconclusive\"; reason: string };\n\n/** A refusal while verifying; `inconclusive` for what cannot be checked rather than what failed. */\nexport class MessageRefusal extends Error {\n constructor(readonly state: \"invalid\" | \"inconclusive\", reason: string) { super(reason); }\n}\nconst invalid = (reason: string) => new MessageRefusal(\"invalid\", reason);\nconst inconclusive = (reason: string) => new MessageRefusal(\"inconclusive\", reason);\n\nconst SIGHASH_DEFAULT = 0x00;\nconst SIGHASH_ALL = 0x01;\nconst OP_RETURN = Uint8Array.of(0x6a);\nconst ZERO32 = new Uint8Array(32);\n\nexport const bip322MessageHash = (message: string) => schnorr.utils.taggedHash(\"BIP0322-signed-message\", utf8Encode(message));\n\n/** The virtual transaction whose only output pays the address; `to_sign` spends it. */\nexport function bip322ToSpend(message: string, scriptPubKey: Uint8Array): Tx {\n return {\n version: 0, lockTime: 0,\n inputs: [{ txid: ZERO32, vout: 0xffffffff, sequence: 0, witness: [], scriptSig: concatBytes(Uint8Array.of(0x00, 0x20), bip322MessageHash(message)) }],\n outputs: [{ value: 0n, script: scriptPubKey }],\n };\n}\n\n/** `to_sign` with every field at the default the simple format assumes. */\nexport function bip322ToSign(toSpend: Tx, witness: Uint8Array[] = []): Tx {\n return {\n version: 0, lockTime: 0,\n inputs: [{ txid: txHash(toSpend), vout: 0, sequence: 0, scriptSig: new Uint8Array(0), witness }],\n outputs: [{ value: 0n, script: OP_RETURN }],\n };\n}\n\n/** Standard base64, whitespace (a pasted line break) ignored; missing padding tolerated. */\nexport function decodeBase64(text: string): Uint8Array {\n const clean = text.replace(/\\s+/g, \"\");\n const padded = clean.length % 4 === 0 ? clean : clean + \"=\".repeat(4 - (clean.length % 4));\n try { return base64.decode(padded); } catch { throw invalid(\"The signature is not valid base64\"); }\n}\n\n// ---- Signature hashes, for the one input BIP-322 signs ----\n\n/** BIP 143, for witness v0. `scriptCode` is the P2PKH script of the key. */\nfunction sighashV0(tx: Tx, scriptCode: Uint8Array, hashType: number): Uint8Array {\n const input = tx.inputs[0];\n return sha256d(\n u32(tx.version),\n sha256d(...tx.inputs.map(i => concatBytes(i.txid, u32(i.vout)))),\n sha256d(...tx.inputs.map(i => u32(i.sequence))),\n input.txid, u32(input.vout), varBytes(scriptCode), u64(0n), u32(input.sequence),\n sha256d(...tx.outputs.map(o => concatBytes(u64(o.value), varBytes(o.script)))),\n u32(tx.lockTime), u32(hashType),\n );\n}\n\n/** BIP 341 key path, SIGHASH_DEFAULT or SIGHASH_ALL, no annex. */\nfunction sighashV1(tx: Tx, scriptPubKey: Uint8Array, hashType: number): Uint8Array {\n const input = tx.inputs[0];\n return schnorr.utils.taggedHash(\"TapSighash\", concatBytes(\n Uint8Array.of(0x00, hashType), u32(tx.version), u32(tx.lockTime),\n sha256(concatBytes(input.txid, u32(input.vout))),\n sha256(u64(0n)),\n sha256(varBytes(scriptPubKey)),\n sha256(u32(input.sequence)),\n sha256(concatBytes(...tx.outputs.map(o => concatBytes(u64(o.value), varBytes(o.script))))),\n Uint8Array.of(0x00), u32(0),\n ));\n}\n\n/** The original sighash, for P2PKH: the input's script replaced by the spent output's, the rest as is. */\nfunction sighashLegacy(tx: Tx, scriptPubKey: Uint8Array, hashType: number): Uint8Array {\n const copy: Tx = { ...tx, inputs: tx.inputs.map((i, n) => ({ ...i, witness: [], scriptSig: n === 0 ? scriptPubKey : new Uint8Array(0) })) };\n return sha256d(encodeTx(copy, false), u32(hashType));\n}\n\n// ---- Script checks ----\n\n/** A check that throws on malformed input (a point off the curve…) simply does not hold. */\nfunction holds(check: () => boolean): boolean {\n try { return check(); } catch { return false; }\n}\n\n/** BIP 66 strict DER, the signature still carrying its sighash byte (Bitcoin Core's IsValidSignatureEncoding). */\nfunction isStrictDer(sig: Uint8Array): boolean {\n if (sig.length < 9 || sig.length > 73 || sig[0] !== 0x30 || sig[1] !== sig.length - 3 || sig[2] !== 0x02) return false;\n const lenR = sig[3];\n if (lenR === 0 || 5 + lenR >= sig.length) return false;\n const lenS = sig[5 + lenR];\n if (lenS === 0 || lenR + lenS + 7 !== sig.length || sig[4 + lenR] !== 0x02) return false;\n if (sig[4] & 0x80 || (lenR > 1 && sig[4] === 0x00 && !(sig[5] & 0x80))) return false;\n if (sig[6 + lenR] & 0x80 || (lenS > 1 && sig[6 + lenR] === 0x00 && !(sig[7 + lenR] & 0x80))) return false;\n return true;\n}\n\n/** An ECDSA check with BIP-322's required rules: SIGHASH_ALL, strict DER, low S, a valid public key. */\nfunction checkEcdsa(sigWithType: Uint8Array, pubkey: Uint8Array, sighash: (hashType: number) => Uint8Array, compressedOnly: boolean) {\n if (sigWithType.length === 0) throw invalid(\"The signature is empty\");\n const valid = pubkey.length === 33 ? pubkey[0] === 0x02 || pubkey[0] === 0x03 : pubkey.length === 65 && !compressedOnly && pubkey[0] === 0x04;\n if (!valid) throw invalid(\"The signature carries a malformed public key\");\n const hashType = sigWithType[sigWithType.length - 1];\n if (hashType !== SIGHASH_ALL) throw invalid(\"BIP-322 signatures must use SIGHASH_ALL\");\n if (!isStrictDer(sigWithType)) throw invalid(\"The signature is not strictly DER-encoded\");\n if (!holds(() => secp256k1.verify(sigWithType.subarray(0, -1), sighash(hashType), pubkey, { prehash: false, lowS: true, format: \"der\" })))\n throw invalid(\"The signature does not match this address and message\");\n}\n\nconst P2PKH_SCRIPT = (hash: Uint8Array) => concatBytes(Uint8Array.of(0x76, 0xa9, 0x14), hash, Uint8Array.of(0x88, 0xac));\n\nfunction checkP2wpkh(tx: Tx, program: Uint8Array) {\n const witness = tx.inputs[0].witness;\n if (witness.length !== 2) throw invalid(\"The signature does not match this address and message\");\n const [sig, pubkey] = witness;\n if (pubkey.length !== 33 || !bytesEqual(hash160(pubkey), program)) throw invalid(\"The signature does not match this address and message\");\n checkEcdsa(sig, pubkey, t => sighashV0(tx, P2PKH_SCRIPT(program), t), true);\n}\n\n/**\n * Whether a script-path witness commits to `outputKey` (BIP 341). When it does, a script runs that this\n * verifier cannot interpret; when it does not, the spend fails whatever the script says.\n */\nfunction commitsToOutputKey(stack: Uint8Array[], outputKey: Uint8Array): boolean {\n const control = stack[stack.length - 1], script = stack[stack.length - 2];\n if (control.length < 33 || (control.length - 33) % 32 !== 0 || control.length > 33 + 32 * 128) return false;\n try {\n const internal = schnorr.utils.lift_x(bytesToNumberBE(control.subarray(1, 33)));\n let node = schnorr.utils.taggedHash(\"TapLeaf\", Uint8Array.of(control[0] & 0xfe), varBytes(script));\n for (let at = 33; at < control.length; at += 32) {\n const sibling = control.subarray(at, at + 32);\n node = schnorr.utils.taggedHash(\"TapBranch\", ...(compareBytes(node, sibling) < 0 ? [node, sibling] : [sibling, node]));\n }\n const tweak = bytesToNumberBE(schnorr.utils.taggedHash(\"TapTweak\", control.subarray(1, 33), node));\n if (tweak >= secp256k1.Point.Fn.ORDER) return false;\n const q = internal.add(secp256k1.Point.BASE.multiply(tweak)).toAffine();\n return q.x === bytesToNumberBE(outputKey) && Number(q.y & 1n) === (control[0] & 1);\n } catch { return false; }\n}\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] - b[i];\n return 0;\n}\n\nfunction checkP2tr(tx: Tx, scriptPubKey: Uint8Array, outputKey: Uint8Array) {\n const witness = tx.inputs[0].witness;\n if (witness.length === 0) throw invalid(\"The signature does not match this address and message\");\n if (witness.length > 1) {\n if (witness[witness.length - 1][0] === 0x50) throw inconclusive(\"Taproot signatures with an annex cannot be checked here\");\n if (commitsToOutputKey(witness, outputKey)) throw inconclusive(\"Taproot script-path signatures cannot be checked here; sign with the address's key path\");\n throw invalid(\"The signature does not match this address and message\");\n }\n const sig = witness[0];\n let hashType: number;\n if (sig.length === 64) hashType = SIGHASH_DEFAULT;\n else if (sig.length === 65 && sig[64] === SIGHASH_ALL) hashType = SIGHASH_ALL;\n else if (sig.length === 65) throw invalid(\"BIP-322 signatures must use SIGHASH_ALL or SIGHASH_DEFAULT\");\n else throw invalid(\"The signature does not match this address and message\");\n if (!holds(() => schnorr.verify(sig.subarray(0, 64), sighashV1(tx, scriptPubKey, hashType), outputKey)))\n throw invalid(\"The signature does not match this address and message\");\n}\n\n/** Exactly two direct pushes, as P2PKH's scriptSig: `<sig> <pubkey>` (MINIMALDATA holds for these sizes). */\nfunction parseTwoPushes(script: Uint8Array): [Uint8Array, Uint8Array] {\n const items: Uint8Array[] = [];\n for (let at = 0; at < script.length;) {\n const n = script[at];\n if (n < 1 || n > 75 || at + 1 + n > script.length) throw invalid(\"The signature does not match this address and message\");\n items.push(script.subarray(at + 1, at + 1 + n));\n at += 1 + n;\n }\n if (items.length !== 2) throw invalid(\"The signature does not match this address and message\");\n return [items[0], items[1]];\n}\n\nfunction checkInput(tx: Tx, address: BitcoinAddressInfo): BitcoinProofScript {\n const input = tx.inputs[0];\n const { scriptPubKey, program } = address;\n switch (address.type) {\n case \"p2wpkh\":\n if (input.scriptSig.length) throw invalid(\"A native SegWit input carries no scriptSig\");\n checkP2wpkh(tx, program);\n return \"p2wpkh\";\n case \"p2tr\":\n if (input.scriptSig.length) throw invalid(\"A native SegWit input carries no scriptSig\");\n checkP2tr(tx, scriptPubKey, program);\n return \"p2tr\";\n case \"p2pkh\": {\n if (input.witness.length) throw invalid(\"A P2PKH input carries no witness\");\n const [sig, pubkey] = parseTwoPushes(input.scriptSig);\n if (!bytesEqual(hash160(pubkey), program)) throw invalid(\"The signature does not match this address and message\");\n checkEcdsa(sig, pubkey, t => sighashLegacy(tx, scriptPubKey, t), false);\n return \"p2pkh\";\n }\n case \"p2sh\": {\n // Only P2SH-P2WPKH: the scriptSig is exactly one push of `0 <20-byte key hash>`.\n const s = input.scriptSig;\n if (s.length !== 23 || s[0] !== 22 || s[1] !== 0x00 || s[2] !== 0x14)\n throw inconclusive(\"Only P2SH-wrapped single-key SegWit (P2SH-P2WPKH) can be checked here, not a multisig or other script\");\n const redeem = s.subarray(1);\n if (!bytesEqual(hash160(redeem), program)) throw invalid(\"The signature does not match this address and message\");\n checkP2wpkh(tx, redeem.subarray(2));\n return \"p2sh-p2wpkh\";\n }\n case \"p2wsh\":\n throw inconclusive(\"Script (P2WSH) addresses such as multisig cannot be checked here\");\n default:\n throw inconclusive(\"This address type cannot be checked here\");\n }\n}\n\n/** Checks a BIP-322 signature — `smp…`, `ful…`, or an unprefixed one read as simple — or throws a `MessageRefusal`. */\nexport function verifyBip322(address: BitcoinAddressInfo, message: string, signature: string): Bip322Valid {\n const text = signature.trim();\n if (text.startsWith(\"pof\")) throw inconclusive(\"Proof-of-funds signatures are not accepted: Ghostly does not check balances or coins\");\n const format: Bip322Format = text.startsWith(\"ful\") ? \"bip322-full\" : \"bip322-simple\";\n // Before BIP-322 1.0.0 signatures had no prefix; the BIP lets a verifier read those as simple.\n const body = text.startsWith(\"smp\") || text.startsWith(\"ful\") ? text.slice(3) : text;\n const bytes = decodeBase64(body);\n if (bytes.length === 0) throw invalid(\"The signature is empty\");\n const toSpend = bip322ToSpend(message, address.scriptPubKey);\n let toSign: Tx;\n if (format === \"bip322-simple\") {\n if (address.type === \"p2pkh\" || address.type === \"p2sh\")\n throw invalid(\"A simple BIP-322 signature is only for native SegWit addresses; this one needs the full format (ful…)\");\n let witness: Uint8Array[];\n try { witness = decodeWitness(bytes); } catch { throw invalid(\"The signature is not a BIP-322 witness\"); }\n toSign = bip322ToSign(toSpend, witness);\n } else {\n try { toSign = decodeTx(bytes); } catch { throw invalid(\"The signature is not a BIP-322 full transaction\"); }\n if (toSign.inputs.length !== 1) throw inconclusive(\"Signatures over extra coins (proof of funds) are not accepted\");\n const [input] = toSign.inputs;\n if (!bytesEqual(input.txid, txHash(toSpend)) || input.vout !== 0) throw invalid(\"The signature does not match this address and message\");\n if (toSign.outputs.length !== 1 || toSign.outputs[0].value !== 0n || !bytesEqual(toSign.outputs[0].script, OP_RETURN))\n throw invalid(\"The signature is not a BIP-322 transaction\");\n if (toSign.version !== 0 && toSign.version !== 2) throw inconclusive(\"Unknown BIP-322 transaction version\");\n }\n const script = checkInput(toSign, address);\n const { lockTime } = toSign, { sequence } = toSign.inputs[0];\n // \"Valid at time T and age S\". For the single-key scripts checked here a time lock gates nothing but\n // when a real spend could confirm, not who holds the key, so it is reported rather than refused.\n return lockTime || sequence ? { format, script, lockTime, sequence } : { format, script };\n}\n","import { secp256k1 } from \"@noble/curves/secp256k1.js\";\nimport { bytesEqual, concatBytes, utf8Encode } from \"./bytes\";\nimport { type BitcoinMessageVerdict, MessageRefusal, decodeBase64, verifyBip322 } from \"./bip322\";\nimport { type BitcoinProofNetwork, BitcoinAddressError, compactSize, decodeBitcoinAddress, hash160, sha256d } from \"./bitcoinScript\";\n\n/**\n * Verifies a signed message for a Bitcoin address, in either format wallets produce:\n *\n * - **BIP-322** (see bip322.ts): `smp…` / `ful…`, or unprefixed from wallets that predate the prefixes.\n * - **Legacy signmessage** (Bitcoin Core `signmessage`, Electrum, most hardware wallets): a 65-byte\n * recoverable ECDSA signature. BIP-322 restricts it to **P2PKH** addresses (1…, m…, n…), and so does\n * this verifier: for SegWit addresses the legacy format does not commit to the script, and wallets\n * disagree on its header bytes (BIP 137 vs Electrum).\n *\n * A valid result proves the signer could sign for the address when they signed. It does not prove a\n * balance, a past payment, or that they would spend from it.\n */\n\nconst MAX_MESSAGE = 16 * 1024;\nconst MAX_SIGNATURE = 16 * 1024;\nconst MAGIC = utf8Encode(\"Bitcoin Signed Message:\\n\");\n\n/** The digest `signmessage` signs: double SHA-256 of the length-prefixed magic and message. */\nexport function legacyMessageHash(message: string): Uint8Array {\n const bytes = utf8Encode(message);\n return sha256d(compactSize(MAGIC.length), MAGIC, compactSize(bytes.length), bytes);\n}\n\n/** Header bytes 27-34 are P2PKH (uncompressed 27-30, compressed 31-34); 35-42 are BIP 137 SegWit headers. */\nexport const isLegacySignature = (bytes: Uint8Array) => bytes.length === 65 && bytes[0] >= 27 && bytes[0] <= 42;\n\nfunction verifyLegacy(address: ReturnType<typeof decodeBitcoinAddress>, message: string, bytes: Uint8Array) {\n if (address.type !== \"p2pkh\")\n throw new MessageRefusal(\"invalid\", \"This is a legacy (signmessage) signature, which Ghostly accepts only for legacy 1…/m…/n… addresses. Sign with BIP-322 for this address.\");\n const header = bytes[0];\n if (header > 34) throw new MessageRefusal(\"invalid\", \"This legacy signature is marked for a SegWit address, not this one\");\n const compressed = header >= 31;\n const recovery = (header - 27) & 3;\n let pubkey: Uint8Array;\n try {\n const point = secp256k1.Signature.fromBytes(concatBytes(Uint8Array.of(recovery), bytes.subarray(1)), \"recovered\").recoverPublicKey(legacyMessageHash(message));\n pubkey = point.toBytes(compressed);\n } catch { throw new MessageRefusal(\"invalid\", \"The signature does not match this address and message\"); }\n if (!bytesEqual(hash160(pubkey), address.program)) throw new MessageRefusal(\"invalid\", \"The signature does not match this address and message\");\n}\n\nexport interface BitcoinMessageInput {\n address: string;\n message: string;\n signature: string;\n /** Mainnet accepts only real-network addresses; Testnet any test network's (testnet, signet, regtest). */\n network: BitcoinProofNetwork;\n}\n\n/** Never throws: every refusal comes back as `invalid` or `inconclusive` with a reason fit to show. */\nexport function verifyBitcoinMessage({ address, message, signature, network }: BitcoinMessageInput): BitcoinMessageVerdict {\n try {\n if (typeof message !== \"string\" || typeof signature !== \"string\" || typeof address !== \"string\") throw new MessageRefusal(\"invalid\", \"Missing address, message or signature\");\n if (utf8Encode(message).length > MAX_MESSAGE) throw new MessageRefusal(\"invalid\", \"The message is too long\");\n const text = signature.trim();\n if (!text) throw new MessageRefusal(\"invalid\", \"The signature is empty\");\n if (text.length > MAX_SIGNATURE) throw new MessageRefusal(\"invalid\", \"The signature is too long\");\n const decoded = decodeBitcoinAddress(address.trim(), network);\n const prefixed = /^(smp|ful|pof)/.test(text);\n if (!prefixed) {\n const bytes = decodeBase64(text);\n if (isLegacySignature(bytes)) {\n verifyLegacy(decoded, message, bytes);\n return { state: \"valid\", format: \"legacy\", script: \"p2pkh\" };\n }\n }\n return { state: \"valid\", ...verifyBip322(decoded, message, text) };\n } catch (e) {\n if (e instanceof MessageRefusal) return { state: e.state, reason: e.message };\n if (e instanceof BitcoinAddressError) return { state: \"invalid\", reason: e.message };\n return { state: \"invalid\", reason: \"The signature could not be read\" };\n }\n}\n","import type { IdentityDisplay, IdentityStatement, VerifiedIdentity } from \"@ghostly/core\";\n\n/**\n * The identity-proof provider contract. A provider is one way to prove control of an external\n * identity (a Nostr key, a domain, a Bitcoin address, an SSH or PGP key, an OpenID Connect account):\n * how the person produces evidence over the shared statement (`signers`), and how any Ghostly app\n * checks it (`verify`). Everything else — the statement bytes, the proof key, sharing per contact,\n * replay protection, storage, expiry, the UI — is shared. See PROOFS.md.\n */\n\n/**\n * Who vouches for the identity. The UI shows the difference:\n * - self-custodied: the person holds the key (Nostr, SSH, PGP, Bitcoin, a domain they control);\n * only they can have produced the evidence.\n * - provider-attested: a company signs that the person logged in to an account (OpenID Connect);\n * the evidence is only as trustworthy as that company.\n */\nexport type IdentityCategory = \"self-custodied\" | \"provider-attested\";\n/** Where Ghostly runs: the web app, the browser extension (engine in an offscreen document), the Tauri app. */\nexport type IdentityPlatform = \"web\" | \"extension\" | \"desktop\";\nexport const IDENTITY_PLATFORMS: readonly IdentityPlatform[] = [\"web\", \"extension\", \"desktop\"];\n\n/**\n * A bounded HTTPS GET through the engine: time-out, size cap (`maxBytes`, default 64 KiB), no credentials,\n * no referrer, refused offline. `redirect` defaults to \"error\": a record that redirects does not count\n * unless the provider says so. `text` is the body as UTF-8; `bytes` is the same body raw (binary\n * answers such as DNS-over-HTTPS `application/dns-message`).\n */\nexport interface IdentityFetchOptions {\n headers?: Record<string, string>; maxBytes?: number; signal?: AbortSignal; redirect?: \"follow\" | \"error\";\n /**\n * A read of one of the profile's own Pkarr relays (a did:dht): read as the chats read them, http:// and a private\n * address included, since the person chose them. Ignored for any other URL.\n */\n ownPkarrRelay?: boolean;\n}\nexport interface IdentityFetchResponse { status: number; contentType: string; text: string; bytes: Uint8Array }\nexport type IdentityFetch = (url: string, options?: IdentityFetchOptions) => Promise<IdentityFetchResponse>;\n\n/**\n * How a provider says a line it works out when it runs (a step naming the person's domain, a progress line) in the\n * app's language: `key` names the line within the provider, `english` is the line itself with `{{name}}` for each of\n * `values`. The UI reads a built-in provider's line under `identities.providers.<provider id>.<key>`, with `english`\n * when its language has none; a provider written outside the app (a plugin) always gets its `english` back, filled in.\n * Its fixed words (`label`, `summary`, a signer's `description`…) need no call: the UI reads them by the same rule,\n * under their own path (`subject.help`, `signers.<signer id>.label`, `signers.<signer id>.fields.<name>.help`).\n */\nexport type ProviderSay = (key: string, english: string, values?: Readonly<Record<string, string | number>>) => string;\n\n/** `english` with its `{{name}}`s filled in: what `ProviderSay` returns where no app language is at hand (the CLI, tests). */\nexport const englishSay: ProviderSay = (_key, english, values) =>\n values ? english.replace(/\\{\\{(\\w+)\\}\\}/g, (all, name: string) => (name in values ? String(values[name]) : all)) : english;\n\nexport interface VerifyContext {\n /** Seconds. Use this, never `Date.now()`, so tests and re-checks agree on time. */\n now: number;\n signal: AbortSignal;\n /** The only way `verify` may reach the network. Never call the global `fetch`. */\n fetch: IdentityFetch;\n}\n\nexport interface SubjectSpec {\n /** \"Public key\", \"Domain\", \"Bitcoin address\", \"Account\". */\n label: string;\n placeholder?: string;\n help?: string;\n /** Choices instead of a text field (an OpenID Connect provider's issuer). */\n options?: readonly { value: string; label: string }[];\n /** The canonical subject for what the person typed (or a signer returned). Throw a message they can act on. */\n normalize(input: string): string;\n /** Short form for badges and lists (\"npub1x…4f2\"). Defaults to the subject. */\n short?(subject: string): string;\n /**\n * What the (normalized) subject turns out to be, shown under the field before anything is signed: a DID's\n * method, its keys and its domain. Runs in the UI on the person's input; may reach the network (the\n * person's own identity). Throw a message they can act on.\n */\n preview?(subject: string, options: { signal: AbortSignal; say?: ProviderSay }): Promise<SubjectPreview>;\n}\n\nexport interface SubjectPreview {\n /** Short facts, in order: \"Method\" → \"did:web\", \"Keys\" → \"#key-1 (Ed25519)\". */\n facts: readonly { label: string; value: string }[];\n /** The ids of the signers that apply to this subject; every signer when omitted. */\n signers?: readonly string[];\n}\n\n/** A field an in-app signer needs (a NIP-46 connection link). `secret` values are never stored or logged. */\nexport interface SignerField {\n name: string;\n label: string;\n kind: \"text\" | \"secret\";\n placeholder?: string;\n help?: string;\n optional?: boolean;\n}\n\n/**\n * A request waiting for the person's approval elsewhere, in one of two ways (Pubky: Passport in a browser window, or\n * Ring by scanning a QR code). The UI shows both on one screen; whichever approves first wins. Its values are secrets\n * (the QR carries a relay key): never logged, never stored.\n */\nexport interface ApprovalRequest {\n /** The primary button. `run` is called synchronously from its click, so a popup it opens keeps the user activation. */\n open?: { label: string; description?: string; run(): void };\n /** A QR code for a phone app, with its caption. */\n qr?: { value: string; label: string };\n /** Short lines under the choices. */\n notes?: readonly string[];\n}\n\n/** A signer's own wait for the person's approval ended (Pubky's relay forgot the request): a time-out, not a failure. */\nexport class SignerTimeout extends Error {}\n\nexport interface SignerContext {\n values: Record<string, string>;\n signal: AbortSignal;\n /**\n * How long the caller waits for the approval (the CLI's --timeout): a signer with a wait of its own takes this one,\n * up to its `maxWaitMs`. Its own wait when absent (the app).\n */\n waitMs?: number;\n /** The signer asks the person to approve on a page (NIP-46 auth_url): the UI shows it as a link, never opens it itself. */\n onAuthUrl(url: string): void;\n onProgress(message: string): void;\n /** The signer waits for an approval elsewhere (`null`: it no longer does). The UI renders it; see `ApprovalRequest`. */\n onApproval?(request: ApprovalRequest | null): void;\n /** Says the signer's progress lines and approval words in the app's language; `englishSay` when absent. */\n say?: ProviderSay;\n}\n\nexport interface SignerSession<E> {\n /** The identity the signer controls, canonical (as `subject.normalize` returns it). */\n subject(): Promise<string>;\n sign(statement: IdentityStatement): Promise<E>;\n}\n\nexport interface InstructionStep {\n text: string;\n /** Shown in a copyable block (a command, a DNS record). */\n copy?: string;\n}\nexport interface SignerInstructions {\n steps: readonly InstructionStep[];\n /** external-tool: the field the output is pasted into. */\n paste?: { label: string; placeholder?: string; multiline?: boolean };\n}\n\ninterface SignerBase {\n /** Unique within the provider: \"nip07\", \"nip46\", \"ssh-keygen\". */\n id: string;\n label: string;\n description?: string;\n /** Defaults to the provider's. */\n platforms?: readonly IdentityPlatform[];\n /** False hides it (no NIP-07 extension in this window). Runs in the UI. */\n available?(): boolean;\n /** The button that starts it (\"Continue on your server\"). Default: \"Sign with <label>\" in-app, \"Continue\" otherwise. */\n action?: string;\n}\n\n/** Signs inside Ghostly through something the person already uses (NIP-07, NIP-46, a wallet API). */\nexport interface InAppSigner<E> extends SignerBase {\n kind: \"in-app\";\n fields?: readonly SignerField[];\n /** The longest it can wait for an approval, whatever `waitMs` says (Pubky: its relay keeps a request five minutes). */\n maxWaitMs?: number;\n /** Opens the signer, runs `work`, and always cleans up (closes connections, drops keys) before resolving. */\n run<T>(ctx: SignerContext, work: (session: SignerSession<E>) => Promise<T>): Promise<T>;\n}\n\n/** The person runs a tool (ssh-keygen, gpg, a Bitcoin wallet) on the statement and pastes the output back. */\nexport interface ExternalToolSigner<E> extends SignerBase {\n kind: \"external-tool\";\n /** `say`: the steps in the app's language (`englishSay` when absent). */\n instructions(statement: IdentityStatement, say?: ProviderSay): SignerInstructions;\n /** What was pasted, as evidence. Throw a message the person can act on (\"That is not an SSH signature\"). */\n parse(pasted: string, statement: IdentityStatement): E | Promise<E>;\n}\n\n/** A popup to the provider's login page (OpenID Connect); the subject comes out of `verify`. */\nexport interface RedirectSigner<E> extends SignerBase {\n kind: \"redirect\";\n start(statement: IdentityStatement, ctx: SignerContext): Promise<E>;\n}\n\n/** The person publishes something the verifier fetches (a DNS TXT record, a /.well-known file). */\nexport interface PublishSigner<E> extends SignerBase {\n kind: \"publish\";\n /** `say`: the steps in the app's language (`englishSay` when absent). */\n instructions(statement: IdentityStatement, say?: ProviderSay): SignerInstructions;\n /** Usually small or empty: the verifier looks the record up itself. */\n evidence(statement: IdentityStatement): E | Promise<E>;\n}\n\nexport type IdentitySigner<E> = InAppSigner<E> | ExternalToolSigner<E> | RedirectSigner<E> | PublishSigner<E>;\n\n/**\n * A provider module's export. Registering it is adding the module under `proofs/providers/` and ONE\n * line in `proofs/registry.ts`.\n */\nexport interface IdentityProofProvider<E = unknown> {\n /** Stable: it is in the statement, on the wire and in storage. `^[a-z][a-z0-9-]{0,31}$`. */\n id: string;\n label: string;\n category: IdentityCategory;\n /**\n * One short line for the picker card, how you make it: \"Sign once with your Nostr signer\". About 40\n * characters at most; the card shows nothing else beside the name and the category.\n */\n summary: string;\n /** The details view (opened from the card, shown again above the form): what is proven and how, a sentence or two. */\n description: string;\n /**\n * What the proof does NOT show, when a contact could easily assume more (\"Does not prove a balance, a past\n * payment, or that you would pay.\"). Shown with the description, never hidden behind a hover.\n */\n limits?: string;\n platforms: readonly IdentityPlatform[];\n subject: SubjectSpec;\n /** How long one proof may last. The person picks up to `maxDays` (never above 400). */\n validity: { defaultDays: number; maxDays: number };\n /**\n * When a verifier's check can go stale (the DNS record may be removed later): the contact's app offers\n * \"Check again\" after this many seconds and shows the last check time. Omit when the evidence is a\n * signature that stays valid until expiry. `perHour`: the most checks the app runs on its own in an hour, for a\n * server that limits lookups per IP (the rest wait for later); well under that limit, so a check a person starts\n * (a new contact's proof, \"Check again\") still gets an answer.\n */\n recheck?: { afterSeconds: number; perHour?: number };\n /** One sentence for people: what `verify` contacts and who learns what. \"Nothing: checked on this device.\" */\n privacy: string;\n /** Mark providers whose flows are not proven against real-world tools yet. */\n experimental?: boolean;\n /** Listed under \"Advanced\" in the picker, for people who know what it is (DIDs), so it does not crowd newcomers. */\n advanced?: boolean;\n signers: readonly IdentitySigner<E>[];\n /**\n * Untrusted evidence off the wire → typed evidence. Strict: exact shape, bounded sizes, no extra keys.\n * The serialized evidence is already capped at 16 KiB before this runs.\n */\n parseEvidence(raw: unknown): E;\n /**\n * Checks `evidence` against exactly `statement.bytes` / `statement.text` and returns what it proves.\n * Throws when it does not. Must:\n * - self-custodied: return `subject === statement.binding.subject`;\n * - provider-attested: return the attested subject and set `attester`;\n * - reach the network only through `ctx.fetch`, and use `ctx.now` for time.\n */\n verify(statement: IdentityStatement, evidence: E, ctx: VerifyContext): Promise<VerifiedIdentity>;\n /**\n * Optional public name/picture for a verified subject (Nostr kind-0). Called ONLY when the person asks,\n * never automatically. Sanitize like avatars: plain-text name, bounded raster re-encoded to a data URL.\n */\n lookupDisplay?(subject: string, options: { signal: AbortSignal }): Promise<IdentityDisplay | undefined>;\n /** The button that runs `lookupDisplay`. Default: \"Show public profile\". */\n lookupLabel?: string;\n /**\n * The verified subject as a URI a public DID document may list in `alsoKnownAs` (the profile's\n * did:dht, and only for identities the person chooses to list there). Omit when the identity has no\n * URI of its own. No comma: did:dht separates the list with commas.\n */\n publicUri?(subject: string): string | undefined;\n /**\n * Takes down what a signer published when the person removes the proof (an AT Protocol record, a Pubky proof file). Runs in\n * the UI, called synchronously from the confirming click (it may open a window first). The shared Pkarr\n * revocation is published either way; if this fails, the person may remove the proof without it.\n */\n unpublish?: {\n /** What the removal adds, for the confirmation: \"Also deletes the record on your server.\" */\n description: string;\n /** `evidence` is what `parseEvidence` accepted when the proof was made (Pubky: the proof file's folder). */\n run(proof: { id: string; subject: string; key: string; evidence: E }, ctx: SignerContext): Promise<void>;\n };\n}\n","import type { BitcoinScriptType } from \"@ghostly/core\";\n\n/**\n * Person-facing steps to sign Ghostly's proof statement for a Bitcoin address, per common wallet: which\n * menu, what to paste where, which format to pick. Ghostly never sees the wallet or its keys; the person\n * pastes the signature back.\n *\n * Only what each wallet's own documentation or UI shows is claimed here. Hardware wallets differ by model\n * and firmware (ADAPTER-ROADMAP.md, \"Hardware and signing\"); their entries point to the vendor's guide.\n */\n\nexport type BitcoinSigningFormat = \"bip322\" | \"legacy\";\n\nexport interface BitcoinWalletGuide {\n id: string;\n name: string;\n /** Address types this wallet can sign for in a format Ghostly accepts. */\n scripts: readonly BitcoinScriptType[];\n format: BitcoinSigningFormat;\n steps: readonly string[];\n /** How to use the test networks, for Testnet mode. */\n testnet?: string;\n note?: string;\n docs?: string;\n}\n\n/** What a proof proves and what it does not; shown next to every Bitcoin proof, given or received. */\nexport const BITCOIN_PROOF_LIMITS = [\n \"Proves: whoever made this signature could sign with the key behind this address when they signed.\",\n \"Does not prove the address holds any balance, now or ever.\",\n \"Does not prove they sent or received any past payment.\",\n \"Does not prove they would pay you, or spend from this address at all.\",\n] as const;\n\nexport const BITCOIN_WALLET_GUIDES: readonly BitcoinWalletGuide[] = [\n {\n id: \"sparrow\",\n name: \"Sparrow Wallet\",\n scripts: [\"p2wpkh\", \"p2tr\", \"p2pkh\"],\n format: \"bip322\",\n steps: [\n \"Open the wallet that holds the address, then Tools → Sign/Verify Message.\",\n \"Address: paste the address you are proving.\",\n \"Message: paste the statement Ghostly shows, exactly as it is.\",\n \"Format: BIP322 (Simple) for a bc1q… or bc1p… address (tb1… on test networks). For a legacy 1… address, Standard (Electrum).\",\n \"Sign Message, then copy the whole Signature (it starts with smp…) and paste it into Ghostly.\",\n ],\n testnet: \"Tools → Restart In → Testnet or Signet, with a wallet on that network.\",\n note: \"Sparrow offers BIP322 (Simple) for software wallets only; a connected hardware wallet signs the Standard (Electrum) format, which Ghostly accepts only for a legacy 1… address.\",\n docs: \"https://sparrowwallet.com/docs/\",\n },\n {\n id: \"bitcoin-core\",\n name: \"Bitcoin Core\",\n scripts: [\"p2pkh\"],\n format: \"legacy\",\n steps: [\n \"Bitcoin Core signs messages in the legacy format only, for a legacy address (1… on mainnet, m… or n… on test networks). Make one in the Receive tab with the Base58 (Legacy) type, or with `getnewaddress \\\"\\\" legacy`.\",\n \"GUI: File → Sign message…; paste the address, paste the statement, Sign Message, copy the signature.\",\n \"Command line: bitcoin-cli signmessage \\\"<address>\\\" '<statement>' (single quotes keep the statement's double quotes intact).\",\n ],\n testnet: \"Run it with -signet, -testnet4 or -regtest; add the same flag to bitcoin-cli.\",\n docs: \"https://developer.bitcoin.org/reference/rpc/signmessage.html\",\n },\n {\n id: \"electrum\",\n name: \"Electrum\",\n scripts: [\"p2pkh\"],\n format: \"legacy\",\n steps: [\n \"Electrum signs in the legacy format, which Ghostly accepts only for a legacy 1… address (m…/n… on test networks); its default bc1… wallets need another wallet.\",\n \"Addresses tab (View → Show Addresses), right-click the address → Sign/verify message.\",\n \"Paste the statement into Message, click Sign, copy the Signature and paste it into Ghostly.\",\n ],\n testnet: \"Start Electrum with --testnet or --signet.\",\n docs: \"https://electrum.readthedocs.io/\",\n },\n {\n id: \"coldcard\",\n name: \"COLDCARD\",\n scripts: [\"p2wpkh\", \"p2tr\", \"p2pkh\"],\n format: \"bip322\",\n steps: [\n \"Follow COLDCARD's BIP-322 guide for your firmware: it signs the statement for one of its addresses via MicroSD, NFC or QR, depending on the model.\",\n \"Give it the statement exactly as Ghostly shows it and the address you are proving.\",\n \"Paste the signature it produces into Ghostly.\",\n ],\n note: \"Older firmware signs only the legacy format (Ghostly accepts that for a legacy 1… address) and limits message length and characters.\",\n docs: \"https://coldcard.com/docs/bip322/\",\n },\n {\n id: \"trezor\",\n name: \"Trezor Suite\",\n scripts: [\"p2pkh\"],\n format: \"legacy\",\n steps: [\n \"Trezor signs messages in the legacy format; Ghostly accepts it for an address of a Legacy account (1…).\",\n \"Open the Legacy account and choose Sign & verify in its menu.\",\n \"Paste the statement into Message, pick the address, Sign, confirm on the device, copy the signature into Ghostly.\",\n ],\n },\n {\n id: \"other\",\n name: \"Another wallet\",\n scripts: [\"p2wpkh\", \"p2tr\", \"p2sh\", \"p2pkh\"],\n format: \"bip322\",\n steps: [\n \"Look for \\\"Sign message\\\" in the wallet. Choose BIP-322 when it asks for a format.\",\n \"Sign the statement exactly as Ghostly shows it, with the address you are proving.\",\n \"A nested SegWit address (3…, or 2… on test networks) needs a full BIP-322 signature (it starts with ful…).\",\n \"Paste the signature into Ghostly; it tells you right away if it does not match.\",\n ],\n },\n];\n\n/** The guides that can sign for an address of this type. */\nexport function guidesFor(script: BitcoinScriptType): BitcoinWalletGuide[] {\n return BITCOIN_WALLET_GUIDES.filter(g => g.scripts.includes(script));\n}\n","import { BitcoinAddressError, decodeAnyBitcoinAddress, verifyBitcoinMessage, type BitcoinMessageVerdict, type BitcoinProofNetwork, type BitcoinScriptType, type IdentityStatement } from \"@ghostly/core\";\nimport { englishSay, type ExternalToolSigner, type IdentityProofProvider, type InstructionStep, type ProviderSay } from \"../contract\";\nimport { BITCOIN_PROOF_LIMITS, BITCOIN_WALLET_GUIDES, guidesFor, type BitcoinWalletGuide } from \"../bitcoinWallets\";\n\n/**\n * Bitcoin address proofs: the person signs the statement with the key behind an address, in their own\n * wallet, and pastes the signature. BIP-322 (simple or full) or, for a legacy P2PKH address only, the\n * legacy `signmessage` format; checked on this device by `verifyBitcoinMessage` (@ghostly/core, pinned to\n * BIP-322 2.0.0). No blockchain lookup: the proof says nothing about coins. See\n * docs/wisps/306-bitcoin.md.\n *\n * The address's own prefix says its network: a proof for a test-network address (tb1…, bcrt1…, m…, n…, 2…)\n * is verified as such and labelled \"test network\" wherever it is shown.\n *\n * TODO(ghostly-wallet signer): \"Sign with my Ghostly wallet\" belongs here as an `in-app` signer once an\n * on-chain source can sign messages. None can today: `OnchainProvider` (engine/paymentAdapters/providers/\n * onchain.ts) has no such method, Bitcoin Core's `signmessage` is legacy-only, and bdk-wallet-web has no\n * message signing. The BDK source keeps its phrase in the engine, so the path is an optional\n * `signMessage?(address, message)` on `OnchainProvider`, implemented in bdk.ts with a BIP-322 simple\n * witness for its own P2WPKH/P2TR address, exposed through an engine RPC that shows the statement and\n * asks first; never sign silently, and never hand the key to the UI.\n */\n\nexport interface BitcoinEvidence {\n /** As the wallet printed it: `smp…`/`ful…`, unprefixed BIP-322, or a legacy base64 signature. */\n signature: string;\n}\n\nconst MAX_SIGNATURE = 8192;\nconst SIGNATURE = /^(smp|ful|pof)?[A-Za-z0-9+/]+={0,2}$/;\n\n/** Each address type's name, said under `scripts.<type>` (exported for the app's drift guard). */\nexport const SCRIPT_NAMES: Record<BitcoinScriptType, string> = {\n p2wpkh: \"native SegWit (bc1q…)\", p2tr: \"Taproot (bc1p…)\", p2sh: \"nested SegWit (3…)\", p2pkh: \"legacy (1…)\",\n p2wsh: \"script / multisig (P2WSH)\", \"witness-unknown\": \"future SegWit version\",\n};\n\nfunction normalizeAddress(input: string): string {\n const value = input.trim();\n let info;\n try { info = decodeAnyBitcoinAddress(value); } catch (e) {\n throw Object.assign(new Error(e instanceof BitcoinAddressError ? e.message : \"Enter a Bitcoin address\"), { cause: e });\n }\n if (info.type === \"p2wsh\" || info.type === \"witness-unknown\")\n throw new Error(\"Ghostly can check proofs for single-key addresses only (bc1q…, bc1p…, 3…, 1…), not multisig or script addresses\");\n // Bech32 may be written in upper case; its canonical form is lower case. Base58 is case-sensitive.\n return info.witnessVersion === undefined ? value : value.toLowerCase();\n}\n\nconst isTestAddress = (address: string) => { try { return decodeAnyBitcoinAddress(address).network === \"testnet\"; } catch { return false; } };\n\nfunction shortAddress(address: string): string {\n return `${address.slice(0, address.startsWith(\"bcrt1\") ? 9 : 7)}…${address.slice(-4)}${isTestAddress(address) ? \" · test network\" : \"\"}`;\n}\n\n/** Wallet steps for this statement's address: the guide's own, or why this wallet cannot sign for it. */\nfunction walletInstructions(guide: BitcoinWalletGuide, statement: IdentityStatement, say: ProviderSay) {\n const address = statement.binding.subject;\n const info = decodeAnyBitcoinAddress(address);\n const steps: InstructionStep[] = [];\n const at = `wallets.${guide.id}`;\n if (!guide.scripts.includes(info.type)) {\n const others = guidesFor(info.type).filter(g => g.id !== \"other\").map(g => g.name);\n const cannot = { wallet: guide.name, type: say(`scripts.${info.type}`, SCRIPT_NAMES[info.type]) };\n steps.push({ text: others.length\n ? say(\"steps.cannotSignTry\", \"{{wallet}} cannot sign for a {{type}} address in a format Ghostly accepts. Try {{others}}, or another wallet that signs BIP-322.\",\n { ...cannot, others: others.reduce((a, b) => say(\"steps.either\", \"{{a}} or {{b}}\", { a, b })) })\n : say(\"steps.cannotSign\", \"{{wallet}} cannot sign for a {{type}} address in a format Ghostly accepts. Use a wallet that signs BIP-322.\", cannot) });\n } else {\n steps.push({ text: say(\"steps.statement\", \"Sign exactly this statement, as one line, without adding a line break:\"), copy: statement.text });\n steps.push({ text: say(\"steps.address\", \"With this address:\"), copy: address });\n guide.steps.forEach((text, i) => steps.push({ text: say(`${at}.step${i + 1}`, text) }));\n if (guide.id === \"bitcoin-core\") steps.push({\n text: info.network === \"testnet\" ? say(\"steps.commandTestnet\", \"Command line (add -signet, -testnet4 or -regtest):\") : say(\"steps.command\", \"Command line:\"),\n copy: `bitcoin-cli signmessage \"${address}\" '${statement.text}'`,\n });\n if (info.network === \"testnet\" && guide.testnet) steps.push({ text: say(\"steps.testnet\", \"Test networks: {{how}}\", { how: say(`${at}.testnet`, guide.testnet) }) });\n if (guide.note) steps.push({ text: say(`${at}.note`, guide.note) });\n }\n steps.push({ text: say(\"steps.limits\", \"This shows you can sign for the address. It does not show a balance, a past payment, or that you would pay.\") });\n return { steps, paste: { label: say(\"paste.label\", \"Signature\"), placeholder: say(\"paste.placeholder\", \"smp… (BIP-322) or the base64 signature your wallet shows\"), multiline: true } };\n}\n\nfunction cleanSignature(pasted: string): string {\n const signature = pasted.replace(/\\s+/g, \"\");\n if (!signature) throw new Error(\"Paste the signature your wallet made\");\n if (signature.length > MAX_SIGNATURE || !SIGNATURE.test(signature)) throw new Error(\"That is not a Bitcoin message signature: paste the whole signature, as the wallet shows it\");\n return signature;\n}\n\nfunction check(statement: IdentityStatement, signature: string): { verdict: Extract<BitcoinMessageVerdict, { state: \"valid\" }>; network: BitcoinProofNetwork } {\n const address = statement.binding.subject;\n const network = decodeAnyBitcoinAddress(address).network;\n const verdict = verifyBitcoinMessage({ address, message: statement.text, signature, network });\n if (verdict.state !== \"valid\") throw new Error(verdict.reason);\n return { verdict, network };\n}\n\nfunction walletSigner(guide: BitcoinWalletGuide): ExternalToolSigner<BitcoinEvidence> {\n return {\n id: guide.id, kind: \"external-tool\", label: guide.name,\n description: guide.format === \"legacy\" ? \"Legacy message signature: for a legacy 1… address only.\" : \"BIP-322 message signature.\",\n instructions: (statement, say = englishSay) => walletInstructions(guide, statement, say),\n parse(pasted, statement) {\n const signature = cleanSignature(pasted);\n // Say right away when it does not match, while the wallet is still open.\n check(statement, signature);\n return { signature };\n },\n };\n}\n\nexport const bitcoin: IdentityProofProvider<BitcoinEvidence> = {\n id: \"bitcoin\",\n label: \"Bitcoin address\",\n category: \"self-custodied\",\n summary: \"Sign a message in your own wallet\",\n description: \"Proves you can sign with the key behind a Bitcoin address: your wallet signs the statement and you paste the signature.\",\n limits: \"It does not prove a balance, a past payment, or that you would pay.\",\n platforms: [\"web\", \"extension\", \"desktop\"],\n subject: {\n label: \"Bitcoin address\",\n placeholder: \"bc1q… (tb1… on test networks)\",\n help: BITCOIN_PROOF_LIMITS.join(\" \"),\n normalize: normalizeAddress,\n short: shortAddress,\n },\n // BIP-21\n publicUri: address => `bitcoin:${address}`,\n validity: { defaultDays: 90, maxDays: 365 },\n privacy: \"Nothing: the signature is checked on this device, with no blockchain lookup. Contacts you share it with learn the address.\",\n signers: BITCOIN_WALLET_GUIDES.map(walletSigner),\n parseEvidence(raw) {\n const e = raw as BitcoinEvidence;\n if (!e || typeof e !== \"object\" || Array.isArray(e) || Object.keys(e).join(\",\") !== \"signature\" || typeof e.signature !== \"string\" ||\n e.signature.length > MAX_SIGNATURE || !SIGNATURE.test(e.signature)) throw new Error(\"That is not a Bitcoin message signature\");\n return { signature: e.signature };\n },\n async verify(statement, evidence) {\n const { verdict, network } = check(statement, evidence.signature);\n const format = verdict.format === \"legacy\" ? \"Legacy signmessage\" : verdict.format === \"bip322-full\" ? \"BIP-322 full\" : \"BIP-322 simple\";\n const script = { p2pkh: \"P2PKH\", p2wpkh: \"P2WPKH\", \"p2sh-p2wpkh\": \"P2SH-P2WPKH\", p2tr: \"P2TR\" }[verdict.script];\n return { subject: statement.binding.subject, source: `${format} signature, ${script}${network === \"testnet\" ? \", test network\" : \"\"}` };\n },\n};\n","/**\n * Where a proof's name came from (`display.source`), and how a Nostr proof was checked (`verified.source`), in the\n * fixed words the providers write them in. The app says these\n * in its own language (`displaySourceOf` reads them back, from new proofs and stored ones alike); any other source is\n * shown as written.\n */\n\n/** The user ID is its holder's own words: shown with that caveat, never as a checked name. */\nexport const OPENPGP_USER_ID_SOURCE = \"User ID on the key, written by its holder: not proof that the name or email is theirs\";\nexport const OPENPGP_KEYSERVER_SOURCE = \"Email confirmed to keys.openpgp.org by its owner: the keyserver's check, not Ghostly's\";\n/** How a Nostr proof was checked (`verified.source`): the event's own signature. */\nexport const NOSTR_SIGNATURE_SOURCE = \"Nostr signature (NIP-01, BIP-340)\";\n\nexport type OidcEmail = \"verified\" | \"unverified\";\n\n/**\n * A sign-in provider's ID token: who signed it, whether it says the email is checked, and whether the name is one the\n * account set for itself (`nameUnchecked`): a display name its holder (or any directory's admin) types, which the\n * provider signs but never checks, so it carries that caveat as an OpenPGP user ID does.\n */\nexport function oidcDisplaySource(provider: string, email?: OidcEmail, nameUnchecked = false): string {\n return `Signed by ${provider}${email === \"verified\" ? `; email verified by ${provider}` : email === \"unverified\" ? `; email not verified by ${provider}` : \"\"}${\n nameUnchecked ? `; name set on the account, not checked by ${provider}` : \"\"}`;\n}\n\nexport type DisplaySource =\n | { kind: \"openpgp-user-id\" }\n | { kind: \"openpgp-keyserver\" }\n | { kind: \"nostr-signature\" }\n | { kind: \"oidc\"; provider: string; email?: OidcEmail; nameUnchecked?: true };\n\n/** Which fixed source a proof of this provider has, or undefined for one shown as written. */\nexport function displaySourceOf(provider: string, source: string): DisplaySource | undefined {\n if (provider === \"nostr\") return source === NOSTR_SIGNATURE_SOURCE ? { kind: \"nostr-signature\" } : undefined;\n if (provider === \"openpgp\") {\n if (source === OPENPGP_USER_ID_SOURCE) return { kind: \"openpgp-user-id\" };\n if (source === OPENPGP_KEYSERVER_SOURCE) return { kind: \"openpgp-keyserver\" };\n return undefined;\n }\n if (provider !== \"oidc\") return undefined;\n const oidc = /^Signed by (.+?)(?:; email (not )?verified by (.+?))?(?:; name set on the account, not checked by (.+))?$/.exec(source);\n if (!oidc || [oidc[3], oidc[4]].some(by => by !== undefined && by !== oidc[1])) return undefined;\n const [, signer, not, also, name] = oidc;\n return { kind: \"oidc\", provider: signer!, ...(also !== undefined ? { email: not ? \"unverified\" : \"verified\" } : {}), ...(name !== undefined ? { nameUnchecked: true as const } : {}) };\n}\n","import type { BunkerPointer, BunkerSigner } from 'nostr-tools/nip46';\nimport type { SimplePool } from 'nostr-tools/pool';\nimport { generateSecretKey } from 'nostr-tools/pure';\nimport type { NostrProofEvent } from '@ghostly/core';\nimport { SignerTimeout } from './contract';\n\nexport interface NostrSigner {\n getPublicKey(): Promise<string>;\n signEvent(event: { kind: number; created_at: number; tags: string[][]; content: string }): Promise<NostrProofEvent>;\n}\nexport function extensionSigner(): NostrSigner | undefined {\n return (globalThis as typeof globalThis & { nostr?: NostrSigner }).nostr;\n}\n/** No NIP-05 lookup, arbitrary fetch, private key import or automatic relay switching. */\nexport function parseProofBunker(input: string): BunkerPointer {\n if (input.length > 4096) throw new Error('Bunker URL too long');\n let uri: URL;\n try { uri = new URL(input); } catch { throw new Error('Enter a bunker:// connection URL from your signer'); }\n const relays = uri.searchParams.getAll('relay');\n if (uri.protocol !== 'bunker:' || !/^[a-f0-9]{64}$/.test(uri.hostname) || uri.username || uri.password || uri.port || uri.hash || (uri.pathname && uri.pathname !== '/') ||\n relays.length < 1 || relays.length > 3) throw new Error('Invalid bunker connection URL');\n for (const address of relays) {\n const relay = new URL(address);\n if (relay.username || relay.password || relay.hash || !(relay.protocol === 'wss:' ||\n (relay.protocol === 'ws:' && ['127.0.0.1', 'localhost', '[::1]'].includes(relay.hostname))))\n throw new Error('Use secure wss:// relays (ws:// is allowed only on loopback for local testing)');\n }\n return { pubkey: uri.hostname, relays, secret: uri.searchParams.get('secret') };\n}\n/**\n * Runs `work` with the person's Nostr signer: the page's NIP-07 extension, or a NIP-46 bunker. `permissions`\n * is what the bunker is asked for (NIP-46 `connect`): the identity proof's `sign_event:30078` by default;\n * the social layer asks for the kinds it publishes. `timeoutMs`: how long the person has to approve, 2 minutes by default\n * (the CLI waits its --timeout).\n */\nexport async function withNostrSigner<T>(options: { bunker?: string; signal: AbortSignal; onAuth(url: string): void; permissions?: string; appName?: string; timeoutMs?: number }, work: (signer: NostrSigner) => Promise<T>): Promise<T> {\n options.signal.throwIfAborted();\n let signer: BunkerSigner | undefined;\n let pool: SimplePool | undefined;\n let clientKey: Uint8Array | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let abort: (() => void) | undefined;\n let closed = false;\n let active: NostrSigner | undefined;\n try {\n const timeout = new Promise<never>((_, reject) => {\n abort = () => { closed = true; reject(new Error('Signing cancelled')); };\n options.signal.addEventListener('abort', abort, { once: true });\n timer = setTimeout(() => { closed = true; reject(new SignerTimeout('Signer timed out. Your Ghostly identity is unchanged.')); }, options.timeoutMs ?? 120_000);\n });\n // Ending once no signer step waits on it: nothing more to cut short.\n timeout.catch(() => {});\n /**\n * Only the signer's own steps (connecting, its key, a signature) are ended by the two minutes or the cancel. What\n * `work` does with an answer, such as the engine checking and saving the proof (a NIP-05 lookup takes up to 30 s),\n * runs to its end: cut short, the person read \"unchanged\" of a proof that was saved (agents#6035).\n */\n const step = async <R>(asked: () => Promise<R>): Promise<R> => {\n if (closed) throw new Error('Signer request cancelled');\n return Promise.race([asked(), timeout]);\n };\n const guard: NostrSigner = {\n getPublicKey: () => step(() => active!.getPublicKey()),\n signEvent: event => step(() => active!.signEvent(event)),\n };\n const connect = async () => {\n if (options.bunker) {\n const bp = parseProofBunker(options.bunker);\n // Loaded here, not with the app: the NIP-46 signer and its relay pool are only for a bunker.\n const [{ BunkerSigner }, { SimplePool }] = await Promise.all([import('nostr-tools/nip46'), import('nostr-tools/pool')]);\n if (closed) throw new Error('Signer request cancelled');\n pool = new SimplePool(); clientKey = generateSecretKey();\n // No timeout of nostr-tools' own (30 s since 2.26): the person approves on their phone, within the wait above.\n signer = BunkerSigner.fromBunker(clientKey, bp, { pool, skipSwitchRelays: true, timeout: 0, onauth: url => {\n try { const u = new URL(url); if (!closed && u.protocol === 'https:' && !u.username && !u.password) options.onAuth(u.href); } catch { /* Invalid signer URL: never navigate. */ }\n } });\n await signer.sendRequest('connect', [bp.pubkey, bp.secret ?? '', options.permissions ?? 'sign_event:30078', JSON.stringify({ name: options.appName ?? 'Ghostly — optional conversation proof' })]);\n active = signer;\n } else {\n active = extensionSigner();\n if (!active) throw new Error('No NIP-07 signer in this window. Use a bunker connection from your Nostr signer.');\n }\n };\n await Promise.race([connect(), timeout]);\n if (closed) throw new Error('Signer request cancelled');\n return await work(guard);\n } finally {\n closed = true;\n if (timer) clearTimeout(timer);\n if (abort) options.signal.removeEventListener('abort', abort);\n await signer?.close(); pool?.destroy(); clientKey?.fill(0);\n }\n}\n","import { schnorr } from \"@noble/curves/secp256k1.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { npubEncode, decode as nip19Decode } from \"nostr-tools/nip19\";\nimport { utf8Encode, type IdentityStatement } from \"@ghostly/core\";\nimport { englishSay, type IdentityProofProvider, type InAppSigner, type SignerSession } from \"../contract\";\nimport { NOSTR_SIGNATURE_SOURCE } from \"../displaySource\";\nimport { extensionSigner, withNostrSigner } from \"../nostr\";\n\n/** A signed Nostr event (NIP-01). The evidence of a Nostr proof. */\nexport interface NostrEvent { id: string; pubkey: string; created_at: number; kind: number; tags: string[][]; content: string; sig: string }\n\n/**\n * NIP-78 application data (kind 30078): no new kind is claimed. Signers show it as such; it is never\n * published to a relay — the event travels only to the contacts the person shares it with.\n */\nexport const NOSTR_PROOF_KIND = 30078;\nconst HEX64 = /^[a-f0-9]{64}$/;\n\n/** The exact event a signer is asked to sign: the statement as content, dated at issue, expiring with it. */\nexport function nostrProofTemplate(statement: IdentityStatement) {\n const { issuedAt, expiresAt } = statement.binding;\n return { kind: NOSTR_PROOF_KIND, created_at: issuedAt, content: statement.text,\n tags: [[\"d\", \"ghostly-identity-proof\"], [\"expiration\", String(expiresAt)]] };\n}\n\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));\n\nfunction normalizeNostrKey(input: string): string {\n const value = input.trim();\n if (HEX64.test(value.toLowerCase())) return value.toLowerCase();\n if (value.startsWith(\"npub1\")) {\n try { const decoded = nip19Decode(value); if (decoded.type === \"npub\") return decoded.data; } catch { /* fall through */ }\n }\n throw new Error(\"Enter a Nostr public key: npub1… or 64 hex characters\");\n}\n\nfunction nostrSigner(id: \"nip07\" | \"nip46\"): InAppSigner<NostrEvent> {\n return {\n id, kind: \"in-app\",\n label: id === \"nip07\" ? \"Browser extension (NIP-07)\" : \"Remote signer (NIP-46)\",\n description: id === \"nip07\" ? \"Approve in the Nostr extension of this browser.\" : \"Paste the bunker:// link from your signer app, then approve there.\",\n fields: id === \"nip46\" ? [{ name: \"bunker\", label: \"Signer connection link\", kind: \"secret\", placeholder: \"bunker://…\" }] : undefined,\n platforms: id === \"nip07\" ? [\"web\", \"desktop\"] : undefined,\n available: id === \"nip07\" ? () => !!extensionSigner() : undefined,\n run: (ctx, work) => withNostrSigner({ bunker: id === \"nip46\" ? ctx.values.bunker : undefined, signal: ctx.signal, onAuth: ctx.onAuthUrl, timeoutMs: ctx.waitMs }, signer => {\n const session: SignerSession<NostrEvent> = {\n subject: async () => normalizeNostrKey(await signer.getPublicKey()),\n sign: async statement => {\n ctx.onProgress((ctx.say ?? englishSay)(\"approve\", \"Approve the Ghostly identity statement in your signer.\"));\n return (await signer.signEvent(nostrProofTemplate(statement))) as NostrEvent;\n },\n };\n return work(session);\n }),\n };\n}\n\nexport const nostr: IdentityProofProvider<NostrEvent> = {\n id: \"nostr\",\n label: \"Nostr\",\n category: \"self-custodied\",\n summary: \"Sign once with your Nostr signer\",\n description: \"Proves you hold a Nostr key: your signer signs the statement, your key never leaves it.\",\n platforms: [\"web\", \"extension\", \"desktop\"],\n subject: {\n label: \"Public key\", placeholder: \"npub1…\",\n normalize: normalizeNostrKey,\n short: key => { const npub = npubEncode(key); return `${npub.slice(0, 10)}…${npub.slice(-4)}`; },\n },\n // NIP-21\n publicUri: key => `nostr:${npubEncode(key)}`,\n validity: { defaultDays: 90, maxDays: 365 },\n privacy: \"Nothing: the signature is checked on this device. The proof is never published to a relay.\",\n signers: [nostrSigner(\"nip07\"), nostrSigner(\"nip46\")],\n parseEvidence(raw) {\n const e = raw as NostrEvent;\n if (!e || typeof e !== \"object\" || Array.isArray(e) || Object.keys(e).sort().join(\",\") !== \"content,created_at,id,kind,pubkey,sig,tags\" ||\n typeof e.id !== \"string\" || !HEX64.test(e.id) || typeof e.pubkey !== \"string\" || !HEX64.test(e.pubkey) ||\n typeof e.sig !== \"string\" || !/^[a-f0-9]{128}$/.test(e.sig) || !Number.isSafeInteger(e.kind) || !Number.isSafeInteger(e.created_at) ||\n typeof e.content !== \"string\" || e.content.length > 2048 || !Array.isArray(e.tags) || e.tags.length > 4 ||\n !e.tags.every(t => Array.isArray(t) && t.length <= 4 && t.every(x => typeof x === \"string\" && x.length <= 128)))\n throw new Error(\"That is not a signed Nostr event\");\n return { id: e.id, pubkey: e.pubkey, created_at: e.created_at, kind: e.kind, tags: e.tags.map(t => [...t]), content: e.content, sig: e.sig };\n },\n async verify(statement, event) {\n const expected = nostrProofTemplate(statement);\n if (event.pubkey !== statement.binding.subject) throw new Error(\"Signed by another Nostr key\");\n if (event.kind !== expected.kind || event.created_at !== expected.created_at || event.content !== expected.content ||\n JSON.stringify(event.tags) !== JSON.stringify(expected.tags)) throw new Error(\"The signer did not sign the exact Ghostly statement\");\n // NIP-01 id, recomputed here: never trust the id or a verification flag the event carries.\n const id = hex(sha256(utf8Encode(JSON.stringify([0, event.pubkey, event.created_at, event.kind, event.tags, event.content]))));\n if (event.id !== id) throw new Error(\"The Nostr event id does not match its content\");\n let valid: boolean;\n try { valid = schnorr.verify(unhex(event.sig), unhex(id), unhex(event.pubkey)); } catch { valid = false; }\n if (!valid) throw new Error(\"Invalid Nostr signature\");\n return { subject: event.pubkey, source: NOSTR_SIGNATURE_SOURCE };\n },\n // The public profile, follows and notes of a verified key are the Nostr social layer's\n // (engine/nostrSocial.ts): loaded on request from the relays the person configured, not here.\n};\n","import { dnsProofName, domainTxtRecord, domainWellKnownFile, normalizeDomain, wellKnownUrl, type DomainRecord, type IdentityStatement } from \"@ghostly/core\";\nimport { englishSay, type IdentityProofProvider, type InAppSigner, type PublishSigner, type SignerSession } from \"../contract\";\nimport { assertDomainRecord, assertNip05, chosenResolver, resolverById } from \"../domain\";\nimport { extensionSigner, withNostrSigner } from \"../nostr\";\nimport { nostr, nostrProofTemplate, type NostrEvent } from \"./nostr\";\n\n/**\n * A long domain as a card shows it: its end, the part that names who owns it (`…ghostly.tools`), never its start, which\n * is whatever the owner chose (`github.com.account-…` under any domain they own). Whole labels from the end, as many as\n * fit in `room` characters; when they leave less than half of it (`…co.uk`, one long label before it), the end's\n * characters instead.\n */\nexport function shortDomain(domain: string, room = 24): string {\n if (domain.length <= room) return domain;\n const labels = domain.split(\".\");\n let end = labels.pop() ?? \"\";\n while (labels.length && end.length + 1 + labels[labels.length - 1]!.length <= room - 1) end = `${labels.pop()}.${end}`;\n if (end.length < room / 2) end = domain.slice(-(room - 1));\n return `…${end}`;\n}\n\n/**\n * A domain the person controls (draft WISP 304, docs/wisps/304-domain.md).\n *\n * The statement (\"I control domain:example.com and authorize the Ghostly key K …\") is vouched for by\n * publishing, once, under the domain: a TXT record at `_ghostly.<domain>` or the file\n * `/.well-known/ghostly.json`, naming the proof key K and the statement id. The id commits the record to\n * the whole statement (dates and nonce too), so one published record vouches for exactly one proof. The\n * record names no contact and no conversation; sharing per contact is the contract's presentation.\n *\n * People who already run NIP-05 can instead sign the statement with the Nostr key their\n * `/.well-known/nostr.json` names for the domain itself (`_`): the proof holds only if both agree.\n */\nexport type DomainEvidence = { method: \"dns\" } | { method: \"https\" } | { method: \"nip05\"; event: NostrEvent };\n\nconst recordFor = (s: IdentityStatement): DomainRecord => ({ key: s.binding.key, proof: s.id });\nconst exactKeys = (raw: unknown, keys: string) => !!raw && typeof raw === \"object\" && !Array.isArray(raw) && Object.keys(raw).sort().join(\",\") === keys;\n\nconst dnsSigner: PublishSigner<DomainEvidence> = {\n id: \"dns\", kind: \"publish\", label: \"DNS TXT record\",\n description: \"Add a TXT record at your DNS host. Contacts' apps look it up through a DNS-over-HTTPS resolver.\",\n instructions(statement, say = englishSay) {\n const domain = statement.binding.subject;\n return { steps: [\n { text: say(\"dns.name\", \"Open the DNS settings of {{domain}} at your registrar or DNS host and add a TXT record with this name. Some hosts add the domain themselves: then enter only the part before {{domain}}.\", { domain }), copy: dnsProofName(domain) },\n { text: say(\"dns.value\", \"Value (one string, exactly as shown):\"), copy: domainTxtRecord(recordFor(statement)) },\n { text: say(\"dns.ttl\", \"Set the TTL to 300 seconds or less, so removing the record takes effect quickly. Then press Check: DNS changes can take a few minutes to appear.\") },\n { text: say(\"dns.public\", \"The record stays public while the proof is in use. Removing it withdraws this proof from every contact at their next check.\") },\n ] };\n },\n evidence: () => ({ method: \"dns\" }),\n};\n\nconst httpsSigner: PublishSigner<DomainEvidence> = {\n id: \"https\", kind: \"publish\", label: \"File on your website\",\n description: \"Upload a small file to your website. Contacts' apps download it from your server.\",\n instructions(statement, say = englishSay) {\n const domain = statement.binding.subject;\n return { steps: [\n { text: say(\"https.file\", \"Create this file on the web server of {{domain}}:\", { domain }), copy: wellKnownUrl(domain) },\n { text: say(\"https.content\", \"With exactly this content:\"), copy: domainWellKnownFile([recordFor(statement)]) },\n { text: say(\"https.serve\", \"Serve it over HTTPS at exactly that address, without any redirect (not even to www), and with this header so browsers may read it:\"), copy: \"Access-Control-Allow-Origin: *\" },\n { text: say(\"https.check\", \"Then press Check. The file stays public while the proof is in use; deleting it withdraws this proof from every contact at their next check.\") },\n ] };\n },\n evidence: () => ({ method: \"https\" }),\n};\n\nconst domainField = { name: \"domain\", label: \"Domain\", kind: \"text\", placeholder: \"example.com\",\n help: \"Its /.well-known/nostr.json must name this Nostr key for \\\"_\\\" (the domain itself).\" } as const;\n\n/** NIP-05: the statement is signed by the Nostr key the domain's nostr.json names for itself. */\nfunction nip05Signer(id: \"nip05-nip07\" | \"nip05-nip46\"): InAppSigner<DomainEvidence> {\n const extension = id === \"nip05-nip07\";\n return {\n id, kind: \"in-app\",\n label: extension ? \"NIP-05 with a browser extension\" : \"NIP-05 with a remote signer\",\n description: \"Already run NIP-05? Sign with the Nostr key your domain's nostr.json names for itself. No new record needed.\",\n fields: extension ? [domainField] : [domainField, { name: \"bunker\", label: \"Signer connection link\", kind: \"secret\", placeholder: \"bunker://…\" }],\n platforms: extension ? [\"web\", \"desktop\"] : undefined,\n available: extension ? () => !!extensionSigner() : undefined,\n run: (ctx, work) => {\n const domain = normalizeDomain(ctx.values.domain ?? \"\");\n return withNostrSigner({ bunker: extension ? undefined : ctx.values.bunker, signal: ctx.signal, onAuth: ctx.onAuthUrl, timeoutMs: ctx.waitMs }, signer => {\n const session: SignerSession<DomainEvidence> = {\n subject: async () => domain,\n sign: async statement => {\n ctx.onProgress((ctx.say ?? englishSay)(\"nip05.approve\", \"Approve the Ghostly identity statement in your signer.\"));\n return { method: \"nip05\", event: (await signer.signEvent(nostrProofTemplate(statement))) as NostrEvent };\n },\n };\n return work(session);\n });\n },\n };\n}\n\nexport const domain: IdentityProofProvider<DomainEvidence> = {\n id: \"domain\",\n label: \"Domain\",\n category: \"self-custodied\",\n summary: \"A DNS record or a file on your site\",\n description: \"Proves you control a domain name: publish a DNS TXT record or a file on its website, once. Contacts' apps look it up when you share it and can check again later.\",\n limits: \"Does not prove who runs the domain, only that whoever added the proof could publish under it.\",\n platforms: [\"web\", \"extension\", \"desktop\"],\n subject: {\n label: \"Domain\", placeholder: \"example.com\",\n help: \"A domain or subdomain you control. A proof for alice.example.com is published under alice.example.com.\",\n normalize: normalizeDomain,\n short: domain => shortDomain(domain),\n },\n publicUri: domain => `https://${domain}`,\n validity: { defaultDays: 90, maxDays: 365 },\n recheck: { afterSeconds: 86_400 },\n privacy: \"DNS: the contact's app asks the DNS-over-HTTPS resolver chosen in its settings (Quad9 by default; the next of Quad9, Cloudflare and Google when it cannot be reached) for the record, \" +\n \"so that resolver learns the domain was checked. Website or NIP-05: the resolver learns the domain, and the domain's web server sees the contact's IP address.\",\n signers: [dnsSigner, httpsSigner, nip05Signer(\"nip05-nip07\"), nip05Signer(\"nip05-nip46\")],\n parseEvidence(raw) {\n const e = raw as DomainEvidence;\n if (exactKeys(raw, \"method\") && (e.method === \"dns\" || e.method === \"https\")) return { method: e.method };\n if (exactKeys(raw, \"event,method\") && e.method === \"nip05\") return { method: \"nip05\", event: nostr.parseEvidence((e as { event: unknown }).event) };\n throw new Error(\"That is not domain proof evidence\");\n },\n async verify(statement, evidence, ctx) {\n const subject = statement.binding.subject;\n if (normalizeDomain(subject) !== subject) throw new Error(\"The domain is not in canonical form\");\n const resolver = chosenResolver();\n const options = { fetch: ctx.fetch, signal: ctx.signal, resolver: resolver.id, now: () => ctx.now * 1000 };\n if (evidence.method === \"nip05\") {\n // The same checks as a Nostr proof, for the key that signed; then the domain must name that key.\n await nostr.verify({ ...statement, binding: { ...statement.binding, subject: evidence.event.pubkey } }, evidence.event, ctx);\n await assertNip05(subject, evidence.event.pubkey, options);\n return { subject, source: `Nostr signature by the key ${wellKnownUrl(subject, \"nip05\")} names for ${subject}` };\n }\n const found = await assertDomainRecord(subject, evidence.method, recordFor(statement), options);\n return { subject, source: evidence.method === \"dns\"\n ? `DNS TXT record at ${dnsProofName(subject)}, via ${resolverById(found.resolver).name}${found.dnssec ? \", DNSSEC validated\" : \"\"}`\n : `File at ${wellKnownUrl(subject)}` };\n },\n};\n","import { fromBase64Url, toBase64Url, utf8Encode } from '@ghostly/core';\nimport type * as OpenPGP from 'openpgp';\n\n/**\n * OpenPGP identity proofs (RFC 9580, and the RFC 4880 v4 keys people actually have).\n *\n * The person signs a Ghostly statement once — the binding by which their\n * OpenPGP key authorizes a Ghostly proof key (see PROOFS.md); each chat\n * then gets a presentation the app signs itself. They sign with their own tooling —\n * `gpg --clearsign`, `gpg --detach-sign --armor`, a YubiKey or another OpenPGP\n * card behind gpg — and pastes the result with their public key. No secret key\n * ever enters Ghostly: a pasted private key is refused before it is parsed.\n *\n * What is shared with a contact is small and self-contained: one signature\n * packet and a minimal copy of the public key (the primary key, its user IDs\n * with their self-signatures, the subkey that signed). The contact verifies it\n * locally with the statement their own app builds; nothing is fetched.\n *\n * A key's user IDs are claims its holder wrote. Possession of the key proves\n * control of the key, not that a name or an email in a user ID belongs to the\n * person — the UI must say so wherever user IDs are shown.\n *\n * OpenPGP.js is loaded lazily (the \"lightweight\" build: ~233 KB minified,\n * ~64 KB gzipped, plus a ~46 KB curve chunk only for ECDSA keys), so nobody\n * pays for it until an OpenPGP proof is opened.\n */\n\nexport const PGP_SCHEME = 'openpgp/1';\n\n/** Strict size limits. Pasted input is the person's own; shared input comes from a peer. */\nexport const PGP_LIMITS = {\n /** A clearsigned statement or an armored detached signature. RSA-4096 with the statement is ~1.5 KB. */\n pastedSignature: 16 * 1024,\n /** An armored public key as exported, before it is minimized. Flooded keys are refused, not trimmed. */\n pastedKey: 256 * 1024,\n /** One signature packet, binary. RSA-4096 with the usual subpackets is ~600 bytes. */\n sharedSignature: 1536,\n /** The minimal key, binary. Both fit, base64url, in the contract's 16 KiB of evidence JSON. */\n sharedKey: 9 * 1024,\n /** User IDs kept in the minimal key and shown. */\n userIds: 16,\n /** Signatures of one kind on one part of a shared key (self-certifications of a user ID, binding signatures, revocations). */\n signaturesPerKind: 2,\n /** Signatures in a shared key, back-signatures included: each costs one verification, ~10 ms in JavaScript for brainpoolP512r1. */\n keySignatures: 20,\n /** Bytes per user ID. */\n userIdLength: 256,\n /** A keyserver response. */\n keyserverResponse: 256 * 1024,\n} as const;\n\n/** Clock difference tolerated between the signer's machine and the verifier. */\nexport const PGP_CLOCK_SKEW = 300;\n\nexport interface PgpEvidence {\n scheme: typeof PGP_SCHEME;\n /** base64url of the minimal transferable public key (binary packets). */\n key: string;\n /** base64url of exactly one signature packet over the statement. */\n signature: string;\n}\n\nexport interface PgpKeyInfo {\n /** Primary key fingerprint, uppercase hex (40 characters for v4, 64 for v6). */\n fingerprint: string;\n /** The key that signs: the primary key or a signing subkey. */\n signingFingerprint: string;\n version: 4 | 6;\n /** \"Ed25519\", \"RSA 3072\", \"ECDSA P-256\", … for the signing key. */\n algorithm: string;\n createdAt: number;\n /** Seconds, or null when the key does not expire. */\n expiresAt: number | null;\n /** Self-certified, unrevoked user IDs: claims by the key holder, not verified facts. */\n userIds: string[];\n}\n\nexport interface PgpVerified extends PgpKeyInfo {\n /** Signature creation time, seconds. */\n signedAt: number;\n}\n\nexport interface PgpVerifyOptions {\n /** Verification time, seconds. The key and its signing subkey must be valid now. */\n now?: number;\n /** Refuse signatures made before this time (seconds), e.g. the start of the binding's validity. */\n signedAfter?: number;\n /** The primary key fingerprint the statement names: any other key is refused, even with a valid signature. */\n expectedFingerprint?: string;\n}\n\ntype Pgp = typeof OpenPGP;\nlet loading: Promise<Pgp> | undefined;\n/** The only place OpenPGP.js is imported: a separate chunk, fetched on first use. */\nexport function loadOpenPgp(): Promise<Pgp> {\n loading ??= import('openpgp/lightweight').then(m => m as unknown as Pgp).catch(e => { loading = undefined; throw e; });\n return loading;\n}\n\nfunction config(pgp: Pgp): OpenPGP.PartialConfig {\n const { hash, publicKey, curve } = pgp.enums;\n return {\n minRSABits: 2048,\n maxUserIDLength: PGP_LIMITS.userIdLength,\n enableParsingV5Entities: false,\n ignoreUnsupportedPackets: true,\n ignoreMalformedPackets: false,\n // Self-signatures from older keys may still use SHA-1; the proof signature may not (below).\n rejectHashAlgorithms: new Set([hash.md5, hash.ripemd]),\n rejectMessageHashAlgorithms: new Set([hash.md5, hash.ripemd, hash.sha1]),\n rejectPublicKeyAlgorithms: new Set([publicKey.elgamal, publicKey.dsa]),\n rejectCurves: new Set([curve.secp256k1]),\n };\n}\n\n/** The allowlist, checked on the primary key and on the key that signs. */\nfunction allowedAlgorithm(packet: OpenPGP.PublicKeyPacket | OpenPGP.SecretKeyPacket | OpenPGP.PublicSubkeyPacket | OpenPGP.SecretSubkeyPacket, signing: boolean): string {\n const { algorithm, bits, curve } = packet.getAlgorithmInfo();\n const names: Record<string, string> = { nistP256: 'P-256', nistP384: 'P-384', nistP521: 'P-521',\n brainpoolP256r1: 'brainpoolP256r1', brainpoolP384r1: 'brainpoolP384r1', brainpoolP512r1: 'brainpoolP512r1' };\n if ((algorithm === 'rsaEncryptSign' || (algorithm === 'rsaSign' && signing)) && bits && bits >= 2048 && bits <= RSA_MAX_BITS) return `RSA ${bits}`;\n if (algorithm === 'ed25519' || (algorithm === 'eddsaLegacy' && curve === 'ed25519Legacy')) return 'Ed25519';\n if (algorithm === 'ed448') return 'Ed448';\n if (algorithm === 'ecdsa' && curve && names[curve]) return `ECDSA ${names[curve]}`;\n const shown = algorithm.startsWith('rsa') ? `RSA ${bits ?? '?'}` : curve ? `${algorithm} ${curve}` : algorithm;\n throw new PgpProofError(`This key uses ${shown}, which Ghostly does not accept. Use Ed25519, ECDSA (P-256, P-384, P-521, brainpool) or RSA with 2048 to ${RSA_MAX_BITS} bits.`);\n}\nconst RSA_MAX_BITS = 8192;\n/** GnuPG and OpenPGP.js make RSA keys with 65537 (17 bits). The same limit as SSH keys (core sshsig). */\nconst RSA_MAX_EXPONENT_BITS = 64;\nconst bitLength = (bytes: Uint8Array) => { const i = bytes.findIndex(b => b !== 0); return i < 0 ? 0 : (bytes.length - i - 1) * 8 + 32 - Math.clz32(bytes[i]); };\n/**\n * Every RSA key in a key, primary and subkeys, sized before any signature on it is verified.\n * Where WebCrypto refuses a key (Chromium: an exponent over 33 bits), OpenPGP.js verifies in\n * JavaScript, one modular squaring per bit of the exponent, blocking the thread.\n */\nfunction assertRsaSizes(key: OpenPGP.PublicKey): void {\n for (const packet of [key.keyPacket, ...key.subkeys.map(s => s.keyPacket)]) {\n if (!packet.getAlgorithmInfo().algorithm.startsWith('rsa')) continue;\n const { n, e } = (packet as unknown as { publicParams: { n?: Uint8Array; e?: Uint8Array } }).publicParams;\n const bits = n ? bitLength(n) : 0, exponentBits = e ? bitLength(e) : 0;\n if (bits > RSA_MAX_BITS) throw new PgpProofError(`This key uses RSA ${bits}, which Ghostly does not accept. Use Ed25519, ECDSA (P-256, P-384, P-521, brainpool) or RSA with 2048 to ${RSA_MAX_BITS} bits.`);\n if (exponentBits > RSA_MAX_EXPONENT_BITS) throw new PgpProofError(`This key uses RSA with a ${exponentBits}-bit public exponent, which Ghostly does not accept. Use a key made by GnuPG (exponent 65537).`);\n }\n}\nconst ALLOWED_HASHES = new Set([8, 9, 10, 11, 12, 14]); // SHA-256, -384, -512, -224, SHA3-256, SHA3-512\n\nexport class PgpProofError extends Error { override name = 'PgpProofError'; }\n/** A copy of a v4 key without user IDs: what keys.openpgp.org serves until its owner confirms an email there. */\nexport const PGP_NO_USER_IDS = 'This copy of the key has no user IDs (keys.openpgp.org leaves them out until you confirm an email there), so it cannot be checked. Paste your public key instead.';\n\n/** Armored blocks in pasted text; more BEGIN lines than any real paste has are refused before the regex scans. */\nfunction armorBlocks(text: string): RegExpExecArray[] {\n if ((text.match(/-----BEGIN PGP /g) ?? []).length > 4) throw new PgpProofError('Paste only what gpg printed: one signature and your public key.');\n return [...text.matchAll(ARMOR)];\n}\n// A clearsigned message has no END line of its own: it ends with its signature block.\nconst ARMOR = /-----BEGIN PGP SIGNED MESSAGE-----[\\s\\S]*?-----END PGP SIGNATURE-----|-----BEGIN PGP ([A-Z ,/0-9]+)-----[\\s\\S]*?-----END PGP \\1-----/g;\n/** The single armored block in pasted text (terminal output may surround it). */\nfunction armoredBlock(text: string, what: 'key' | 'signature'): { type: string; block: string } {\n if (/PRIVATE KEY BLOCK/.test(text))\n throw new PgpProofError('This is a PRIVATE key. Never paste it anywhere: Ghostly only needs your public key (gpg --armor --export).');\n const blocks = armorBlocks(text);\n if (blocks.length === 0) throw new PgpProofError(what === 'key' ? 'Paste an armored public key: it starts with -----BEGIN PGP PUBLIC KEY BLOCK-----.' : 'Paste the whole signed text: it starts with -----BEGIN PGP SIGNED MESSAGE----- (or -----BEGIN PGP SIGNATURE----- for a detached signature).');\n if (blocks.length > 1) throw new PgpProofError(`Paste only one ${what === 'key' ? 'public key' : 'signature'}.`);\n return { type: blocks[0][1] ?? 'SIGNED MESSAGE', block: blocks[0][0] };\n}\n\nfunction secondsOf(date: Date | number | null | typeof Infinity): number | null {\n if (date === null || date === Infinity) return null;\n return Math.floor((date instanceof Date ? date.getTime() : date) / 1000);\n}\nconst hexOf = (bytes: Uint8Array) => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('').toUpperCase();\nconst nowSeconds = () => Math.floor(Date.now() / 1000);\n/** Clearsigned text as it is hashed: trailing whitespace dropped, no final newline. */\nexport function canonicalStatement(statement: string): string {\n return statement.replace(/\\r\\n?/g, '\\n').split('\\n').map(l => l.replace(/[ \\t]+$/, '')).join('\\n').replace(/\\n+$/, '');\n}\n\n/**\n * One paste holding what gpg printed: the signed statement (clearsigned, or a detached signature) and,\n * optionally, the public key. Anything around the blocks (prompts, blank lines) is ignored.\n */\nexport function splitPgpPaste(pasted: string): { signature: string; publicKey?: string } {\n if (typeof pasted !== 'string' || pasted.length > PGP_LIMITS.pastedKey + PGP_LIMITS.pastedSignature) throw new PgpProofError('This is too large. Paste only what gpg printed.');\n if (/PRIVATE KEY BLOCK/.test(pasted)) throw new PgpProofError('This is a PRIVATE key. Never paste it anywhere: Ghostly only needs your public key (gpg --armor --export).');\n const blocks = armorBlocks(pasted).map(m => ({ type: m[1] ?? 'SIGNED MESSAGE', block: m[0] }));\n const keys = blocks.filter(b => b.type === 'PUBLIC KEY BLOCK'), others = blocks.filter(b => b.type !== 'PUBLIC KEY BLOCK');\n if (keys.length > 1) throw new PgpProofError('Paste only one public key.');\n if (others.length === 0) throw new PgpProofError('Paste the signed statement too: it starts with -----BEGIN PGP SIGNED MESSAGE-----.');\n if (others.length > 1) throw new PgpProofError('Paste only one signature.');\n return { signature: others[0].block, publicKey: keys[0]?.block };\n}\n\n/** Refuses a statement that `gpg --clearsign` would alter (dash-escaping, trailing spaces) or that is not plain text. */\nexport function assertSignableStatement(statement: string): void {\n if (!statement || statement.length > 4096 || statement !== canonicalStatement(statement) || /^-/m.test(statement) || /[^\\x20-\\x7e\\n]/.test(statement))\n throw new PgpProofError('Statement is not signable as plain text');\n}\n\n/** Why a key or a subkey is not usable now, in words the person can act on. */\nasync function explainInvalidKey(key: OpenPGP.PublicKey, keyId: OpenPGP.KeyID | undefined, at: Date, cfg: OpenPGP.PartialConfig, when: 'now' | 'signing'): Promise<never> {\n const past = when === 'signing' ? ' when it signed' : '';\n if (await key.isRevoked(undefined, undefined, at, cfg as OpenPGP.Config).catch(() => false))\n throw new PgpProofError(`This key has been revoked${past}. A revoked key proves nothing.`);\n // A v4 key's expiry and flags are in its user IDs' self-signatures: a copy without them cannot be checked.\n if (key.keyPacket.version === 4 && !key.users.length) throw new PgpProofError(PGP_NO_USER_IDS);\n try { await key.verifyPrimaryKey(at, undefined, cfg as OpenPGP.Config); }\n catch (e) {\n const expiry = await key.getExpirationTime(undefined, cfg as OpenPGP.Config).catch(() => null);\n if (expiry instanceof Date && expiry <= at) throw new PgpProofError(`This key expired on ${expiry.toISOString().slice(0, 10)}${past}. Extend its expiry (gpg --quick-set-expire) and export it again.`);\n throw new PgpProofError(`This key is not valid${past}: ${message(e)}`);\n }\n const sub = keyId ? key.getSubkeys(keyId)[0] : undefined;\n if (sub) {\n if (sub.revocationSignatures.length && await sub.verify(at, cfg as OpenPGP.Config).then(() => false, e => /revoked/i.test(message(e))))\n throw new PgpProofError(`The subkey that signed (${sub.getFingerprint().toUpperCase()}) has been revoked${past}.`);\n const expiry = await sub.getExpirationTime(at, cfg as OpenPGP.Config).catch(() => null);\n if (expiry instanceof Date && expiry <= at) throw new PgpProofError(`The subkey that signed expired on ${expiry.toISOString().slice(0, 10)}${past}.`);\n throw new PgpProofError(`The subkey that signed is not a valid signing subkey${past}.`);\n }\n throw new PgpProofError(`The key that signed is not a valid signing key${past}.`);\n}\nconst message = (e: unknown) => e instanceof Error ? e.message : String(e);\n\nconst keyVersionRefused = (version: number) => `This is an OpenPGP v${version} key, which Ghostly does not accept. Use a v4 key (gpg makes Ed25519 ones) or a v6 key.`;\n/** The version byte of the public or secret key packet `bytes` start with, read from its header alone. */\nfunction firstKeyVersion(bytes: Uint8Array): number | undefined {\n const [h, l] = bytes;\n if (!(h & 0x80)) return undefined;\n const newFormat = !!(h & 0x40), tag = newFormat ? h & 0x3f : (h >> 2) & 0x0f;\n if (tag !== 5 && tag !== 6) return undefined;\n // New format: a one, two or five byte length (a key packet has no partial lengths). Old format: one, two or four.\n const at = newFormat ? (l < 192 ? 2 : l < 224 ? 3 : l === 255 ? 6 : undefined) : [2, 3, 5][h & 3];\n return at === undefined ? undefined : bytes[at];\n}\n\n/** Parses exactly one public key; refuses private keys, v3/v5 keys and key rings. */\nasync function readOneKey(pgp: Pgp, input: { armored: string } | { binary: Uint8Array }): Promise<OpenPGP.PublicKey> {\n const cfg = config(pgp);\n let keys: OpenPGP.Key[];\n try {\n keys = 'armored' in input ? await pgp.readKeys({ armoredKeys: input.armored, config: cfg }) : await pgp.readKeys({ binaryKeys: input.binary, config: cfg });\n } catch (e) {\n // OpenPGP.js skips a v5 key packet unread (GnuPG 2.3 and later make Ed448 keys as v5), so it finds no key at all.\n const bytes = 'armored' in input ? await pgp.unarmor(input.armored).then(a => a.data as Uint8Array, () => undefined) : input.binary;\n if (bytes && firstKeyVersion(bytes) === 5) throw new PgpProofError(keyVersionRefused(5));\n throw new PgpProofError(`Could not read this public key: ${message(e)}`);\n }\n if (keys.length !== 1) throw new PgpProofError('Paste one public key, not a key ring.');\n const [key] = keys;\n if (key.isPrivate()) throw new PgpProofError('This is a PRIVATE key. Ghostly only needs your public key (gpg --armor --export).');\n const version = key.keyPacket.version;\n if (version !== 4 && version !== 6) throw new PgpProofError(keyVersionRefused(version));\n assertRsaSizes(key as OpenPGP.PublicKey);\n return key as OpenPGP.PublicKey;\n}\n\ntype Sig = OpenPGP.SignaturePacket;\ninterface SignedPart { sigs: Sig[]; type: OpenPGP.enums.signature; data: object; by: OpenPGP.PublicKeyPacket | OpenPGP.PublicSubkeyPacket }\n/** Every signature group of a key, with what it signs. */\nfunction signedParts(pgp: Pgp, key: OpenPGP.PublicKey): SignedPart[] {\n const t = pgp.enums.signature, primary = key.keyPacket as OpenPGP.PublicKeyPacket;\n const direct = (key as unknown as { directSignatures?: Sig[] }).directSignatures ?? [];\n return [\n { sigs: key.revocationSignatures, type: t.keyRevocation, data: { key: primary }, by: primary },\n { sigs: direct, type: t.key, data: { key: primary }, by: primary },\n ...key.users.flatMap(u => [\n { sigs: u.selfCertifications, type: t.certGeneric, data: { userID: u.userID, key: primary }, by: primary },\n { sigs: u.revocationSignatures, type: t.certRevocation, data: { userID: u.userID, key: primary }, by: primary },\n ]),\n ...key.subkeys.flatMap(s => {\n const data = { key: primary, bind: s.keyPacket };\n return [\n { sigs: s.bindingSignatures, type: t.subkeyBinding, data, by: primary },\n { sigs: s.bindingSignatures.flatMap(b => b.embeddedSignature ? [b.embeddedSignature] : []), type: t.keyBinding, data, by: s.keyPacket as OpenPGP.PublicSubkeyPacket },\n { sigs: s.revocationSignatures, type: t.subkeyRevocation, data, by: primary },\n ];\n }),\n ];\n}\n/** Whether a signature verifies, at `date` or, with null, whenever. OpenPGP.js caches a success, not a failure. */\nconst holds = (part: SignedPart, sig: Sig, date: Date | null, cfg: OpenPGP.PartialConfig) =>\n sig.verify(part.by, part.type, part.data, date as Date, undefined, cfg as OpenPGP.Config).then(() => true, () => false);\n\n/**\n * A contact's key has the shape `minimalKey` writes, and every signature in it verifies, before OpenPGP.js\n * looks at it: it re-verifies a signature that failed on each of its passes over the key, so padding a key\n * with spoiled copies of its own self-signatures (which pass the hash-prefix check) multiplied the cost of a check.\n * Here each signature is verified once, success is cached, and the first failure refuses the key.\n */\nasync function assertMinimalKey(pgp: Pgp, key: OpenPGP.PublicKey): Promise<void> {\n const cfg = config(pgp);\n const parts = signedParts(pgp, key);\n if (key.users.length > PGP_LIMITS.userIds || key.subkeys.length > 1 || key.users.some(u => !u.userID || u.otherCertifications.length) ||\n parts.some(p => p.sigs.length > PGP_LIMITS.signaturesPerKind) || parts.reduce((n, p) => n + p.sigs.length, 0) > PGP_LIMITS.keySignatures)\n throw new PgpProofError('Invalid OpenPGP proof');\n for (const part of parts) for (const sig of part.sigs) if (!await holds(part, sig, null, cfg)) throw new PgpProofError('Invalid OpenPGP proof');\n}\n\n/** The newest signature of `part` valid at each date, once each: what a check at those dates uses. */\nasync function newestValid(part: SignedPart, dates: Date[], cfg: OpenPGP.PartialConfig): Promise<Sig[]> {\n const kept = new Set<Sig>();\n for (const date of dates) {\n let best: Sig | undefined;\n for (const sig of part.sigs) if ((!best || sig.created! >= best.created!) && await holds(part, sig, date, cfg)) best = sig;\n if (best) kept.add(best);\n }\n return [...kept];\n}\n\n/** Valid, unrevoked, self-certified user IDs at `at`. */\nasync function validUserIds(key: OpenPGP.PublicKey, at: Date, cfg: OpenPGP.PartialConfig): Promise<OpenPGP.User[]> {\n const valid: OpenPGP.User[] = [];\n for (const user of key.users) {\n if (!user.userID || valid.length >= PGP_LIMITS.userIds) continue;\n if (await user.verify(at, cfg as OpenPGP.Config).then(() => true, () => false)) valid.push(user);\n }\n return valid;\n}\n\n/**\n * The transferable key a contact receives: primary key and its direct/revocation\n * signatures, valid user IDs with self-certifications only (third-party\n * certifications and photos dropped), and the one subkey that signed. Of each\n * kind of self-signature, only the newest valid now and the newest valid when\n * it signed are kept (superseded ones are what `assertMinimalKey` refuses).\n */\nasync function minimalKey(pgp: Pgp, key: OpenPGP.PublicKey, signer: OpenPGP.PublicKey | OpenPGP.Subkey, at: Date, signedAt: Date, cfg: OpenPGP.PartialConfig): Promise<Uint8Array> {\n const parts = signedParts(pgp, key);\n const part = (sigs: Sig[]) => parts.find(p => p.sigs === sigs)!;\n const kept = (sigs: Sig[]) => newestValid(part(sigs), [at, signedAt], cfg);\n // Revocations count whenever they were made: the newest that verify are kept.\n const revocations = async (sigs: Sig[]) => {\n const valid: Sig[] = [];\n for (const sig of sigs) if (await holds(part(sigs), sig, null, cfg)) valid.push(sig);\n return valid.sort((a, b) => b.created!.getTime() - a.created!.getTime()).slice(0, PGP_LIMITS.signaturesPerKind);\n };\n const packets = new pgp.PacketList<OpenPGP.AnyPacket>();\n packets.push(key.keyPacket, ...await revocations(key.revocationSignatures));\n // Direct-key self-signatures carry v6 key properties; OpenPGP.js keeps them here.\n packets.push(...await kept(parts[1].sigs)); // signedParts lists them second\n for (const user of await validUserIds(key, at, cfg)) packets.push(user.userID!, ...await kept(user.selfCertifications), ...await revocations(user.revocationSignatures));\n if (signer !== key) {\n const sub = signer as OpenPGP.Subkey;\n packets.push(sub.keyPacket, ...await kept(sub.bindingSignatures), ...await revocations(sub.revocationSignatures));\n }\n const sigs = packets.filter((p): p is Sig => p instanceof pgp.SignaturePacket);\n const bytes = new pgp.PublicKey(packets).write();\n if (bytes.length > PGP_LIMITS.sharedKey || sigs.length + sigs.filter(s => s.embeddedSignature).length > PGP_LIMITS.keySignatures)\n throw new PgpProofError('This key is too large to share, even without third-party certifications. Remove old user IDs or use a smaller key.');\n return bytes;\n}\n\nasync function keyInfo(key: OpenPGP.PublicKey, signer: OpenPGP.PublicKey | OpenPGP.Subkey, algorithm: string, at: Date, cfg: OpenPGP.PartialConfig): Promise<PgpKeyInfo> {\n const expiry = await key.getExpirationTime(undefined, cfg as OpenPGP.Config).catch(() => null);\n const subExpiry = signer !== key ? await (signer as OpenPGP.Subkey).getExpirationTime(at, cfg as OpenPGP.Config).catch(() => null) : null;\n const expires = [secondsOf(expiry), secondsOf(subExpiry)].filter((x): x is number => x !== null);\n return {\n fingerprint: key.getFingerprint().toUpperCase(),\n signingFingerprint: signer.getFingerprint().toUpperCase(),\n version: key.keyPacket.version as 4 | 6,\n algorithm,\n createdAt: secondsOf(key.getCreationTime())!,\n expiresAt: expires.length ? Math.min(...expires) : null,\n userIds: (await validUserIds(key, at, cfg)).map(u => u.userID!.userID),\n };\n}\n\n/** What a pasted public key is, before anything is signed: fingerprint and user IDs to show. */\nexport async function readPgpPublicKey(armored: string, options: { now?: number } = {}): Promise<PgpKeyInfo> {\n if (typeof armored !== 'string' || armored.length > PGP_LIMITS.pastedKey) throw new PgpProofError('This public key is too large. Export it with --export-options export-minimal.');\n const { type, block } = armoredBlock(armored, 'key');\n if (type !== 'PUBLIC KEY BLOCK') throw new PgpProofError('Paste a public key block (gpg --armor --export).');\n const pgp = await loadOpenPgp();\n const cfg = config(pgp);\n const key = await readOneKey(pgp, { armored: block });\n const at = new Date((options.now ?? nowSeconds()) * 1000);\n allowedAlgorithm(key.keyPacket, false);\n let signer: OpenPGP.PublicKey | OpenPGP.Subkey;\n try { signer = await key.getSigningKey(undefined, at, undefined, cfg as OpenPGP.Config) as OpenPGP.PublicKey | OpenPGP.Subkey; }\n catch { return explainInvalidKey(key, undefined, at, cfg, 'now'); }\n return keyInfo(key, signer, allowedAlgorithm(signer.keyPacket, true), at, cfg);\n}\n\nasync function readSignaturePacket(pgp: Pgp, input: { armored: string } | { binary: Uint8Array }): Promise<OpenPGP.SignaturePacket> {\n let sig: OpenPGP.Signature;\n try {\n sig = 'armored' in input ? await pgp.readSignature({ armoredSignature: input.armored, config: config(pgp) }) : await pgp.readSignature({ binarySignature: input.binary, config: config(pgp) });\n } catch (e) { throw new PgpProofError(`Could not read this signature: ${message(e)}`); }\n const packets = sig.packets.filterByTag(pgp.enums.packet.signature) as unknown as OpenPGP.SignaturePacket[];\n if (sig.packets.length !== 1 || packets.length !== 1) throw new PgpProofError('Sign with one key only: this signature has several signers.');\n return packets[0];\n}\n\n/**\n * The core check, shared by the person (on paste) and the contact (on receipt):\n * one signature over the statement, by a key or signing subkey of `key` that is\n * valid both when it signed and now, with allowed algorithms and hash.\n */\nasync function verifyPacket(pgp: Pgp, key: OpenPGP.PublicKey, sig: OpenPGP.SignaturePacket, statement: string, options: PgpVerifyOptions): Promise<{ info: PgpVerified; signer: OpenPGP.PublicKey | OpenPGP.Subkey }> {\n const cfg = config(pgp);\n const now = options.now ?? nowSeconds();\n const at = new Date(now * 1000);\n const { signature } = pgp.enums;\n if (sig.signatureType !== signature.text && sig.signatureType !== signature.binary) throw new PgpProofError('This is not a signature over a text or a file.');\n if (sig.hashAlgorithm === null || !ALLOWED_HASHES.has(sig.hashAlgorithm)) throw new PgpProofError('This signature uses a weak hash (SHA-1 or older). Sign again with gpg\\'s default (SHA-256 or stronger): --digest-algo SHA256.');\n if (!sig.created) throw new PgpProofError('This signature has no creation time.');\n const signedAt = secondsOf(sig.created)!;\n if (signedAt > now + PGP_CLOCK_SKEW) throw new PgpProofError('This signature is dated in the future. Check the clock of the machine that signed.');\n if (options.expectedFingerprint !== undefined && key.getFingerprint().toUpperCase() !== options.expectedFingerprint.toUpperCase())\n throw new PgpProofError('This key is not the one the statement names.');\n const issuer = key.getKeys(sig.issuerKeyID)[0];\n if (!issuer) throw new PgpProofError(`This signature was made by another key (${sig.issuerKeyID.toHex().toUpperCase()}), not the public key given.`);\n if (sig.issuerFingerprint && hexOf(sig.issuerFingerprint) !== issuer.getFingerprint().toUpperCase())\n throw new PgpProofError('This signature was made by another key, not the public key given.');\n allowedAlgorithm(key.keyPacket, false);\n // Valid now (not expired, not revoked, signing-capable with its back-signature)…\n let signer: OpenPGP.PublicKey | OpenPGP.Subkey;\n try { signer = await key.getSigningKey(sig.issuerKeyID, at, undefined, cfg as OpenPGP.Config) as OpenPGP.PublicKey | OpenPGP.Subkey; }\n catch { return explainInvalidKey(key, sig.issuerKeyID, at, cfg, 'now'); }\n const algorithm = allowedAlgorithm(signer.keyPacket, true);\n // …and when it signed.\n const created = new Date(Math.min(signedAt, now) * 1000);\n try { await key.getSigningKey(sig.issuerKeyID, created, undefined, cfg as OpenPGP.Config); }\n catch { return explainInvalidKey(key, sig.issuerKeyID, created, cfg, 'signing'); }\n // After the key checks, so an expired or revoked key is reported as such.\n if (options.signedAfter !== undefined && signedAt < options.signedAfter - PGP_CLOCK_SKEW) throw new PgpProofError('This signature is older than the statement it should sign.');\n // A detached signature over a file holds its final newline; clearsigned text does not.\n const text = canonicalStatement(statement);\n const packets = new pgp.PacketList<OpenPGP.AnyPacket>(); packets.push(sig);\n const detached = new pgp.Signature(packets as OpenPGP.PacketList<OpenPGP.SignaturePacket>);\n let verified = false;\n for (const candidate of [text, `${text}\\n`, `${text}\\r\\n`]) {\n const message = await pgp.createMessage({ binary: utf8Encode(candidate) });\n const result = await pgp.verify({ message, signature: detached, verificationKeys: key, date: new Date(Math.max(now, signedAt) * 1000), config: cfg });\n if (result.signatures.length === 1 && await result.signatures[0].verified.then(() => true, () => false)) { verified = true; break; }\n }\n if (!verified) throw new PgpProofError('This signature is not over the Ghostly statement (it signs other text, or it was changed).');\n return { info: { ...await keyInfo(key, signer, algorithm, at, cfg), signedAt }, signer };\n}\n\n/**\n * The person's side: checks what they pasted against the statement and\n * produces the evidence to share. Either a clearsigned statement or an\n * armored detached signature is accepted.\n */\nexport async function preparePgpEvidence(input: { statement: string; signature: string; publicKey: string }, options: PgpVerifyOptions = {}): Promise<{ evidence: PgpEvidence; verified: PgpVerified }> {\n if (typeof input.signature !== 'string' || input.signature.length > PGP_LIMITS.pastedSignature) throw new PgpProofError('This signature is too large. Paste only the output of gpg --clearsign.');\n if (typeof input.publicKey !== 'string' || input.publicKey.length > PGP_LIMITS.pastedKey) throw new PgpProofError('This public key is too large. Export it with --export-options export-minimal.');\n const { type, block } = armoredBlock(input.signature, 'signature');\n const keyBlock = armoredBlock(input.publicKey, 'key');\n if (keyBlock.type !== 'PUBLIC KEY BLOCK') throw new PgpProofError('Paste a public key block (gpg --armor --export).');\n if (type === 'MESSAGE') throw new PgpProofError('This is a signed message (gpg --sign). Use gpg --clearsign, or --detach-sign --armor.');\n if (type === 'PUBLIC KEY BLOCK') throw new PgpProofError('This is a public key; paste it in the public key field and the signature here.');\n const pgp = await loadOpenPgp();\n const key = await readOneKey(pgp, { armored: keyBlock.block });\n let sig: OpenPGP.SignaturePacket;\n if (type === 'SIGNED MESSAGE') {\n let cleartext: OpenPGP.CleartextMessage;\n try { cleartext = await pgp.readCleartextMessage({ cleartextMessage: block, config: config(pgp) }); }\n catch (e) { throw new PgpProofError(`Could not read this signed text: ${message(e)}`); }\n if (canonicalStatement(cleartext.getText()) !== canonicalStatement(input.statement))\n throw new PgpProofError('This signs different text. Sign exactly the statement shown, without editing it.');\n // Typed as private in OpenPGP.js's declarations, public at runtime.\n const packets = (cleartext as unknown as { signature: OpenPGP.Signature }).signature.packets;\n if (packets.length !== 1 || !(packets[0] instanceof pgp.SignaturePacket)) throw new PgpProofError('Sign with one key only: this signature has several signers.');\n sig = packets[0];\n } else if (type === 'SIGNATURE') sig = await readSignaturePacket(pgp, { armored: block });\n else throw new PgpProofError('Paste the output of gpg --clearsign (or gpg --detach-sign --armor).');\n const { info, signer } = await verifyPacket(pgp, key, sig, input.statement, options);\n const single = new pgp.PacketList<OpenPGP.AnyPacket>(); single.push(sig);\n const signature = new pgp.Signature(single as OpenPGP.PacketList<OpenPGP.SignaturePacket>).write();\n if (signature.length > PGP_LIMITS.sharedSignature) throw new PgpProofError('This signature is too large to share.');\n const now = options.now ?? nowSeconds();\n const at = new Date(now * 1000), signedAt = new Date(Math.min(info.signedAt, now) * 1000);\n const evidence: PgpEvidence = { scheme: PGP_SCHEME, key: toBase64Url(await minimalKey(pgp, key, signer, at, signedAt, config(pgp))), signature: toBase64Url(signature) };\n return { evidence, verified: info };\n}\n\nconst b64 = /^[A-Za-z0-9_-]+$/;\n/** Untrusted evidence off the wire: exact shape, bounded, canonical base64url. Checked before any OpenPGP parsing. */\nexport function parsePgpEvidence(raw: unknown): PgpEvidence {\n const e = raw as PgpEvidence;\n if (!e || typeof e !== 'object' || Array.isArray(e) || e.scheme !== PGP_SCHEME || Object.keys(e).sort().join(',') !== 'key,scheme,signature' ||\n typeof e.key !== 'string' || typeof e.signature !== 'string' || !b64.test(e.key) || !b64.test(e.signature) ||\n e.key.length > Math.ceil(PGP_LIMITS.sharedKey * 4 / 3) || e.signature.length > Math.ceil(PGP_LIMITS.sharedSignature * 4 / 3))\n throw new PgpProofError('Invalid OpenPGP proof');\n let canonical: boolean;\n try { canonical = toBase64Url(fromBase64Url(e.key)) === e.key && toBase64Url(fromBase64Url(e.signature)) === e.signature; } catch { canonical = false; }\n if (!canonical) throw new PgpProofError('Invalid OpenPGP proof encoding');\n return { scheme: PGP_SCHEME, key: e.key, signature: e.signature };\n}\n\n/** The contact's side: verifies shared evidence against the statement their own app built. */\nexport async function verifyPgpEvidence(raw: PgpEvidence, statement: string, options: PgpVerifyOptions = {}): Promise<PgpVerified> {\n const evidence = parsePgpEvidence(raw);\n const keyBytes = fromBase64Url(evidence.key), sigBytes = fromBase64Url(evidence.signature);\n const pgp = await loadOpenPgp();\n const key = await readOneKey(pgp, { binary: keyBytes });\n await assertMinimalKey(pgp, key);\n const sig = await readSignaturePacket(pgp, { binary: sigBytes });\n return (await verifyPacket(pgp, key, sig, statement, options)).info;\n}\n\n/** Groups of four, as gpg prints fingerprints. */\nexport function formatFingerprint(fingerprint: string): string {\n return fingerprint.replace(/(.{4})/g, '$1 ').trim();\n}\n\n/** keys.openpgp.org publishes a user ID only after its owner confirms the email. */\nexport const KEYSERVER = 'https://keys.openpgp.org';\nexport interface KeyserverKey { armored: string; source: typeof KEYSERVER; fetchedAt: number }\n/**\n * Fetches a public key from keys.openpgp.org. Only ever called when the person\n * asks for it, after the UI said this contacts that server.\n */\nexport async function fetchKeyFromKeyserver(query: string, options: { signal?: AbortSignal; fetch?: typeof fetch; now?: number } = {}): Promise<KeyserverKey> {\n const q = query.trim().replace(/\\s+/g, '').replace(/^0x/i, '');\n let path: string;\n if (/^[A-Fa-f0-9]{40}$/.test(q) || /^[A-Fa-f0-9]{64}$/.test(q)) path = `/vks/v1/by-fingerprint/${q.toUpperCase()}`;\n else if (/^[^\\s@<>]{1,64}@[^\\s@<>]{1,190}$/.test(query.trim())) path = `/vks/v1/by-email/${encodeURIComponent(query.trim())}`;\n else throw new PgpProofError('Enter a full fingerprint (40 hex characters) or an email address.');\n const response = await (options.fetch ?? fetch)(`${KEYSERVER}${path}`, { signal: options.signal, credentials: 'omit', referrerPolicy: 'no-referrer', redirect: 'error' });\n if (response.status === 404) throw new PgpProofError('keys.openpgp.org has no key for this. Paste your public key instead.');\n if (!response.ok) throw new PgpProofError(`keys.openpgp.org answered ${response.status}. Paste your public key instead.`);\n const length = Number(response.headers.get('content-length') ?? 0);\n if (length > PGP_LIMITS.keyserverResponse) throw new PgpProofError('The key from keys.openpgp.org is too large.');\n const armored = await response.text();\n if (armored.length > PGP_LIMITS.keyserverResponse) throw new PgpProofError('The key from keys.openpgp.org is too large.');\n return { armored, source: KEYSERVER, fetchedAt: options.now ?? nowSeconds() };\n}\n\n/**\n * Emails keys.openpgp.org vouches for on this key: it publishes a user ID only\n * once the email's owner confirmed it, so every user ID in its copy is one the\n * keyserver checked. That is the keyserver's check, and says nothing about a name.\n */\nexport async function keyserverVerifiedEmails(keyserverArmored: string, fingerprint: string, options: { now?: number } = {}): Promise<string[]> {\n let info: PgpKeyInfo;\n // No user IDs in its copy: the keyserver confirmed no email (a revocation it holds is still said, above that).\n try { info = await readPgpPublicKey(keyserverArmored, options); }\n catch (e) { if (e instanceof PgpProofError && e.message === PGP_NO_USER_IDS) return []; throw e; }\n if (info.fingerprint !== fingerprint.toUpperCase()) throw new PgpProofError('keys.openpgp.org returned a different key.');\n const emails = info.userIds.map(u => /<([^<>\\s]+@[^<>\\s]+)>\\s*$/.exec(u)?.[1] ?? (/^[^<>\\s]+@[^<>\\s]+$/.test(u) ? u : undefined));\n return [...new Set(emails.filter((e): e is string => !!e).map(e => e.toLowerCase()))];\n}\n","import type { IdentityStatement } from \"@ghostly/core\";\nimport { englishSay, type ExternalToolSigner, type IdentityProofProvider, type ProviderSay, type SignerInstructions } from \"../contract\";\nimport {\n KEYSERVER, PgpProofError, assertSignableStatement, fetchKeyFromKeyserver, formatFingerprint, keyserverVerifiedEmails, parsePgpEvidence,\n preparePgpEvidence, splitPgpPaste, verifyPgpEvidence, type PgpEvidence,\n} from \"../openpgp\";\nimport { OPENPGP_KEYSERVER_SOURCE as KEYSERVER_SOURCE, OPENPGP_USER_ID_SOURCE as USER_ID_SOURCE } from \"../displaySource\";\n\n/**\n * OpenPGP keys, signed with the person's own gpg — a YubiKey or another OpenPGP card works unchanged,\n * since gpg drives it. The subject is the primary key's fingerprint. See docs/wisps/305-openpgp.md.\n */\n\n/** A v4 (40 hex) or v6 (64 hex) fingerprint, as gpg prints it or not: spaces and 0x are dropped. */\nexport function normalizeFingerprint(input: string): string {\n const value = input.trim().replace(/^0x/i, \"\").replace(/\\s+/g, \"\").toUpperCase();\n if (/^[A-F0-9]{40}$/.test(value) || /^[A-F0-9]{64}$/.test(value)) return value;\n if (/^[A-F0-9]{8}$|^[A-F0-9]{16}$/.test(value)) throw new PgpProofError(\"Use the full fingerprint, not a key ID: gpg --fingerprint shows it.\");\n throw new PgpProofError(\"Enter your key's fingerprint: 40 hex characters (gpg --fingerprint).\");\n}\n\n\nfunction steps(statement: IdentityStatement, exportKey: boolean, say: ProviderSay): SignerInstructions {\n assertSignableStatement(statement.text);\n // The statement is one line of space-separated fields with no quote in it, so it is safe in single quotes.\n if (statement.text.includes(\"'\")) throw new PgpProofError(\"Statement is not signable as plain text\");\n const fpr = normalizeFingerprint(statement.binding.subject);\n const sign = `gpg --local-user ${fpr} --clearsign --output - ghostly-identity.txt`;\n return {\n steps: [\n { text: say(\"steps.save\", \"Save the statement to a file (it is one line, with no newline at the end):\"), copy: `printf '%s' '${statement.text}' > ghostly-identity.txt` },\n exportKey\n ? { text: say(\"steps.signExport\", \"Sign it and export your public key, then copy everything this prints:\"), copy: `${sign} && gpg --armor --export --export-options export-minimal ${fpr}` }\n : { text: say(\"steps.sign\", \"Sign it, then copy everything this prints:\"), copy: sign },\n { text: say(\"steps.card\", \"On a YubiKey or another OpenPGP card, gpg asks for the card's PIN, and for a touch if the card requires one. Without a shell, save the statement below in a text file and sign that file.\"), copy: statement.text },\n ],\n paste: {\n label: exportKey ? say(\"paste.signedAndKey\", \"Signed statement and public key\") : say(\"paste.signed\", \"Signed statement\"),\n placeholder: \"-----BEGIN PGP SIGNED MESSAGE-----\", multiline: true,\n },\n };\n}\n\nasync function evidenceFrom(statement: IdentityStatement, signature: string, publicKey: string): Promise<PgpEvidence> {\n const { evidence } = await preparePgpEvidence({ statement: statement.text, signature, publicKey },\n { expectedFingerprint: normalizeFingerprint(statement.binding.subject), signedAfter: statement.binding.issuedAt });\n return evidence;\n}\n\nconst gpg: ExternalToolSigner<PgpEvidence> = {\n id: \"gpg\", kind: \"external-tool\", label: \"gpg\",\n description: \"Sign with gpg and paste what it prints, public key included. Nothing is looked up.\",\n instructions: (statement, say = englishSay) => steps(statement, true, say),\n async parse(pasted, statement) {\n const { signature, publicKey } = splitPgpPaste(pasted);\n if (!publicKey) throw new PgpProofError(\"Paste your public key too: the second command prints it (-----BEGIN PGP PUBLIC KEY BLOCK-----).\");\n return evidenceFrom(statement, signature, publicKey);\n },\n};\n\nconst gpgKeyserver: ExternalToolSigner<PgpEvidence> = {\n id: \"gpg-keys-openpgp-org\", kind: \"external-tool\", label: \"gpg, key from keys.openpgp.org\",\n description: \"Sign with gpg and paste the signature; Ghostly then fetches your public key from keys.openpgp.org, which learns which key was looked up.\",\n instructions: (statement, say = englishSay) => steps(statement, false, say),\n async parse(pasted, statement) {\n const { signature, publicKey } = splitPgpPaste(pasted);\n // Only here, on the person's choice of this signer, is the keyserver contacted.\n const key = publicKey ?? (await fetchKeyFromKeyserver(statement.binding.subject)).armored;\n return evidenceFrom(statement, signature, key);\n },\n};\n\nexport const openpgp: IdentityProofProvider<PgpEvidence> = {\n id: \"openpgp\",\n label: \"OpenPGP key\",\n category: \"self-custodied\",\n summary: \"Sign with gpg and paste the result\",\n description: \"Proves you hold an OpenPGP key: sign the statement with gpg (a YubiKey works too) and paste the result.\",\n limits: \"Holding a key does not prove the names or emails in its user IDs.\",\n platforms: [\"web\", \"extension\", \"desktop\"],\n subject: {\n label: \"Key fingerprint\", placeholder: \"40 hex characters, from gpg --fingerprint\",\n help: \"The primary key's full fingerprint. Holding a key does not prove the names or emails in its user IDs.\",\n normalize: normalizeFingerprint,\n short: fpr => `…${formatFingerprint(fpr.slice(-16))}`,\n },\n // The fingerprint URI scheme OpenPGP apps share keys with.\n publicUri: fpr => `openpgp4fpr:${fpr}`,\n validity: { defaultDays: 90, maxDays: 365 },\n privacy: `Nothing: the signature is checked on this device. ${KEYSERVER.replace(\"https://\", \"\")} is contacted only if you choose it for your key, or ask it to confirm emails.`,\n signers: [gpg, gpgKeyserver],\n lookupLabel: \"Check emails with keys.openpgp.org\",\n parseEvidence: raw => parsePgpEvidence(raw),\n async verify(statement, evidence, ctx) {\n ctx.signal.throwIfAborted();\n const { binding } = statement;\n const verified = await verifyPgpEvidence(evidence, statement.text, { now: ctx.now, signedAfter: binding.issuedAt, expectedFingerprint: normalizeFingerprint(binding.subject) });\n const subkey = verified.signingFingerprint !== verified.fingerprint;\n const [userId] = verified.userIds;\n return {\n subject: verified.fingerprint,\n source: `OpenPGP signature (${verified.algorithm}${subkey ? \" signing subkey\" : \"\"}, v${verified.version} key)`,\n ...(verified.expiresAt !== null && verified.expiresAt < binding.expiresAt ? { expiresAt: verified.expiresAt } : {}),\n ...(userId ? { display: { name: userId, source: USER_ID_SOURCE, fetchedAt: ctx.now } } : {}),\n };\n },\n /** On request only: which emails on this key keys.openpgp.org confirmed, and whether it holds a revocation. */\n async lookupDisplay(subject, { signal }) {\n const fpr = normalizeFingerprint(subject);\n const found = await fetchKeyFromKeyserver(fpr, { signal });\n const emails = await keyserverVerifiedEmails(found.armored, fpr);\n if (!emails.length) return undefined;\n return { name: emails[0], url: `${KEYSERVER}/search?q=${fpr}`, source: KEYSERVER_SOURCE, fetchedAt: found.fetchedAt };\n },\n};\n","import {\n parseSshPublicKey, parseSshSignature, sshSignCommand, SshSigError, SSHSIG_MAX_ARMOR, SSHSIG_NAMESPACE, utf8Encode, verifySshSignature,\n type IdentityStatement, type SshSignatureCheck,\n} from \"@ghostly/core\";\nimport { englishSay, type ExternalToolSigner, type IdentityProofProvider, type VerifyContext } from \"../contract\";\nimport { checkSshForge, SSH_FORGE_HOST, SSH_FORGE_LABEL, validForgeLogin, type SshForge } from \"../sshForges\";\n\n/**\n * SSH keys (draft WISP 307-ssh). The person signs the binding statement once with their own\n * `ssh-keygen -Y sign -n ghostly` and pastes the armored SSHSIG; the private key never enters Ghostly.\n *\n * - `ssh` the subject is the key's SHA-256 fingerprint; checked on this device, no network.\n * - `ssh-github` the subject is a GitHub account: the signing key must be one of the SSH keys GitHub\n * - `ssh-gitlab` publishes for it (GitLab alike). No OAuth: only the account holder can add a key, so\n * \"this account lists the key\" links the two. Re-checked, since keys get removed.\n */\n\nexport interface SshEvidence { signature: string }\n\nconst FINGERPRINT = /^SHA256:[A-Za-z0-9+/]{43}$/;\n/** The line `ssh-keygen -l -f key.pub` prints: bits, fingerprint, comment, type (\"256 SHA256:… me@laptop (ED25519)\"). */\nconst KEYGEN_LIST_LINE = /^\\d+ (SHA256:[A-Za-z0-9+/]{43}) .* \\([A-Z0-9-]+\\)$/;\n\nfunction normalizeKeySubject(input: string): string {\n const value = input.trim();\n if (FINGERPRINT.test(value)) return value;\n const listed = KEYGEN_LIST_LINE.exec(value);\n if (listed) return listed[1];\n try { return parseSshPublicKey(value).fingerprint; }\n catch (e) {\n // Say why a real key is refused (a DSA key, a small RSA key); anything else gets the instruction.\n if (e instanceof SshSigError && /^(Unsupported SSH key type|RSA keys must)/.test(e.message)) throw Object.assign(new Error(e.message), { cause: e });\n throw Object.assign(new Error(\"Paste your public key (the one line in ~/.ssh/id_ed25519.pub) or its SHA256: fingerprint\"), { cause: e });\n }\n}\n\nfunction normalizeLogin(forge: SshForge, input: string): string {\n const login = input.trim().replace(/^@/, \"\").toLowerCase();\n if (!validForgeLogin(forge, login)) throw new Error(`Enter a ${SSH_FORGE_LABEL[forge]} username`);\n return login;\n}\n\n/**\n * The armored block, without what the terminal showed around it (ssh-keygen's \"Signing data on standard input\", a prompt);\n * the last one when the command ran more than once there (Add started over, a run without -n ghostly).\n */\nconst ARMOR = /-----BEGIN SSH SIGNATURE-----[\\s\\S]*?-----END SSH SIGNATURE-----/g;\nconst armorIn = (pasted: string) => pasted.length > 4 * SSHSIG_MAX_ARMOR ? pasted : pasted.match(ARMOR)?.pop() ?? pasted;\n\n/** The armor, re-wrapped canonically, so evidence is the same whatever the clipboard did to it. */\nfunction canonicalArmor(pasted: string): string {\n const armor = armorIn(pasted);\n const parsed = parseSshSignature(armor);\n if (parsed.namespace !== SSHSIG_NAMESPACE) throw new Error(`That signature is for \"${parsed.namespace}\", not \"${SSHSIG_NAMESPACE}\": run the command with -n ${SSHSIG_NAMESPACE}`);\n const body = armor.replace(/\\r\\n/g, \"\\n\").trim().split(\"\\n\").map(l => l.trim()).slice(1, -1).join(\"\");\n return `-----BEGIN SSH SIGNATURE-----\\n${body.match(/.{1,70}/g)!.join(\"\\n\")}\\n-----END SSH SIGNATURE-----\\n`;\n}\n\n/** Exactly the statement; or with one trailing newline (\"\\r\\n\" on Windows), which an editor adds when the\n * statement is saved to a file and signed there (the Windows route). Nothing else is accepted. */\nasync function verifyStatementSignature(statement: IdentityStatement, evidence: SshEvidence): Promise<SshSignatureCheck> {\n let last: unknown;\n for (const bytes of [statement.bytes, utf8Encode(`${statement.text}\\n`), utf8Encode(`${statement.text}\\r\\n`)]) {\n try { return await verifySshSignature(evidence.signature, bytes); }\n catch (e) { if (!(e instanceof SshSigError) || !/does not match this statement/.test(e.message)) throw e; last = e; }\n }\n throw Object.assign(new Error(\"The signature is not over this statement: copy the command again and sign exactly what it shows\"), { cause: last });\n}\n\nconst keyKind = (c: SshSignatureCheck) => c.securityKey\n ? `security key, touch${c.securityKey.userVerified ? \" and PIN\" : \"\"} confirmed`\n : c.key.type === \"ssh-rsa\" ? `RSA ${c.key.bits}` : c.key.type.replace(/^ssh-|^ecdsa-sha2-/, \"\");\n\nfunction sshKeygenSigner(forAccount?: SshForge): ExternalToolSigner<SshEvidence> {\n return {\n id: \"ssh-keygen\", kind: \"external-tool\", label: \"ssh-keygen\",\n description: forAccount\n ? `Sign with an SSH key that your ${SSH_FORGE_LABEL[forAccount]} account lists (Settings → SSH keys).`\n : \"Sign with OpenSSH's ssh-keygen (8.1 or later): a key file, ssh-agent, or a FIDO security key.\",\n instructions: (statement, say = englishSay) => {\n let command: string | undefined;\n try { command = sshSignCommand(statement.text); } catch { command = undefined; }\n const sign = { namespace: SSHSIG_NAMESPACE };\n return {\n steps: [\n ...(command ? [{ text: say(\"steps.run\", \"Run this in a terminal (macOS, Linux, or Git Bash/WSL on Windows). If your key is not ~/.ssh/id_ed25519, change the path after -f; a .pub path works when the private key is in ssh-agent or on a security key.\"), copy: command }] : []),\n { text: command\n ? say(\"steps.orSave\", \"Or save this statement to a file, run ssh-keygen -Y sign -n {{namespace}} -f <your key> <file>, and paste the <file>.sig it writes.\", sign)\n : say(\"steps.save\", \"Save this statement to a file, run ssh-keygen -Y sign -n {{namespace}} -f <your key> <file>, and paste the <file>.sig it writes.\", sign), copy: statement.text },\n { text: say(\"steps.paste\", \"Paste the whole signature it prints, from -----BEGIN SSH SIGNATURE----- to -----END SSH SIGNATURE-----. Your private key never leaves your computer.\") },\n ],\n paste: { label: say(\"paste.label\", \"SSH signature\"), placeholder: \"-----BEGIN SSH SIGNATURE-----\", multiline: true },\n };\n },\n parse(pasted, statement) {\n const signature = canonicalArmor(pasted);\n if (!forAccount) {\n const { key } = parseSshSignature(signature);\n if (key.fingerprint !== statement.binding.subject) throw new Error(`That signature was made by ${key.fingerprint}, not the key you entered (${statement.binding.subject})`);\n }\n return { signature };\n },\n };\n}\n\nfunction parseSshEvidence(raw: unknown): SshEvidence {\n const e = raw as SshEvidence;\n if (!e || typeof e !== \"object\" || Array.isArray(e) || Object.keys(e).join(\",\") !== \"signature\" ||\n typeof e.signature !== \"string\" || e.signature.length > SSHSIG_MAX_ARMOR) throw new Error(\"That is not an SSH signature\");\n return { signature: e.signature };\n}\n\nconst shortFingerprint = (f: string) => `${f.slice(0, 15)}…${f.slice(-4)}`;\n\nexport const ssh: IdentityProofProvider<SshEvidence> = {\n id: \"ssh\",\n label: \"SSH key\",\n category: \"self-custodied\",\n summary: \"Sign once with ssh-keygen\",\n description: \"Proves you hold an SSH key, including FIDO security keys: sign the statement once with ssh-keygen and paste the signature.\",\n platforms: [\"web\", \"extension\", \"desktop\"],\n subject: {\n label: \"Public key\", placeholder: \"ssh-ed25519 AAAA… (or SHA256:…)\",\n help: \"Your public key, the one line in the .pub file. Contacts see its fingerprint.\",\n normalize: normalizeKeySubject, short: shortFingerprint,\n },\n validity: { defaultDays: 90, maxDays: 365 },\n privacy: \"Nothing: the signature is checked on this device. The key's fingerprint links every chat you share it in.\",\n signers: [sshKeygenSigner()],\n parseEvidence: parseSshEvidence,\n async verify(statement, evidence) {\n const check = await verifyStatementSignature(statement, evidence);\n if (check.key.fingerprint !== statement.binding.subject) throw new Error(\"Signed by another SSH key\");\n return { subject: statement.binding.subject, source: `SSH signature (${keyKind(check)})` };\n },\n};\n\nfunction forgeProvider(forge: SshForge): IdentityProofProvider<SshEvidence> {\n const label = SSH_FORGE_LABEL[forge], host = SSH_FORGE_HOST[forge];\n return {\n id: `ssh-${forge}`,\n label: `${label} (SSH key)`,\n category: \"self-custodied\",\n summary: `A key your ${label} account lists`,\n description: `Proves you hold an SSH key your ${label} account publishes: sign the statement once with ssh-keygen. No ${label} login.`,\n limits: `Does not prove a ${label} login: only that a key the account lists is yours, for as long as it stays listed.`,\n platforms: [\"web\", \"extension\", \"desktop\"],\n subject: { label: `${label} username`, placeholder: forge === \"github\" ? \"octocat\" : \"username\", normalize: input => normalizeLogin(forge, input) },\n publicUri: login => `https://${forge === \"github\" ? \"github.com\" : \"gitlab.com\"}/${login}`,\n validity: { defaultDays: 90, maxDays: 365 },\n // Keys get removed from accounts; the contact's app offers \"Check again\" after this. GitHub answers 60 lookups an\n // hour per IP without a login: the automatic re-check spends at most half of them.\n recheck: { afterSeconds: 600, ...forge === \"github\" && { perHour: 30 } },\n privacy: `Your contact's app asks ${host} for this account's public SSH keys, when you share it and on each re-check: ${label} learns the account was looked up, and from which IP address. So does this app when you add it.`,\n signers: [sshKeygenSigner(forge)],\n parseEvidence: parseSshEvidence,\n async verify(statement, evidence, ctx: VerifyContext) {\n const login = statement.binding.subject;\n if (normalizeLogin(forge, login) !== login) throw new Error(`Not a ${label} username`);\n const check = await verifyStatementSignature(statement, evidence);\n const status = await checkSshForge(forge, login, check.key, ctx.fetch, ctx.signal);\n if (status === \"no-account\") throw new Error(`${label} has no account ${login}`);\n if (status === \"not-listed\") throw new Error(`${label}: ${login} does not list the key that signed (${check.key.fingerprint})`);\n return { subject: login, source: `${label}: ${login} (via published SSH key)` };\n },\n };\n}\n\nexport const sshGithub = forgeProvider(\"github\");\nexport const sshGitlab = forgeProvider(\"gitlab\");\n","import type { FoundUpdate } from \"../../../apps/ui/src/lib/updates\";\nimport type { AttachMark, ClientMessage, PostedEvent } from \"./shared/rpc\";\nimport type { OidcPlatform } from \"./proofs/oidc/providers\";\nimport type { OidcWindow } from \"./proofs/oidc/flow\";\nimport type { AtprotoHost } from \"./proofs/atproto/oauth\";\nimport type { CallMedia } from \"@ghostly/core\";\n\n/**\n * What differs between the places this peer runs. The extension keeps the\n * peer in an offscreen document and reaches it through extension messaging;\n * the web app runs it in the page. Everything else is shared.\n */\nexport interface EngineConnection {\n /** An engine call, or an ask for a chat's whole history (`HistoryRequest`). */\n send(request: ClientMessage): void;\n}\n\n/**\n * How a client finds a new version of itself and puts it in place. The web\n * app reloads the tab; an extension from the store reloads itself; an unpacked\n * extension can only point at the download. A host that leaves this out has no\n * updater, and the UI never mentions one.\n */\nexport interface UpdateSource {\n /** Where someone installing by hand should go. */\n downloadUrl: string;\n /** The newest published version, or null when this client already runs it. */\n check(): Promise<FoundUpdate | null>;\n /** Never called for `apply: \"manual\"`. `onProgress` is used where the platform reports it. */\n install(update: FoundUpdate, onProgress?: (fraction: number) => void): Promise<void>;\n /**\n * Calls `listener` when a file of this build is gone from the server (the web app's worker got a 404 for one), so\n * the app checks at once. Returns what stops listening. Left out where the host cannot tell.\n */\n onBuildGone?(listener: () => void): () => void;\n}\n\nexport interface BrowserHost {\n version: string;\n /** Something the user should know about this client, shown in the sidebar. */\n notice?: string;\n /** Left out where this client has no way to learn about new versions. */\n updates?: UpdateSource;\n /**\n * Where this host frames mini-apps (WISP 1200): its runner page, served with the runner's policy as a header. Left\n * out where it runs none (the extension, until it gets its own runner).\n */\n appRunner?: string;\n /** The runner for apps granted `internet` (WISP 1200 · Permissions), under a policy that allows HTTPS and WSS. */\n appNetRunner?: string;\n /**\n * The host serves its runner itself, always with the runner's policy (Desktop: Rust's `ghostly-app` scheme, to app\n * windows only), so the page does not ask for its header. Left out where a web server serves it (it may be one\n * without the header).\n */\n appRunnerServed?: boolean;\n features: {\n /** Can this host reach web apps on the user's machine? A web page only can if they allow it with CORS. */\n shareLocalServices: boolean;\n /** Can this host show a contact's web app on an origin of its own? */\n openServices: boolean;\n /** Can this host restart as another local profile (WISP 04)? The page's own peer, or the extension's offscreen one. */\n profiles?: boolean;\n };\n /**\n * Starts a new peer in place of one that stopped for good (\"Clear all data\"). Left out where the peer lives in the\n * page: reloading the page starts it again. The extension's peer outlives its pages, so it is restarted on purpose.\n */\n restartEngine?(): Promise<void>;\n /**\n * Reaches the peer. `onDisconnect` fires when it goes away; the client then connects again. `since`: the mark this\n * app's pages last mirrored (`AttachMark`), for a host whose peer sends each page what changed since (the extension).\n */\n connect(onMessage: (message: PostedEvent) => void, onDisconnect: () => void, since?: AttachMark): Promise<EngineConnection>;\n /**\n * Asks the user for access to a local origin, where the platform has such a thing: `originPattern` is the\n * extension's host pattern (`http://localhost/*`), `origin` the exact address with its port (`http://localhost:3400`),\n * which the desktop app has Rust ask about in a native dialog.\n */\n requestLocalAccess(originPattern: string, origin: string): Promise<boolean>;\n /**\n * Runs `task` (the share's `addService`, right after `requestLocalAccess` said yes) while no `forgetLocalAccess` or\n * `releaseUnusedLocalAccess`, from this page or another, can give `originPattern` back. Resolves false without running\n * it when the access went back between the two: ask again. Left out where nothing gives access back under a share\n * (Desktop keeps one list per profile, in Rust).\n */\n withLocalAccess?(originPattern: string, task: () => Promise<void>): Promise<boolean>;\n /**\n * May the peer reach `origin` for a contact now? The extension: only an address the person allowed in this browser\n * for this profile (not one that came with a restored or moved profile). Left out where nothing else is asked.\n */\n localAccessAllowed?(origin: string): Promise<boolean>;\n /**\n * The profile no longer shares any app at `origin` (desktop: off Rust's list of addresses it may reach; the extension\n * gives Chrome back `localAccessPattern(origin)` once no profile shares an app at that host, on any port).\n */\n forgetLocalAccess?(origin: string): Promise<void>;\n /**\n * A profile's shared apps all went at once (\"Clear all data\", a profile deleted): the host gives back the local\n * access no profile on this device still needs. The extension's host permissions are every profile's at once.\n */\n releaseUnusedLocalAccess?(): Promise<void>;\n /**\n * `tag` (`viewerTag` of this side's key for the chat) goes in the app's origin, so each profile's storage for it is its own.\n * `relayOnly`: Hide my IP from contacts is on, and the app loads nothing but its own origin while open\n * (`viewerServicePolicy`): a picture or script from a server the contact names would show it this device's address.\n */\n openService(peerPubKeyZ32: string, serviceId: string, tag: string, relayOnly: boolean): Promise<void>;\n /**\n * Erases what the contacts' apps opened from one chat (`tag`, as `openService` was given it) or by one profile\n * (`profile`, its id) kept on this device: their origins' storage, caches and worker. The web app clears its own\n * origins, Desktop has Rust clear its viewers' (`forget_service_origins`), the extension has Chrome clear its viewer\n * tabs' (`chrome.browsingData`).\n */\n forgetServices?(which: { tag: string } | { profile: string }): Promise<void>;\n /**\n * Opens a `lightning:` or `bitcoin:` link in a wallet on this device. Left out where a plain link\n * already does it (a web page); the desktop app and the extension have to hand it to the system.\n */\n openPaymentLink?(uri: string): Promise<void>;\n /**\n * Puts the app's window in or out of full screen. The desktop app on Linux has it: WebKitGTK's element full screen\n * aborts the app there, so the page fills the window with the video instead (apps/desktop/src/fullscreen.rs).\n */\n fullscreenWindow?(on: boolean): Promise<void>;\n /**\n * Hands a link to the system's share sheet, pointing at `anchor` (the button, in CSS pixels).\n * Resolves to false where the platform has no sheet to show; left out where the page's own Web\n * Share API is the way (a web page).\n */\n shareText?(text: string, anchor?: ShareAnchor): Promise<boolean>;\n /**\n * The clipboard's text, read by the platform itself, for a paste button the user just clicked.\n * Left out where the page's `navigator.clipboard.readText()` is the way (a web page, the\n * extension); the desktop app reads natively because WKWebView asks for a second click.\n */\n readClipboardText?(): Promise<string>;\n /**\n * Files copied in a file manager, or a picture, read by the platform itself for a paste whose event\n * carried neither files nor text (a webview that hides them from the page). Left out where the page\n * sees them in the paste event (a browser, WebKit on macOS).\n */\n readClipboardFiles?(): Promise<ClipboardFile[]>;\n /**\n * Copies a secret (an invite, a device's link, a group's link, ecash) marked as sensitive: the Android app, whose\n * system shows every copy in a preview and whose keyboards keep a history of them, but neither for a sensitive one.\n * The page's own copy cannot mark it. Left out where the page's copy is the way.\n */\n copySecret?(text: string): Promise<void>;\n /**\n * Where calls get their media, when not from the page's own WebRTC. Ghostly Desktop on Linux: WebKitGTK has\n * no WebRTC there, and GStreamer runs the calls. Left out where the page has it.\n */\n callMedia?: CallMedia;\n /** Signing in with an OpenID Connect provider for an identity proof. Left out where the platform cannot. */\n oidc?: OidcHost;\n /** Signing in to the person's AT Protocol server (Bluesky or another PDS) for an identity proof. Left out where the platform cannot. */\n atproto?: AtprotoHost;\n /**\n * Opens Pubky Passport's authorize page (`https://passport.pubky.app/authorize#d=…`, the request in its fragment)\n * outside the app. The desktop app hands it to the system browser; left out where the page opens a popup itself.\n */\n openPubkyPassport?(url: string): Promise<void>;\n /**\n * A Pubky cookie session's requests to the homeserver, made outside the page with a cookie jar of their own: the\n * desktop app, whose WKWebView drops the homeserver's session cookie (a third-party one there). Left out where\n * the page's own fetch keeps it.\n */\n pubkyCookieSession?(): PubkyCookieSession;\n /**\n * Keeps the computer from sleeping while idle, or lets it sleep again (\"Keep this computer awake\", WISP 06 § User\n * experience): the desktop app, so a phone can take the profile over while the person is out. Resolves to whether\n * it is held now. Left out where the platform cannot (a web page, the extension). `files`: a file on its way is\n * (one of) the reasons; the Android app holds only for that, a foreground service with its notification, as Android\n * freezes an app out of sight otherwise.\n */\n keepAwake?(on: boolean, files: boolean): Promise<boolean>;\n /**\n * Keeps the app out of the system's app switcher picture while the app lock is on or a secret is on screen\n * (`on`), or lets it be taken again:\n * the Android app, whose switcher takes its picture before the page hears it is going, so the lock's cover comes too\n * late for it. Left out where the page's cover is enough.\n */\n hideFromSwitcher?(on: boolean): Promise<void>;\n}\n\n/** One approval's cookie session, outside the page: its cookies never reach the page, and `close` forgets them. */\nexport interface PubkyCookieSession {\n fetch(request: { url: string; method: string; headers: [string, string][]; body: Uint8Array | null }): Promise<{ status: number; headers: [string, string][]; body: Uint8Array }>;\n close(): void;\n}\n\n/** Where a share sheet points: the button that opened it, in CSS pixels from the page's top left. */\nexport interface ShareAnchor { x: number; y: number; width: number; height: number }\n\nexport interface OidcHost {\n platform: OidcPlatform;\n /**\n * Call it straight from the click: the web app opens its popup and the\n * extension asks for the `identity` permission before anything is awaited,\n * or the browser blocks them.\n */\n open(): Promise<OidcWindow>;\n}\n\nlet current: BrowserHost | null = null;\n\n/** Must be called before anything in `platform/` is used. */\nexport function setBrowserHost(host: BrowserHost): void {\n current = host;\n}\n\nexport function getBrowserHost(): BrowserHost {\n if (!current) throw new Error(\"No browser host configured\");\n return current;\n}\n\n/**\n * The extension's host permission for a local origin (`http://127.0.0.1:3400` is `http://127.0.0.1/*`): one host on\n * every port, as Chrome takes it. What `requestLocalAccess` asks for, and what the extension later gives back.\n */\nexport function localAccessPattern(origin: string): string {\n const url = new URL(origin);\n return `${url.protocol}//${url.hostname}/*`;\n}\n\n/** `releaseUnusedLocalAccess` of the host, where it has one: never throws. */\nexport async function releaseUnusedLocalAccessOf(): Promise<void> {\n await current?.releaseUnusedLocalAccess?.().catch(() => {});\n}\n\n/** `forgetServices` of the host, where it has one: never throws (no host, or one that failed, holds nothing up). */\nexport async function forgetServicesOf(which: { tag: string } | { profile: string }): Promise<void> {\n await current?.forgetServices?.(which).catch(() => {});\n}\n\n/**\n * One thing a paste brought, held by the platform: a file (its name) or a picture (no name: the page\n * names it). `read` hands its bytes a step at a time; `done` says the page has what it wants of\n * it (or gave up), so the platform lets its copy go: nothing is read after it.\n */\nexport interface ClipboardFile {\n name: string | null;\n size: number;\n mime: string | null;\n read(offset: number, length: number): Promise<Uint8Array>;\n done?(): void;\n}\n","/**\n * A provider's signing keys, fetched from its pinned JWKS URL with limits and\n * cached. A key ID that is not in the cached set triggers one early refetch\n * (providers rotate keys), rate-limited so that a stream of made-up key IDs\n * cannot turn a contact's app into a request generator.\n */\n\nimport { IdentityCheckUnavailable } from '@ghostly/core';\n\nexport interface Jwk {\n kty: string; kid?: string; use?: string; alg?: string; key_ops?: string[];\n n?: string; e?: string; crv?: string; x?: string; y?: string;\n /** Microsoft adds the issuer each key signs for. */\n issuer?: string;\n}\n/**\n * How keys are fetched. In `verify` this is the engine's `ctx.fetch` (HTTPS GET, no credentials, no\n * redirects, time-out, size cap); `cacheControl` is used when the fetcher reports it.\n */\nexport type JwksFetch = (url: string, options: { maxBytes: number }) => Promise<{ status: number; text: string; cacheControl?: string | null }>;\n\nexport const JWKS_MAX_BYTES = 64 * 1024;\nexport const JWKS_MAX_KEYS = 32;\nconst MIN_TTL_MS = 5 * 60_000;\nconst MAX_TTL_MS = 24 * 60 * 60_000;\nconst DEFAULT_TTL_MS = 60 * 60_000;\n/** A missing `kid` refetches at most this often per URL. */\nexport const REFETCH_INTERVAL_MS = 60_000;\n\n/** `tried`: the last early refetch for an unknown `kid`, answered or not, so a failing endpoint is not asked on every call. */\ninterface Entry { keys: Jwk[]; expires: number; fetched: number; tried?: number }\n\nfunction allowedUrl(url: string): boolean {\n try {\n const u = new URL(url);\n return u.protocol === 'https:' && !u.username && !u.password && !u.hash;\n } catch { return false; }\n}\n\nfunction ttl(cacheControl: string | null | undefined): number {\n const maxAge = /(?:^|[,\\s])max-age=(\\d+)/i.exec(cacheControl ?? '')?.[1];\n const ms = maxAge ? Number(maxAge) * 1000 : DEFAULT_TTL_MS;\n return Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, ms));\n}\n\nfunction parseKeys(text: string): Jwk[] {\n if (text.length > JWKS_MAX_BYTES) throw new Error('Provider key set too large');\n let doc: { keys?: unknown };\n try { doc = JSON.parse(text) as { keys?: unknown }; } catch { throw new Error('Invalid provider key set'); }\n if (!doc || !Array.isArray(doc.keys) || doc.keys.length > JWKS_MAX_KEYS) throw new Error('Invalid provider key set');\n return doc.keys.filter((k): k is Jwk => !!k && typeof k === 'object' && typeof (k as Jwk).kty === 'string');\n}\n\nexport class JwksCache {\n private entries = new Map<string, Entry>();\n private inflight = new Map<string, Promise<Entry>>();\n constructor(private options: { now?: () => number } = {}) {}\n private now() { return (this.options.now ?? Date.now)(); }\n\n private load(url: string, fetcher: JwksFetch): Promise<Entry> {\n const running = this.inflight.get(url);\n if (running) return running;\n const task = (async () => {\n if (!allowedUrl(url)) throw new Error('Provider key URL refused');\n // Keys that could not be read (not reached, an error status, a page that is not a key set) say nothing of the token.\n let response: Awaited<ReturnType<JwksFetch>>;\n try { response = await fetcher(url, { maxBytes: JWKS_MAX_BYTES }); }\n catch (e) { throw e instanceof IdentityCheckUnavailable ? e : new IdentityCheckUnavailable(`Provider keys could not be fetched: ${e instanceof Error ? e.message : String(e)}`); }\n if (response.status !== 200) throw new IdentityCheckUnavailable(`Provider keys unavailable (${response.status})`);\n let keys: Jwk[];\n try { keys = parseKeys(response.text); } catch (e) { throw new IdentityCheckUnavailable((e as Error).message); }\n const fetched = this.now();\n const entry = { keys, fetched, expires: fetched + ttl(response.cacheControl) };\n this.entries.set(url, entry);\n return entry;\n })();\n this.inflight.set(url, task);\n return task.finally(() => this.inflight.delete(url));\n }\n\n /** The key with this `kid`, refetching once when it is unknown (rotation) or the cache expired. */\n async key(url: string, kid: string, fetcher: JwksFetch): Promise<Jwk | undefined> {\n let entry = this.entries.get(url);\n if (!entry || entry.expires <= this.now()) entry = await this.load(url, fetcher);\n let found = entry.keys.find(k => k.kid === kid);\n if (!found && this.now() - Math.max(entry.fetched, entry.tried ?? 0) >= REFETCH_INTERVAL_MS) {\n // Counted before it is asked: a refetch that fails (an error status, the network down) still waits out the minute.\n entry.tried = this.now();\n entry = await this.load(url, fetcher);\n found = entry.keys.find(k => k.kid === kid);\n }\n return found;\n }\n\n clear(): void { this.entries.clear(); }\n}\n\n/** One cache per app: every contact's proofs share the providers' keys. */\nexport const sharedJwksCache = new JwksCache();\n","import { IDENTITY_CLOCK_SKEW, fromBase64Url, toBase64Url, utf8Decode, utf8Encode } from '@ghostly/core';\nimport { audiences, issuerFor, type OidcAlg, type OidcProvider, type OidcProviderId } from './providers';\nimport { sharedJwksCache, type Jwk, type JwksCache, type JwksFetch } from './jwks';\n\n/**\n * Checks an ID token the way a contact must: the provider's signature under\n * a key from its own JWKS, the pinned `alg`, the issuer, `aud` = one of\n * Ghostly's client IDs for that provider, the time window, and `nonce` = the\n * hash of the exact Ghostly proof statement. Nothing here talks to a Ghostly\n * server, and nothing here trusts what the token says about its own key.\n */\n\n/** Seconds of clock difference accepted on `iat`, `nbf` and `exp`. */\nexport const CLOCK_TOLERANCE = 60;\n/** An ID token that claims to live longer than a day is not a sign-in result. */\nconst MAX_LIFETIME = 24 * 60 * 60;\n/** Room for Microsoft's larger tokens, well inside a peer frame. */\nexport const MAX_ID_TOKEN_LENGTH = 6144;\nconst SEGMENT = /^[A-Za-z0-9_-]+$/;\nconst REFUSED_HEADERS = ['crit', 'jku', 'jwk', 'x5u', 'x5c', 'zip', 'enc'];\n\nexport class OidcVerificationError extends Error {\n constructor(message: string) { super(message); this.name = 'OidcVerificationError'; }\n}\nconst refuse = (message: string): never => { throw new OidcVerificationError(message); };\n\n/** What a contact is shown: only claims the provider signed, bounded. */\nexport interface OidcIdentity {\n provider: OidcProviderId;\n issuer: string;\n subject: string;\n audience: string;\n issuedAt: number;\n expiresAt: number;\n email?: string;\n emailVerified?: boolean;\n name?: string;\n username?: string;\n /** Microsoft's directory (tenant) ID. */\n tenant?: string;\n}\n\nfunction segment(value: string): Uint8Array {\n if (!SEGMENT.test(value)) refuse('Malformed ID token');\n let bytes: Uint8Array;\n try { bytes = fromBase64Url(value); } catch { return refuse('Malformed ID token'); }\n if (toBase64Url(bytes) !== value) refuse('Malformed ID token');\n return bytes;\n}\n\nfunction json(value: string): Record<string, unknown> {\n let parsed: unknown;\n try { parsed = JSON.parse(utf8Decode(segment(value))); } catch (e) { if (e instanceof OidcVerificationError) throw e; return refuse('Malformed ID token'); }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) refuse('Malformed ID token');\n return parsed as Record<string, unknown>;\n}\n\nconst text = (value: unknown, max: number): string | undefined =>\n typeof value === 'string' && value.length > 0 && value.length <= max ? value : undefined;\n\n/** Splits and decodes without verifying anything. Only for display of a token already verified. */\nexport function decodeIdToken(token: string): { header: Record<string, unknown>; claims: Record<string, unknown>; signature: Uint8Array; signed: Uint8Array } {\n if (typeof token !== 'string' || token.length > MAX_ID_TOKEN_LENGTH) refuse('ID token missing or too large');\n const parts = token.split('.');\n if (parts.length !== 3) refuse('Not a signed ID token');\n return { header: json(parts[0]), claims: json(parts[1]), signature: segment(parts[2]), signed: utf8Encode(`${parts[0]}.${parts[1]}`) };\n}\n\nasync function verifySignature(alg: OidcAlg, jwk: Jwk, signed: Uint8Array, signature: Uint8Array): Promise<boolean> {\n if (jwk.use !== undefined && jwk.use !== 'sig') refuse('Provider key is not a signing key');\n if (jwk.alg !== undefined && jwk.alg !== alg) refuse('Provider key is for another algorithm');\n if (jwk.key_ops !== undefined && !(Array.isArray(jwk.key_ops) && jwk.key_ops.includes('verify'))) refuse('Provider key is not a signing key');\n let key: CryptoKey;\n if (alg === 'RS256') {\n if (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') return refuse('Provider key does not match the token algorithm');\n const modulus = segment(jwk.n);\n const bits = (modulus.length - (modulus[0] === 0 ? 1 : 0)) * 8;\n if (bits < 2048 || bits > 8192) refuse('Provider key size refused');\n key = await crypto.subtle.importKey('jwk', { kty: 'RSA', n: jwk.n, e: jwk.e, ext: true }, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']);\n return crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, signature as BufferSource, signed as BufferSource);\n }\n if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || typeof jwk.x !== 'string' || typeof jwk.y !== 'string') return refuse('Provider key does not match the token algorithm');\n if (signature.length !== 64) refuse('Invalid ID token signature');\n key = await crypto.subtle.importKey('jwk', { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, ext: true }, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']);\n return crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, signature as BufferSource, signed as BufferSource);\n}\n\n/** Whether `iss` is this provider's, as it words it (Microsoft: with the token's own tenant). */\nexport function issuerMatches(provider: OidcProvider, claims: Record<string, unknown>): boolean {\n const iss = text(claims.iss, 512);\n return !!iss && issuerFor(provider, claims).includes(iss);\n}\n\nexport interface VerifyOptions {\n provider: OidcProvider;\n /** The nonce the sign-in was asked for: an identity proof's `statement.id`. */\n nonce: string;\n /** How the provider's keys are fetched: `ctx.fetch` in a proof's `verify`. */\n fetch: JwksFetch;\n /** Unix seconds. */\n now?: number;\n jwks?: JwksCache;\n /**\n * `[from, to]` in Unix seconds: the token must have been issued in this window. For a proof, the\n * sign-in that followed the statement; the token's own `exp` (an hour) then does not matter, the\n * statement's validity does. Without it, the token must still be unexpired.\n */\n issuedWithin?: [number, number];\n}\n\nexport async function verifyIdToken(token: string, options: VerifyOptions): Promise<OidcIdentity> {\n const { provider, nonce } = options;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n const { header, claims, signature, signed } = decodeIdToken(token);\n\n // The algorithm is the provider's, never the token's choice: `none`, HS256\n // (a public key used as an HMAC secret) and anything unpinned stop here.\n const alg = header.alg;\n if (typeof alg !== 'string' || !provider.algs.includes(alg as OidcAlg)) refuse(`Algorithm ${typeof alg === 'string' ? alg : 'missing'} is not accepted for ${provider.name}`);\n if (header.typ !== undefined && (typeof header.typ !== 'string' || header.typ.toUpperCase() !== 'JWT')) refuse('Not an ID token');\n for (const name of REFUSED_HEADERS) if (name in header) refuse('ID token header refused');\n const kid = text(header.kid, 256) ?? refuse('ID token names no provider key');\n\n if (!issuerMatches(provider, claims)) refuse(`Token was not issued by ${provider.name}`);\n const iss = claims.iss as string;\n\n const expected = audiences(provider);\n if (!expected.length) refuse(`${provider.name} is not configured in this Ghostly build`);\n const aud = typeof claims.aud === 'string' ? [claims.aud] : Array.isArray(claims.aud) && claims.aud.every(a => typeof a === 'string') ? claims.aud as string[] : [];\n const audience = aud.find(a => expected.includes(a)) ?? refuse('Token was issued to another app');\n if (aud.length > 1 && claims.azp !== audience) refuse('Token was issued to another app');\n if (claims.azp !== undefined && claims.azp !== audience) refuse('Token was issued to another app');\n\n const iat = claims.iat, exp = claims.exp, nbf = claims.nbf;\n if (typeof iat !== 'number' || typeof exp !== 'number' || !Number.isFinite(iat) || !Number.isFinite(exp)) return refuse('Token has no validity window');\n if (exp <= iat || exp - iat > MAX_LIFETIME) refuse('Token validity window refused');\n // A proof's sign-in may be checked on a clock as slow as the proof engine accepts.\n if (iat > now + (options.issuedWithin ? IDENTITY_CLOCK_SKEW : CLOCK_TOLERANCE)) refuse('Token is not valid yet');\n if (options.issuedWithin) {\n const [from, to] = options.issuedWithin;\n if (iat < from || iat > to) refuse('The sign-in does not belong to this proof: it happened at another time');\n } else {\n if (typeof nbf === 'number' && nbf > now + CLOCK_TOLERANCE) refuse('Token is not valid yet');\n if (exp + CLOCK_TOLERANCE < now) refuse('Token expired');\n }\n\n if (typeof claims.nonce !== 'string' || claims.nonce !== nonce) refuse('Token answers another proof request');\n const subject = text(claims.sub, 255) ?? refuse('Token names no account');\n\n const jwk = await (options.jwks ?? sharedJwksCache).key(provider.jwksUri, kid, options.fetch) ?? refuse(`${provider.name} does not publish the key that signed this token`);\n if (provider.id === 'microsoft' && jwk.issuer !== undefined && jwk.issuer !== provider.issuer && jwk.issuer !== iss) refuse('Provider key belongs to another issuer');\n let valid = false;\n try { valid = await verifySignature(alg as OidcAlg, jwk, signed, signature); }\n catch (e) { if (e instanceof OidcVerificationError) throw e; refuse('Invalid ID token signature'); }\n if (!valid) refuse('Invalid ID token signature');\n\n const verified = claims.email_verified === true || claims.email_verified === 'true' ? true : claims.email_verified === false || claims.email_verified === 'false' ? false : undefined;\n return {\n provider: provider.id, issuer: iss, subject, audience, issuedAt: Math.floor(iat), expiresAt: Math.floor(exp),\n email: text(claims.email, 320), emailVerified: text(claims.email, 320) ? verified : undefined,\n name: text(claims.name, 200), username: text(claims.preferred_username, 200) ?? text(claims.nickname, 200),\n tenant: provider.id === 'microsoft' ? text(claims.tid, 64) : undefined,\n };\n}\n","import { randomBytes, toBase64Url, utf8Encode } from '@ghostly/core';\nimport { clientIdFor, type OidcPlatform, type OidcProvider, type OidcReveal } from './providers';\nimport { decodeIdToken, issuerMatches } from './verify';\n\n/**\n * The sign-in half: send the person to the provider with the identity proof's\n * statement id as `nonce`, and take back only the ID token. The token's\n * signature is checked by the proof's `verify`, before saving and on every\n * contact's device; here only that it answers this request. Access and refresh tokens are never requested\n * where the provider allows it, and dropped (and revoked) where it does not.\n */\n\n/** How a platform shows the provider's page and hands back where it redirected. */\nexport interface OidcWindow {\n /** The redirect URI registered for this platform. */\n redirectUri: string;\n /** Extra state prefix the platform needs to route the answer back (desktop: its loopback port). */\n statePrefix?: string;\n /** Opens `url` and resolves with the full URL the provider redirected to. */\n authorize(url: string, signal: AbortSignal): Promise<string>;\n /** Releases the window or listener, answered or not. */\n close(): void;\n}\n\nexport interface OidcRequest {\n url: string;\n state: string;\n nonce: string;\n redirectUri: string;\n clientId: string;\n /** PKCE verifier, only for `code`. Held in memory for the one exchange. */\n verifier?: string;\n}\n\n/** Optional platform prefix (desktop `d.<port>.`, Android deep link `a.`), then 32 random bytes. */\nconst STATE = /^(?:d\\.\\d{1,5}\\.|a\\.)?[A-Za-z0-9_-]{43}$/;\n\nexport function scopeFor(provider: OidcProvider, reveal: OidcReveal[]): { scope: string; claims?: string } {\n const scopes = provider.id === 'apple' ? [] : ['openid'];\n const claims: string[] = [];\n for (const r of reveal) {\n const option = provider.reveal[r];\n if (!option) continue;\n if (option.scope) scopes.push(option.scope);\n if (option.claims) claims.push(...option.claims);\n }\n return { scope: scopes.join(' '), claims: claims.length ? JSON.stringify({ id_token: Object.fromEntries(claims.map(c => [c, null])) }) : undefined };\n}\n\nexport async function authorizationRequest(options: { provider: OidcProvider; platform: OidcPlatform; nonce: string; reveal: OidcReveal[]; redirectUri: string; statePrefix?: string }): Promise<OidcRequest> {\n const { provider } = options;\n const clientId = clientIdFor(provider, options.platform);\n if (!clientId) throw new Error(`${provider.name} sign-in is not set up in this Ghostly build yet.`);\n const { nonce } = options;\n if (!/^[A-Za-z0-9_-]{16,128}$/.test(nonce)) throw new Error('Invalid sign-in nonce');\n const state = `${options.statePrefix ?? ''}${toBase64Url(randomBytes(32))}`;\n const url = new URL(provider.authorizationEndpoint);\n const { scope, claims } = scopeFor(provider, options.reveal);\n const params: Record<string, string> = {\n client_id: clientId, redirect_uri: options.redirectUri, response_type: provider.responseType,\n nonce, state, ...(scope ? { scope } : {}), ...(claims ? { claims } : {}), ...provider.extraParams,\n };\n let verifier: string | undefined;\n if (provider.responseType === 'code') {\n verifier = toBase64Url(randomBytes(32));\n params.code_challenge = toBase64Url(new Uint8Array(await crypto.subtle.digest('SHA-256', utf8Encode(verifier) as BufferSource)));\n params.code_challenge_method = 'S256';\n }\n for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);\n return { url: url.toString(), state, nonce, redirectUri: options.redirectUri, clientId, verifier };\n}\n\n/** Parameters from the redirect: the fragment for implicit responses, the query for `code`. */\nexport function callbackParams(redirected: string, redirectUri: string): URLSearchParams {\n const url = new URL(redirected), expected = new URL(redirectUri);\n if (url.origin !== expected.origin || url.pathname !== expected.pathname) throw new Error('Sign-in returned to an unexpected address.');\n const params = new URLSearchParams(url.hash.slice(1));\n for (const [k, v] of new URLSearchParams(url.search)) if (!params.has(k)) params.set(k, v);\n return params;\n}\n\nconst PROVIDER_ERRORS: Record<string, string> = {\n access_denied: 'Sign-in was cancelled.',\n login_required: 'Sign in to your account and try again.',\n consent_required: 'Consent was not given.',\n interaction_required: 'The provider needs you to finish signing in.',\n unauthorized_client: 'This provider has not accepted Ghostly’s sign-in yet.',\n invalid_request: 'The provider refused the sign-in request.',\n};\n\nasync function exchangeCode(provider: OidcProvider, request: OidcRequest, code: string, doFetch: typeof fetch): Promise<string> {\n if (!provider.tokenEndpoint || !request.verifier) throw new Error('This provider cannot finish sign-in here.');\n const response = await doFetch(provider.tokenEndpoint, {\n method: 'POST', redirect: 'error', credentials: 'omit', referrerPolicy: 'no-referrer', cache: 'no-store',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: request.redirectUri, client_id: request.clientId, code_verifier: request.verifier }),\n });\n const body = await response.json().catch(() => ({})) as { id_token?: unknown; access_token?: unknown; refresh_token?: unknown };\n // Only the ID token leaves this function. The others were never wanted:\n // revoke them without waiting, and let them go out of scope.\n for (const token of [body.refresh_token, body.access_token]) {\n if (typeof token === 'string' && provider.revocationEndpoint)\n void doFetch(provider.revocationEndpoint, { method: 'POST', redirect: 'error', credentials: 'omit', referrerPolicy: 'no-referrer',\n headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ token, client_id: request.clientId }) }).catch(() => {});\n }\n if (!response.ok || typeof body.id_token !== 'string') throw new Error(`${provider.name} did not return an ID token.`);\n return body.id_token;\n}\n\n/** Turns the redirect into the ID token: state, provider error, code exchange if needed, and that it answers this request. */\nexport async function completeSignIn(provider: OidcProvider, request: OidcRequest, redirected: string, options: { fetch?: typeof fetch } = {}): Promise<string> {\n const params = callbackParams(redirected, request.redirectUri);\n const state = params.get('state');\n if (!state || !STATE.test(state) || state !== request.state) throw new Error('Sign-in answer does not belong to this request.');\n const error = params.get('error');\n if (error) throw new Error(PROVIDER_ERRORS[error] ?? 'The provider refused the sign-in.');\n let idToken: string | null;\n if (provider.responseType === 'code') {\n const code = params.get('code');\n if (!code || code.length > 2048) throw new Error(`${provider.name} did not return a sign-in code.`);\n idToken = await exchangeCode(provider, request, code, options.fetch ?? fetch);\n } else idToken = params.get('id_token');\n // Apple's code needs a client secret to redeem, which Ghostly does not have: it is dropped with the rest.\n if (!idToken) throw new Error(`${provider.name} did not return an ID token.`);\n const { claims } = decodeIdToken(idToken);\n if (claims.nonce !== request.nonce || !issuerMatches(provider, claims)) throw new Error(`${provider.name} answered another sign-in request.`);\n return idToken;\n}\n\n/** Everything the prover does: sign in on this platform and return the ID token for this nonce. */\nexport async function signInForProof(options: {\n provider: OidcProvider; platform: OidcPlatform; nonce: string; reveal: OidcReveal[];\n window: OidcWindow; signal: AbortSignal; fetch?: typeof fetch;\n}): Promise<string> {\n const { window: w } = options;\n try {\n options.signal.throwIfAborted();\n const request = await authorizationRequest({ ...options, redirectUri: w.redirectUri, statePrefix: w.statePrefix });\n const redirected = await w.authorize(request.url, options.signal);\n options.signal.throwIfAborted();\n const idToken = await completeSignIn(options.provider, request, redirected, options);\n refuseUnchosenClaims(options.provider, idToken, options.reveal);\n return idToken;\n } finally { w.close(); }\n}\n\n/** A token the provider filled with more than the person chose to share never becomes evidence: it would go to every contact. */\nexport function refuseUnchosenClaims(provider: OidcProvider, idToken: string, reveal: OidcReveal[]): void {\n const { claims } = decodeIdToken(idToken);\n for (const [claim, coveredBy] of Object.entries(provider.disclosing ?? {})) {\n if (claims[claim] === undefined || reveal.includes(coveredBy)) continue;\n throw new Error(claim === 'hd'\n ? `This is a work or school ${provider.name} account: ${provider.name} adds its organisation’s domain to the sign-in, and your contacts would see it. Choose to share your email too, or sign in with a personal account.`\n : `${provider.name} added more to the sign-in than you chose to share. Choose to share your ${coveredBy} too, or sign in with another account.`);\n }\n}\n","import { IDENTITY_CLOCK_SKEW, type IdentityStatement } from \"@ghostly/core\";\nimport { englishSay, type IdentityProofProvider, type IdentityPlatform, type RedirectSigner } from \"../contract\";\nimport { getBrowserHost, type OidcHost } from \"../../host\";\nimport { audiences, isConfigured, oidcProviders, providerForIssuer, type OidcProvider, type OidcReveal } from \"../oidc/providers\";\nimport { signInForProof } from \"../oidc/flow\";\nimport { MAX_ID_TOKEN_LENGTH, verifyIdToken } from \"../oidc/verify\";\nimport { JwksCache, sharedJwksCache } from \"../oidc/jwks\";\nimport { oidcDisplaySource } from \"../displaySource\";\n\n/**\n * Identity proofs through OpenID Connect: the person signs in with a provider (Google, Microsoft,\n * Apple, GitLab, Twitch) whose ID token carries the statement id as `nonce`. The token is the evidence;\n * a contact's app checks the provider's signature against its published keys, the issuer, Ghostly's\n * client ID, the nonce and when the sign-in happened. No Ghostly server is involved, and the proof is\n * only as good as the provider's word: it is attested, not a key the person holds.\n *\n * The statement's subject is the issuer the person picked; the account comes out of `verify`.\n * Configuration and flows per provider: ../oidc/, docs/OIDC-PROVIDERS.md, docs/wisps/3xx-oidc-proofs.md.\n */\nexport interface OidcEvidence { token: string }\n\n/** How long after the statement the sign-in may have happened: time to pick an account and approve. */\nconst SIGN_IN_WINDOW = 15 * 60;\nconst TOKEN = /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/;\nconst SUB = /^[\\x21-\\x7e]{1,255}$/;\n\nfunction currentHost(): OidcHost | undefined {\n try { return getBrowserHost().oidc; } catch { return undefined; }\n}\n\nconst hostOf = (issuer: string) => { try { return new URL(issuer).host; } catch { return issuer; } };\n\nexport interface OidcIdentityOptions {\n /** The OIDC providers this build knows (tests pass configured ones). */\n providers?: () => OidcProvider[];\n /** The platform's sign-in window. */\n host?: () => OidcHost | undefined;\n /** Provider keys, cached across proofs. */\n jwks?: JwksCache;\n /** The UI-side fetch for GitLab's code exchange. */\n fetch?: typeof fetch;\n}\n\nexport function createOidcIdentityProvider(options: OidcIdentityOptions = {}): IdentityProofProvider<OidcEvidence> {\n const providers = options.providers ?? (() => oidcProviders());\n const host = options.host ?? currentHost;\n const configured = () => providers().filter(p => audiences(p).length > 0);\n\n const signer = (id: string, label: string, description: string, reveal: OidcReveal[]): RedirectSigner<OidcEvidence> => ({\n id, kind: \"redirect\", label, description,\n available: () => { const h = host(); return !!h && providers().some(p => isConfigured(p, h.platform)); },\n start(statement: IdentityStatement, ctx) {\n // Before any await: the popup and the extension's permission prompt need the click's user activation.\n const h = host();\n const opening = h?.open();\n return (async () => {\n if (!h || !opening) throw new Error(\"Signing in with a provider is not available here.\");\n const provider = providerForIssuer(statement.binding.subject, providers());\n if (!provider || !isConfigured(provider, h.platform)) { void opening.then(w => w.close(), () => {}); throw new Error(\"This provider is not set up in this Ghostly build.\"); }\n ctx.onProgress((ctx.say ?? englishSay)(\"signIn\", \"Sign in with {{provider}} in the window that opened.\", { provider: provider.name }));\n const token = await signInForProof({\n provider, platform: h.platform, nonce: statement.id, window: await opening, signal: ctx.signal, fetch: options.fetch,\n // What the provider cannot put in its token is not asked for.\n reveal: reveal.filter(r => provider.reveal[r]),\n });\n return { token };\n })();\n },\n });\n\n return {\n id: \"oidc\",\n label: \"Account at a provider\",\n category: \"provider-attested\",\n summary: \"Sign in with Google, Microsoft, Apple…\",\n description: \"Sign in with Google, Microsoft, Apple, GitLab or Twitch: the provider vouches to Ghostly, with a signed token, that the account is yours.\",\n limits: \"Attested by the provider, not by a key you hold: your contact trusts that company.\",\n platforms: [\"web\", \"extension\", \"desktop\"] satisfies IdentityPlatform[],\n subject: {\n label: \"Provider\",\n help: \"Your contact sees your account’s identifier at that provider, plus what you choose to add. GitLab also adds the groups you belong to directly; Apple never gives Ghostly your email.\",\n get options() { return configured().map(p => ({ value: p.issuer, label: p.name })); },\n normalize(input: string) {\n const provider = providerForIssuer(input.trim(), configured());\n if (!provider) throw new Error(\"Choose a provider\");\n return provider.issuer;\n },\n short: subject => providerForIssuer(subject, providers())?.name ?? hostOf(subject),\n },\n // Providers rotate their signing keys within weeks (Google about every two); a contact can only\n // check a token while its key is still published, so a proof is short-lived.\n validity: { defaultDays: 7, maxDays: 14 },\n privacy: \"Your contact’s app downloads the provider’s public keys (for example from www.googleapis.com), so the provider sees that some app checked a sign-in, not whose. Your contact sees the account identifier and what you chose to share.\",\n signers: [\n signer(\"oidc-account\", \"Sign in: share the account only\", \"The token carries the provider’s identifier for your account, nothing else.\", []),\n signer(\"oidc-email\", \"Sign in: share the account and email\", \"Adds your email address, where the provider offers it.\", [\"email\"]),\n signer(\"oidc-profile\", \"Sign in: share the account, email and name\", \"Adds your email address and name or username, where the provider offers them.\", [\"email\", \"profile\"]),\n ],\n parseEvidence(raw) {\n const e = raw as OidcEvidence;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw) || Object.keys(raw).join(\",\") !== \"token\" ||\n typeof e.token !== \"string\" || e.token.length > MAX_ID_TOKEN_LENGTH || !TOKEN.test(e.token)) throw new Error(\"Invalid sign-in token\");\n return { token: e.token };\n },\n async verify(statement, { token }, ctx) {\n const provider = providerForIssuer(statement.binding.subject, providers());\n if (!provider) throw new Error(\"This app does not know this provider\");\n const id = await verifyIdToken(token, {\n provider, nonce: statement.id, now: ctx.now, jwks: options.jwks ?? sharedJwksCache,\n fetch: async (url, { maxBytes }) => { const r = await ctx.fetch(url, { maxBytes, signal: ctx.signal }); return { status: r.status, text: r.text }; },\n issuedWithin: [statement.binding.issuedAt - IDENTITY_CLOCK_SKEW, statement.binding.issuedAt + SIGN_IN_WINDOW],\n });\n if (!SUB.test(id.subject)) throw new Error(\"The provider’s account identifier cannot be shown\");\n const attester = hostOf(provider.issuer);\n const person = id.name ?? id.username;\n // A display name is the account's own words (its holder's, or any directory admin's): only a GitLab or Twitch\n // username, unique at the provider, is the provider's. Any other carries that caveat, never shown as checked.\n const handle = !id.name && (provider.id === \"gitlab\" || provider.id === \"twitch\");\n // Only an email the provider marks verified names the account; one it does not (Microsoft never says) is left out.\n const email = id.emailVerified ? id.email : undefined;\n const name = email ? (person && `${person} · ${email}`.length <= 64 ? `${person} · ${email}` : email) : person;\n const url = id.username && /^[A-Za-z0-9_.-]{1,64}$/.test(id.username)\n ? provider.id === \"gitlab\" ? `https://gitlab.com/${id.username}` : provider.id === \"twitch\" ? `https://www.twitch.tv/${id.username}` : undefined\n : undefined;\n return {\n // Microsoft's issuer names the account's tenant; the others are fixed.\n subject: `${provider.id === \"microsoft\" ? id.issuer : provider.issuer}#${id.subject}`,\n attester,\n source: `ID token signed by ${attester}`,\n // With an email, always: a recheck then replaces a display stored before (which kept the email as the name).\n ...(name || url || id.email ? { display: {\n ...(name ? { name } : {}), ...(url ? { url } : {}), fetchedAt: id.issuedAt,\n source: oidcDisplaySource(provider.name, id.email ? id.emailVerified ? \"verified\" : \"unverified\" : undefined, !!person && !handle),\n } } : {}),\n };\n },\n };\n}\n\nexport const oidc = createOidcIdentityProvider();\n","import {\n DidDhtError, DidError, DID_DOCUMENT_MAX_BYTES, IdentityCheckUnavailable, resolveDidDht, DID_FILE_MAX_BYTES, didWebDocumentUrl, didWebFileUrl, didWebHost, parseDid, parseDidDocument, staticDidDocument,\n type DidDocumentView, type DidMethod,\n} from \"@ghostly/core\";\nimport type { IdentityFetch } from \"./contract\";\nimport { assertPublicHost, chosenResolver, DomainCheckError, type DohResolverId } from \"./domain\";\nimport { pkarrRelays } from \"./pkarrRelays\";\n\n/**\n * Network side of DID proofs: resolving a DID to the keys its document lists, under the same limits as the\n * other providers. did:key and did:jwk need no network. did:web is one HTTPS GET of its did.json (bounded,\n * no redirect, after checking that the domain's addresses are public, like the domain proof). did:dht is a\n * signed Pkarr record read from one of the profile's Pkarr relays (`resolveDidDht`, WISP 310-did-dht).\n *\n * What a check reveals, and to whom:\n * - did:web: the DNS-over-HTTPS resolver learns the domain; the domain's web server, run by the person\n * being checked, sees this device's IP address and when.\n * - did:dht: the Pkarr relay asked (one of the profile's, Network settings) learns which DID was looked up, from\n * which IP address.\n */\n\nexport interface DidResolution {\n method: DidMethod;\n document: DidDocumentView;\n /** did:web: the host, and where its did.json was read. */\n host?: string;\n documentUrl?: string;\n /** did:dht: the relay that answered. */\n relay?: string;\n}\n\nexport interface DidResolveOptions {\n fetch: IdentityFetch;\n signal?: AbortSignal;\n /** Milliseconds. */\n now?: () => number;\n resolver?: DohResolverId;\n /** did:dht resolution; tests pass their own. */\n dht?: typeof resolveDidDht;\n}\n\n/** Resolutions are shared for this long: back-to-back checks and the add dialog's preview, never a stale key for long. */\nconst CACHE_MS = 30_000;\nconst cache = new Map<string, { until: number; result: Promise<DidResolution> }>();\n/** The last document seen per DID, without expiry, for the signer's instructions (which cannot wait). */\nconst seen = new Map<string, DidResolution>();\n\n/** Tests only. */\nexport function clearDidCache(): void { cache.clear(); seen.clear(); }\n\n/** What this app last resolved for `did`, if anything: the add dialog's instructions name its keys. */\nexport const lastDidResolution = (did: string): DidResolution | undefined => seen.get(did);\n\nasync function fetchDidWeb(did: string, url: string, maxBytes: number, options: DidResolveOptions): Promise<string | undefined> {\n const host = didWebHost(did);\n try {\n await assertPublicHost(host, { fetch: options.fetch, signal: options.signal, resolver: options.resolver ?? chosenResolver().id, now: options.now });\n } catch (e) { throw e instanceof DomainCheckError ? new DidError(e.message) : e; }\n let response: Awaited<ReturnType<IdentityFetch>>;\n try {\n response = await options.fetch(url, { headers: { accept: \"application/did+json, application/json\" }, maxBytes, signal: options.signal, redirect: \"error\" });\n } catch (e) {\n if (options.signal?.aborted) throw e;\n if (/too large/i.test(String(e))) throw new DidError(`${url} is too large`);\n // What this side's network did is not the contact's to learn (the host and port are theirs to choose).\n throw new IdentityCheckUnavailable(`${host} could not be reached. It must serve ${url} over HTTPS, without a redirect, with the header Access-Control-Allow-Origin: *`);\n }\n if (response.status === 404 || response.status === 410) return undefined;\n if (response.status >= 300 && response.status < 400) throw new IdentityCheckUnavailable(`${host} answered with a redirect; it must serve exactly ${url}`);\n if (response.status !== 200) throw new IdentityCheckUnavailable(`${host} answered ${response.status} for ${url}`);\n try { return new TextDecoder(\"utf-8\", { fatal: true }).decode(response.bytes); } catch { throw new DidError(`${url} is not text`); }\n}\n\nasync function resolve(did: string, method: DidMethod, options: DidResolveOptions): Promise<DidResolution> {\n if (method === \"key\" || method === \"jwk\") return { method, document: staticDidDocument(did) };\n if (method === \"web\") {\n const documentUrl = didWebDocumentUrl(did);\n const text = await fetchDidWeb(did, documentUrl, DID_DOCUMENT_MAX_BYTES, options);\n if (text === undefined) throw new DidError(`No DID document at ${documentUrl}`);\n let raw: unknown;\n try { raw = JSON.parse(text); } catch { throw new DidError(`${documentUrl} is not JSON`); }\n return { method, document: parseDidDocument(did, raw), host: didWebHost(did), documentUrl };\n }\n // No relay answered (not reached, or an error status): this side's network, which says nothing of the DID.\n const fetch: IdentityFetch = (url, init) => options.fetch(url, { ...init, ownPkarrRelay: true });\n const found = await (options.dht ?? resolveDidDht)(did, { fetch, signal: options.signal, relays: pkarrRelays() })\n .catch((e: unknown) => { throw e instanceof DidDhtError && e.code === \"unreachable\" ? new IdentityCheckUnavailable(e.message) : e; });\n if (found.metadata.deactivated) throw new DidError(\"This DID is deactivated: its owner retired it\");\n return { method, document: parseDidDocument(did, found.document), relay: found.relay };\n}\n\n/** A DID's document as far as Ghostly uses it. Concurrent and back-to-back resolutions share one lookup. */\nexport async function resolveDid(input: string, options: DidResolveOptions): Promise<DidResolution> {\n const { did, method } = parseDid(input);\n const now = options.now ?? Date.now;\n const hit = cache.get(did);\n if (hit && hit.until > now()) return hit.result;\n const entry = { until: now() + CACHE_MS, result: resolve(did, method, options) };\n cache.set(did, entry);\n if (cache.size > 64) cache.delete(cache.keys().next().value!);\n try {\n const result = await entry.result;\n seen.delete(did);\n seen.set(did, result);\n if (seen.size > 16) seen.delete(seen.keys().next().value!);\n return result;\n } catch (e) {\n if (cache.get(did) === entry) cache.delete(did);\n throw e;\n }\n}\n\n/** The statement file a did:web publishes for proof `proofId`; undefined when the server says it is not there. */\nexport async function fetchDidWebFile(did: string, proofId: string, options: DidResolveOptions): Promise<string | undefined> {\n return fetchDidWeb(did, didWebFileUrl(did, proofId), DID_FILE_MAX_BYTES, options);\n}\n","import {\n checkDidJws, checkDidSignature, DidError, DID_JWS_MAX_LENGTH, didGhostlyServiceEntry, didJwsAlg, didSignedMessages, didWebFile, didWebFileNames,\n didWebFileUrl, normalizeDid, parseDid, parseDidSignaturePaste, signingKeys, staticDidDocument, strictBase64Url, toBase64Url,\n type DidCurve, type DidKey, type IdentityStatement,\n} from \"@ghostly/core\";\nimport { englishSay, type ExternalToolSigner, type IdentityProofProvider, type ProviderSay, type PublishSigner, type SignerInstructions, type SubjectPreview } from \"../contract\";\nimport { fetchDidWebFile, lastDidResolution, resolveDid, type DidResolution } from \"../did\";\nimport { ownDid } from \"../ownDid\";\nimport { boundedIdentityFetch } from \"../verify\";\n\n/**\n * A decentralized identifier (W3C DID Core), draft WISP 311-did. The subject is the DID; the statement is\n * vouched for by a key its document lists under `authentication` or `assertionMethod` (a JWS or a raw\n * signature pasted back, like SSH and PGP), or, for did:web, by publishing it where the DID document lives\n * (a file beside did.json, or a service entry in it), like the domain proof.\n *\n * Methods: did:key and did:jwk (the key is the identifier: checked offline), did:dht (a signed Pkarr\n * record), did:web (HTTPS). Every check resolves the DID again, so a key removed from a did:web or did:dht\n * document stops counting at the contact's next check.\n */\n\nexport type DidEvidence =\n | { method: \"jws\"; vm: string; jws: string }\n | { method: \"sig\"; vm: string; sig: string }\n | { method: \"file\" }\n | { method: \"service\" };\n\nconst VM = /^did:[a-z0-9]+:[\\x21-\\x7e]+#[\\x21-\\x7e]+$/;\nconst SIG = /^[A-Za-z0-9_-]{86}$/;\nconst exactKeys = (raw: unknown, keys: string) => !!raw && typeof raw === \"object\" && !Array.isArray(raw) && Object.keys(raw).sort().join(\",\") === keys;\nconst validVm = (vm: unknown): vm is string => typeof vm === \"string\" && vm.length <= 640 && VM.test(vm);\n\nexport { setOwnDidSource } from \"../ownDid\";\n\n/** The add dialog's checks run in the UI, with the same bounded fetch the engine uses. */\nconst uiFetch = boundedIdentityFetch({ online: () => globalThis.navigator?.onLine !== false });\n\n/** `#key-1`, shortened when a multibase fragment is long. */\nconst fragment = (id: string) => {\n const f = id.slice(id.indexOf(\"#\"));\n return f.length > 20 ? `${f.slice(0, 11)}…${f.slice(-4)}` : f;\n};\n\nfunction shortDid(did: string): string {\n if (did.length <= 30) return did;\n const { method, id } = parseDidSafe(did);\n if (method === \"web\") return `did:web:${id.split(\":\")[0]}${id.includes(\":\") ? \":…\" : \"\"}`;\n return `did:${method}:${id.slice(0, 8)}…${id.slice(-4)}`;\n}\nconst parseDidSafe = (did: string) => { try { return parseDid(did); } catch { return { did, method: did.split(\":\")[1] ?? \"\", id: did.split(\":\").slice(2).join(\":\") }; } };\n\n/** Keys the instructions can name before anything is fetched: the identifier's own, or what the preview resolved. */\nfunction knownKeys(did: string): DidKey[] {\n const { method } = parseDid(did);\n if (method === \"key\" || method === \"jwk\") return signingKeys(staticDidDocument(did));\n const seen = lastDidResolution(did);\n return seen ? signingKeys(seen.document) : [];\n}\n\nconst NOBLE: Record<DidCurve, { name: string; module: string }> = {\n Ed25519: { name: \"ed25519\", module: \"ed25519.js\" },\n secp256k1: { name: \"secp256k1\", module: \"secp256k1.js\" },\n \"P-256\": { name: \"p256\", module: \"nist.js\" },\n};\n\nfunction joseScript(statement: string, kid?: string): string {\n return [\n \"// npm install jose; then: node sign.mjs your-private-key.jwk.json\",\n \"import { readFileSync } from \\\"node:fs\\\";\",\n \"import { CompactSign, importJWK } from \\\"jose\\\";\",\n `const statement = ${JSON.stringify(statement)};`,\n \"const jwk = JSON.parse(readFileSync(process.argv[2], \\\"utf8\\\"));\",\n \"const alg = { Ed25519: \\\"EdDSA\\\", \\\"P-256\\\": \\\"ES256\\\" }[jwk.crv];\",\n \"const jws = await new CompactSign(new TextEncoder().encode(statement))\",\n ` .setProtectedHeader({ alg${kid ? `, kid: ${JSON.stringify(kid)}` : \"\"} })`,\n \" .sign(await importJWK(jwk, alg));\",\n \"console.log(jws);\",\n ].join(\"\\n\");\n}\n\nfunction nobleScript(statement: string, curve: DidCurve): string {\n const lib = NOBLE[curve];\n return [\n \"// npm install @noble/curves; then: node sign.mjs your-private-key.hex\",\n \"import { readFileSync } from \\\"node:fs\\\";\",\n `import { ${lib.name} } from \"@noble/curves/${lib.module}\";`,\n `const statement = new TextEncoder().encode(${JSON.stringify(statement)});`,\n \"const secret = Uint8Array.from(Buffer.from(readFileSync(process.argv[2], \\\"utf8\\\").trim(), \\\"hex\\\"));\",\n `console.log(Buffer.from(${lib.name}.sign(statement, secret)).toString(\"hex\"));`,\n ].join(\"\\n\");\n}\n\n/** OpenSSL alone: the signature comes out as one line of base64 (xxd, for hex, is missing on many Linux systems). */\nfunction opensslCommand(statement: string, curve: DidCurve): string {\n const save = `printf '%s' '${statement}' > statement.txt`;\n return curve === \"Ed25519\"\n ? `${save} && openssl pkeyutl -sign -rawin -inkey key.pem -in statement.txt | openssl base64 -A`\n : `${save} && openssl dgst -sha256 -sign key.pem statement.txt | openssl base64 -A`;\n}\n\nconst signer: ExternalToolSigner<DidEvidence> = {\n id: \"sign\", kind: \"external-tool\", label: \"Sign with a key of the DID\",\n description: \"Sign the statement with a key your DID document lists for authentication or assertionMethod, and paste a JWS or the raw signature. The private key never enters Ghostly.\",\n instructions(statement, say = englishSay): SignerInstructions {\n const did = statement.binding.subject;\n if (statement.text.includes(\"'\")) throw new DidError(\"Statement is not signable as plain text\");\n const keys = knownKeys(did);\n const key = keys.length === 1 ? keys[0] : undefined;\n const curve = key?.curve ?? keys[0]?.curve ?? \"Ed25519\";\n const which = keys.length ? keys.map(k => `${fragment(k.id)} (${k.curve})`).join(\", \") : say(\"steps.anyKey\", \"a key listed under authentication or assertionMethod\");\n return {\n steps: [\n { text: say(\"steps.sign\", \"Sign this statement with the private key of {{key}}. It is one line, with no newline at the end:\", { key: which }), copy: statement.text },\n ...(curve === \"secp256k1\" ? [] : [{ text: say(\"steps.jose\", \"With jose (Node.js 20 or later), a JWS: save this as sign.mjs and run it with your {{curve}} private key as a JWK file.\", { curve }), copy: joseScript(statement.text, key?.id) }]),\n { text: say(\"steps.noble\", \"With @noble/curves (Node.js), a raw signature: save this as sign.mjs and run it with your {{curve}} private key in hex.\", { curve }), copy: nobleScript(statement.text, curve) },\n { text: say(\"steps.openssl\", \"Or with OpenSSL 3 and your {{curve}} key in PEM:\", { curve }), copy: opensslCommand(statement.text, curve) },\n { text: say(\"steps.paste\", \"Paste what it prints: a compact JWS ({{alg}}, attached or detached), or the signature in hex or base64. If your DID lists several keys, you may write the key id first: #key-1 <signature>.\", { alg: didJwsAlg(curve) }) },\n ],\n paste: { label: say(\"paste.label\", \"JWS or signature\"), placeholder: say(\"paste.placeholder\", \"eyJhbGciOi… or the signature in hex\"), multiline: true },\n };\n },\n async parse(pasted, statement) {\n const did = statement.binding.subject;\n const paste = parseDidSignaturePaste(pasted);\n const { document } = await resolveDid(did, { fetch: uiFetch });\n const messages = didSignedMessages(statement.text);\n if (paste.kind === \"jws\") return { method: \"jws\", vm: checkDidJws(paste.jws, messages, document).key.id, jws: paste.jws };\n const check = checkDidSignature(paste.signature, messages, document, paste.vm);\n return { method: \"sig\", vm: check.key.id, sig: toBase64Url(check.signature) };\n },\n};\n\nconst webOnly = (statement: IdentityStatement) => {\n const did = statement.binding.subject;\n if (parseDid(did).method !== \"web\") throw new DidError(\"Publishing works for did:web only: sign the statement instead\");\n return did;\n};\n\nconst fileSigner: PublishSigner<DidEvidence> = {\n id: \"file\", kind: \"publish\", label: \"Publish a file beside did.json\",\n description: \"did:web only: upload a small file next to your did.json. Contacts' apps download both from your server.\",\n instructions(statement, say = englishSay) {\n const did = webOnly(statement);\n return { steps: [\n { text: say(\"file.create\", \"Create this file on your web server, beside your did.json:\"), copy: didWebFileUrl(did, statement.id) },\n { text: say(\"file.content\", \"With exactly this content:\"), copy: didWebFile(did, statement.text) },\n { text: say(\"file.serve\", \"Serve it over HTTPS at exactly that address, without any redirect, and with this header so browsers may read it (your did.json needs it too):\"), copy: \"Access-Control-Allow-Origin: *\" },\n { text: say(\"file.check\", \"Then press Check. The file stays public while the proof is in use; deleting it withdraws this proof from every contact at their next check.\") },\n ] };\n },\n evidence: () => ({ method: \"file\" }),\n};\n\nconst serviceSigner: PublishSigner<DidEvidence> = {\n id: \"service\", kind: \"publish\", label: \"Add a service to did.json\",\n description: \"did:web only: add one entry to the service list of your did.json. Contacts' apps read it there.\",\n instructions(statement, say = englishSay) {\n const did = webOnly(statement);\n const seen = lastDidResolution(did);\n return { steps: [\n { text: seen?.documentUrl\n ? say(\"service.addAt\", \"Add this entry to the \\\"service\\\" list of your did.json ({{url}}):\", { url: seen.documentUrl })\n : say(\"service.add\", \"Add this entry to the \\\"service\\\" list of your did.json:\"), copy: JSON.stringify(didGhostlyServiceEntry(did, statement.binding.key, statement.id), null, 2) },\n { text: say(\"service.check\", \"Then press Check. Removing the entry withdraws this proof from every contact at their next check.\") },\n ] };\n },\n evidence: () => ({ method: \"service\" }),\n};\n\nfunction previewOf(r: DidResolution, say: ProviderSay): SubjectPreview {\n const keys = signingKeys(r.document);\n const unusable = r.document.keys.length - keys.length + r.document.skipped;\n if (!keys.length && r.method !== \"web\") throw new DidError(\"This DID lists no Ed25519, secp256k1 or P-256 key for authentication or assertionMethod, so it cannot sign\");\n const method = `did:${r.method}`;\n const facts: { label: string; value: string }[] = [{\n label: say(\"preview.method\", \"Method\"),\n value: r.method === \"key\" || r.method === \"jwk\" ? say(\"preview.keyIsIdentifier\", \"{{method}}, the key is the identifier\", { method }) : method,\n }];\n if (r.host) facts.push({ label: say(\"preview.domain\", \"Domain\"), value: r.host });\n if (r.documentUrl) facts.push({ label: say(\"preview.document\", \"Document\"), value: r.documentUrl });\n if (r.relay) facts.push({ label: say(\"preview.relay\", \"Relay\"), value: r.relay.replace(/^https:\\/\\//, \"\") });\n facts.push({\n label: keys.length === 1 ? say(\"preview.key\", \"Key\") : say(\"preview.keys\", \"Keys\"),\n value: keys.length ? keys.map(k => `${fragment(k.id)} (${k.curve})`).join(\", \") : say(\"preview.noKeys\", \"none that can sign: publish instead\"),\n });\n if (unusable > 0) facts.push({\n label: say(\"preview.notUsable\", \"Not usable\"),\n value: unusable === 1\n ? say(\"preview.unusableOne\", \"1 key: another curve, or not for authentication or assertionMethod\")\n : say(\"preview.unusable\", \"{{count}} keys: another curve, or not for authentication or assertionMethod\", { count: unusable }),\n });\n return { facts, signers: r.method === \"web\" ? [...(keys.length ? [\"sign\"] : []), \"file\", \"service\"] : [\"sign\"] };\n}\n\nexport const did: IdentityProofProvider<DidEvidence> = {\n id: \"did\",\n label: \"DID\",\n category: \"self-custodied\",\n summary: \"did:key, did:jwk, did:dht or did:web\",\n description: \"Proves you control a decentralized identifier (W3C DID): sign the statement with a key its DID document lists, or, for did:web, publish it beside your did.json.\",\n limits: \"Does not prove who controls the DID, only that whoever added the proof held one of its keys (or its website).\",\n platforms: [\"web\", \"extension\", \"desktop\"],\n advanced: true,\n experimental: true,\n subject: {\n label: \"DID\", placeholder: \"did:key:z6Mk… or did:web:example.com\",\n help: \"did:key, did:jwk, did:dht or did:web. Contacts see the whole DID, and the key that signed.\",\n normalize(input) {\n const canonical = normalizeDid(input);\n if (canonical === ownDid()) throw new DidError(\"That is this profile's own Ghostly DID: your contacts already see your Ghostly identity. Add another DID.\");\n return canonical;\n },\n short: shortDid,\n preview: async (subject, { signal, say = englishSay }) => previewOf(await resolveDid(subject, { fetch: uiFetch, signal }), say),\n },\n // A proven DID is already a URI: the profile's own did:dht may list it under alsoKnownAs.\n publicUri: subject => subject,\n validity: { defaultDays: 90, maxDays: 365 },\n // A did:web or did:dht document can drop a key, or the file be deleted: contacts can check again.\n recheck: { afterSeconds: 86_400 },\n privacy: \"did:key and did:jwk: nothing, checked on this device. did:web: the contact's app asks its DNS-over-HTTPS resolver for your domain and downloads your did.json, \" +\n \"so your web server sees the contact's IP address. did:dht: one of the contact's Pkarr relays (their Network settings) learns which DID was looked up.\",\n signers: [signer, fileSigner, serviceSigner],\n parseEvidence(raw) {\n const e = raw as Record<string, unknown>;\n if (exactKeys(raw, \"jws,method,vm\") && e.method === \"jws\" && typeof e.jws === \"string\" && e.jws.length <= DID_JWS_MAX_LENGTH && validVm(e.vm)) return { method: \"jws\", vm: e.vm, jws: e.jws };\n if (exactKeys(raw, \"method,sig,vm\") && e.method === \"sig\" && typeof e.sig === \"string\" && SIG.test(e.sig) && validVm(e.vm)) return { method: \"sig\", vm: e.vm, sig: e.sig };\n if (exactKeys(raw, \"method\") && (e.method === \"file\" || e.method === \"service\")) return { method: e.method };\n throw new Error(\"That is not DID proof evidence\");\n },\n async verify(statement, evidence, ctx) {\n const subject = statement.binding.subject;\n const { method } = parseDid(subject);\n if (normalizeDid(subject) !== subject) throw new DidError(\"The DID is not in canonical form\");\n if ((evidence.method === \"file\" || evidence.method === \"service\") && method !== \"web\") throw new DidError(\"Only a did:web can publish its proof\");\n const options = { fetch: ctx.fetch, signal: ctx.signal, now: () => ctx.now * 1000 };\n const { document, host } = await resolveDid(subject, options);\n const messages = didSignedMessages(statement.text);\n if (evidence.method === \"jws\" || evidence.method === \"sig\") {\n const check = evidence.method === \"jws\"\n ? checkDidJws(evidence.jws, messages, document)\n : checkDidSignature(strictBase64Url(evidence.sig), messages, document, evidence.vm);\n if (check.key.id !== evidence.vm) throw new DidError(\"Signed by another key than the proof names\");\n return { subject, source: `did:${method} · ${evidence.method === \"jws\" ? `${check.alg} JWS` : `${check.alg} signature`} by ${fragment(check.key.id)}` };\n }\n if (evidence.method === \"service\") {\n if (!document.services.some(s => s.proof === statement.id && s.key === statement.binding.key)) throw new DidError(\"The did.json has no Ghostly service for this proof: it was removed, or not added yet\");\n return { subject, source: `did:web · service in the did.json of ${host}` };\n }\n const text = await fetchDidWebFile(subject, statement.id, options);\n if (text === undefined) throw new DidError(`${didWebFileUrl(subject, statement.id)} was not found: it was deleted, or not uploaded yet`);\n if (!didWebFileNames(text, subject, statement.text)) throw new DidError(`${didWebFileUrl(subject, statement.id)} is not the statement of this proof`);\n return { subject, source: `did:web · statement file beside the did.json of ${host}` };\n },\n};\n","import {\n ATPROTO_DECLARED_SCOPE, ATPROTO_FULL_SCOPE, ATPROTO_PROOF_COLLECTION, ATPROTO_PROOF_SCOPE, atprotoProofRecord, atprotoProofRkey,\n type AtprotoDidDocument, type IdentityStatement,\n} from \"@ghostly/core\";\nimport { englishSay, type IdentityFetch, type IdentityPlatform, type ProviderSay } from \"../contract\";\nimport { resolveAtprotoDid, resolveAtprotoHandle, type AtprotoResolveOptions } from \"./resolve\";\n\n/**\n * The prover's half of AT Protocol proofs: AT Protocol OAuth (PAR + PKCE + DPoP, through the official\n * `@atproto/oauth-client`) against the person's own server, then one record written or deleted. Every\n * flow gets a fresh client whose stores live in memory only: the DPoP key (a non-extractable WebCrypto\n * key), the PKCE verifier and the tokens exist for this one flow, are never logged or persisted, and the\n * session is revoked (signOut) as soon as the record is written. Nothing is kept for later: removing\n * the proof asks the person again.\n *\n * The client is identified by the URL of its metadata document (no registration with anyone):\n * https://ghostly.tools/oauth/client-metadata.json, which is ATPROTO_CLIENT_METADATA verbatim\n * (apps/website/public/oauth/client-metadata.json; a unit test keeps the two equal). A web app served from\n * a loopback address (development, the e2e suite) uses AT Protocol's `http://localhost` development\n * client instead, which needs no document.\n */\n\nexport const ATPROTO_CLIENT_ID = \"https://ghostly.tools/oauth/client-metadata.json\";\n/** The extension's id in the Chrome Web Store: its chromiumapp.org redirect is registered. Unpacked builds have another id. */\nexport const EXTENSION_ID = \"nbedaagicniejlmfcncndfjcejaidbcf\";\nexport const ATPROTO_REDIRECTS = {\n /** The web app's static callback page (shared with OpenID Connect): the answer stays in the fragment. */\n web: \"https://app.ghostly.tools/oidc-callback.html\",\n /** chrome.identity.launchWebAuthFlow catches it without loading it. */\n extension: `https://${EXTENSION_ID}.chromiumapp.org/atproto`,\n /** The desktop app's one-shot listener on 127.0.0.1; the port is not part of the match. */\n desktop: \"http://127.0.0.1/oidc-callback\",\n} as const;\n\n/**\n * `native` because the desktop app's loopback redirect is only allowed for native clients; HTTPS\n * redirects (web, extension) are allowed for them too. No `refresh_token` grant: Ghostly never keeps\n * a session, so it never gets a refresh token to lose.\n */\nexport const ATPROTO_CLIENT_METADATA = {\n client_id: ATPROTO_CLIENT_ID,\n client_name: \"Ghostly\",\n client_uri: \"https://ghostly.tools\",\n logo_uri: \"https://ghostly.tools/icon-192.png\",\n application_type: \"native\",\n grant_types: [\"authorization_code\"],\n response_types: [\"code\"],\n scope: ATPROTO_DECLARED_SCOPE,\n token_endpoint_auth_method: \"none\",\n dpop_bound_access_tokens: true,\n redirect_uris: [ATPROTO_REDIRECTS.web, ATPROTO_REDIRECTS.extension, ATPROTO_REDIRECTS.desktop],\n} as const;\n\n/** AT Protocol's development client: no document, loopback redirects only, any port. */\nexport function loopbackClientMetadata(redirectUri: string) {\n const registered = new URL(redirectUri);\n registered.port = \"\";\n const id = `http://localhost?${new URLSearchParams({ redirect_uri: registered.href, scope: ATPROTO_DECLARED_SCOPE })}`;\n return {\n client_id: id, application_type: \"native\", grant_types: [\"authorization_code\"], response_types: [\"code\"], scope: ATPROTO_DECLARED_SCOPE,\n token_endpoint_auth_method: \"none\", dpop_bound_access_tokens: true, redirect_uris: [registered.href],\n } as const;\n}\n\nconst isLoopback = (url: string) => { try { const u = new URL(url); return u.protocol === \"http:\" && (u.hostname === \"127.0.0.1\" || u.hostname === \"[::1]\"); } catch { return false; } };\nconst withoutPort = (url: string) => { const u = new URL(url); u.port = \"\"; return u.href; };\n\n/**\n * The client for a redirect: the published one, or the development client on a loopback web app. A\n * loopback redirect is registered without its port (servers match any port), but the library checks\n * the exact address locally, so the one in use is added to the copy it gets; the server only ever sees\n * the client id and reads the registered addresses itself.\n */\nexport function clientMetadataFor(platform: IdentityPlatform, redirectUri: string) {\n const base = platform === \"web\" && isLoopback(redirectUri) ? loopbackClientMetadata(redirectUri) : ATPROTO_CLIENT_METADATA;\n const registered = base.redirect_uris as readonly string[];\n const matches = registered.includes(redirectUri) || (isLoopback(redirectUri) && registered.includes(withoutPort(redirectUri)));\n if (!matches) throw new Error(\"This Ghostly build cannot sign in to an AT Protocol server here (its return address is not registered).\");\n return { ...base, redirect_uris: [...new Set([redirectUri, ...registered])] };\n}\n\n/** How a platform shows the server's page and hands back where it redirected. */\nexport interface AtprotoWindow {\n /** The redirect URI for this platform, as used in the request (the desktop's carries its port). */\n redirectUri: string;\n /** Opens `url`; resolves with the full address the server redirected to, carrying `state`. */\n authorize(url: string, state: string, signal: AbortSignal): Promise<string>;\n /** Releases the window or listener, answered or not. */\n close(): void;\n}\n\nexport interface AtprotoHost {\n platform: IdentityPlatform;\n /** Call it straight from the click: the web app opens its popup before anything is awaited. */\n open(): Promise<AtprotoWindow>;\n}\n\n/** Which permission to ask for: only Ghostly's records, or the whole repository (older servers). */\nexport type AtprotoAccess = \"proof-records\" | \"full\";\nexport const scopeFor = (access: AtprotoAccess) => (access === \"full\" ? ATPROTO_FULL_SCOPE : ATPROTO_PROOF_SCOPE);\n\n/** The server refused the narrow permission: it predates granular scopes. */\nexport class AtprotoScopeError extends Error {}\n\n/** The account a handle (or a DID typed as is) names, with its document. */\nexport async function lookupAtprotoAccount(input: string, options: AtprotoResolveOptions & { normalize(input: string): string | null }): Promise<AtprotoDidDocument> {\n const value = input.trim();\n if (value.startsWith(\"did:\")) return resolveAtprotoDid(value, options);\n const handle = options.normalize(value);\n if (!handle) throw new Error(\"That is not a handle (like alice.bsky.social)\");\n const did = await resolveAtprotoHandle(handle, options);\n if (!did) throw new Error(`${handle} does not point to an AT Protocol account`);\n const doc = await resolveAtprotoDid(did, options);\n if (doc.handle !== handle) throw new Error(`${handle} points to an account that names another handle`);\n return doc;\n}\n\nexport interface AtprotoFlowOptions {\n platform: IdentityPlatform;\n window: AtprotoWindow;\n account: AtprotoDidDocument;\n access: AtprotoAccess;\n signal: AbortSignal;\n /** The resolution the library uses: the same bounded lookups as the verifier. */\n resolve: AtprotoResolveOptions;\n onProgress(message: string): void;\n /** Says the progress lines in the app's language (the AT Protocol provider's `say`); English when absent. */\n say?: ProviderSay;\n /** The HTTP client for the OAuth requests and the record (the page's fetch). */\n fetch?: typeof fetch;\n}\n\nconst MESSAGES: Record<string, string> = {\n access_denied: \"You declined on your server. Nothing was published.\",\n login_required: \"Log in on your server and try again.\",\n consent_required: \"Your server needs your approval to continue.\",\n};\n\n/** The redirect's parameters: the fragment (Ghostly asks for fragment responses), then the query. */\nexport function callbackParams(redirected: string, redirectUri: string): URLSearchParams {\n const url = new URL(redirected), expected = new URL(redirectUri);\n if (url.origin !== expected.origin || url.pathname !== expected.pathname) throw new Error(\"Sign-in returned to an unexpected address.\");\n const params = new URLSearchParams(url.hash.slice(1));\n for (const [k, v] of new URLSearchParams(url.search)) if (!params.has(k)) params.set(k, v);\n return params;\n}\n\nconst pdsHost = (pds: string) => new URL(pds).host;\n\n/** Runs OAuth for `account`, hands `work` a session scoped to this flow, and always revokes it afterwards. */\nasync function withSession<T>(options: AtprotoFlowOptions, work: (session: { did: string; fetchHandler(path: string, init?: RequestInit): Promise<Response> }) => Promise<T>): Promise<T> {\n const { window: w, account, signal } = options;\n signal.throwIfAborted();\n const [{ OAuthClient }, { WebcryptoKey }] = await Promise.all([import(\"@atproto/oauth-client\"), import(\"@atproto/jwk-webcrypto\")]);\n const states = new Map<string, unknown>(), sessions = new Map<string, unknown>();\n let state: string | undefined;\n const memory = <V>(map: Map<string, V>, onSet?: (key: string) => void) => ({\n async get(key: string) { return map.get(key); },\n async set(key: string, value: V) { onSet?.(key); map.set(key, value); },\n async del(key: string) { map.delete(key); },\n });\n const client = new OAuthClient({\n responseMode: \"fragment\",\n clientMetadata: clientMetadataFor(options.platform, w.redirectUri) as never,\n stateStore: memory(states, key => { state = key; }) as never,\n sessionStore: memory(sessions) as never,\n runtimeImplementation: {\n createKey: algs => WebcryptoKey.generate(algs),\n getRandomValues: length => crypto.getRandomValues(new Uint8Array(length)),\n digest: async (data, { name }) => new Uint8Array(await crypto.subtle.digest(`SHA-${name.slice(3)}`, data)),\n },\n // The same lookups the verifier makes, bounded, through the person's DoH resolver: no third-party handle resolver.\n identityResolver: {\n async resolve(input: string) {\n const did = input.startsWith(\"did:\") ? input : await resolveAtprotoHandle(input, options.resolve);\n if (!did) throw new Error(\"The account could not be resolved\");\n const doc = await fetchDidJson(did, options.resolve);\n return { did, didDoc: doc.json, handle: doc.parsed.handle ?? \"handle.invalid\" } as never;\n },\n },\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n allowHttp: false,\n });\n let url: URL;\n try {\n url = await client.authorize(account.did, { scope: scopeFor(options.access), redirect_uri: w.redirectUri as never, signal });\n } catch (e) {\n const text = String((e as { error?: string })?.error ?? (e as Error)?.message ?? e);\n if (/invalid_scope/i.test(text) || /scope/i.test(String((e as { errorDescription?: string })?.errorDescription ?? \"\"))) throw new AtprotoScopeError(\n \"Your server does not offer a permission limited to Ghostly's records: it only offers full access to your account. Choose \\\"Your server, full access\\\" to continue anyway; Ghostly still only writes this one record.\");\n // eslint-disable-next-line preserve-caught-error -- A message people can act on; the library's error stays out of the UI (ES2020 has no Error.cause).\n throw new Error(`Your server (${pdsHost(account.pds)}) refused to start the sign-in.`);\n }\n if (!state) throw new Error(\"The sign-in could not start.\");\n options.onProgress((options.say ?? englishSay)(\"progress.approve\", \"Approve on {{server}} in the window that opened…\", { server: pdsHost(account.pds) }));\n const redirected = await w.authorize(url.href, state, signal);\n signal.throwIfAborted();\n const params = callbackParams(redirected, w.redirectUri);\n const error = params.get(\"error\");\n if (error) throw new Error(MESSAGES[error] ?? \"Your server refused the sign-in.\");\n let session: Awaited<ReturnType<typeof client.callback>>[\"session\"];\n try { ({ session } = await client.callback(params, { redirect_uri: w.redirectUri as never })); }\n catch { throw new Error(\"The sign-in could not be completed. Nothing was published.\"); }\n try {\n if (session.did !== account.did) throw new Error(\"You logged in to another account than the one you typed. Nothing was published.\");\n return await work(session);\n } finally {\n // Revokes the tokens on the server; the DPoP key and verifier go out of scope with the client.\n await session.signOut().catch(() => {});\n sessions.clear(); states.clear();\n }\n}\n\n/** A DID's document, checked, and the JSON the library reads its services from. */\nasync function fetchDidJson(did: string, options: AtprotoResolveOptions): Promise<{ parsed: AtprotoDidDocument; json: unknown }> {\n let json: unknown;\n const recording: IdentityFetch = async (url, init) => {\n const response = await options.fetch(url, init);\n try { json = JSON.parse(response.text); } catch { /* resolveAtprotoDid says so */ }\n return response;\n };\n const parsed = await resolveAtprotoDid(did, { ...options, fetch: recording });\n return { parsed, json };\n}\n\nasync function xrpcError(response: Response): Promise<string> {\n const body = await response.json().catch(() => ({})) as { error?: string; message?: string };\n return `${body.error ?? response.status}${body.message ? `: ${body.message}` : \"\"}`;\n}\n\n/** Writes the proof record (rkey = the proof key) and returns once the server has it. */\nexport async function publishAtprotoProof(statement: IdentityStatement, options: AtprotoFlowOptions): Promise<void> {\n await withSession(options, async session => {\n options.onProgress((options.say ?? englishSay)(\"progress.publishing\", \"Publishing the proof on {{server}}…\", { server: pdsHost(options.account.pds) }));\n const response = await session.fetchHandler(\"/xrpc/com.atproto.repo.createRecord\", {\n method: \"POST\", headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ repo: session.did, collection: ATPROTO_PROOF_COLLECTION, rkey: atprotoProofRkey(statement.binding.key), record: atprotoProofRecord(statement, new Date()) }),\n });\n if (response.status === 403) throw new AtprotoScopeError(\"Your server did not let Ghostly write its record. Choose \\\"Your server, full access\\\" to try again.\");\n if (!response.ok) throw new Error(`Your server did not publish the record (${await xrpcError(response)}).`);\n });\n}\n\n/** Deletes the proof record. Deleting a record that is not there succeeds. */\nexport async function unpublishAtprotoProof(proofKey: string, options: AtprotoFlowOptions): Promise<void> {\n await withSession(options, async session => {\n options.onProgress((options.say ?? englishSay)(\"progress.deleting\", \"Deleting the record on {{server}}…\", { server: pdsHost(options.account.pds) }));\n const response = await session.fetchHandler(\"/xrpc/com.atproto.repo.deleteRecord\", {\n method: \"POST\", headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ repo: session.did, collection: ATPROTO_PROOF_COLLECTION, rkey: atprotoProofRkey(proofKey) }),\n });\n if (response.status === 403) throw new AtprotoScopeError(\"Your server did not let Ghostly delete its record.\");\n if (!response.ok) throw new Error(`Your server did not delete the record (${await xrpcError(response)}).`);\n });\n}\n","import {\n ATPROTO_PROOF_COLLECTION, AtprotoProofError, atprotoProofRkey, checkAtprotoProofRecord, IdentityCheckUnavailable, isAtprotoDid, normalizeAtprotoHandle, shortAtprotoDid,\n verifyAtprotoRecordProof,\n} from \"@ghostly/core\";\nimport { englishSay, type IdentityFetch, type IdentityProofProvider, type InAppSigner, type SignerContext } from \"../contract\";\nimport { getBrowserHost } from \"../../host\";\nimport { boundedIdentityFetch } from \"../verify\";\nimport { chosenResolver } from \"../domain\";\nimport { lookupAtprotoAccount, publishAtprotoProof, unpublishAtprotoProof, type AtprotoAccess, type AtprotoHost, AtprotoScopeError } from \"../atproto/oauth\";\nimport { assertPublicServer, resolveAtprotoDid, verifiedAtprotoHandle, type AtprotoResolveOptions } from \"../atproto/resolve\";\n\n/**\n * Identity proofs for an AT Protocol account (Bluesky, or any PDS): the account publishes, in its own\n * repository, one record of the collection `tools.ghostly.proof` carrying the statement, keyed by the\n * proof key. Publishing takes an OAuth approval on the person's server that lets Ghostly create and\n * delete records of that collection only. A contact's app checks it without logging in: the DID\n * document (PLC directory or did:web) names the signing key and the server; the server's\n * `com.atproto.sync.getRecord` answer is a CAR whose commit must be signed by that key and whose tree\n * must lead to the record. The handle is shown only when it resolves back to the DID.\n *\n * The subject is the DID (it outlives handles). Evidence is empty: everything is fetched from the\n * account's own repository, so deleting the record (removing the proof here does) makes re-checks fail.\n * See docs/wisps/312-atproto.md and docs/lexicons/tools.ghostly.proof.json.\n */\nexport type AtprotoEvidence = Record<string, never>;\n\n/** The proof CAR: a commit, the tree path and one small record. Real repositories' paths are a few KiB. */\nexport const RECORD_PROOF_MAX_BYTES = 256 * 1024;\n\nfunction currentHost(): AtprotoHost | undefined {\n try { return getBrowserHost().atproto; } catch { return undefined; }\n}\n\nconst hostOf = (url: string) => new URL(url).host;\n\n/** Why the card shows the DID and no handle. */\nconst HANDLE_NOT_SHOWN = {\n none: \"The account's DID document names no handle\",\n elsewhere: \"The account's handle does not point back to it, so it is not shown\",\n unchecked: \"The account's handle could not be checked, so it is not shown\",\n} as const;\n\nexport interface AtprotoIdentityOptions {\n /** The platform's sign-in window. */\n host?: () => AtprotoHost | undefined;\n /** The UI side's network for looking the account up before signing in. */\n fetch?: IdentityFetch;\n /** The page's fetch for OAuth and the record (tests pass a fake server). */\n oauthFetch?: typeof fetch;\n /** The PLC directory (tests). */\n plc?: string;\n}\n\nexport function createAtprotoIdentityProvider(options: AtprotoIdentityOptions = {}): IdentityProofProvider<AtprotoEvidence> {\n const host = options.host ?? currentHost;\n const uiFetch = () => options.fetch ?? boundedIdentityFetch({ online: () => true });\n const resolveOptions = (fetch: IdentityFetch, signal?: AbortSignal): AtprotoResolveOptions =>\n ({ fetch, signal, resolver: chosenResolver().id, ...(options.plc ? { plc: options.plc } : {}) });\n\n /** Opens the window from the click, looks the account up, then runs OAuth for `work`; always closes the window. */\n function signIn<T>(input: string, access: AtprotoAccess, ctx: SignerContext, work: (flow: Parameters<typeof publishAtprotoProof>[1]) => Promise<T>): Promise<T> {\n // Before any await: the web app's popup needs the click's user activation.\n const h = host();\n const opening = h?.open();\n return (async () => {\n if (!h || !opening) throw new Error(\"Signing in to an AT Protocol server is not available here.\");\n const w = await opening;\n try {\n const resolve = resolveOptions(uiFetch(), ctx.signal);\n ctx.onProgress((ctx.say ?? englishSay)(\"progress.lookingUp\", \"Looking up {{account}}…\", { account: input.trim() }));\n const account = await lookupAtprotoAccount(input, { ...resolve, normalize: normalizeAtprotoHandle });\n ctx.signal.throwIfAborted();\n return await work({ platform: h.platform, window: w, account, access, signal: ctx.signal, resolve, onProgress: ctx.onProgress, say: ctx.say, fetch: options.oauthFetch });\n } finally { w.close(); }\n })();\n }\n\n const signer = (id: string, access: AtprotoAccess, label: string, description: string): InAppSigner<AtprotoEvidence> => ({\n id, kind: \"in-app\", label, description,\n action: access === \"full\" ? \"Continue on your server (full access)\" : \"Continue on your server\",\n available: () => !!host(),\n fields: [{\n name: \"handle\", label: \"Handle\", kind: \"text\", placeholder: \"alice.bsky.social\",\n help: \"Your Bluesky handle, your own domain if you use one, or your DID.\",\n }],\n run(ctx, work) {\n return signIn(ctx.values.handle ?? \"\", access, ctx, flow => work({\n subject: async () => flow.account.did,\n sign: async statement => { await publishAtprotoProof(statement, flow); return {}; },\n }));\n },\n });\n\n // Removing asks for a fresh approval; the server that refused the narrow permission once is asked for full access.\n const fullAccessServers = new Set<string>();\n\n return {\n id: \"atproto\",\n label: \"Bluesky / AT Protocol\",\n category: \"self-custodied\",\n summary: \"Publish a record on your Bluesky server\",\n description: \"Proves you control a Bluesky (AT Protocol) account: approve on your server, and Ghostly publishes one record in your account's repository. It is public, like the rest of your repository: anyone can see this account made a Ghostly proof, not who you share it with. Contacts check it without logging in.\",\n limits: \"Signed with your account's key, which your server usually holds. It proves control of the account, not who you are; the handle is shown only while it points back to the account.\",\n platforms: [\"web\", \"extension\", \"desktop\"],\n subject: {\n label: \"Account (DID)\",\n placeholder: \"did:plc:…\",\n normalize(input: string) {\n const did = input.trim();\n if (!isAtprotoDid(did)) throw new Error(\"Not an AT Protocol account (did:plc or did:web)\");\n return did;\n },\n short: shortAtprotoDid,\n },\n // The account's AT URI, for a public DID document's alsoKnownAs (#247), when the person lists it there.\n publicUri: did => `at://${did}`,\n validity: { defaultDays: 90, maxDays: 365 },\n // The record can be deleted any time: contacts look again after an hour.\n recheck: { afterSeconds: 3600 },\n privacy: \"Your contact's app asks the PLC directory (or your did:web host) for your account's document, your server for the record, and its DNS-over-HTTPS resolver or your handle's website for your handle, so they learn this account was checked.\",\n signers: [\n signer(\"atproto-oauth\", \"proof-records\", \"Your server (Bluesky or another PDS)\",\n \"Opens your server's login page. Ghostly asks only to create and delete its own proof records: never to post, read your messages or edit your profile.\"),\n signer(\"atproto-oauth-full\", \"full\", \"Your server, full access (older servers)\",\n \"Asks for access to your whole account, for servers that cannot limit Ghostly's permission. Ghostly suggests it when your server refuses the narrower sign-in or the record's write. Ghostly still only writes this one record, and gives the access back right away.\"),\n ],\n parseEvidence(raw) {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw) || Object.keys(raw).length) throw new Error(\"Invalid AT Protocol evidence\");\n return {};\n },\n async verify(statement, _evidence, ctx) {\n const did = statement.binding.subject;\n if (!isAtprotoDid(did)) throw new Error(\"Not an AT Protocol account\");\n const resolve = resolveOptions(ctx.fetch, ctx.signal);\n // The server comes from the DID document, never from the proof.\n const doc = await resolveAtprotoDid(did, resolve);\n await assertPublicServer(hostOf(doc.pds).replace(/:\\d+$/, \"\"), resolve);\n const rkey = atprotoProofRkey(statement.binding.key);\n const url = `${doc.pds}/xrpc/com.atproto.sync.getRecord?${new URLSearchParams({ did, collection: ATPROTO_PROOF_COLLECTION, rkey })}`;\n let response: Awaited<ReturnType<IdentityFetch>>;\n try { response = await ctx.fetch(url, { headers: { accept: \"application/vnd.ipld.car\" }, maxBytes: RECORD_PROOF_MAX_BYTES, signal: ctx.signal, redirect: \"error\" }); }\n catch (e) {\n // eslint-disable-next-line preserve-caught-error -- A message people can act on; the library's error stays out of the UI (ES2020 has no Error.cause).\n if (/too large/i.test(String(e))) throw new Error(\"The account's server sent a proof that is too large\");\n // What this side's network did stays here: the contact is not told which server, port or answer was seen.\n throw new IdentityCheckUnavailable(`The account's server (${hostOf(doc.pds)}) could not be reached`);\n }\n if (response.status !== 200) {\n let code = \"\";\n try { code = String((JSON.parse(response.text) as { error?: unknown }).error ?? \"\"); } catch { /* not JSON */ }\n if (code === \"RecordNotFound\") throw new Error(\"The record is no longer in the account's repository\");\n if (/^Repo(NotFound|Deactivated|Takendown|Suspended)$/.test(code)) throw new Error(\"The account is no longer on its server\");\n throw new IdentityCheckUnavailable(`The account's server (${hostOf(doc.pds)}) did not send the record`);\n }\n let proof: ReturnType<typeof verifyAtprotoRecordProof>;\n try { proof = verifyAtprotoRecordProof(response.bytes, { did, key: doc.key, collection: ATPROTO_PROOF_COLLECTION, rkey }); }\n // eslint-disable-next-line preserve-caught-error -- A message people can act on; the library's error stays out of the UI (ES2020 has no Error.cause).\n catch (e) { throw new Error(e instanceof AtprotoProofError ? `The account's repository does not prove the record: ${e.message}` : \"The account's repository could not be read\"); }\n if (!proof.record) throw new Error(\"The record is no longer in the account's repository\");\n checkAtprotoProofRecord(proof.record.value, statement);\n const { handle, missing } = await verifiedAtprotoHandle(doc, resolve);\n return {\n subject: did,\n source: `Record signed with the account's key, from ${hostOf(doc.pds)}`,\n display: {\n ...(handle ? { name: `@${handle}` } : {}),\n url: `https://bsky.app/profile/${did}`,\n source: missing ? HANDLE_NOT_SHOWN[missing] : \"Handle checked both ways: it points to this account\",\n fetchedAt: ctx.now,\n },\n };\n },\n unpublish: {\n description: \"Also deletes the record on your server: your server asks you to approve.\",\n run(proof, ctx) {\n return signIn(proof.subject, \"proof-records\", ctx, async flow => {\n const access: AtprotoAccess = fullAccessServers.has(flow.account.pds) ? \"full\" : \"proof-records\";\n try { await unpublishAtprotoProof(proof.key, { ...flow, access }); }\n catch (e) {\n if (e instanceof AtprotoScopeError && access !== \"full\") {\n fullAccessServers.add(flow.account.pds);\n // eslint-disable-next-line preserve-caught-error -- A message people can act on; the library's error stays out of the UI (ES2020 has no Error.cause).\n throw new Error(\"Your server only offers full access to your account. Try again to approve that; Ghostly only deletes this one record.\");\n }\n throw e;\n }\n });\n },\n },\n };\n}\n\nexport const atproto = createAtprotoIdentityProvider();\n","import {\n homeserverWebEndpoint, IdentityCheckUnavailable, openRelayPayload, pubkyHomeserverOf, PUBKY_PROOF_MAX_BYTES, RELAY_PAYLOAD_MAX_BYTES,\n type HomeserverEndpoint,\n} from \"@ghostly/core\";\nimport type { AuthFlow, GrantAuthFlow, Session } from \"@synonymdev/pubky\";\nimport { englishSay, SignerTimeout, type ApprovalRequest, type IdentityFetch, type ProviderSay } from \"./contract\";\nimport { assertPublicHost, chosenResolver, type DohResolverId } from \"./domain\";\nimport { getBrowserHost, type PubkyCookieSession } from \"../host\";\nimport { PUBKY_RELAYS } from \"./pubkyRelays\";\n\nexport { PUBKY_RELAYS };\n\n/**\n * Pubky, browser side: reading a key's records and files the way a contact's app does (through the proof\n * contract's bounded `ctx.fetch` only), and asking the person to approve one Pubky auth request in Pubky Ring or\n * Pubky Passport (https://github.com/pubky/pubky-passport/blob/main/docs/integration.md). See WISP 302.\n */\n\n// -- reading ---------------------------------------------------------------------------------------\n\n\n/**\n * The newest DNS packet the relays hold for `key`, its signature checked against `key`. Every relay is asked; one\n * that is down, answers garbage or holds an older packet does not count. Throws when none has a valid one: as\n * IdentityCheckUnavailable when none answered (not reached, or an error status), since that says nothing of the key.\n */\nexport async function pubkyRecords(key: string, fetch: IdentityFetch, signal?: AbortSignal, relays: readonly string[] = PUBKY_RELAYS): Promise<Uint8Array> {\n const failed: unknown[] = [];\n let answered = false;\n const answers = await Promise.all(relays.map(async relay => {\n let r;\n try { r = await fetch(`${relay.replace(/\\/+$/, \"\")}/${key}`, { maxBytes: RELAY_PAYLOAD_MAX_BYTES, signal }); }\n catch (e) { failed.push(e); return undefined; }\n if (r.status === 200 || r.status === 404) answered = true;\n try { return r.status === 200 ? openRelayPayload(key, r.bytes) : undefined; } catch { return undefined; }\n }));\n const newest = answers.filter(a => !!a).sort((a, b) => (b.seq > a.seq ? 1 : b.seq < a.seq ? -1 : 0))[0];\n // No relay answered at all (offline, a time-out, an error status): say that, not that the key has no records.\n if (!newest && failed.length === relays.length && (failed[0] instanceof IdentityCheckUnavailable || /too large/i.test(String(failed[0])))) throw failed[0];\n if (!newest && !answered) throw new IdentityCheckUnavailable(\"No relay answered\");\n if (!newest) throw new NoPkarrRecords(\"This Pubky key has no records on the Pkarr relays\");\n return newest.dnsPacket;\n}\n\nclass NoPkarrRecords extends Error {}\n\n/** Where `key`'s homeserver answers browsers: its `_pubky` record, then the homeserver's own HTTPS record. */\nexport async function pubkyHomeserver(key: string, fetch: IdentityFetch, signal?: AbortSignal, relays?: readonly string[]): Promise<{ homeserver: string; endpoint: HomeserverEndpoint }> {\n const homeserver = pubkyHomeserverOf(await pubkyRecords(key, fetch, signal, relays), key);\n if (!homeserver) throw new Error(\"This Pubky key names no homeserver\");\n let records: Uint8Array;\n try { records = await pubkyRecords(homeserver, fetch, signal, relays); }\n catch (e) {\n // The homeserver's own key, not the person's: say whose records are missing.\n // eslint-disable-next-line preserve-caught-error -- The same failure, named for the right key (ES2020 has no Error.cause).\n if (e instanceof NoPkarrRecords) throw new Error(\"The homeserver of this Pubky key has no records on the Pkarr relays\");\n throw e;\n }\n const endpoint = homeserverWebEndpoint(records, homeserver);\n if (!endpoint) throw new Error(\"The homeserver of this Pubky key publishes no address a browser can reach\");\n return { homeserver, endpoint };\n}\n\n/**\n * A public file of `key` at `path`, from the homeserver its own records name: bounded, no redirects, the owner in the\n * `pubky-host` header the way the SDK addresses it. `undefined` when the homeserver says it is not there.\n *\n * The key's owner chooses that host, so it is contacted only on port 443 and only once its addresses are all public\n * (the name is resolved first through the chosen DNS-over-HTTPS resolver): a proof never makes a contact's app knock\n * on its own network. Failures on the way there are IdentityCheckUnavailable, which the contact is not told about.\n */\nexport async function readPubkyFile(key: string, path: `/pub/${string}`, fetch: IdentityFetch, signal?: AbortSignal, relays?: readonly string[], resolver: DohResolverId = chosenResolver().id): Promise<{ text: string | undefined; host: string }> {\n const { endpoint: { host, port } } = await pubkyHomeserver(key, fetch, signal, relays);\n if (port !== undefined) throw new IdentityCheckUnavailable(`The homeserver ${host} answers on port ${port}; only port 443 is contacted`);\n try { await assertPublicHost(host, { fetch, signal, resolver }); }\n catch (e) { throw new IdentityCheckUnavailable(`The homeserver ${host} was not contacted: ${e instanceof Error ? e.message : String(e)}`); }\n let r: Awaited<ReturnType<IdentityFetch>>;\n try { r = await fetch(`https://${host}${path}`, { headers: { \"pubky-host\": key }, maxBytes: PUBKY_PROOF_MAX_BYTES, signal }); }\n catch (e) {\n // A file over the cap is the owner's doing, and says nothing about this side's network.\n if (/too large/i.test(String(e))) throw e;\n throw new IdentityCheckUnavailable(`The homeserver ${host} could not be reached`);\n }\n if (r.status === 404) return { text: undefined, host };\n if (r.status !== 200) throw new IdentityCheckUnavailable(`The homeserver ${host} answered ${r.status}`);\n return { text: r.text, host };\n}\n\n// -- approving -------------------------------------------------------------------------------------\n\n/** The app identifier Pubky Ring and Passport list the grant under. */\nexport const PUBKY_CLIENT_ID = \"ghostly.tools\";\nexport const PASSPORT_ORIGIN = \"https://passport.pubky.app\";\n/** How long one request waits: Pubky's relay keeps a message about five minutes. */\nexport const PUBKY_APPROVAL_TIMEOUT = 5 * 60_000;\nconst POLL_EVERY = 1_000;\n\n/**\n * Passport's authorize page for a request. The authorization URL carries the relay secret: it goes in the fragment\n * (never sent to a server), encoded exactly once, and is never logged.\n */\nexport const passportUrl = (authorizationUrl: string) => `${PASSPORT_ORIGIN}/authorize#d=${encodeURIComponent(authorizationUrl)}`;\n\n/** Messages from the SDK may quote the request: nothing that looks like one reaches the UI or a log. */\nconst redact = (text: string) => text.replace(/pubkyauth:\\/\\/\\S*/gi, \"(request)\").replace(/#d=\\S*/g, \"#d=(request)\");\nconst failure = (what: string, e: unknown) => new Error(`${what}${e instanceof Error && e.message ? `: ${redact(e.message)}` : \"\"}`);\n\n/** An approved Pubky session, only as long as `work` runs: the key, and writes inside the one folder granted. */\nexport interface PubkyApprovedSession {\n key: string;\n put(path: `/pub/${string}`, text: string): Promise<void>;\n delete(path: `/pub/${string}`): Promise<void>;\n}\n\nexport interface PubkyApprovalOptions {\n /** The one capability asked for, `/pub/…/:w`. A session granted anything else is refused. */\n capability: `/pub/${string}/:w`;\n signal: AbortSignal;\n onApproval(request: ApprovalRequest | null): void;\n onProgress(message: string): void;\n /** Says the request's words and progress lines in the app's language (the Pubky provider's `say`); English when absent. */\n say?: ProviderSay;\n /** Where Passport opens. The desktop app hands it to the system browser; elsewhere a popup from the click. */\n openPassport?: (url: string) => Window | null | void;\n /** Tests: the SDK's relay, and a shorter wait. */\n relay?: string;\n timeoutMs?: number;\n}\n\n/**\n * Opens a Passport window from the click that calls it. It must run synchronously in the click handler, before\n * anything is awaited, or the browser blocks the popup; the desktop app opens the system browser instead.\n */\nexport function openPassportWindow(url: string): Window | null | void {\n let host: ReturnType<typeof getBrowserHost> | undefined;\n try { host = getBrowserHost(); } catch { host = undefined; }\n if (host?.openPubkyPassport) { void host.openPubkyPassport(url).catch(() => {}); return; }\n // Not `noopener`: the reference lets Ghostly close the window once either signer approved.\n return window.open(url, \"pubky-passport\", \"popup,width=520,height=760\");\n}\n\n/** What a request of either kind offers while it waits: one poll at a time, freed once no poll is in flight. */\ninterface PendingRequest { tryPollOnce(): Promise<Session | undefined>; free(): void }\n\n/** A 401 or 403 from the homeserver: the session it was given is not one it accepts. */\nconst refused = (e: unknown) => {\n const status = (e as { data?: { statusCode?: unknown } } | null)?.data?.statusCode;\n return status === 401 || status === 403;\n};\n\n/**\n * Polls every request until one of them is approved and resolves with that session and its request; a cancel, the\n * deadline or a failed poll ends the wait for all of them. Each request is freed once its last poll has settled\n * (never while one is in flight), and a session that lands after the end is signed out at once; `onSettled` runs\n * once all of that is done.\n */\nfunction firstApproval(requests: readonly PendingRequest[], signal: AbortSignal, timeoutMs: number, onSettled: () => void): Promise<{ session: Session; request: PendingRequest }> {\n return new Promise((resolve, reject) => {\n let over = false;\n let polling = requests.length;\n const wakers = new Set<() => void>();\n const end = (settle: () => void) => {\n if (over) return;\n over = true;\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", cancel);\n for (const wake of wakers) wake();\n settle();\n };\n const cancel = () => end(() => reject(signal.reason));\n const timer = setTimeout(() => end(() => reject(new SignerTimeout(\"Nobody approved the request in time. Start again for a new one.\"))), timeoutMs);\n if (signal.aborted) cancel(); else signal.addEventListener(\"abort\", cancel, { once: true });\n const pause = () => new Promise<void>(done => {\n const wake = () => { clearTimeout(t); wakers.delete(wake); done(); };\n const t = setTimeout(wake, POLL_EVERY);\n wakers.add(wake);\n });\n\n // The end does not wait for a poll in flight (one that got an approval is still redeeming it at the homeserver):\n // its request is freed when it settles, and a session it brings is signed out.\n const poll = async (request: PendingRequest) => {\n try {\n while (!over) {\n let session: Session | undefined;\n try { session = await request.tryPollOnce(); }\n catch (e) { end(() => reject(failure(\"The Pubky request failed\", e))); return; }\n if (session && over) { try { await session.signout(); } catch { /* best effort */ } finally { session.free(); } return; }\n if (session) { const approved = session; end(() => resolve({ session: approved, request })); return; }\n if (!over) await pause();\n }\n } finally {\n request.free();\n if (--polling === 0) onSettled();\n }\n };\n for (const request of requests) void poll(request);\n });\n}\n\n/**\n * A request of a cookie session (Ring's approval) to its homeserver: its `/session` or a file of its storage\n * (`/storage/<key>/pub/…`, or `/pub/…` where the homeserver does not address storage by path), sent with the\n * browser's credentials. A grant session's requests carry an `Authorization` header instead, and the relay's\n * and the Pkarr relays' are elsewhere: those stay the page's.\n */\nconst cookieSessionRequest = (request: Request) =>\n request.credentials === \"include\" && !request.headers.has(\"authorization\") && /^\\/(?:session$|storage\\/|pub\\/)/.test(new URL(request.url).pathname);\n\n/** Statuses a Response carries no body with. */\nconst NO_BODY = new Set([204, 205, 304]);\n\n/**\n * Sends the SDK's cookie-session requests through `transport` until the returned function runs. The SDK fetches with\n * the global fetch, so this wraps it; everything else goes on to the page's fetch as it was. The cookie the\n * homeserver sets stays in the transport: the page, and so the SDK, never sees it.\n */\nfunction routeCookieSession(transport: PubkyCookieSession): () => void {\n const pageFetch = globalThis.fetch;\n let closed = false;\n const routed = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n // A Request made from another takes its body over: whatever is made here is what goes on.\n const request = input instanceof Request && init === undefined ? input : new Request(input, init);\n // Once closed, a wrapper something else has wrapped since stays in place: it only passes requests on.\n if (closed || !cookieSessionRequest(request)) return pageFetch(request);\n request.signal.throwIfAborted();\n const body = request.body ? new Uint8Array(await request.arrayBuffer()) : null;\n let answer;\n try { answer = await transport.fetch({ url: request.url, method: request.method, headers: [...request.headers], body }); }\n catch (e) { throw Object.assign(new TypeError(e instanceof Error ? e.message : String(e)), { cause: e }); }\n const response = new Response(NO_BODY.has(answer.status) ? null : answer.body as BodyInit, { status: answer.status, headers: answer.headers });\n // The SDK parses the answer's URL, which a Response made here does not have: it is the request's (no redirects).\n Object.defineProperty(response, \"url\", { value: request.url });\n return response;\n };\n globalThis.fetch = routed;\n return () => {\n if (closed) return;\n closed = true;\n if (globalThis.fetch === routed) globalThis.fetch = pageFetch;\n transport.close();\n };\n}\n\n/** The host's way around a page that drops the homeserver's cookie, if it has one. */\nfunction cookieSessionTransport(): PubkyCookieSession | undefined {\n try { return getBrowserHost().pubkyCookieSession?.(); } catch { return undefined; }\n}\n\n/**\n * Starts one request for `capability` in each of the two forms Pubky signers read (a grant request for Passport, a\n * cookie request for Ring's QR code: see below), shows both on one screen, and waits for whichever is approved\n * first, then runs `work` with that session. The session lives only in this renderer's memory while `work` runs,\n * and is signed out afterwards; nothing about it is stored. An approval that arrives after the end is signed out.\n */\nexport async function withPubkyApproval<T>(options: PubkyApprovalOptions, work: (session: PubkyApprovedSession) => Promise<T>): Promise<T> {\n const { signal } = options;\n signal.throwIfAborted();\n const { AuthFlow, GrantAuthFlow, AuthFlowKind } = await import(\"@synonymdev/pubky\");\n signal.throwIfAborted();\n const relay = options.relay ?? null;\n let grant: GrantAuthFlow, cookie: AuthFlow;\n try {\n // The flow's proof-of-possession key stays in this flow's memory (not the SDK's delegated IndexedDB key).\n grant = GrantAuthFlow.start(options.capability, AuthFlowKind.signin(), { clientId: PUBKY_CLIENT_ID, relay, xCallback: { xSource: \"Ghostly\" } });\n } catch (e) { throw failure(\"Could not start a Pubky request\", e); }\n try {\n // Same capability and relay, its own secret. The SDK deprecates this flow, but it is the one Ring's store build reads.\n cookie = AuthFlow.start(options.capability, AuthFlowKind.signin(), relay, { xSource: \"Ghostly\" });\n } catch (e) { grant.free(); throw failure(\"Could not start a Pubky request\", e); }\n\n const opened: { window?: Window | null } = {};\n const say = options.say ?? englishSay;\n options.onApproval({\n open: {\n label: say(\"approval.passport\", \"Approve in your browser (Pubky Passport)\"),\n description: say(\"approval.passportAbout\", \"Opens Pubky Passport. No Passport identity yet? It offers “Continue with Google” and makes one.\"),\n run: () => {\n const window = (options.openPassport ?? openPassportWindow)(passportUrl(grant.authorizationUrl));\n opened.window = window ?? null;\n // null: the browser refused the popup (undefined: it opened elsewhere, the system browser).\n if (window === null) options.onProgress(say(\"progress.popupBlocked\", \"Your browser blocked the Passport window: allow pop-ups for Ghostly and press the button again, or scan the code with Pubky Ring.\"));\n },\n },\n // Ring gets the cookie request (`pubkyauth://signin?…`), not the grant one: the Ring in the app stores (1.19)\n // predates pubky/pubky-ring#360 and answers \"Unrecognized format\" to a `signin_grant` link. Move this to\n // grant.authorizationUrl, and drop the cookie flow, once Ring's store build parses `signin_grant`.\n qr: { value: cookie.authorizationUrl, label: say(\"approval.ring\", \"Or scan with Pubky Ring\") },\n notes: [\n say(\"approval.googleNote\", \"An identity Passport makes with Google is recovered with Google plus Passport: both are needed, neither alone can.\"),\n say(\"approval.qrNote\", \"The code is your request: scan it yourself, and do not share it.\"),\n ],\n });\n\n // Where the page would drop the cookie session's cookie (the desktop app), its requests go through the host, from\n // the first poll (an approval is redeemed inside one) until the last poll has settled and the work is over.\n const transport = cookieSessionTransport();\n const unroute = transport ? routeCookieSession(transport) : () => {};\n let settled!: () => void;\n const polled = new Promise<void>(done => { settled = done; });\n try {\n return await approveAndWork(options, work, { grant, cookie, opened, settled, cookieKept: !!transport });\n } finally {\n void polled.then(unroute);\n }\n}\n\n/**\n * The rest of `withPubkyApproval`, once both requests are shown: the wait, the check, and the work. `cookieKept`: the\n * host keeps a cookie session's cookie, so a refusal is not the page's cookie policy.\n */\nasync function approveAndWork<T>(options: PubkyApprovalOptions, work: (session: PubkyApprovedSession) => Promise<T>, { grant, cookie, opened, settled, cookieKept }: {\n grant: GrantAuthFlow; cookie: AuthFlow; opened: { window?: Window | null }; settled: () => void; cookieKept: boolean;\n}): Promise<T> {\n const { signal } = options;\n let session: Session, viaCookie: boolean;\n try {\n const first = await firstApproval([grant, cookie], signal, options.timeoutMs ?? PUBKY_APPROVAL_TIMEOUT, settled);\n session = first.session;\n viaCookie = first.request === cookie;\n } finally {\n options.onApproval(null);\n try { if (opened.window && !opened.window.closed) opened.window.close(); } catch { /* another origin's window: best effort */ }\n }\n\n options.onProgress((options.say ?? englishSay)(\"progress.approved\", \"Approved. Checking what Pubky granted…\"));\n let key: string;\n try {\n const info = session.info;\n const publicKey = info.publicKey;\n try {\n key = publicKey.z32();\n const granted = info.capabilities;\n if (granted.length !== 1 || granted[0] !== options.capability)\n throw new Error(\"The signer granted different permissions than Ghostly asked for (one proof folder). Nothing was written.\");\n } finally { publicKey.free(); info.free(); }\n } catch (e) {\n await session.signout().catch(() => {});\n session.free();\n throw e;\n }\n\n // A cookie session lives in the homeserver's cookie, a third-party cookie in a page. WebKit (Safari) and Vanadium drop it, so the\n // homeserver then refuses the session's writes: say that, not \"401\". The desktop app keeps it outside its WebView.\n const fail = (what: string) => (e: unknown) => {\n if (viaCookie && !cookieKept && refused(e))\n throw new Error(\"Pubky Ring approved, but this browser blocks your homeserver's sign-in cookie (Vanadium and Safari block cookies from other sites), so nothing was written. Approve with Pubky Passport instead, or use Firefox or the Ghostly desktop app.\");\n throw failure(what, e);\n };\n const approved = session;\n try {\n return await work({\n key,\n put: (path, text) => approved.storage.putText(path, text).catch(fail(\"Could not write to your homeserver\")),\n delete: path => approved.storage.delete(path).catch(fail(\"Could not delete from your homeserver\")),\n });\n } finally {\n // The grant is only needed for this: end it, and forget the session.\n try { await approved.signout(); } catch { /* the grant expires on its own */ }\n approved.free();\n }\n}\n","import {\n isPubkyKey, isPubkyProofFolder, newPubkyProofFolder, normalizePubkyKey, pubkyProofCapability, pubkyProofFile, pubkyProofPath,\n} from \"@ghostly/core\";\nimport { englishSay, type IdentityPlatform, type IdentityProofProvider, type InAppSigner } from \"../contract\";\nimport { PUBKY_APPROVAL_TIMEOUT, readPubkyFile, withPubkyApproval, type PubkyApprovalOptions } from \"../pubky\";\n\n/**\n * A Pubky identity (WISP 302, docs/wisps/302-pubky.md), proven by publication: Pubky Ring and Pubky Passport sign\n * only standard Pubky auth requests, so Ghostly asks, in ONE request either of them can approve, for write access to\n * one fresh folder of the key's homeserver (`/pub/ghostly.app/proofs/<random>/`), and writes the identity statement\n * there. Contacts' apps read the file back from the homeserver the key's own signed Pkarr records name. The session\n * is used once, in memory, and signed out; removing the proof needs a new approval to delete the file.\n */\nexport interface PubkyEvidence { folder: string }\n\nconst short = (key: string) => `pubky${key.slice(0, 4)}…${key.slice(-4)}`;\n\n/** Strict: exactly `{ folder }`, 64 hex characters. Nothing else, so no evidence can name a host or another path. */\nfunction parseEvidence(raw: unknown): PubkyEvidence {\n const e = raw as PubkyEvidence;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw) || Object.keys(raw).join(\",\") !== \"folder\" || !isPubkyProofFolder(e.folder))\n throw new Error(\"That is not Pubky proof evidence\");\n return { folder: e.folder };\n}\n\nexport interface PubkyIdentityOptions {\n /** Pkarr relays the verifier reads (tests). */\n relays?: readonly string[];\n /** The approval flow's knobs (tests: a local relay, a Passport stand-in). */\n approval?: Partial<Pick<PubkyApprovalOptions, \"relay\" | \"timeoutMs\" | \"openPassport\">>;\n}\n\nexport function createPubkyIdentityProvider(options: PubkyIdentityOptions = {}): IdentityProofProvider<PubkyEvidence> {\n const approve = <T>(capability: `/pub/${string}/:w`, ctx: Parameters<InAppSigner<PubkyEvidence>[\"run\"]>[0], work: Parameters<typeof withPubkyApproval<T>>[1]) => {\n if (!ctx.onApproval) throw new Error(\"This screen cannot show a Pubky request\");\n const wait = ctx.waitMs ? { timeoutMs: Math.min(ctx.waitMs, PUBKY_APPROVAL_TIMEOUT) } : {};\n return withPubkyApproval({ ...options.approval, ...wait, capability, signal: ctx.signal, onApproval: ctx.onApproval, onProgress: ctx.onProgress, say: ctx.say }, work);\n };\n\n const signer: InAppSigner<PubkyEvidence> = {\n id: \"pubky-auth\", kind: \"in-app\",\n label: \"Pubky Ring or Pubky Passport\",\n action: \"Continue\",\n maxWaitMs: PUBKY_APPROVAL_TIMEOUT,\n description: \"One request: approve it in Pubky Passport in your browser, or scan it with Pubky Ring. Ghostly only asks to write one small file to a new folder of your homeserver.\",\n run(ctx, work) {\n const folder = newPubkyProofFolder();\n return approve(pubkyProofCapability(folder), ctx, async session => {\n let written: `/pub/${string}` | undefined;\n try {\n return await work({\n subject: async () => session.key,\n async sign(statement) {\n if (statement.binding.subject !== session.key) throw new Error(\"That is another Pubky identity\");\n ctx.onProgress((ctx.say ?? englishSay)(\"progress.writing\", \"Writing the proof to your homeserver…\"));\n const path = pubkyProofPath(folder, statement.id);\n await session.put(path, pubkyProofFile(statement));\n written = path;\n return { folder };\n },\n });\n } catch (e) {\n // Not saved (a failed check, a cancel): the file does not stay behind.\n if (written) await session.delete(written).catch(() => {});\n throw e;\n }\n });\n },\n };\n\n return {\n id: \"pubky\",\n label: \"Pubky\",\n category: \"self-custodied\",\n summary: \"Approve in Pubky Ring or Passport\",\n description: \"Proves you hold a Pubky key: approve one request in Pubky Ring or Pubky Passport, and Ghostly writes a small proof file to your homeserver. Contacts’ apps read it back through your key’s own records.\",\n limits: \"The file is on your homeserver: whoever runs it could write there too. It does not prove who holds the key.\",\n platforms: [\"web\", \"extension\", \"desktop\"] satisfies IdentityPlatform[],\n subject: {\n label: \"Pubky key\",\n placeholder: \"pubky…\",\n help: \"Comes from Pubky Ring or Passport when you approve.\",\n normalize: normalizePubkyKey,\n short,\n },\n validity: { defaultDays: 90, maxDays: 365 },\n // The file can be deleted, or the key can move to another homeserver, before the proof expires.\n recheck: { afterSeconds: 86_400 },\n privacy: \"Your contact’s app reads your key’s records from Pubky’s Pkarr relays (pkarr.pubky.org, pkarr.pubky.app), looks up your homeserver’s address through its DNS-over-HTTPS resolver (or the next one when that cannot be reached; it only contacts a public address, on port 443), and reads the proof file from your homeserver, which sees the contact’s IP address.\",\n signers: [signer],\n // Pubky's own URI form for a key, as its SDK writes resources (`pubky://<key>/…`).\n publicUri: key => `pubky://${key}`,\n parseEvidence,\n async verify(statement, { folder }, ctx) {\n const key = statement.binding.subject;\n if (!isPubkyKey(key)) throw new Error(\"That is not a Pubky key\");\n const { text, host } = await readPubkyFile(key, pubkyProofPath(folder, statement.id), ctx.fetch, ctx.signal, options.relays);\n if (text === undefined) throw new Error(\"The proof file is not on the homeserver\");\n if (text !== pubkyProofFile(statement)) throw new Error(\"The file on the homeserver is not this proof\");\n return { subject: key, source: `File on the homeserver ${host}, found through the key’s own Pkarr records` };\n },\n unpublish: {\n description: \"Also deletes the proof file on your homeserver: that takes one more approval in Pubky Ring or Passport, since Ghostly kept no access to it.\",\n async run({ id, subject, evidence }, ctx) {\n // Stored when the proof was made: parsed like any evidence, so a bad record never names another path.\n const { folder } = parseEvidence(evidence);\n const path = pubkyProofPath(folder, id);\n return approve(pubkyProofCapability(folder), ctx, async session => {\n if (session.key !== subject) throw new Error(\"That is another Pubky identity: approve with the one this proof is for\");\n ctx.onProgress((ctx.say ?? englishSay)(\"progress.deleting\", \"Deleting the proof file from your homeserver…\"));\n await session.delete(path);\n });\n },\n },\n };\n}\n\nexport const pubky = createPubkyIdentityProvider();\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","import type { IdentityProofProvider } from \"./contract\";\nimport { bitcoin } from \"./providers/bitcoin\";\nimport { nostr } from \"./providers/nostr\";\nimport { domain } from \"./providers/domain\";\nimport { openpgp } from \"./providers/openpgp\";\nimport { ssh, sshGithub, sshGitlab } from \"./providers/ssh\";\nimport { oidc } from \"./providers/oidc\";\nimport { did } from \"./providers/did\";\nimport { atproto } from \"./providers/atproto\";\nimport { pubky } from \"./providers/pubky\";\nimport { FAKE_IDENTITY_PROVIDERS, testIdentitiesEnabled } from \"./testing\";\nimport { registeredIdentityProviders, reserveAdapterIds } from \"../plugins/registry\";\n\n/**\n * Every identity-proof provider built into Ghostly. Adding one is adding its module under `providers/`\n * and ONE line here; see PROOFS.md. The order is the order of the picker on the Identities page. A\n * provider written outside the app registers through `plugins/registry.ts` (the SDK) and comes after.\n */\nexport const IDENTITY_PROVIDERS: readonly IdentityProofProvider[] = [\n nostr,\n pubky,\n domain,\n openpgp,\n bitcoin,\n ssh, sshGithub, sshGitlab,\n oidc,\n did,\n atproto,\n];\n\nreserveAdapterIds(\"identity\", IDENTITY_PROVIDERS.map((p) => p.id));\n\nconst warned = new Set<string>();\n/** The built-in providers, then the ones plugins registered (a built-in's id wins), then the fakes when this browser asked for them (e2e). */\nexport function identityProviders(): readonly IdentityProofProvider[] {\n const external = registeredIdentityProviders().filter((p) => {\n const taken = IDENTITY_PROVIDERS.some((b) => b.id === p.id);\n if (taken && !warned.has(p.id)) { warned.add(p.id); console.error(`[ghostly] identity provider ${p.id} from a plugin is ignored: a built-in has that id`); }\n return !taken;\n });\n return [...IDENTITY_PROVIDERS, ...external, ...(testIdentitiesEnabled() ? FAKE_IDENTITY_PROVIDERS : [])];\n}\n\nexport function identityProvider(id: string, providers = identityProviders()): IdentityProofProvider | undefined {\n return providers.find(p => p.id === id);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAM,OAAO;AACb,IAAM,QAAQ;;AAEd,IAAM,OAAO;AACb,IAAM,MAAM;AAYZ,IAAM,OAAO,MAAkB,OAAgB,KAAK,OAAO,IAAK,KAA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