@orangecheck/sdk 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/canonical.ts","../src/utils/logger.ts","../src/nostr.ts","../src/nostr-crypto.ts","../src/attestation.ts"],"names":["log"],"mappings":";AA8BA,SAAS,WAAW,KAAA,EAA2B;AAC3C,EAAA,OAAO,MAAM,IAAA,CAAK,KAAK,CAAA,CAClB,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAC1C,KAAK,EAAE,CAAA;AAChB;AAmLA,eAAsB,sBAAsB,OAAA,EAAkC;AAE1E,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAChC,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,MAAA,CAAO,OAAO,CAAA;AAGnC,EAAA,MAAM,aAAa,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,WAAW,IAAI,CAAA;AAG7D,EAAA,OAAO,UAAA,CAAW,IAAI,UAAA,CAAW,UAAU,CAAC,CAAA;AAChD;AAeA,eAAsB,yBAAA,CAClB,SACA,SAAA,EACA,MAAA,EACA,SACA,UAAA,EACA,UAAA,GAAyB,EAAC,EACE;AAC5B,EAAA,MAAM,cAAA,GAAiB,MAAM,qBAAA,CAAsB,OAAO,CAAA;AAG1D,EAAA,MAAM,aAAA,GAAgB,OAAA,CAAQ,KAAA,CAAM,qBAAqB,CAAA;AACzD,EAAA,MAAM,YAAY,aAAA,GAAgB,CAAC,sBAAK,IAAI,IAAA,IAAO,WAAA,EAAY;AAG/D,EAAA,MAAM,aAAa,UAAA,CAAW,OAAA;AAG9B,EAAA,MAAM,WAAA,GAAc,UAAA,CAAW,WAAA,EAAa,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,K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AAE,QAAA,EAAU,UAAA,IAAc,uCAAuC,CAAA;AAC1E,EAAA,OAAO,oBAAA,CAAqB,EAAE,QAAA,EAAU,EAAE,UAAU,UAAA,EAAW,EAAG,QAAQ,CAAA;AAC9E;AAMO,SAAS,2BAA2B,UAAA,EAAuC;AAC9E,EAAA,OAAO,UAAA,CAAW,GAAA,CAAI,CAAC,EAAA,KAAO,CAAA,EAAG,EAAA,CAAG,QAAQ,CAAA,CAAA,EAAI,EAAA,CAAG,UAAU,CAAA,CAAE,CAAA,CAAE,KAAK,IAAI,CAAA;AAC9E;AAOO,SAAS,kBAAA,CACZ,aAAA,EACA,OAAA,GAAU,wBAAA,EACJ;AACN,EAAA,OAAO,CAAA,EAAG,OAAO,CAAA,QAAA,EAAW,aAAa,CAAA,CAAA;AAC7C;AAOO,SAAS,4BAA4B,GAAA,EAA4B;AACpE,EAAA,IAAI;AACA,IAAA,MAAM,CAAA,GAAI,IAAI,GAAA,CAAI,GAAG,CAAA;AAErB,IAAA,MAAM,CAAA,GAAI,CAAA,CAAE,QAAA,CAAS,KAAA,CAAM,gCAAgC,CAAA;AAC3D,IAAA,IAAI,CAAA,EAAG,OAAO,CAAA,CAAE,CAAC,EAAG,WAAA,EAAY;AAEhC,IAAA,MAAM,CAAA,GAAI,CAAA,CAAE,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA;AACjC,IAAA,IAAI,KAAK,iBAAA,CAAkB,IAAA,CAAK,CAAC,CAAA,EAAG,OAAO,EAAE,WAAA,EAAY;AACzD,IAAA,OAAO,IAAA;AAAA,EACX,CAAA,CAAA,MAAQ;AACJ,IAAA,OAAO,IAAA;AAAA,EACX;AACJ","file":"attestation.mjs","sourcesContent":["/**\n * Canonical message builder per SPEC.md §2\n *\n * - LF line endings, exactly one trailing LF\n * - 7 fixed core lines in strict order and wording\n * - Optional extensions appended as key: value with lexicographically sorted lowercase keys\n */\n\nimport type { AttestationEnvelope, IdentityBinding, Scheme } from './types';\n\n/**\n * Input for building a canonical message\n */\nexport interface CanonicalInput {\n /** Bitcoin address */\n address: string;\n /** Optional identity bindings */\n identities?: IdentityBinding[];\n}\n\n/**\n * Extension key-value pairs for canonical message\n */\nexport type Extensions = Record<string, string | undefined>;\n\n/**\n * Convert bytes to lowercase hex string\n * @param bytes - Byte array to convert\n * @returns Lowercase hex string\n */\nfunction toLowerHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Generate a random 16-byte nonce as lowercase hex\n * Uses Web Crypto API when available, falls back to Math.random()\n * @returns 32-character lowercase hex string\n */\nexport function randomNonce16BHexLower(): string {\n const arr = new Uint8Array(16);\n\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(arr);\n return toLowerHex(arr);\n }\n } catch {\n // Fall through to non-cryptographic fallback\n }\n\n // No silent Math.random fallback: a nonce is a load-bearing security\n // primitive. A deployment without `crypto.getRandomValues` MUST fix its\n // environment rather than sign with weak randomness.\n throw new Error('crypto.getRandomValues unavailable — refusing to mint a weak nonce');\n}\n\n/**\n * Reject characters that would break the line-oriented canonical grammar\n * or the comma-separated identities list. If any of these slipped through,\n * an attacker could smuggle a forged `address:` or extension line into the\n * signed payload: `identities: alice\\naddress: bc1qEVIL…` would parse as a\n * second address line. Catch it at the boundary, not at verification time.\n *\n * Also rejects a colon in the identifier so a bad actor can't turn\n * `github:alice:extra` into a different protocol binding on parse.\n */\nconst IDENTITY_PROTOCOL_RE = /^[a-z][a-z0-9_-]*$/;\nconst IDENTITY_FORBIDDEN_CHARS = /[\\r\\n,]/;\n\nfunction assertSafeIdentity({ protocol, identifier }: IdentityBinding): void {\n if (!IDENTITY_PROTOCOL_RE.test(protocol)) {\n throw new Error(\n `invalid identity protocol: ${JSON.stringify(protocol)} — must match /^[a-z][a-z0-9_-]*$/`\n );\n }\n if (!identifier || IDENTITY_FORBIDDEN_CHARS.test(identifier)) {\n throw new Error(\n `invalid identity identifier: ${JSON.stringify(identifier)} — must be non-empty and contain no newlines or commas`\n );\n }\n}\n\n/**\n * Format identities as comma-separated protocol:identifier pairs, sorted lexicographically\n * @param identities - Array of identity bindings\n * @returns Comma-separated string of protocol:identifier pairs\n */\nexport function formatIdentities(identities: IdentityBinding[] = []): string {\n if (identities.length === 0) {\n return '';\n }\n for (const id of identities) assertSafeIdentity(id);\n\n // Format as protocol:identifier and sort lexicographically\n const formatted = identities\n .map(({ protocol, identifier }) => `${protocol}:${identifier}`)\n .sort();\n\n return formatted.join(',');\n}\n\n/**\n * Parse identities from comma-separated protocol:identifier format\n * @param identitiesStr - Comma-separated identity string\n * @returns Array of identity bindings\n * @throws {Error} If identity format is invalid\n */\nexport function parseIdentities(identitiesStr: string): IdentityBinding[] {\n if (!identitiesStr || identitiesStr.trim() === '') {\n return [];\n }\n // The identities field lives on one line of the canonical message. If it\n // contains a raw LF/CR, it's either corrupt or an attempt to smuggle a\n // fake core line into the parser. Refuse instead of trying to recover.\n if (IDENTITY_FORBIDDEN_CHARS.test(identitiesStr.replace(/,/g, ''))) {\n throw new Error('identities field contains forbidden characters (newline)');\n }\n\n const bindings = identitiesStr.split(',').map((binding) => {\n const colonIndex = binding.indexOf(':');\n if (colonIndex === -1) {\n throw new Error(`Invalid identity binding format: ${binding}`);\n }\n return {\n protocol: binding.substring(0, colonIndex).trim(),\n identifier: binding.substring(colonIndex + 1).trim(),\n };\n });\n\n for (const b of bindings) {\n if (!b.protocol || !b.identifier) {\n throw new Error(`Invalid identity binding: ${b.protocol}:${b.identifier}`);\n }\n assertSafeIdentity(b);\n }\n return bindings;\n}\n\n/**\n * Optional deterministic overrides for message building. Only intended for\n * tests / conformance vectors; production callers should let the builder\n * mint a fresh nonce + timestamp per message.\n */\nexport interface BuildOptions {\n /** 32-char lowercase hex. Default: freshly-generated cryptographic nonce. */\n nonce?: string;\n /** RFC-3339 UTC. Default: `new Date().toISOString()`. */\n issuedAt?: string;\n}\n\n/**\n * Build a canonical message following OrangeCheck Protocol v0 specification\n * @param input - Canonical input with address and identities\n * @param extensions - Optional extension key-value pairs\n * @param options - Optional deterministic overrides (testing only)\n * @returns Canonical message string with LF line endings\n */\nexport function buildCanonicalMessage(\n { address, identities }: CanonicalInput,\n extensions: Extensions = {},\n options: BuildOptions = {}\n): string {\n const nonce = options.nonce ?? randomNonce16BHexLower();\n if (!/^[0-9a-f]{32}$/.test(nonce)) {\n throw new Error(`invalid nonce: must be 32 lowercase hex chars`);\n }\n const issuedAt = options.issuedAt ?? new Date().toISOString();\n\n // Format identities\n const identitiesStr = formatIdentities(identities);\n\n // Core (strict wording + order per SPEC.md §2)\n const core = [\n 'orangecheck',\n `identities: ${identitiesStr}`,\n `address: ${address}`,\n 'purpose: portable reputation attestation (non-custodial)',\n `nonce: ${nonce}`,\n `issued_at: ${issuedAt}`,\n 'ack: I attest control of this address and bind it to my identities.',\n ];\n\n // Normalize and sort extensions\n const normExt: Record<string, string> = {};\n for (const [k, v] of Object.entries(extensions)) {\n if (v == null || v === '') {\n continue;\n }\n const key = k.toLowerCase();\n normExt[key] = String(v);\n }\n\n const extLines = Object.keys(normExt)\n .sort()\n .map((k) => `${k}: ${normExt[k]!}`);\n\n const all = [...core, ...extLines];\n\n // Join with LF and ensure exactly one trailing LF\n return all.join('\\n') + '\\n';\n}\n\n/**\n * Generate attestation ID from canonical message\n *\n * attestation_id = SHA-256(canonical_message)\n *\n * @param message - Canonical message string\n * @returns Lowercase hex SHA-256 hash\n */\nexport async function generateAttestationId(message: string): Promise<string> {\n // Convert message to UTF-8 bytes\n const encoder = new TextEncoder();\n const data = encoder.encode(message);\n\n // Compute SHA-256 hash\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n // Convert to lowercase hex\n return toLowerHex(new Uint8Array(hashBuffer));\n}\n\n/**\n * Create an attestation envelope for publishing\n *\n * This wraps the canonical message with metadata for Nostr publishing\n *\n * @param message - Canonical message\n * @param signature - BIP-322 or legacy signature\n * @param scheme - Signature scheme used\n * @param address - Bitcoin address\n * @param identities - Identity bindings\n * @param extensions - Optional extensions\n * @returns Attestation envelope ready for publishing\n */\nexport async function createAttestationEnvelope(\n message: string,\n signature: string,\n scheme: Scheme,\n address: string,\n identities: IdentityBinding[],\n extensions: Extensions = {}\n): Promise<AttestationEnvelope> {\n const attestation_id = await generateAttestationId(message);\n\n // Extract issued_at from message\n const issuedAtMatch = message.match(/issued_at: ([^\\n]+)/);\n const issued_at = issuedAtMatch?.[1] ?? new Date().toISOString();\n\n // Extract expires from extensions if present\n const expires_at = extensions.expires;\n\n // Extract relay hints from extensions if present\n const relay_hints = extensions.relay_hints?.split(',').map((r) => r.trim());\n\n // Extract publish targets from extensions if present\n const publish_targets = extensions.publish?.split(',').map((t) => t.trim());\n\n // Base64url encode the message\n const encoder = new TextEncoder();\n const messageBytes = encoder.encode(message);\n const base64 = btoa(String.fromCharCode(...messageBytes));\n const message_b64url = base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n\n // Construct verification URL\n const verification_url = `https://attest.ochk.io/attest/${attestation_id}`;\n\n return {\n attestation_id,\n scheme,\n address,\n identities,\n message,\n message_b64url,\n signature,\n issued_at,\n expires_at,\n verification_url,\n publish_targets,\n relay_hints,\n };\n}\n","/**\n * Simple logger for SDK\n * Can be disabled in production builds\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\n/**\n * Logger context type\n */\nexport type LogContext = Record<string, unknown>;\n\n/**\n * Logger interface\n */\nexport interface Logger {\n debug: (contextOrMessage: string | LogContext, message?: string) => void;\n info: (contextOrMessage: string | LogContext, message?: string) => void;\n warn: (contextOrMessage: string | LogContext, message?: string) => void;\n error: (contextOrMessage: string | LogContext, message?: string) => void;\n}\n\nlet logLevel: LogLevel = 'none';\n\n/**\n * Set the global log level\n * @param level - Log level to set\n */\nexport function setLogLevel(level: LogLevel): void {\n logLevel = level;\n}\n\n/**\n * Get the current log level\n * @returns Current log level\n */\nexport function getLogLevel(): LogLevel {\n return logLevel;\n}\n\n/**\n * Create a namespaced logger\n * @param namespace - Logger namespace\n * @returns Logger instance\n */\nexport function createLogger(namespace: string): Logger {\n const shouldLog = (level: Exclude<LogLevel, 'none'>): boolean => {\n if (logLevel === 'none') return false;\n\n const levels: Exclude<LogLevel, 'none'>[] = ['debug', 'info', 'warn', 'error'];\n const currentLevelIndex = levels.indexOf(logLevel as Exclude<LogLevel, 'none'>);\n const messageLevelIndex = levels.indexOf(level);\n\n return messageLevelIndex >= currentLevelIndex;\n };\n\n const formatMessage = (msg: string): string => `[${namespace}] ${msg}`;\n\n return {\n debug: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('debug')) {\n if (typeof contextOrMessage === 'string') {\n console.debug(formatMessage(contextOrMessage));\n } else {\n console.debug(formatMessage(message ?? 'Debug'), contextOrMessage);\n }\n }\n },\n info: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('info')) {\n if (typeof contextOrMessage === 'string') {\n console.info(formatMessage(contextOrMessage));\n } else {\n console.info(formatMessage(message ?? 'Info'), contextOrMessage);\n }\n }\n },\n warn: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('warn')) {\n if (typeof contextOrMessage === 'string') {\n console.warn(formatMessage(contextOrMessage));\n } else {\n console.warn(formatMessage(message ?? 'Warning'), contextOrMessage);\n }\n }\n },\n error: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('error')) {\n if (typeof contextOrMessage === 'string') {\n console.error(formatMessage(contextOrMessage));\n } else {\n console.error(formatMessage(message ?? 'Error'), contextOrMessage);\n }\n }\n },\n };\n}\n\n/**\n * Log verification error\n * @param protocol - Identity protocol\n * @param identifier - Identity identifier\n * @param error - Error object\n * @param context - Additional context\n */\nexport function logVerificationError(\n protocol: string,\n identifier: string,\n error: Error,\n context?: LogContext\n): void {\n const logger = createLogger('identity-verification');\n logger.error(\n {\n protocol,\n identifier,\n error: error.message,\n stack: error.stack,\n ...context,\n },\n 'Verification failed'\n );\n}\n","/**\n * Nostr Integration for OrangeCheck Protocol\n *\n * Implements NIP-78 (Application-specific data) for attestation publishing\n */\n\nimport type { AttestationEnvelope, IdentityBinding, NostrEvent } from './types';\n\nimport { createLogger } from './utils/logger';\n\nconst log = createLogger('ocp/nostr');\n\n/**\n * NIP-78 event kind for OrangeCheck attestations\n */\nexport const ATTESTATION_EVENT_KIND = 30078;\n\n/**\n * Default Nostr relays for OrangeCheck attestation publishing and lookup.\n *\n * Well-known relays with good uptime, plus the first-party family relay.\n * `relay.ochk.io` was missing here while attest.ochk.io's verifier has always\n * read from it, so the SDK and the reference implementation were looking in\n * different places — the SDK could miss a family attestation that the hosted\n * API found. It runs a kind allowlist (30078-30087, 30110-30114) and canonical OC d-tag\n * prefixes, and is always co-published alongside the public relays, never the\n * only copy. See https://github.com/orangecheck/oc-relay-infra.\n *\n * Order matters only for readability; queries fan out to all of them and\n * merge. Pass your own `relays` to any query to override this entirely — the\n * protocol does not require trusting any particular relay.\n *\n * A NOTE ON `relay.damus.io`, deliberately kept. It is reachable from a browser\n * (measured ~391ms, real events returned) and NOT reachable from at least one\n * serverless runtime — Vercel's, where it fails to connect on every attempt,\n * consistently, over hours. Its NIP-11 declares no `auth_required`,\n * `payment_required` or `restricted_writes`, so this reads as datacenter-IP\n * filtering in front of it rather than policy, and it can change in either\n * direction without notice.\n *\n * It stays for three reasons: it is one of the most widely read relays, so an\n * attestation published there is findable by the most people; the browser is\n * the dominant path for this SDK (wallet signing happens there), and it works\n * there; and since FANOUT_DEADLINE_MS below is a SHARED budget, a relay that\n * fails to connect resolves immediately and costs no latency. Removing a relay\n * that works for most callers, to tidy a status field on one runtime, is the\n * wrong trade.\n *\n * If you run this SDK server-side and want certainty about coverage, pass\n * `relays` explicitly. Silent partial coverage — believing you reached four\n * relays when you reached three — is the real hazard here, not latency.\n */\nexport const DEFAULT_RELAYS: string[] = [\n 'wss://relay.damus.io',\n 'wss://nos.lol',\n 'wss://relay.snort.social',\n 'wss://relay.ochk.io',\n];\n\n/**\n * Wall-clock budget for a whole relay fan-out, shared by every relay in it.\n *\n * Queries below use Promise.allSettled, so a fan-out used to take as long as\n * its SLOWEST relay — and with a dead relay in DEFAULT_RELAYS that meant the\n * per-relay 10s timeout, every single call. Measured on 1.4.0:\n *\n * check({ addr }) with the old defaults 10.4s\n * check({ addr }) with the dead relay out 1.0s\n *\n * That is not merely slow, it broke a dependent outright: @orangecheck/gate\n * races check() against a 5s lookupTimeoutMs, so a 10.4s lookup lost the race\n * every time and no address-based gate decision could ever succeed.\n *\n * A shared deadline fixes the class: whichever relay is dead or slow next, a\n * fan-out costs at most this. Healthy relays answer well inside it (~1s for a\n * cold WebSocket plus a query). QUERY_TIMEOUT_MS remains the per-relay ceiling.\n *\n * The value is deliberately BELOW @orangecheck/gate's 5s default\n * lookupTimeoutMs, so a gate decision can still resolve in the worst case\n * rather than always losing its own race. Raising this above 5000 silently\n * breaks that dependent — change both together, or don't.\n */\nexport const FANOUT_DEADLINE_MS = 4000;\nconst QUERY_TIMEOUT_MS = 10000;\n\n/** Remaining budget for a relay, given the fan-out's shared deadline. */\nfunction budgetFor(deadlineAt: number): number {\n return Math.max(0, Math.min(QUERY_TIMEOUT_MS, deadlineAt - Date.now()));\n}\n\n/**\n * Create a NIP-78 event for an OrangeCheck attestation\n *\n * Kind: 30078 (Parameterized Replaceable Event)\n * d-tag: attestation_id (makes it replaceable by attestation ID)\n *\n * @param envelope - Attestation envelope\n * @param pubkey - Nostr public key (hex format)\n * @returns Unsigned Nostr event\n */\nexport function createAttestationEvent(\n envelope: AttestationEnvelope,\n pubkey: string\n): Omit<NostrEvent, 'id' | 'sig'> {\n // NIP-12 relays index SINGLE-LETTER tags only. A multi-letter tag like\n // `address` is stored verbatim and stays readable in the event, but it is\n // never indexed, so no `#address` filter can ever retrieve it. Without the\n // `t` tags below an attestation published by this SDK is invisible to\n // every by-address query on every relay — including attest.ochk.io's own\n // verifier, which queries `#t`. Keep both: `t` is what makes it findable,\n // `address` is human-readable diagnostics and is not load-bearing.\n const tags: string[][] = [\n ['d', envelope.attestation_id], // Parameterized replaceable event identifier (indexed)\n ['t', envelope.address], // Indexed btc-address tag — query with `#t`\n ['t', 'oc-attest'], // Family marker — `#t=[\"oc-attest\"]` for cross-cut discovery\n ['address', envelope.address], // Diagnostic / legacy — relay won't index this\n ['scheme', envelope.scheme], // Signature scheme (bip322 or legacy)\n ['issued_at', envelope.issued_at], // ISO timestamp\n ];\n\n // Add identity tags\n for (const identity of envelope.identities) {\n tags.push(['i', `${identity.protocol}:${identity.identifier}`]);\n }\n\n // Add expiration if present\n if (envelope.expires_at) {\n tags.push(['expires', envelope.expires_at]);\n }\n\n // Add relay hints if present\n if (envelope.relay_hints?.length) {\n for (const relay of envelope.relay_hints) {\n tags.push(['relay', relay]);\n }\n }\n\n // Content is the full attestation envelope as JSON\n const content = JSON.stringify(envelope, null, 2);\n\n return {\n kind: ATTESTATION_EVENT_KIND,\n tags,\n content,\n created_at: Math.floor(Date.parse(envelope.issued_at) / 1000),\n pubkey,\n };\n}\n\n/**\n * Parse identity bindings from Nostr event tags\n *\n * @param event - Nostr event\n * @returns Array of identity bindings\n */\nexport function parseIdentitiesFromEvent(event: NostrEvent): IdentityBinding[] {\n const identities: IdentityBinding[] = [];\n\n for (const tag of event.tags) {\n if (tag[0] === 'i' && tag[1]) {\n const colonIndex = tag[1].indexOf(':');\n if (colonIndex !== -1) {\n identities.push({\n protocol: tag[1].substring(0, colonIndex),\n identifier: tag[1].substring(colonIndex + 1),\n });\n }\n }\n }\n\n return identities;\n}\n\n/**\n * Extract attestation ID from Nostr event d-tag\n *\n * @param event - Nostr event\n * @returns Attestation ID or undefined if not found\n */\nexport function getAttestationIdFromEvent(event: NostrEvent): string | undefined {\n const dTag = event.tags.find((tag) => tag[0] === 'd');\n return dTag?.[1];\n}\n\n/**\n * Extract Bitcoin address from Nostr event tags\n *\n * @param event - Nostr event\n * @returns Bitcoin address or undefined if not found\n */\nexport function getAddressFromEvent(event: NostrEvent): string | undefined {\n const addressTag = event.tags.find((tag) => tag[0] === 'address');\n return addressTag?.[1];\n}\n\n/**\n * Publish a Nostr event to multiple relays\n * Returns array of relay URLs that successfully accepted the event\n */\nexport async function publishToRelays(\n event: NostrEvent,\n relays: string[] = DEFAULT_RELAYS\n): Promise<{ success: string[]; failed: string[] }> {\n const success: string[] = [];\n const failed: string[] = [];\n\n log.info({ eventId: event.id, relayCount: relays.length }, 'Publishing event to relays');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const publishPromises = relays.map(async (relayUrl) => {\n let ws: WebSocket | null = null;\n\n // One outcome per relay, first one wins. Without this a relay that\n // ACKs `OK true` and then emits an error or close event during\n // teardown lands in BOTH arrays, and the caller reports \"published\n // to 3 · rejected 3\" over the same three relays. The `failed.includes`\n // check this replaces only ever de-duplicated `failed` against\n // itself, so it could not catch a success/failure split.\n // attest.ochk.io's copy of this file has carried the guard for a\n // while; this is the back-port.\n let settled = false;\n const recordSuccess = (): void => {\n if (settled) return;\n settled = true;\n success.push(relayUrl);\n };\n const recordFailure = (): void => {\n if (settled) return;\n settled = true;\n failed.push(relayUrl);\n };\n\n try {\n // Connect to relay\n ws = new WebSocket(relayUrl);\n const wsRef = ws; // Capture for closures\n\n await new Promise<void>((resolve, reject) => {\n // One outer deadline covers connect + OK round-trip. The old\n // code cleared this on `onopen`, which meant a relay that\n // opened but never sent OK would hang the promise forever.\n const deadline = setTimeout(() => {\n wsRef.close();\n reject(new Error('Relay publish timeout'));\n }, budgetFor(deadlineAt));\n\n const cleanup = () => {\n clearTimeout(deadline);\n wsRef.close();\n };\n\n wsRef.onopen = () => {\n // Do NOT clear the deadline — we still need it in case\n // the relay never responds with OK.\n wsRef.send(JSON.stringify(['EVENT', event]));\n };\n\n wsRef.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n // Check for OK response\n if (data[0] === 'OK' && data[1] === event.id) {\n if (data[2] === true) {\n recordSuccess();\n cleanup();\n resolve();\n } else {\n log.warn(\n { relay: relayUrl, reason: data[3] },\n 'Relay rejected event'\n );\n recordFailure();\n cleanup();\n reject(new Error(data[3] || 'Relay rejected event'));\n }\n }\n } catch (err) {\n log.error(\n { relay: relayUrl, error: err },\n 'Failed to parse relay response'\n );\n recordFailure();\n cleanup();\n reject(err);\n }\n };\n\n wsRef.onerror = (err) => {\n log.error({ relay: relayUrl, error: err }, 'WebSocket error');\n recordFailure();\n cleanup();\n reject(err);\n };\n\n wsRef.onclose = () => {\n // Socket closed before we resolved/rejected — counts as\n // failure. clearTimeout here is safe (cleanup handles both).\n clearTimeout(deadline);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to publish to relay');\n recordFailure();\n } finally {\n // Ensure WebSocket is closed\n if (ws && ws.readyState !== WebSocket.CLOSED) {\n ws.close();\n }\n }\n });\n\n await Promise.allSettled(publishPromises);\n\n log.info({ successCount: success.length, failedCount: failed.length }, 'Publishing complete');\n\n return { success, failed };\n}\n\n/**\n * Query relays for attestations by attestation ID\n */\nexport async function queryByAttestationId(\n attestationId: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<NostrEvent[]> {\n const events: NostrEvent[] = [];\n\n log.info({ attestationId, relayCount: relays.length }, 'Querying relays for attestation');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const queryPromises = relays.map(async (relayUrl) => {\n let ws: WebSocket | null = null;\n\n try {\n ws = new WebSocket(relayUrl);\n const wsRef = ws; // Capture for closures\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n wsRef.close();\n reject(new Error('Query timeout'));\n }, budgetFor(deadlineAt));\n\n const cleanup = () => {\n clearTimeout(timeout);\n wsRef.close();\n };\n\n wsRef.onopen = () => {\n // Send REQ message for kind 30078 with d-tag = attestation_id\n const subscriptionId = `ochk_${Date.now()}`;\n wsRef.send(\n JSON.stringify([\n 'REQ',\n subscriptionId,\n {\n kinds: [30078],\n '#d': [attestationId],\n limit: 1,\n },\n ])\n );\n };\n\n wsRef.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n if (data[0] === 'EVENT') {\n events.push(data[2]);\n } else if (data[0] === 'EOSE') {\n cleanup();\n resolve();\n }\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to parse event');\n }\n };\n\n wsRef.onerror = (err) => {\n log.error({ relay: relayUrl, error: err }, 'WebSocket error during query');\n cleanup();\n reject(err);\n };\n\n wsRef.onclose = () => {\n clearTimeout(timeout);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to query relay');\n } finally {\n // Ensure WebSocket is closed\n if (ws && ws.readyState !== WebSocket.CLOSED) {\n ws.close();\n }\n }\n });\n\n await Promise.allSettled(queryPromises);\n\n log.info({ eventCount: events.length }, 'Query complete');\n\n return events;\n}\n\n/**\n * Query relays for attestations by Bitcoin address\n */\nexport async function queryByAddress(\n address: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<NostrEvent[]> {\n const events: NostrEvent[] = [];\n\n log.info({ address, relayCount: relays.length }, 'Querying relays for address');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const queryPromises = relays.map(async (relayUrl) => {\n try {\n const ws = new WebSocket(relayUrl);\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n ws.close();\n reject(new Error('Query timeout'));\n }, budgetFor(deadlineAt));\n\n ws.onopen = () => {\n const subscriptionId = `ochk_addr_${Date.now()}`;\n ws.send(\n JSON.stringify([\n 'REQ',\n subscriptionId,\n {\n kinds: [30078],\n // `#t`, NOT `#address`: NIP-12 relays index\n // single-letter tags only, so `#address`\n // matched nothing on any relay and this\n // function returned empty for every real\n // attestation. attest.ochk.io's verifier has\n // queried `#t` since the same fix landed\n // there; this is the back-port.\n '#t': [address],\n limit: 50,\n },\n ])\n );\n };\n\n ws.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n if (data[0] === 'EVENT') {\n events.push(data[2]);\n } else if (data[0] === 'EOSE') {\n clearTimeout(timeout);\n ws.close();\n resolve();\n }\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to parse event');\n }\n };\n\n ws.onerror = (err) => {\n clearTimeout(timeout);\n log.error({ relay: relayUrl, error: err }, 'WebSocket error during query');\n reject(err);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to query relay');\n }\n });\n\n await Promise.allSettled(queryPromises);\n\n log.info({ eventCount: events.length }, 'Query complete');\n\n return events;\n}\n\n/**\n * Query relays for attestations by identity (any protocol)\n */\nexport async function queryByIdentity(\n protocol: string,\n identifier: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<NostrEvent[]> {\n const events: NostrEvent[] = [];\n const identityTag = `${protocol}:${identifier}`;\n\n log.info({ protocol, identifier, relayCount: relays.length }, 'Querying relays for identity');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const queryPromises = relays.map(async (relayUrl) => {\n try {\n const ws = new WebSocket(relayUrl);\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n ws.close();\n reject(new Error('Query timeout'));\n }, budgetFor(deadlineAt));\n\n ws.onopen = () => {\n const subscriptionId = `ochk_identity_${Date.now()}`;\n ws.send(\n JSON.stringify([\n 'REQ',\n subscriptionId,\n {\n kinds: [30078],\n '#i': [identityTag],\n limit: 10,\n },\n ])\n );\n };\n\n ws.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n if (data[0] === 'EVENT') {\n events.push(data[2]);\n } else if (data[0] === 'EOSE') {\n clearTimeout(timeout);\n ws.close();\n resolve();\n }\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to parse event');\n }\n };\n\n ws.onerror = (err) => {\n clearTimeout(timeout);\n log.error({ relay: relayUrl, error: err }, 'WebSocket error during query');\n reject(err);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to query relay');\n }\n });\n\n await Promise.allSettled(queryPromises);\n\n log.info({ eventCount: events.length }, 'Query complete');\n\n return events;\n}\n\n/**\n * Verify attestation envelope integrity\n * Checks that the attestation ID matches the message hash\n */\nexport async function verifyAttestationEnvelope(envelope: AttestationEnvelope): Promise<boolean> {\n try {\n // Re-compute attestation ID from message\n const encoder = new TextEncoder();\n const data = encoder.encode(envelope.message);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const computedId = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n\n return computedId === envelope.attestation_id;\n } catch (err) {\n log.error({ error: err }, 'Failed to verify attestation envelope');\n return false;\n }\n}\n\n/**\n * Parse attestation envelope from Nostr event content\n */\nexport function parseAttestationFromEvent(event: NostrEvent): AttestationEnvelope | null {\n try {\n const envelope = JSON.parse(event.content) as AttestationEnvelope;\n return envelope;\n } catch (err) {\n log.error({ eventId: event.id, error: err }, 'Failed to parse attestation from event');\n return null;\n }\n}\n","/**\n * Nostr Cryptographic Functions\n * Implements NIP-01 event ID computation and signature verification\n */\n\nimport type { NostrEvent } from './types';\n\nimport { createLogger } from './utils/logger';\n\ntype Nip07Window = {\n nostr?: {\n getPublicKey: () => Promise<string>;\n signEvent: (event: Omit<NostrEvent, 'id' | 'sig'>) => Promise<NostrEvent>;\n _metadata?: { name?: string; version?: string };\n };\n};\n\nconst log = createLogger('ocp/nostr-crypto');\n\n/**\n * Compute Nostr event ID according to NIP-01\n * Event ID is the SHA-256 hash of the serialized event\n * Serialization: [0, pubkey, created_at, kind, tags, content]\n */\nexport async function computeNostrEventId(event: Omit<NostrEvent, 'id' | 'sig'>): Promise<string> {\n // Serialize event according to NIP-01\n const serialized = JSON.stringify([\n 0, // Reserved for future use\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n\n log.debug({ serialized }, 'Computing event ID');\n\n // Compute SHA-256 hash\n const encoder = new TextEncoder();\n const data = encoder.encode(serialized);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n // Convert to lowercase hex\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n\n log.debug({ eventId: hashHex }, 'Computed event ID');\n\n return hashHex;\n}\n\n/**\n * Verify Nostr event ID\n * Recomputes the ID and checks if it matches\n */\nexport async function verifyNostrEventId(event: NostrEvent): Promise<boolean> {\n const computedId = await computeNostrEventId(event);\n return computedId === event.id;\n}\n\n/**\n * Check if NIP-07 extension is available\n * NIP-07 provides window.nostr for signing events\n */\nexport function isNip07Available(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return !!(window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n}\n\n/**\n * Get Nostr public key from NIP-07 extension\n * Returns null if extension not available or user denies\n */\nexport async function getNostrPublicKey(): Promise<string | null> {\n if (!isNip07Available()) {\n log.warn('NIP-07 extension not available');\n return null;\n }\n\n try {\n const nostr = (window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n const pubkey = await nostr.getPublicKey();\n log.info({ pubkey }, 'Got Nostr public key from NIP-07');\n return pubkey;\n } catch (err) {\n log.error({ error: err }, 'Failed to get Nostr public key');\n return null;\n }\n}\n\n/**\n * Sign Nostr event using NIP-07 extension\n * Returns signed event with id and sig fields\n */\nexport async function signNostrEvent(\n event: Omit<NostrEvent, 'id' | 'sig'>\n): Promise<NostrEvent | null> {\n if (!isNip07Available()) {\n log.warn('NIP-07 extension not available');\n return null;\n }\n\n try {\n const nostr = (window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n\n // NIP-07 signEvent expects the event without id and sig\n const signedEvent = await nostr.signEvent(event);\n\n log.info({ eventId: signedEvent.id }, 'Signed Nostr event with NIP-07');\n\n return signedEvent as NostrEvent;\n } catch (err) {\n log.error({ error: err }, 'Failed to sign Nostr event');\n return null;\n }\n}\n\n// Previously this file exported `generateEphemeralKeypair()` and\n// `signEventWithEphemeralKey()` for demo purposes. Both produced non-schnorr\n// values that Nostr relays would silently reject — creating the false\n// impression that publishing had succeeded. They have been removed. All Nostr\n// signing now flows through `signNostrEvent()` / `window.nostr` (NIP-07).\n\n/**\n * Validate Nostr event structure\n */\nexport function validateNostrEvent(event: unknown): event is NostrEvent {\n if (typeof event !== 'object' || event === null) return false;\n const e = event as Record<string, unknown>;\n\n if (typeof e.id !== 'string' || (e.id as string).length !== 64) return false;\n if (typeof e.pubkey !== 'string' || (e.pubkey as string).length !== 64) return false;\n if (typeof e.created_at !== 'number') return false;\n if (typeof e.kind !== 'number') return false;\n if (!Array.isArray(e.tags)) return false;\n if (typeof e.content !== 'string') return false;\n if (typeof e.sig !== 'string' || (e.sig as string).length !== 128) return false;\n\n return true;\n}\n\n/**\n * Get NIP-07 extension info\n */\nexport function getNip07Info(): {\n available: boolean;\n name?: string;\n version?: string;\n} {\n if (!isNip07Available()) {\n return { available: false };\n }\n\n const nostr = (window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n\n return {\n available: true,\n name: nostr._metadata?.name,\n version: nostr._metadata?.version,\n };\n}\n","/**\n * Attestation Manager\n *\n * High-level API for creating, publishing, and discovering OrangeCheck attestations\n */\n\nimport type { AttestationEnvelope, IdentityBinding, NostrEvent, Scheme } from './types';\n\nimport { createAttestationEnvelope } from './canonical';\nimport {\n createAttestationEvent,\n DEFAULT_RELAYS,\n parseAttestationFromEvent,\n publishToRelays,\n queryByAddress,\n queryByAttestationId,\n queryByIdentity,\n verifyAttestationEnvelope,\n} from './nostr';\nimport { isNip07Available, signNostrEvent } from './nostr-crypto';\nimport { createLogger } from './utils/logger';\n\nconst log = createLogger('ocp/attestation');\n\n/**\n * Options for creating an attestation\n */\nexport interface CreateAttestationOptions {\n /** Canonical message */\n message: string;\n /** BIP-322 or legacy signature */\n signature: string;\n /** Signature scheme used */\n scheme: Scheme;\n /** Bitcoin address */\n address: string;\n /** Optional identity bindings */\n identities?: IdentityBinding[];\n /** Optional extension key-value pairs */\n extensions?: Record<string, string | undefined>;\n}\n\n/**\n * Options for publishing an attestation to Nostr\n */\nexport interface PublishAttestationOptions {\n /** Attestation envelope to publish */\n envelope: AttestationEnvelope;\n /** Nostr public key (npub or hex) for signing the event */\n npub: string;\n /** Optional relay URLs (defaults to DEFAULT_RELAYS) */\n relays?: string[];\n}\n\n/**\n * Options for discovering attestations\n */\nexport interface DiscoverAttestationOptions {\n /** Search by attestation ID */\n attestationId?: string;\n /** Search by Bitcoin address */\n address?: string;\n /** Search by identity binding */\n identity?: { protocol: string; identifier: string };\n /** Optional relay URLs to query */\n relays?: string[];\n}\n\n/**\n * Result of publishing an attestation\n */\nexport interface PublishResult {\n /** Relays that successfully received the event */\n success: string[];\n /** Relays that failed to receive the event */\n failed: string[];\n}\n\n/**\n * Custom error for attestation operations\n */\nexport class AttestationError extends Error {\n constructor(\n message: string,\n public readonly code?: string\n ) {\n super(message);\n this.name = 'AttestationError';\n }\n}\n\n/**\n * Create an attestation envelope from a signed message\n *\n * @param options - Attestation creation options\n * @returns Attestation envelope ready for publishing\n * @throws {AttestationError} If envelope integrity check fails\n *\n * @example\n * ```typescript\n * const envelope = await createAttestation({\n * message: canonicalMessage,\n * signature: 'AkcwRAIg...',\n * scheme: 'bip322',\n * address: 'bc1q...',\n * identities: [{ protocol: 'nostr', identifier: 'npub1...' }],\n * });\n * ```\n */\nexport async function createAttestation(\n options: CreateAttestationOptions\n): Promise<AttestationEnvelope> {\n const { message, signature, scheme, address, identities = [], extensions = {} } = options;\n\n log.info({ address, identityCount: identities.length }, 'Creating attestation');\n\n const envelope = await createAttestationEnvelope(\n message,\n signature,\n scheme,\n address,\n identities,\n extensions\n );\n\n // Verify envelope integrity\n const isValid = await verifyAttestationEnvelope(envelope);\n if (!isValid) {\n throw new AttestationError(\n 'Attestation envelope integrity check failed',\n 'INTEGRITY_CHECK_FAILED'\n );\n }\n\n log.info({ attestationId: envelope.attestation_id }, 'Attestation created successfully');\n\n return envelope;\n}\n\n/**\n * Publish an attestation to Nostr relays\n *\n * Uses NIP-07 if available, falls back to ephemeral key for demo\n *\n * @param options - Publishing options\n * @returns Object with successful and failed relay URLs\n * @throws {AttestationError} If signing fails\n *\n * @example\n * ```typescript\n * const result = await publishAttestation({\n * envelope,\n * npub: 'npub1...',\n * relays: ['wss://relay.damus.io'],\n * });\n * console.log('Published to:', result.success);\n * ```\n */\nexport async function publishAttestation(\n options: PublishAttestationOptions\n): Promise<PublishResult> {\n const { envelope, npub, relays = DEFAULT_RELAYS } = options;\n\n log.info(\n { attestationId: envelope.attestation_id, relayCount: relays.length },\n 'Publishing attestation'\n );\n\n // Create unsigned event\n const unsignedEvent = createAttestationEvent(envelope, npub);\n\n // Nostr publishing requires a valid schnorr signature. Only NIP-07\n // (window.nostr) is supported. If no signer is present we refuse to\n // publish rather than emit an invalid-sig event that every relay will\n // silently reject — which would make the caller think it had succeeded.\n if (!isNip07Available()) {\n log.warn('NIP-07 unavailable — skipping Nostr publish');\n throw new Error(\n 'nostr_signer_unavailable: install a NIP-07 extension (e.g. nos2x, Alby) to publish'\n );\n }\n\n log.info('Using NIP-07 to sign event');\n const signedEvent = await signNostrEvent(unsignedEvent);\n if (!signedEvent) {\n throw new Error('nostr_signing_failed: NIP-07 extension rejected or errored');\n }\n\n const result = await publishToRelays(signedEvent, relays);\n\n log.info(\n {\n attestationId: envelope.attestation_id,\n successCount: result.success.length,\n failedCount: result.failed.length,\n },\n 'Publishing complete'\n );\n\n return result;\n}\n\n/**\n * Discover attestations from Nostr relays\n */\nexport async function discoverAttestations(\n options: DiscoverAttestationOptions\n): Promise<AttestationEnvelope[]> {\n const { attestationId, address, identity, relays = DEFAULT_RELAYS } = options;\n\n let events: NostrEvent[] = [];\n\n if (attestationId) {\n log.info({ attestationId }, 'Discovering by attestation ID');\n events = await queryByAttestationId(attestationId, relays);\n } else if (address) {\n log.info({ address }, 'Discovering by Bitcoin address');\n events = await queryByAddress(address, relays);\n } else if (identity) {\n log.info({ identity }, 'Discovering by identity');\n events = await queryByIdentity(identity.protocol, identity.identifier, relays);\n } else {\n throw new Error('Must provide attestationId, address, or identity');\n }\n\n // Parse and verify envelopes\n const envelopes: AttestationEnvelope[] = [];\n for (const event of events) {\n const envelope = parseAttestationFromEvent(event);\n if (envelope) {\n // Verify envelope integrity\n const isValid = await verifyAttestationEnvelope(envelope);\n if (isValid) {\n envelopes.push(envelope);\n } else {\n log.warn(\n { attestationId: envelope.attestation_id },\n 'Skipping invalid attestation envelope'\n );\n }\n }\n }\n\n log.info({ eventCount: events.length, validCount: envelopes.length }, 'Discovery complete');\n\n return envelopes;\n}\n\n/**\n * Verify an attestation by fetching it from Nostr and checking integrity\n */\nexport async function verifyAttestationById(\n attestationId: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<AttestationEnvelope | null> {\n log.info({ attestationId }, 'Verifying attestation by ID');\n\n const envelopes = await discoverAttestations({ attestationId, relays });\n\n if (envelopes.length === 0) {\n log.warn({ attestationId }, 'Attestation not found on any relay');\n return null;\n }\n\n if (envelopes.length > 1) {\n log.warn(\n { attestationId, count: envelopes.length },\n 'Multiple attestations found with same ID - using first'\n );\n }\n\n return envelopes[0] || null;\n}\n\n/**\n * Get all attestations for a Bitcoin address\n */\nexport async function getAttestationsForAddress(\n address: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<AttestationEnvelope[]> {\n log.info({ address }, 'Getting all attestations for address');\n return discoverAttestations({ address, relays });\n}\n\n/**\n * Get all attestations for an identity\n */\nexport async function getAttestationsForIdentity(\n protocol: string,\n identifier: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<AttestationEnvelope[]> {\n log.info({ protocol, identifier }, 'Getting all attestations for identity');\n return discoverAttestations({ identity: { protocol, identifier }, relays });\n}\n\n/**\n * Format identities for display as a comma-separated `protocol:identifier` list.\n * Same wire format the canonical message uses.\n */\nexport function formatIdentitiesForDisplay(identities: IdentityBinding[]): string {\n return identities.map((id) => `${id.protocol}:${id.identifier}`).join(', ');\n}\n\n/**\n * Build the canonical shareable URL for an attestation. Matches the live\n * `/attest/[id]` route on attest.ochk.io. Pass a different `baseUrl` for forks /\n * self-hosted verifiers.\n */\nexport function getVerificationUrl(\n attestationId: string,\n baseUrl = 'https://attest.ochk.io'\n): string {\n return `${baseUrl}/attest/${attestationId}`;\n}\n\n/**\n * Reverse of `getVerificationUrl` — pull an attestation id back out of a\n * `/attest/<id>` or legacy `/verify?id=<id>` URL. Returns `null` if the URL\n * shape doesn't match.\n */\nexport function extractAttestationIdFromUrl(url: string): string | null {\n try {\n const u = new URL(url);\n // New canonical form: /attest/<id>\n const m = u.pathname.match(/^\\/attest\\/([0-9a-f]{64})\\/?$/i);\n if (m) return m[1]!.toLowerCase();\n // Legacy form: /verify?id=<id>\n const q = u.searchParams.get('id');\n if (q && /^[0-9a-f]{64}$/i.test(q)) return q.toLowerCase();\n return null;\n } catch {\n return null;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/canonical.ts","../src/nostr-pubkey.ts","../src/utils/logger.ts","../src/nostr.ts","../src/nostr-crypto.ts","../src/attestation.ts"],"names":["log"],"mappings":";;;AA8BA,SAAS,WAAW,KAAA,EAA2B;AAC3C,EAAA,OAAO,MAAM,IAAA,CAAK,KAAK,CAAA,CAClB,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAC1C,KAAK,EAAE,CAAA;AAChB;AAmLA,eAAsB,sBAAsB,OAAA,EAAkC;AAE1E,EAAA,MAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAChC,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,MAAA,CAAO,OAAO,CAAA;AAGnC,EAAA,MAAM,aAAa,MAAM,MAA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AC,CAAA,EAAG,OAAO,EAAE,WAAA,EAAY;AACzD,IAAA,OAAO,IAAA;AAAA,EACX,CAAA,CAAA,MAAQ;AACJ,IAAA,OAAO,IAAA;AAAA,EACX;AACJ","file":"attestation.mjs","sourcesContent":["/**\n * Canonical message builder per SPEC.md §2\n *\n * - LF line endings, exactly one trailing LF\n * - 7 fixed core lines in strict order and wording\n * - Optional extensions appended as key: value with lexicographically sorted lowercase keys\n */\n\nimport type { AttestationEnvelope, IdentityBinding, Scheme } from './types';\n\n/**\n * Input for building a canonical message\n */\nexport interface CanonicalInput {\n /** Bitcoin address */\n address: string;\n /** Optional identity bindings */\n identities?: IdentityBinding[];\n}\n\n/**\n * Extension key-value pairs for canonical message\n */\nexport type Extensions = Record<string, string | undefined>;\n\n/**\n * Convert bytes to lowercase hex string\n * @param bytes - Byte array to convert\n * @returns Lowercase hex string\n */\nfunction toLowerHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Generate a random 16-byte nonce as lowercase hex\n * Uses Web Crypto API when available, falls back to Math.random()\n * @returns 32-character lowercase hex string\n */\nexport function randomNonce16BHexLower(): string {\n const arr = new Uint8Array(16);\n\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(arr);\n return toLowerHex(arr);\n }\n } catch {\n // Fall through to non-cryptographic fallback\n }\n\n // No silent Math.random fallback: a nonce is a load-bearing security\n // primitive. A deployment without `crypto.getRandomValues` MUST fix its\n // environment rather than sign with weak randomness.\n throw new Error('crypto.getRandomValues unavailable — refusing to mint a weak nonce');\n}\n\n/**\n * Reject characters that would break the line-oriented canonical grammar\n * or the comma-separated identities list. If any of these slipped through,\n * an attacker could smuggle a forged `address:` or extension line into the\n * signed payload: `identities: alice\\naddress: bc1qEVIL…` would parse as a\n * second address line. Catch it at the boundary, not at verification time.\n *\n * Also rejects a colon in the identifier so a bad actor can't turn\n * `github:alice:extra` into a different protocol binding on parse.\n */\nconst IDENTITY_PROTOCOL_RE = /^[a-z][a-z0-9_-]*$/;\nconst IDENTITY_FORBIDDEN_CHARS = /[\\r\\n,]/;\n\nfunction assertSafeIdentity({ protocol, identifier }: IdentityBinding): void {\n if (!IDENTITY_PROTOCOL_RE.test(protocol)) {\n throw new Error(\n `invalid identity protocol: ${JSON.stringify(protocol)} — must match /^[a-z][a-z0-9_-]*$/`\n );\n }\n if (!identifier || IDENTITY_FORBIDDEN_CHARS.test(identifier)) {\n throw new Error(\n `invalid identity identifier: ${JSON.stringify(identifier)} — must be non-empty and contain no newlines or commas`\n );\n }\n}\n\n/**\n * Format identities as comma-separated protocol:identifier pairs, sorted lexicographically\n * @param identities - Array of identity bindings\n * @returns Comma-separated string of protocol:identifier pairs\n */\nexport function formatIdentities(identities: IdentityBinding[] = []): string {\n if (identities.length === 0) {\n return '';\n }\n for (const id of identities) assertSafeIdentity(id);\n\n // Format as protocol:identifier and sort lexicographically\n const formatted = identities\n .map(({ protocol, identifier }) => `${protocol}:${identifier}`)\n .sort();\n\n return formatted.join(',');\n}\n\n/**\n * Parse identities from comma-separated protocol:identifier format\n * @param identitiesStr - Comma-separated identity string\n * @returns Array of identity bindings\n * @throws {Error} If identity format is invalid\n */\nexport function parseIdentities(identitiesStr: string): IdentityBinding[] {\n if (!identitiesStr || identitiesStr.trim() === '') {\n return [];\n }\n // The identities field lives on one line of the canonical message. If it\n // contains a raw LF/CR, it's either corrupt or an attempt to smuggle a\n // fake core line into the parser. Refuse instead of trying to recover.\n if (IDENTITY_FORBIDDEN_CHARS.test(identitiesStr.replace(/,/g, ''))) {\n throw new Error('identities field contains forbidden characters (newline)');\n }\n\n const bindings = identitiesStr.split(',').map((binding) => {\n const colonIndex = binding.indexOf(':');\n if (colonIndex === -1) {\n throw new Error(`Invalid identity binding format: ${binding}`);\n }\n return {\n protocol: binding.substring(0, colonIndex).trim(),\n identifier: binding.substring(colonIndex + 1).trim(),\n };\n });\n\n for (const b of bindings) {\n if (!b.protocol || !b.identifier) {\n throw new Error(`Invalid identity binding: ${b.protocol}:${b.identifier}`);\n }\n assertSafeIdentity(b);\n }\n return bindings;\n}\n\n/**\n * Optional deterministic overrides for message building. Only intended for\n * tests / conformance vectors; production callers should let the builder\n * mint a fresh nonce + timestamp per message.\n */\nexport interface BuildOptions {\n /** 32-char lowercase hex. Default: freshly-generated cryptographic nonce. */\n nonce?: string;\n /** RFC-3339 UTC. Default: `new Date().toISOString()`. */\n issuedAt?: string;\n}\n\n/**\n * Build a canonical message following OrangeCheck Protocol v0 specification\n * @param input - Canonical input with address and identities\n * @param extensions - Optional extension key-value pairs\n * @param options - Optional deterministic overrides (testing only)\n * @returns Canonical message string with LF line endings\n */\nexport function buildCanonicalMessage(\n { address, identities }: CanonicalInput,\n extensions: Extensions = {},\n options: BuildOptions = {}\n): string {\n const nonce = options.nonce ?? randomNonce16BHexLower();\n if (!/^[0-9a-f]{32}$/.test(nonce)) {\n throw new Error(`invalid nonce: must be 32 lowercase hex chars`);\n }\n const issuedAt = options.issuedAt ?? new Date().toISOString();\n\n // Format identities\n const identitiesStr = formatIdentities(identities);\n\n // Core (strict wording + order per SPEC.md §2)\n const core = [\n 'orangecheck',\n `identities: ${identitiesStr}`,\n `address: ${address}`,\n 'purpose: portable reputation attestation (non-custodial)',\n `nonce: ${nonce}`,\n `issued_at: ${issuedAt}`,\n 'ack: I attest control of this address and bind it to my identities.',\n ];\n\n // Normalize and sort extensions\n const normExt: Record<string, string> = {};\n for (const [k, v] of Object.entries(extensions)) {\n if (v == null || v === '') {\n continue;\n }\n const key = k.toLowerCase();\n normExt[key] = String(v);\n }\n\n const extLines = Object.keys(normExt)\n .sort()\n .map((k) => `${k}: ${normExt[k]!}`);\n\n const all = [...core, ...extLines];\n\n // Join with LF and ensure exactly one trailing LF\n return all.join('\\n') + '\\n';\n}\n\n/**\n * Generate attestation ID from canonical message\n *\n * attestation_id = SHA-256(canonical_message)\n *\n * @param message - Canonical message string\n * @returns Lowercase hex SHA-256 hash\n */\nexport async function generateAttestationId(message: string): Promise<string> {\n // Convert message to UTF-8 bytes\n const encoder = new TextEncoder();\n const data = encoder.encode(message);\n\n // Compute SHA-256 hash\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n // Convert to lowercase hex\n return toLowerHex(new Uint8Array(hashBuffer));\n}\n\n/**\n * Create an attestation envelope for publishing\n *\n * This wraps the canonical message with metadata for Nostr publishing\n *\n * @param message - Canonical message\n * @param signature - BIP-322 or legacy signature\n * @param scheme - Signature scheme used\n * @param address - Bitcoin address\n * @param identities - Identity bindings\n * @param extensions - Optional extensions\n * @returns Attestation envelope ready for publishing\n */\nexport async function createAttestationEnvelope(\n message: string,\n signature: string,\n scheme: Scheme,\n address: string,\n identities: IdentityBinding[],\n extensions: Extensions = {}\n): Promise<AttestationEnvelope> {\n const attestation_id = await generateAttestationId(message);\n\n // Extract issued_at from message\n const issuedAtMatch = message.match(/issued_at: ([^\\n]+)/);\n const issued_at = issuedAtMatch?.[1] ?? new Date().toISOString();\n\n // Extract expires from extensions if present\n const expires_at = extensions.expires;\n\n // Extract relay hints from extensions if present\n const relay_hints = extensions.relay_hints?.split(',').map((r) => r.trim());\n\n // Extract publish targets from extensions if present\n const publish_targets = extensions.publish?.split(',').map((t) => t.trim());\n\n // Base64url encode the message\n const encoder = new TextEncoder();\n const messageBytes = encoder.encode(message);\n const base64 = btoa(String.fromCharCode(...messageBytes));\n const message_b64url = base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n\n // Construct verification URL\n const verification_url = `https://attest.ochk.io/attest/${attestation_id}`;\n\n return {\n attestation_id,\n scheme,\n address,\n identities,\n message,\n message_b64url,\n signature,\n issued_at,\n expires_at,\n verification_url,\n publish_targets,\n relay_hints,\n };\n}\n","import { bech32 } from '@scure/base';\n\nconst HEX_64_RE = /^[0-9a-f]{64}$/;\n\nfunction toHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\n/** A Nostr public key as lowercase hex, from either `npub1…` or hex. Null if it is neither. */\nexport function nostrPubkeyToHex(value: string): string | null {\n const trimmed = value.trim().toLowerCase();\n if (HEX_64_RE.test(trimmed)) return trimmed;\n if (!trimmed.startsWith('npub1')) return null;\n try {\n const decoded = bech32.decode(trimmed as `${string}1${string}`, 1023);\n if (decoded.prefix !== 'npub') return null;\n const bytes = bech32.fromWords(decoded.words);\n return bytes.length === 32 ? toHex(Uint8Array.from(bytes)) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Every spelling of one Nostr key an attestation may carry in its `i` tag.\n * SPEC §2 prescribes `npub1…`; the reference site also accepts hex.\n */\nexport function nostrIdentifierForms(identifier: string): string[] {\n const hex = nostrPubkeyToHex(identifier);\n if (!hex) return [identifier];\n const bytes = Uint8Array.from(hex.match(/../g)!.map((b) => parseInt(b, 16)));\n return [bech32.encode('npub', bech32.toWords(bytes), 1023), hex];\n}\n","/**\n * Simple logger for SDK\n * Can be disabled in production builds\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\n/**\n * Logger context type\n */\nexport type LogContext = Record<string, unknown>;\n\n/**\n * Logger interface\n */\nexport interface Logger {\n debug: (contextOrMessage: string | LogContext, message?: string) => void;\n info: (contextOrMessage: string | LogContext, message?: string) => void;\n warn: (contextOrMessage: string | LogContext, message?: string) => void;\n error: (contextOrMessage: string | LogContext, message?: string) => void;\n}\n\nlet logLevel: LogLevel = 'none';\n\n/**\n * Set the global log level\n * @param level - Log level to set\n */\nexport function setLogLevel(level: LogLevel): void {\n logLevel = level;\n}\n\n/**\n * Get the current log level\n * @returns Current log level\n */\nexport function getLogLevel(): LogLevel {\n return logLevel;\n}\n\n/**\n * Create a namespaced logger\n * @param namespace - Logger namespace\n * @returns Logger instance\n */\nexport function createLogger(namespace: string): Logger {\n const shouldLog = (level: Exclude<LogLevel, 'none'>): boolean => {\n if (logLevel === 'none') return false;\n\n const levels: Exclude<LogLevel, 'none'>[] = ['debug', 'info', 'warn', 'error'];\n const currentLevelIndex = levels.indexOf(logLevel as Exclude<LogLevel, 'none'>);\n const messageLevelIndex = levels.indexOf(level);\n\n return messageLevelIndex >= currentLevelIndex;\n };\n\n const formatMessage = (msg: string): string => `[${namespace}] ${msg}`;\n\n return {\n debug: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('debug')) {\n if (typeof contextOrMessage === 'string') {\n console.debug(formatMessage(contextOrMessage));\n } else {\n console.debug(formatMessage(message ?? 'Debug'), contextOrMessage);\n }\n }\n },\n info: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('info')) {\n if (typeof contextOrMessage === 'string') {\n console.info(formatMessage(contextOrMessage));\n } else {\n console.info(formatMessage(message ?? 'Info'), contextOrMessage);\n }\n }\n },\n warn: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('warn')) {\n if (typeof contextOrMessage === 'string') {\n console.warn(formatMessage(contextOrMessage));\n } else {\n console.warn(formatMessage(message ?? 'Warning'), contextOrMessage);\n }\n }\n },\n error: (contextOrMessage: string | LogContext, message?: string): void => {\n if (shouldLog('error')) {\n if (typeof contextOrMessage === 'string') {\n console.error(formatMessage(contextOrMessage));\n } else {\n console.error(formatMessage(message ?? 'Error'), contextOrMessage);\n }\n }\n },\n };\n}\n\n/**\n * Log verification error\n * @param protocol - Identity protocol\n * @param identifier - Identity identifier\n * @param error - Error object\n * @param context - Additional context\n */\nexport function logVerificationError(\n protocol: string,\n identifier: string,\n error: Error,\n context?: LogContext\n): void {\n const logger = createLogger('identity-verification');\n logger.error(\n {\n protocol,\n identifier,\n error: error.message,\n stack: error.stack,\n ...context,\n },\n 'Verification failed'\n );\n}\n","/**\n * Nostr Integration for OrangeCheck Protocol\n *\n * Implements NIP-78 (Application-specific data) for attestation publishing\n */\n\nimport type { AttestationEnvelope, IdentityBinding, NostrEvent } from './types';\n\nimport { nostrIdentifierForms } from './nostr-pubkey';\nimport { createLogger } from './utils/logger';\n\nconst log = createLogger('ocp/nostr');\n\n/**\n * NIP-78 event kind for OrangeCheck attestations\n */\nexport const ATTESTATION_EVENT_KIND = 30078;\n\n/**\n * Default Nostr relays for OrangeCheck attestation publishing and lookup.\n *\n * Well-known relays with good uptime, plus the first-party family relay.\n * `relay.ochk.io` was missing here while attest.ochk.io's verifier has always\n * read from it, so the SDK and the reference implementation were looking in\n * different places — the SDK could miss a family attestation that the hosted\n * API found. It runs a kind allowlist (30078-30087, 30110-30114) and canonical OC d-tag\n * prefixes, and is always co-published alongside the public relays, never the\n * only copy. See https://github.com/orangecheck/oc-relay-infra.\n *\n * Order matters only for readability; queries fan out to all of them and\n * merge. Pass your own `relays` to any query to override this entirely — the\n * protocol does not require trusting any particular relay.\n *\n * A NOTE ON `relay.damus.io`, deliberately kept. It is reachable from a browser\n * (measured ~391ms, real events returned) and NOT reachable from at least one\n * serverless runtime — Vercel's, where it fails to connect on every attempt,\n * consistently, over hours. Its NIP-11 declares no `auth_required`,\n * `payment_required` or `restricted_writes`, so this reads as datacenter-IP\n * filtering in front of it rather than policy, and it can change in either\n * direction without notice.\n *\n * It stays for three reasons: it is one of the most widely read relays, so an\n * attestation published there is findable by the most people; the browser is\n * the dominant path for this SDK (wallet signing happens there), and it works\n * there; and since FANOUT_DEADLINE_MS below is a SHARED budget, a relay that\n * fails to connect resolves immediately and costs no latency. Removing a relay\n * that works for most callers, to tidy a status field on one runtime, is the\n * wrong trade.\n *\n * If you run this SDK server-side and want certainty about coverage, pass\n * `relays` explicitly. Silent partial coverage — believing you reached four\n * relays when you reached three — is the real hazard here, not latency.\n */\nexport const DEFAULT_RELAYS: string[] = [\n 'wss://relay.damus.io',\n 'wss://nos.lol',\n 'wss://relay.snort.social',\n 'wss://relay.ochk.io',\n];\n\n/**\n * Wall-clock budget for a whole relay fan-out, shared by every relay in it.\n *\n * Queries below use Promise.allSettled, so a fan-out used to take as long as\n * its SLOWEST relay — and with a dead relay in DEFAULT_RELAYS that meant the\n * per-relay 10s timeout, every single call. Measured on 1.4.0:\n *\n * check({ addr }) with the old defaults 10.4s\n * check({ addr }) with the dead relay out 1.0s\n *\n * That is not merely slow, it broke a dependent outright: @orangecheck/gate\n * races check() against a 5s lookupTimeoutMs, so a 10.4s lookup lost the race\n * every time and no address-based gate decision could ever succeed.\n *\n * A shared deadline fixes the class: whichever relay is dead or slow next, a\n * fan-out costs at most this. Healthy relays answer well inside it (~1s for a\n * cold WebSocket plus a query). QUERY_TIMEOUT_MS remains the per-relay ceiling.\n *\n * The value is deliberately BELOW @orangecheck/gate's 5s default\n * lookupTimeoutMs, so a gate decision can still resolve in the worst case\n * rather than always losing its own race. Raising this above 5000 silently\n * breaks that dependent — change both together, or don't.\n */\nexport const FANOUT_DEADLINE_MS = 4000;\nconst QUERY_TIMEOUT_MS = 10000;\n\n/** Remaining budget for a relay, given the fan-out's shared deadline. */\nfunction budgetFor(deadlineAt: number): number {\n return Math.max(0, Math.min(QUERY_TIMEOUT_MS, deadlineAt - Date.now()));\n}\n\n/**\n * Create a NIP-78 event for an OrangeCheck attestation\n *\n * Kind: 30078 (Parameterized Replaceable Event)\n * d-tag: attestation_id (makes it replaceable by attestation ID)\n *\n * @param envelope - Attestation envelope\n * @param pubkey - Nostr public key (hex format)\n * @returns Unsigned Nostr event\n */\nexport function createAttestationEvent(\n envelope: AttestationEnvelope,\n pubkey: string\n): Omit<NostrEvent, 'id' | 'sig'> {\n // NIP-12 relays index SINGLE-LETTER tags only. A multi-letter tag like\n // `address` is stored verbatim and stays readable in the event, but it is\n // never indexed, so no `#address` filter can ever retrieve it. Without the\n // `t` tags below an attestation published by this SDK is invisible to\n // every by-address query on every relay — including attest.ochk.io's own\n // verifier, which queries `#t`. Keep both: `t` is what makes it findable,\n // `address` is human-readable diagnostics and is not load-bearing.\n const tags: string[][] = [\n ['d', envelope.attestation_id], // Parameterized replaceable event identifier (indexed)\n ['t', envelope.address], // Indexed btc-address tag — query with `#t`\n ['t', 'oc-attest'], // Family marker — `#t=[\"oc-attest\"]` for cross-cut discovery\n ['address', envelope.address], // Diagnostic / legacy — relay won't index this\n ['scheme', envelope.scheme], // Signature scheme (bip322 or legacy)\n ['issued_at', envelope.issued_at], // ISO timestamp\n ];\n\n // Add identity tags\n for (const identity of envelope.identities) {\n tags.push(['i', `${identity.protocol}:${identity.identifier}`]);\n }\n\n // Add expiration if present\n if (envelope.expires_at) {\n tags.push(['expires', envelope.expires_at]);\n }\n\n // Add relay hints if present\n if (envelope.relay_hints?.length) {\n for (const relay of envelope.relay_hints) {\n tags.push(['relay', relay]);\n }\n }\n\n // Content is the full attestation envelope as JSON\n const content = JSON.stringify(envelope, null, 2);\n\n return {\n kind: ATTESTATION_EVENT_KIND,\n tags,\n content,\n created_at: Math.floor(Date.parse(envelope.issued_at) / 1000),\n pubkey,\n };\n}\n\n/**\n * Parse identity bindings from Nostr event tags\n *\n * @param event - Nostr event\n * @returns Array of identity bindings\n */\nexport function parseIdentitiesFromEvent(event: NostrEvent): IdentityBinding[] {\n const identities: IdentityBinding[] = [];\n\n for (const tag of event.tags) {\n if (tag[0] === 'i' && tag[1]) {\n const colonIndex = tag[1].indexOf(':');\n if (colonIndex !== -1) {\n identities.push({\n protocol: tag[1].substring(0, colonIndex),\n identifier: tag[1].substring(colonIndex + 1),\n });\n }\n }\n }\n\n return identities;\n}\n\n/**\n * Extract attestation ID from Nostr event d-tag\n *\n * @param event - Nostr event\n * @returns Attestation ID or undefined if not found\n */\nexport function getAttestationIdFromEvent(event: NostrEvent): string | undefined {\n const dTag = event.tags.find((tag) => tag[0] === 'd');\n return dTag?.[1];\n}\n\n/**\n * Extract Bitcoin address from Nostr event tags\n *\n * @param event - Nostr event\n * @returns Bitcoin address or undefined if not found\n */\nexport function getAddressFromEvent(event: NostrEvent): string | undefined {\n const addressTag = event.tags.find((tag) => tag[0] === 'address');\n return addressTag?.[1];\n}\n\n/**\n * Publish a Nostr event to multiple relays\n * Returns array of relay URLs that successfully accepted the event\n */\nexport async function publishToRelays(\n event: NostrEvent,\n relays: string[] = DEFAULT_RELAYS\n): Promise<{ success: string[]; failed: string[] }> {\n const success: string[] = [];\n const failed: string[] = [];\n\n log.info({ eventId: event.id, relayCount: relays.length }, 'Publishing event to relays');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const publishPromises = relays.map(async (relayUrl) => {\n let ws: WebSocket | null = null;\n\n // One outcome per relay, first one wins. Without this a relay that\n // ACKs `OK true` and then emits an error or close event during\n // teardown lands in BOTH arrays, and the caller reports \"published\n // to 3 · rejected 3\" over the same three relays. The `failed.includes`\n // check this replaces only ever de-duplicated `failed` against\n // itself, so it could not catch a success/failure split.\n // attest.ochk.io's copy of this file has carried the guard for a\n // while; this is the back-port.\n let settled = false;\n const recordSuccess = (): void => {\n if (settled) return;\n settled = true;\n success.push(relayUrl);\n };\n const recordFailure = (): void => {\n if (settled) return;\n settled = true;\n failed.push(relayUrl);\n };\n\n try {\n // Connect to relay\n ws = new WebSocket(relayUrl);\n const wsRef = ws; // Capture for closures\n\n await new Promise<void>((resolve, reject) => {\n // One outer deadline covers connect + OK round-trip. The old\n // code cleared this on `onopen`, which meant a relay that\n // opened but never sent OK would hang the promise forever.\n const deadline = setTimeout(() => {\n wsRef.close();\n reject(new Error('Relay publish timeout'));\n }, budgetFor(deadlineAt));\n\n const cleanup = () => {\n clearTimeout(deadline);\n wsRef.close();\n };\n\n wsRef.onopen = () => {\n // Do NOT clear the deadline — we still need it in case\n // the relay never responds with OK.\n wsRef.send(JSON.stringify(['EVENT', event]));\n };\n\n wsRef.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n // Check for OK response\n if (data[0] === 'OK' && data[1] === event.id) {\n if (data[2] === true) {\n recordSuccess();\n cleanup();\n resolve();\n } else {\n log.warn(\n { relay: relayUrl, reason: data[3] },\n 'Relay rejected event'\n );\n recordFailure();\n cleanup();\n reject(new Error(data[3] || 'Relay rejected event'));\n }\n }\n } catch (err) {\n log.error(\n { relay: relayUrl, error: err },\n 'Failed to parse relay response'\n );\n recordFailure();\n cleanup();\n reject(err);\n }\n };\n\n wsRef.onerror = (err) => {\n log.error({ relay: relayUrl, error: err }, 'WebSocket error');\n recordFailure();\n cleanup();\n reject(err);\n };\n\n wsRef.onclose = () => {\n // Socket closed before we resolved/rejected — counts as\n // failure. clearTimeout here is safe (cleanup handles both).\n clearTimeout(deadline);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to publish to relay');\n recordFailure();\n } finally {\n // Ensure WebSocket is closed\n if (ws && ws.readyState !== WebSocket.CLOSED) {\n ws.close();\n }\n }\n });\n\n await Promise.allSettled(publishPromises);\n\n log.info({ successCount: success.length, failedCount: failed.length }, 'Publishing complete');\n\n return { success, failed };\n}\n\n/**\n * Query relays for attestations by attestation ID\n */\nexport async function queryByAttestationId(\n attestationId: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<NostrEvent[]> {\n const events: NostrEvent[] = [];\n\n log.info({ attestationId, relayCount: relays.length }, 'Querying relays for attestation');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const queryPromises = relays.map(async (relayUrl) => {\n let ws: WebSocket | null = null;\n\n try {\n ws = new WebSocket(relayUrl);\n const wsRef = ws; // Capture for closures\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n wsRef.close();\n reject(new Error('Query timeout'));\n }, budgetFor(deadlineAt));\n\n const cleanup = () => {\n clearTimeout(timeout);\n wsRef.close();\n };\n\n wsRef.onopen = () => {\n // Send REQ message for kind 30078 with d-tag = attestation_id\n const subscriptionId = `ochk_${Date.now()}`;\n wsRef.send(\n JSON.stringify([\n 'REQ',\n subscriptionId,\n {\n kinds: [30078],\n '#d': [attestationId],\n limit: 1,\n },\n ])\n );\n };\n\n wsRef.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n if (data[0] === 'EVENT') {\n events.push(data[2]);\n } else if (data[0] === 'EOSE') {\n cleanup();\n resolve();\n }\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to parse event');\n }\n };\n\n wsRef.onerror = (err) => {\n log.error({ relay: relayUrl, error: err }, 'WebSocket error during query');\n cleanup();\n reject(err);\n };\n\n wsRef.onclose = () => {\n clearTimeout(timeout);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to query relay');\n } finally {\n // Ensure WebSocket is closed\n if (ws && ws.readyState !== WebSocket.CLOSED) {\n ws.close();\n }\n }\n });\n\n await Promise.allSettled(queryPromises);\n\n log.info({ eventCount: events.length }, 'Query complete');\n\n return events;\n}\n\n/**\n * Query relays for attestations by Bitcoin address\n */\nexport async function queryByAddress(\n address: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<NostrEvent[]> {\n const events: NostrEvent[] = [];\n\n log.info({ address, relayCount: relays.length }, 'Querying relays for address');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const queryPromises = relays.map(async (relayUrl) => {\n try {\n const ws = new WebSocket(relayUrl);\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n ws.close();\n reject(new Error('Query timeout'));\n }, budgetFor(deadlineAt));\n\n ws.onopen = () => {\n const subscriptionId = `ochk_addr_${Date.now()}`;\n ws.send(\n JSON.stringify([\n 'REQ',\n subscriptionId,\n {\n kinds: [30078],\n // `#t`, NOT `#address`: NIP-12 relays index\n // single-letter tags only, so `#address`\n // matched nothing on any relay and this\n // function returned empty for every real\n // attestation. attest.ochk.io's verifier has\n // queried `#t` since the same fix landed\n // there; this is the back-port.\n '#t': [address],\n limit: 50,\n },\n ])\n );\n };\n\n ws.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n if (data[0] === 'EVENT') {\n events.push(data[2]);\n } else if (data[0] === 'EOSE') {\n clearTimeout(timeout);\n ws.close();\n resolve();\n }\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to parse event');\n }\n };\n\n ws.onerror = (err) => {\n clearTimeout(timeout);\n log.error({ relay: relayUrl, error: err }, 'WebSocket error during query');\n reject(err);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to query relay');\n }\n });\n\n await Promise.allSettled(queryPromises);\n\n log.info({ eventCount: events.length }, 'Query complete');\n\n return events;\n}\n\n/**\n * Query relays for attestations by identity (any protocol)\n */\nexport async function queryByIdentity(\n protocol: string,\n identifier: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<NostrEvent[]> {\n const events: NostrEvent[] = [];\n const identityTag = `${protocol}:${identifier}`;\n const identityTags =\n protocol === 'nostr'\n ? nostrIdentifierForms(identifier).map((f) => `nostr:${f}`)\n : [identityTag];\n\n log.info({ protocol, identifier, relayCount: relays.length }, 'Querying relays for identity');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const queryPromises = relays.map(async (relayUrl) => {\n try {\n const ws = new WebSocket(relayUrl);\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n ws.close();\n reject(new Error('Query timeout'));\n }, budgetFor(deadlineAt));\n\n ws.onopen = () => {\n const subscriptionId = `ochk_identity_${Date.now()}`;\n ws.send(\n JSON.stringify([\n 'REQ',\n subscriptionId,\n {\n kinds: [30078],\n '#i': identityTags,\n limit: 10,\n },\n ])\n );\n };\n\n ws.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n if (data[0] === 'EVENT') {\n events.push(data[2]);\n } else if (data[0] === 'EOSE') {\n clearTimeout(timeout);\n ws.close();\n resolve();\n }\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to parse event');\n }\n };\n\n ws.onerror = (err) => {\n clearTimeout(timeout);\n log.error({ relay: relayUrl, error: err }, 'WebSocket error during query');\n reject(err);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to query relay');\n }\n });\n\n await Promise.allSettled(queryPromises);\n\n log.info({ eventCount: events.length }, 'Query complete');\n\n return events;\n}\n\n/**\n * Query relays for the most recent attestations across every publisher.\n *\n * For aggregate views (network stats, a recent-activity feed), not per-subject\n * lookups. Filters on the `#t=[\"oc-attest\"]` family marker because kind 30078\n * is shared by every NIP-78 app: an unfiltered window fills with other apps'\n * data. Returns envelopes whose attestation_id matches their message,\n * deduplicated by attestation_id. Signatures are not checked — call verify()\n * on anything you act on.\n */\nexport async function queryRecent(\n relays: string[] = DEFAULT_RELAYS,\n limit: number = 200\n): Promise<AttestationEnvelope[]> {\n const events: NostrEvent[] = [];\n\n log.info({ relayCount: relays.length, limit }, 'Querying relays for recent attestations');\n\n // One shared deadline for the whole fan-out — see FANOUT_DEADLINE_MS.\n const deadlineAt = Date.now() + FANOUT_DEADLINE_MS;\n\n const queryPromises = relays.map(async (relayUrl) => {\n try {\n const ws = new WebSocket(relayUrl);\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n ws.close();\n reject(new Error('Query timeout'));\n }, budgetFor(deadlineAt));\n\n ws.onopen = () => {\n const subscriptionId = `ochk_recent_${Date.now()}`;\n ws.send(\n JSON.stringify([\n 'REQ',\n subscriptionId,\n { kinds: [ATTESTATION_EVENT_KIND], '#t': ['oc-attest'], limit },\n ])\n );\n };\n\n ws.onmessage = (msg) => {\n try {\n const data = JSON.parse(msg.data);\n if (data[0] === 'EVENT') {\n const ev = data[2] as NostrEvent;\n const scheme = ev.tags?.find((t) => t[0] === 'scheme')?.[1];\n const dTag = ev.tags?.find((t) => t[0] === 'd')?.[1];\n if ((scheme === 'bip322' || scheme === 'legacy') && dTag) {\n events.push(ev);\n }\n } else if (data[0] === 'EOSE') {\n clearTimeout(timeout);\n ws.close();\n resolve();\n }\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to parse event');\n }\n };\n\n ws.onerror = (err) => {\n clearTimeout(timeout);\n log.error({ relay: relayUrl, error: err }, 'WebSocket error during query');\n reject(err);\n };\n });\n } catch (err) {\n log.error({ relay: relayUrl, error: err }, 'Failed to query relay');\n }\n });\n\n await Promise.allSettled(queryPromises);\n\n const seen = new Set<string>();\n const envelopes: AttestationEnvelope[] = [];\n for (const ev of events) {\n const envelope = parseAttestationFromEvent(ev);\n if (!envelope || seen.has(envelope.attestation_id)) continue;\n if (!(await verifyAttestationEnvelope(envelope))) continue;\n seen.add(envelope.attestation_id);\n envelopes.push(envelope);\n }\n\n log.info({ eventCount: events.length, unique: envelopes.length }, 'Recent query complete');\n\n return envelopes;\n}\n\n/**\n * Verify attestation envelope integrity\n * Checks that the attestation ID matches the message hash\n */\nexport async function verifyAttestationEnvelope(envelope: AttestationEnvelope): Promise<boolean> {\n try {\n // Re-compute attestation ID from message\n const encoder = new TextEncoder();\n const data = encoder.encode(envelope.message);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const computedId = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n\n return computedId === envelope.attestation_id;\n } catch (err) {\n log.error({ error: err }, 'Failed to verify attestation envelope');\n return false;\n }\n}\n\n/**\n * Parse attestation envelope from Nostr event content\n */\nexport function parseAttestationFromEvent(event: NostrEvent): AttestationEnvelope | null {\n try {\n const envelope = JSON.parse(event.content) as AttestationEnvelope;\n return envelope;\n } catch (err) {\n log.error({ eventId: event.id, error: err }, 'Failed to parse attestation from event');\n return null;\n }\n}\n","/**\n * Nostr Cryptographic Functions\n * Implements NIP-01 event ID computation and signature verification\n */\n\nimport type { NostrEvent } from './types';\n\nimport { createLogger } from './utils/logger';\n\ntype Nip07Window = {\n nostr?: {\n getPublicKey: () => Promise<string>;\n signEvent: (event: Omit<NostrEvent, 'id' | 'sig'>) => Promise<NostrEvent>;\n _metadata?: { name?: string; version?: string };\n };\n};\n\nconst log = createLogger('ocp/nostr-crypto');\n\n/**\n * Compute Nostr event ID according to NIP-01\n * Event ID is the SHA-256 hash of the serialized event\n * Serialization: [0, pubkey, created_at, kind, tags, content]\n */\nexport async function computeNostrEventId(event: Omit<NostrEvent, 'id' | 'sig'>): Promise<string> {\n // Serialize event according to NIP-01\n const serialized = JSON.stringify([\n 0, // Reserved for future use\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n\n log.debug({ serialized }, 'Computing event ID');\n\n // Compute SHA-256 hash\n const encoder = new TextEncoder();\n const data = encoder.encode(serialized);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\n // Convert to lowercase hex\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n\n log.debug({ eventId: hashHex }, 'Computed event ID');\n\n return hashHex;\n}\n\n/**\n * Verify Nostr event ID\n * Recomputes the ID and checks if it matches\n */\nexport async function verifyNostrEventId(event: NostrEvent): Promise<boolean> {\n const computedId = await computeNostrEventId(event);\n return computedId === event.id;\n}\n\n/**\n * Check if NIP-07 extension is available\n * NIP-07 provides window.nostr for signing events\n */\nexport function isNip07Available(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n\n return !!(window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n}\n\n/**\n * Get Nostr public key from NIP-07 extension\n * Returns null if extension not available or user denies\n */\nexport async function getNostrPublicKey(): Promise<string | null> {\n if (!isNip07Available()) {\n log.warn('NIP-07 extension not available');\n return null;\n }\n\n try {\n const nostr = (window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n const pubkey = await nostr.getPublicKey();\n log.info({ pubkey }, 'Got Nostr public key from NIP-07');\n return pubkey;\n } catch (err) {\n log.error({ error: err }, 'Failed to get Nostr public key');\n return null;\n }\n}\n\n/**\n * Sign Nostr event using NIP-07 extension\n * Returns signed event with id and sig fields\n */\nexport async function signNostrEvent(\n event: Omit<NostrEvent, 'id' | 'sig'>\n): Promise<NostrEvent | null> {\n if (!isNip07Available()) {\n log.warn('NIP-07 extension not available');\n return null;\n }\n\n try {\n const nostr = (window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n\n // NIP-07 signEvent expects the event without id and sig\n const signedEvent = await nostr.signEvent(event);\n\n log.info({ eventId: signedEvent.id }, 'Signed Nostr event with NIP-07');\n\n return signedEvent as NostrEvent;\n } catch (err) {\n log.error({ error: err }, 'Failed to sign Nostr event');\n return null;\n }\n}\n\n// Previously this file exported `generateEphemeralKeypair()` and\n// `signEventWithEphemeralKey()` for demo purposes. Both produced non-schnorr\n// values that Nostr relays would silently reject — creating the false\n// impression that publishing had succeeded. They have been removed. All Nostr\n// signing now flows through `signNostrEvent()` / `window.nostr` (NIP-07).\n\n/**\n * Validate Nostr event structure\n */\nexport function validateNostrEvent(event: unknown): event is NostrEvent {\n if (typeof event !== 'object' || event === null) return false;\n const e = event as Record<string, unknown>;\n\n if (typeof e.id !== 'string' || (e.id as string).length !== 64) return false;\n if (typeof e.pubkey !== 'string' || (e.pubkey as string).length !== 64) return false;\n if (typeof e.created_at !== 'number') return false;\n if (typeof e.kind !== 'number') return false;\n if (!Array.isArray(e.tags)) return false;\n if (typeof e.content !== 'string') return false;\n if (typeof e.sig !== 'string' || (e.sig as string).length !== 128) return false;\n\n return true;\n}\n\n/**\n * Get NIP-07 extension info\n */\nexport function getNip07Info(): {\n available: boolean;\n name?: string;\n version?: string;\n} {\n if (!isNip07Available()) {\n return { available: false };\n }\n\n const nostr = (window as unknown as { nostr?: Nip07Window['nostr'] }).nostr!;\n\n return {\n available: true,\n name: nostr._metadata?.name,\n version: nostr._metadata?.version,\n };\n}\n","/**\n * Attestation Manager\n *\n * High-level API for creating, publishing, and discovering OrangeCheck attestations\n */\n\nimport type { AttestationEnvelope, IdentityBinding, NostrEvent, Scheme } from './types';\n\nimport { createAttestationEnvelope } from './canonical';\nimport {\n createAttestationEvent,\n DEFAULT_RELAYS,\n parseAttestationFromEvent,\n publishToRelays,\n queryByAddress,\n queryByAttestationId,\n queryByIdentity,\n verifyAttestationEnvelope,\n} from './nostr';\nimport { isNip07Available, signNostrEvent } from './nostr-crypto';\nimport { createLogger } from './utils/logger';\n\nconst log = createLogger('ocp/attestation');\n\n/**\n * Options for creating an attestation\n */\nexport interface CreateAttestationOptions {\n /** Canonical message */\n message: string;\n /** BIP-322 or legacy signature */\n signature: string;\n /** Signature scheme used */\n scheme: Scheme;\n /** Bitcoin address */\n address: string;\n /** Optional identity bindings */\n identities?: IdentityBinding[];\n /** Optional extension key-value pairs */\n extensions?: Record<string, string | undefined>;\n}\n\n/**\n * Options for publishing an attestation to Nostr\n */\nexport interface PublishAttestationOptions {\n /** Attestation envelope to publish */\n envelope: AttestationEnvelope;\n /** Nostr public key (npub or hex) for signing the event */\n npub: string;\n /** Optional relay URLs (defaults to DEFAULT_RELAYS) */\n relays?: string[];\n}\n\n/**\n * Options for discovering attestations\n */\nexport interface DiscoverAttestationOptions {\n /** Search by attestation ID */\n attestationId?: string;\n /** Search by Bitcoin address */\n address?: string;\n /** Search by identity binding */\n identity?: { protocol: string; identifier: string };\n /** Optional relay URLs to query */\n relays?: string[];\n}\n\n/**\n * Result of publishing an attestation\n */\nexport interface PublishResult {\n /** Relays that successfully received the event */\n success: string[];\n /** Relays that failed to receive the event */\n failed: string[];\n}\n\n/**\n * Custom error for attestation operations\n */\nexport class AttestationError extends Error {\n constructor(\n message: string,\n public readonly code?: string\n ) {\n super(message);\n this.name = 'AttestationError';\n }\n}\n\n/**\n * Create an attestation envelope from a signed message\n *\n * @param options - Attestation creation options\n * @returns Attestation envelope ready for publishing\n * @throws {AttestationError} If envelope integrity check fails\n *\n * @example\n * ```typescript\n * const envelope = await createAttestation({\n * message: canonicalMessage,\n * signature: 'AkcwRAIg...',\n * scheme: 'bip322',\n * address: 'bc1q...',\n * identities: [{ protocol: 'nostr', identifier: 'npub1...' }],\n * });\n * ```\n */\nexport async function createAttestation(\n options: CreateAttestationOptions\n): Promise<AttestationEnvelope> {\n const { message, signature, scheme, address, identities = [], extensions = {} } = options;\n\n log.info({ address, identityCount: identities.length }, 'Creating attestation');\n\n const envelope = await createAttestationEnvelope(\n message,\n signature,\n scheme,\n address,\n identities,\n extensions\n );\n\n // Verify envelope integrity\n const isValid = await verifyAttestationEnvelope(envelope);\n if (!isValid) {\n throw new AttestationError(\n 'Attestation envelope integrity check failed',\n 'INTEGRITY_CHECK_FAILED'\n );\n }\n\n log.info({ attestationId: envelope.attestation_id }, 'Attestation created successfully');\n\n return envelope;\n}\n\n/**\n * Publish an attestation to Nostr relays\n *\n * Uses NIP-07 if available, falls back to ephemeral key for demo\n *\n * @param options - Publishing options\n * @returns Object with successful and failed relay URLs\n * @throws {AttestationError} If signing fails\n *\n * @example\n * ```typescript\n * const result = await publishAttestation({\n * envelope,\n * npub: 'npub1...',\n * relays: ['wss://relay.damus.io'],\n * });\n * console.log('Published to:', result.success);\n * ```\n */\nexport async function publishAttestation(\n options: PublishAttestationOptions\n): Promise<PublishResult> {\n const { envelope, npub, relays = DEFAULT_RELAYS } = options;\n\n log.info(\n { attestationId: envelope.attestation_id, relayCount: relays.length },\n 'Publishing attestation'\n );\n\n // Create unsigned event\n const unsignedEvent = createAttestationEvent(envelope, npub);\n\n // Nostr publishing requires a valid schnorr signature. Only NIP-07\n // (window.nostr) is supported. If no signer is present we refuse to\n // publish rather than emit an invalid-sig event that every relay will\n // silently reject — which would make the caller think it had succeeded.\n if (!isNip07Available()) {\n log.warn('NIP-07 unavailable — skipping Nostr publish');\n throw new Error(\n 'nostr_signer_unavailable: install a NIP-07 extension (e.g. nos2x, Alby) to publish'\n );\n }\n\n log.info('Using NIP-07 to sign event');\n const signedEvent = await signNostrEvent(unsignedEvent);\n if (!signedEvent) {\n throw new Error('nostr_signing_failed: NIP-07 extension rejected or errored');\n }\n\n const result = await publishToRelays(signedEvent, relays);\n\n log.info(\n {\n attestationId: envelope.attestation_id,\n successCount: result.success.length,\n failedCount: result.failed.length,\n },\n 'Publishing complete'\n );\n\n return result;\n}\n\n/**\n * An event's index tags are unsigned, so a relay hit proves nothing until they\n * agree with the envelope. Requiring the `t` address tag also keeps every\n * attestation findable by address, which check()'s shared-stake audit relies on.\n */\nfunction eventIndexesEnvelope(event: NostrEvent, envelope: AttestationEnvelope): boolean {\n const d = event.tags.find((t) => t[0] === 'd')?.[1];\n const id = envelope.attestation_id;\n if (d !== id && d !== `orangecheck:${id}`) return false;\n return event.tags.some((t) => t[0] === 't' && t[1] === envelope.address);\n}\n\n/**\n * Discover attestations from Nostr relays\n */\nexport async function discoverAttestations(\n options: DiscoverAttestationOptions\n): Promise<AttestationEnvelope[]> {\n const { attestationId, address, identity, relays = DEFAULT_RELAYS } = options;\n\n let events: NostrEvent[] = [];\n\n if (attestationId) {\n log.info({ attestationId }, 'Discovering by attestation ID');\n events = await queryByAttestationId(attestationId, relays);\n } else if (address) {\n log.info({ address }, 'Discovering by Bitcoin address');\n events = await queryByAddress(address, relays);\n } else if (identity) {\n log.info({ identity }, 'Discovering by identity');\n events = await queryByIdentity(identity.protocol, identity.identifier, relays);\n } else {\n throw new Error('Must provide attestationId, address, or identity');\n }\n\n // Parse and verify envelopes\n const envelopes: AttestationEnvelope[] = [];\n for (const event of events) {\n const envelope = parseAttestationFromEvent(event);\n if (envelope && !eventIndexesEnvelope(event, envelope)) {\n log.warn({ eventId: event.id }, 'Skipping event whose index tags disagree with its envelope');\n } else if (envelope) {\n // Verify envelope integrity\n const isValid = await verifyAttestationEnvelope(envelope);\n if (isValid) {\n envelopes.push(envelope);\n } else {\n log.warn(\n { attestationId: envelope.attestation_id },\n 'Skipping invalid attestation envelope'\n );\n }\n }\n }\n\n log.info({ eventCount: events.length, validCount: envelopes.length }, 'Discovery complete');\n\n return envelopes;\n}\n\n/**\n * Verify an attestation by fetching it from Nostr and checking integrity\n */\nexport async function verifyAttestationById(\n attestationId: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<AttestationEnvelope | null> {\n log.info({ attestationId }, 'Verifying attestation by ID');\n\n const envelopes = await discoverAttestations({ attestationId, relays });\n\n if (envelopes.length === 0) {\n log.warn({ attestationId }, 'Attestation not found on any relay');\n return null;\n }\n\n if (envelopes.length > 1) {\n log.warn(\n { attestationId, count: envelopes.length },\n 'Multiple attestations found with same ID - using first'\n );\n }\n\n return envelopes[0] || null;\n}\n\n/**\n * Get all attestations for a Bitcoin address\n */\nexport async function getAttestationsForAddress(\n address: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<AttestationEnvelope[]> {\n log.info({ address }, 'Getting all attestations for address');\n return discoverAttestations({ address, relays });\n}\n\n/**\n * Get all attestations for an identity\n */\nexport async function getAttestationsForIdentity(\n protocol: string,\n identifier: string,\n relays: string[] = DEFAULT_RELAYS\n): Promise<AttestationEnvelope[]> {\n log.info({ protocol, identifier }, 'Getting all attestations for identity');\n return discoverAttestations({ identity: { protocol, identifier }, relays });\n}\n\n/**\n * Format identities for display as a comma-separated `protocol:identifier` list.\n * Same wire format the canonical message uses.\n */\nexport function formatIdentitiesForDisplay(identities: IdentityBinding[]): string {\n return identities.map((id) => `${id.protocol}:${id.identifier}`).join(', ');\n}\n\n/**\n * Build the canonical shareable URL for an attestation. Matches the live\n * `/attest/[id]` route on attest.ochk.io. Pass a different `baseUrl` for forks /\n * self-hosted verifiers.\n */\nexport function getVerificationUrl(\n attestationId: string,\n baseUrl = 'https://attest.ochk.io'\n): string {\n return `${baseUrl}/attest/${attestationId}`;\n}\n\n/**\n * Reverse of `getVerificationUrl` — pull an attestation id back out of a\n * `/attest/<id>` or legacy `/verify?id=<id>` URL. Returns `null` if the URL\n * shape doesn't match.\n */\nexport function extractAttestationIdFromUrl(url: string): string | null {\n try {\n const u = new URL(url);\n // New canonical form: /attest/<id>\n const m = u.pathname.match(/^\\/attest\\/([0-9a-f]{64})\\/?$/i);\n if (m) return m[1]!.toLowerCase();\n // Legacy form: /verify?id=<id>\n const q = u.searchParams.get('id');\n if (q && /^[0-9a-f]{64}$/i.test(q)) return q.toLowerCase();\n return null;\n } catch {\n return null;\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { I as IdentityBinding, S as Scheme, A as AttestationEnvelope } from './types-BJKDroFv.mjs';
1
+ import { I as IdentityBinding, S as Scheme, A as AttestationEnvelope } from './types-D9Tb1roj.mjs';
2
2
 
3
3
  interface CanonicalInput {
4
4
  address: string;
@@ -1,4 +1,4 @@
1
- import { I as IdentityBinding, S as Scheme, A as AttestationEnvelope } from './types-BJKDroFv.js';
1
+ import { I as IdentityBinding, S as Scheme, A as AttestationEnvelope } from './types-D9Tb1roj.js';
2
2
 
3
3
  interface CanonicalInput {
4
4
  address: string;
@@ -1,4 +1,4 @@
1
- import { S as Scheme } from './types-BJKDroFv.mjs';
1
+ import { S as Scheme } from './types-D9Tb1roj.mjs';
2
2
 
3
3
  interface IssueChallengeOptions {
4
4
  address: string;
@@ -1,4 +1,4 @@
1
- import { S as Scheme } from './types-BJKDroFv.js';
1
+ import { S as Scheme } from './types-D9Tb1roj.js';
2
2
 
3
3
  interface IssueChallengeOptions {
4
4
  address: string;
@@ -1,4 +1,4 @@
1
- import { N as NostrEvent, I as IdentityBinding } from './types-BJKDroFv.mjs';
1
+ import { c as NostrEvent, I as IdentityBinding } from './types-D9Tb1roj.mjs';
2
2
 
3
3
  interface DnsVerificationResult {
4
4
  verified: boolean;
@@ -1,4 +1,4 @@
1
- import { N as NostrEvent, I as IdentityBinding } from './types-BJKDroFv.js';
1
+ import { c as NostrEvent, I as IdentityBinding } from './types-D9Tb1roj.js';
2
2
 
3
3
  interface DnsVerificationResult {
4
4
  verified: boolean;
package/dist/identity.js CHANGED
@@ -374,6 +374,25 @@ function isGitHubIdentityVerified(attestationId, _username, cachedGists) {
374
374
  function getGistCreationUrl() {
375
375
  return "https://gist.github.com/";
376
376
  }
377
+ var HEX_64_RE = /^[0-9a-f]{64}$/;
378
+ function toHex(bytes) {
379
+ let out = "";
380
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
381
+ return out;
382
+ }
383
+ function nostrPubkeyToHex(value) {
384
+ const trimmed = value.trim().toLowerCase();
385
+ if (HEX_64_RE.test(trimmed)) return trimmed;
386
+ if (!trimmed.startsWith("npub1")) return null;
387
+ try {
388
+ const decoded = base.bech32.decode(trimmed, 1023);
389
+ if (decoded.prefix !== "npub") return null;
390
+ const bytes = base.bech32.fromWords(decoded.words);
391
+ return bytes.length === 32 ? toHex(Uint8Array.from(bytes)) : null;
392
+ } catch {
393
+ return null;
394
+ }
395
+ }
377
396
  var DEFAULT_RELAYS = [
378
397
  "wss://relay.damus.io",
379
398
  "wss://nos.lol",
@@ -383,8 +402,8 @@ var DEFAULT_RELAYS = [
383
402
 
384
403
  // src/identity/nostr.ts
385
404
  var log4 = createLogger("identity-verification/nostr");
386
- var HEX_64_RE = /^[0-9a-f]{64}$/;
387
- function toHex(bytes) {
405
+ var HEX_64_RE2 = /^[0-9a-f]{64}$/;
406
+ function toHex2(bytes) {
388
407
  let out = "";
389
408
  for (const b of bytes) out += b.toString(16).padStart(2, "0");
390
409
  return out;
@@ -398,22 +417,9 @@ function fromHex(hex) {
398
417
  return out;
399
418
  }
400
419
  function npubToHex(npub) {
401
- const trimmed = npub.trim();
402
- if (HEX_64_RE.test(trimmed.toLowerCase())) {
403
- return trimmed.toLowerCase();
404
- }
405
- if (!trimmed.toLowerCase().startsWith("npub1")) {
406
- throw new Error(`not an npub: ${trimmed.slice(0, 12)}\u2026`);
407
- }
408
- const decoded = base.bech32.decode(trimmed.toLowerCase(), 1023);
409
- if (decoded.prefix !== "npub") {
410
- throw new Error(`bech32 prefix mismatch: expected npub, got ${decoded.prefix}`);
411
- }
412
- const bytes = base.bech32.fromWords(decoded.words);
413
- if (bytes.length !== 32) {
414
- throw new Error(`invalid npub payload length: ${bytes.length}`);
415
- }
416
- return toHex(Uint8Array.from(bytes));
420
+ const hex = nostrPubkeyToHex(npub);
421
+ if (!hex) throw new Error(`not an npub: ${npub.trim().slice(0, 12)}\u2026`);
422
+ return hex;
417
423
  }
418
424
  async function queryNostrEvents(options) {
419
425
  const { authors, kinds, search, relays = DEFAULT_RELAYS, limit = 100 } = options;
@@ -485,7 +491,7 @@ async function queryNostrEvents(options) {
485
491
  }
486
492
  async function verifyNostrEventSignature(event) {
487
493
  try {
488
- if (!event.id || !event.sig || !event.pubkey || typeof event.id !== "string" || typeof event.sig !== "string" || typeof event.pubkey !== "string" || event.sig.length !== 128 || !HEX_64_RE.test(event.id) || !HEX_64_RE.test(event.pubkey)) {
494
+ if (!event.id || !event.sig || !event.pubkey || typeof event.id !== "string" || typeof event.sig !== "string" || typeof event.pubkey !== "string" || event.sig.length !== 128 || !HEX_64_RE2.test(event.id) || !HEX_64_RE2.test(event.pubkey)) {
489
495
  return false;
490
496
  }
491
497
  const preimage = JSON.stringify([
@@ -496,7 +502,7 @@ async function verifyNostrEventSignature(event) {
496
502
  event.tags ?? [],
497
503
  event.content ?? ""
498
504
  ]);
499
- const computedId = toHex(sha2_js.sha256(new TextEncoder().encode(preimage)));
505
+ const computedId = toHex2(sha2_js.sha256(new TextEncoder().encode(preimage)));
500
506
  if (computedId !== event.id.toLowerCase()) {
501
507
  log4.warn(
502
508
  { eventId: event.id, computedId },