@zkproofport-app/sdk 0.5.0-beta.0 → 0.5.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/deeplink.ts","../src/qrcode.ts","../src/offChainVerifier.ts","../src/relayStatus.ts","../src/ProofportSDK.ts"],"sourcesContent":["/**\n * ZKProofport SDK Constants\n */\n\nimport type { CircuitType, SDKEnvironment } from './types';\n\n/**\n * Pre-configured relay server URLs for each environment.\n * Used by `ProofportSDK.create('production')` for zero-config initialization.\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * // Uses RELAY_URLS.production = 'https://relay.zkproofport.app'\n * ```\n */\nexport const RELAY_URLS: Record<SDKEnvironment, string> = {\n production: 'https://relay.zkproofport.app',\n staging: 'https://stg-relay.zkproofport.app',\n local: 'http://localhost:4001',\n};\n\n/**\n * Default deep link URL scheme for ZKProofport mobile app.\n * Used to construct deep link URLs that open the mobile app.\n *\n * @example\n * ```typescript\n * const deepLink = `${DEFAULT_SCHEME}://proof-request?...`;\n * // Results in: zkproofport://proof-request?...\n * ```\n */\nexport const DEFAULT_SCHEME = 'zkproofport';\n\n/**\n * Deep link URL hosts for different proof request flows.\n * Used as the host component in deep link URLs.\n *\n * @example\n * ```typescript\n * const requestUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_REQUEST}`;\n * const responseUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_RESPONSE}`;\n * ```\n */\nexport const DEEP_LINK_HOSTS = {\n /** Host for proof requests sent to mobile app */\n PROOF_REQUEST: 'proof-request',\n /** Host for proof responses returned from mobile app */\n PROOF_RESPONSE: 'proof-response',\n} as const;\n\n/**\n * Circuit metadata containing display names, descriptions, and public input specifications.\n * Each circuit has a defined number and layout of public inputs that must match\n * the Noir circuit definition.\n *\n * @example\n * ```typescript\n * const metadata = CIRCUIT_METADATA['coinbase_attestation'];\n * console.log(metadata.name); // \"Coinbase KYC\"\n * console.log(metadata.publicInputsCount); // 128\n * ```\n */\nexport const CIRCUIT_METADATA: Record<CircuitType, {\n name: string;\n description: string;\n publicInputsCount: number;\n publicInputNames: string[];\n}> = {\n coinbase_attestation: {\n name: 'Coinbase KYC',\n description: 'Prove Coinbase identity verification',\n // 4 x `pub [u8; 32]` in coinbase-attestation/src/main.nr, flattened to\n // bytes: signal_hash, signer_list_merkle_root, scope, nullifier.\n // Read 2 here until 2026-09-04, which was wrong under any reading —\n // the circuit has never had two public inputs, logical or flattened.\n publicInputsCount: 128,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root'],\n },\n coinbase_country_attestation: {\n name: 'Coinbase Country',\n description: 'Prove Coinbase country verification',\n // 32 + 32 + (10 x 2) + 1 + 1 + 32 + 32 = 150, counted off\n // coinbase-country-attestation/src/main.nr. Read 14 until 2026-09-04.\n publicInputsCount: 150,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root', 'country_list', 'country_list_length', 'is_included'],\n },\n oidc_domain_attestation: {\n name: 'OIDC Domain',\n description: 'Prove email domain affiliation via OIDC JWT',\n publicInputsCount: 148,\n publicInputNames: ['pubkey_modulus_limbs', 'domain', 'scope', 'nullifier', 'provider'],\n },\n // Planned circuit — the identifier is reserved and the circuit exists, but it\n // is not officially supported yet. See CIRCUIT_SUPPORT_STATUS in ./circuits.\n // Forked from coinbase_attestation, then given the EIP-712 pair and a\n // branch: with an action the wallet signs the typed data and signal_hash is\n // zero; without one it signs signal_hash and the pair is zero. Read off the\n // compiled ABI (6 x [u8; 32] = 192): signal_hash 0-31, domain_separator\n // 32-63, action_hash 64-95, signer_list_merkle_root 96-127, scope 128-159,\n // nullifier 160-191.\n //\n // signal_hash is NOT part of this circuit's nullifier: a nullifier derived\n // from a public input nobody signs and nothing constrains would let one\n // wallet mint as many nullifiers as it likes; here the secret is the address\n // plus a constant compiled into the circuit.\n giwa_attestation: {\n name: 'GIWA Attestation',\n description: 'Prove GIWA identity verification, optionally authorizing one EIP-712 action (planned — not officially supported yet)',\n publicInputsCount: 192,\n publicInputNames: ['signal_hash', 'domain_separator', 'action_hash', 'signer_list_merkle_root', 'scope', 'nullifier'],\n },\n // Experimental, GIWA Sepolia only. The wallet signs the request (an EIP-712\n // action, or signal_hash when none is given -- the same branch as GIWA), and\n // the same key must have signed a payAndIssueEAS() call to the Playground\n // faucet. No issuer list, so no merkle root: 5 x [u8; 32] = 160, read off the\n // compiled ABI -- signal_hash 0-31, domain_separator 32-63, action_hash\n // 64-95, scope 96-127, nullifier 128-159.\n dojang_playground: {\n name: 'Dojang Playground',\n description: 'Prove this wallet issued itself a Dojang through the GIWA Playground, optionally authorizing one EIP-712 action',\n publicInputsCount: 160,\n publicInputNames: ['signal_hash', 'domain_separator', 'action_hash', 'scope', 'nullifier'],\n },\n // Korea Mobile ID (mDL) circuits. Planned — not officially supported yet.\n // Counts are byte-flattened field totals from the compiled circuit ABIs:\n // [u8; 32] arrays contribute 32 inputs each.\n mdl_kr_ownership: {\n name: 'Korea Mobile ID — Ownership',\n description: \"Prove valid Korean mobile driver's license ownership with selective disclosure\",\n publicInputsCount: 97,\n publicInputNames: ['scope', 'nullifier_value', 'disclose_flags', 'owner_commit'],\n },\n mdl_kr_age: {\n name: 'Korea Mobile ID — Age',\n description: \"Prove minimum age from Korean mobile driver's license without revealing birth date\",\n publicInputsCount: 66,\n publicInputNames: ['scope', 'nullifier_value', 'age_threshold', 'current_year'],\n },\n mdl_kr_region: {\n name: 'Korea Mobile ID — Region',\n description: \"Prove si/do residency from Korean mobile driver's license without revealing address\",\n publicInputsCount: 96,\n publicInputNames: ['scope', 'nullifier_value', 'region_code'],\n },\n};\n\n\n\n/**\n * Default proof request expiration time in milliseconds.\n * Requests older than this are considered expired and should not be processed.\n *\n * Default: 10 minutes (600,000 ms)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * // ...\n * createdAt: Date.now(),\n * expiresAt: Date.now() + DEFAULT_REQUEST_EXPIRY_MS\n * };\n * ```\n */\nexport const DEFAULT_REQUEST_EXPIRY_MS = 10 * 60 * 1000;\n\n/**\n * Maximum data size (in bytes) that can be encoded in a QR code.\n * Based on QR Code Version 40 with L (Low) error correction level.\n *\n * Requests exceeding this size should use alternative methods (HTTP, WebSocket).\n *\n * @example\n * ```typescript\n * const deepLinkUrl = generateDeepLink(request);\n * if (deepLinkUrl.length > MAX_QR_DATA_SIZE) {\n * console.warn('Request too large for QR code');\n * }\n * ```\n */\nexport const MAX_QR_DATA_SIZE = 2953; // Version 40 with L error correction\n\n// Moved to @zkproofport-app/core, re-exported so existing imports keep working.\nexport {\n VERIFIER_ABI,\n RPC_ENDPOINTS,\n COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT,\n COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT,\n MDL_KR_PUBLIC_INPUT_LAYOUT,\n OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT,\n} from '@zkproofport-app/core';\n","/**\n * Deep Link utilities for ZKProofport SDK\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n OidcDomainInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n DeepLinkComponents,\n CircuitType,\n} from './types';\nimport { DEFAULT_SCHEME, DEEP_LINK_HOSTS } from './constants';\nimport { isCircuitId, ALL_CIRCUIT_IDS } from './circuits';\nimport { validateTypedAction } from './typedAction';\nimport { circuitActionBinding } from './circuits';\n\n/**\n * Generates a unique request ID for proof requests.\n *\n * Creates an ID by combining a base36-encoded timestamp with a random string,\n * prefixed with \"req-\". This ensures uniqueness across concurrent requests.\n *\n * @returns A unique string identifier in the format \"req-{timestamp}-{random}\"\n *\n * @example\n * ```typescript\n * const id = generateRequestId();\n * // \"req-lh8k3f2g-a9b7c4d2\"\n * ```\n */\nexport function generateRequestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 10);\n return `req-${timestamp}-${random}`;\n}\n\n/**\n * Encodes an object into a URL-safe base64url string with UTF-8 support.\n *\n * Converts the input object to JSON, then encodes it using base64url format\n * (RFC 4648 §5) which replaces '+' with '-', '/' with '_', and removes padding.\n * Works in both browser and Node.js environments.\n *\n * @param data - The object to encode (will be JSON stringified)\n * @returns Base64url-encoded string safe for URL parameters\n *\n * @example\n * ```typescript\n * const encoded = encodeData({ circuit: 'coinbase_attestation', requestId: 'req-123' });\n * // \"eyJjaXJjdWl0IjoiY29pbmJhc2VfYXR0ZXN0YXRpb24iLCJyZXF1ZXN0SWQiOiJyZXEtMTIzIn0\"\n * ```\n */\nexport function encodeData(data: object): string {\n const json = JSON.stringify(data);\n // Use base64url encoding (URL-safe) with UTF-8 support\n if (typeof btoa === 'function') {\n // Browser: UTF-8 encode first, then base64\n const utf8Encoded = encodeURIComponent(json).replace(/%([0-9A-F]{2})/g, (_, p1) =>\n String.fromCharCode(parseInt(p1, 16))\n );\n return btoa(utf8Encoded)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n }\n // Node.js environment\n return Buffer.from(json, 'utf-8')\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Decodes a base64url-encoded string back into a typed object.\n *\n * Reverses the encoding process by converting base64url to standard base64,\n * decoding it, and parsing the resulting JSON. Handles UTF-8 correctly in\n * both browser and Node.js environments.\n *\n * @typeParam T - The expected type of the decoded object\n * @param encoded - Base64url-encoded string (from encodeData)\n * @returns Decoded and parsed object of type T\n *\n * @throws {SyntaxError} If the decoded string is not valid JSON\n *\n * @example\n * ```typescript\n * const request = decodeData<ProofRequest>(encodedString);\n * console.log(request.circuit); // \"coinbase_attestation\"\n * ```\n */\nexport function decodeData<T>(encoded: string): T {\n // Restore base64 padding\n let base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');\n while (base64.length % 4) {\n base64 += '=';\n }\n\n let json: string;\n if (typeof atob === 'function') {\n // Browser: decode base64, then UTF-8 decode\n const decoded = atob(base64);\n json = decodeURIComponent(\n decoded.split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join('')\n );\n } else {\n json = Buffer.from(base64, 'base64').toString('utf-8');\n }\n\n return JSON.parse(json) as T;\n}\n\n/**\n * Builds a deep link URL for a proof request.\n *\n * Encodes the proof request and constructs a deep link URL that can be opened\n * by the ZKProofport mobile app. The URL format is:\n * `{scheme}://proof-request?data={encodedRequest}`\n *\n * @param request - The proof request to encode in the deep link\n * @param scheme - Custom URL scheme (defaults to \"zkproofport\")\n * @returns Complete deep link URL ready to be opened or embedded in a QR code\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n * const url = buildProofRequestUrl(request);\n * // \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\"\n * ```\n */\nexport function buildProofRequestUrl(\n request: ProofRequest,\n scheme: string = DEFAULT_SCHEME\n): string {\n const encodedRequest = encodeData(request);\n return `${scheme}://${DEEP_LINK_HOSTS.PROOF_REQUEST}?data=${encodedRequest}`;\n}\n\n/**\n * Builds a callback URL with proof response data as query parameters.\n *\n * Appends proof response fields to the provided callback URL. For completed proofs,\n * includes proof data, public inputs, and nullifier. For errors, includes error message.\n *\n * @internal Used by the mobile app to construct callback URLs — not intended for SDK consumers.\n *\n * @param callbackUrl - Base callback URL (from the original proof request)\n * @param response - Proof response containing status and optional proof data\n * @returns Complete callback URL with proof response as query parameters\n */\nexport function buildCallbackUrl(\n callbackUrl: string,\n response: ProofResponse\n): string {\n const url = new URL(callbackUrl);\n url.searchParams.set('requestId', response.requestId);\n url.searchParams.set('status', response.status);\n\n if (response.status === 'completed' && response.proof) {\n url.searchParams.set('proof', response.proof);\n if (response.publicInputs) {\n url.searchParams.set('publicInputs', response.publicInputs.join(','));\n }\n if (response.numPublicInputs !== undefined) {\n url.searchParams.set('numPublicInputs', response.numPublicInputs.toString());\n }\n if (response.timestamp) {\n url.searchParams.set('timestamp', response.timestamp.toString());\n }\n } else if (response.status === 'error' && response.error) {\n url.searchParams.set('error', response.error);\n }\n\n return url.toString();\n}\n\n/**\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a ZKProofport deep link URL.\n * Returns null if the URL is invalid or missing required parameters.\n *\n * @param url - Deep link URL (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Decoded ProofRequest object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\";\n * const request = parseProofRequestUrl(url);\n * if (request) {\n * console.log(request.circuit); // \"coinbase_attestation\"\n * }\n * ```\n */\nexport function parseProofRequestUrl(url: string): ProofRequest | null {\n try {\n const urlObj = new URL(url);\n const data = urlObj.searchParams.get('data');\n\n if (!data) {\n return null;\n }\n\n return decodeData<ProofRequest>(data);\n } catch (error) {\n console.error('Failed to parse proof request URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a proof response from a callback URL.\n *\n * Extracts proof response data from query parameters in a callback URL.\n * Handles both successful proof completions and error responses.\n * Returns null if required parameters (requestId, status) are missing.\n *\n * @param url - Callback URL with proof response query parameters\n * @returns Decoded ProofResponse object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const callbackUrl = \"https://example.com/callback?requestId=req-123&status=completed&proof=0x...\";\n * const response = parseProofResponseUrl(callbackUrl);\n * if (response && response.status === 'completed') {\n * console.log(response.proof); // \"0x...\"\n * }\n * ```\n */\nexport function parseProofResponseUrl(url: string): ProofResponse | null {\n try {\n const urlObj = new URL(url);\n const requestId = urlObj.searchParams.get('requestId');\n const status = urlObj.searchParams.get('status') as ProofResponse['status'];\n\n if (!requestId || !status) {\n return null;\n }\n\n // A missing or unrecognised circuit is a REJECTION, not a default.\n //\n // This used to fall back to `coinbase_attestation`. A callback carrying a\n // country or OIDC proof, or a circuit this build has never heard of, was\n // then handed to the caller labelled Coinbase KYC -- the parse succeeded,\n // the label was wrong, and nothing downstream could tell. Whoever reads\n // `response.circuit` decides which verifier and which public-input layout\n // to use, so the wrong label is a proof checked against another circuit's\n // bytes.\n const circuit = urlObj.searchParams.get('circuit');\n if (!circuit || !isCircuitId(circuit)) {\n return null;\n }\n\n const response: ProofResponse = {\n requestId,\n circuit,\n status,\n };\n\n if (status === 'completed') {\n response.proof = urlObj.searchParams.get('proof') || undefined;\n const publicInputsStr = urlObj.searchParams.get('publicInputs');\n if (publicInputsStr) {\n response.publicInputs = publicInputsStr.split(',');\n }\n const numPublicInputs = urlObj.searchParams.get('numPublicInputs');\n if (numPublicInputs) {\n response.numPublicInputs = parseInt(numPublicInputs, 10);\n }\n const timestamp = urlObj.searchParams.get('timestamp');\n if (timestamp) {\n response.timestamp = parseInt(timestamp, 10);\n }\n } else if (status === 'error') {\n response.error = urlObj.searchParams.get('error') || undefined;\n }\n\n return response;\n } catch (error) {\n console.error('Failed to parse proof response URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a deep link URL into its component parts.\n *\n * Breaks down a custom scheme URL into scheme, host, path, and query parameters.\n * Useful for routing and handling different types of deep links.\n *\n * @param url - Custom scheme URL to parse (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Object containing scheme, host, path, and params, or null if invalid\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request/verify?data=abc123\";\n * const components = parseDeepLink(url);\n * // {\n * // scheme: \"zkproofport\",\n * // host: \"proof-request\",\n * // path: \"/verify\",\n * // params: { data: \"abc123\" }\n * // }\n * ```\n */\nexport function parseDeepLink(url: string): DeepLinkComponents | null {\n try {\n // Handle custom scheme URLs\n const schemeMatch = url.match(/^([a-z][a-z0-9+.-]*):\\/\\/(.+)$/i);\n if (!schemeMatch) {\n return null;\n }\n\n const scheme = schemeMatch[1];\n const rest = schemeMatch[2];\n\n // Parse host and path\n const [hostPath, queryString] = rest.split('?');\n const [host, ...pathParts] = hostPath.split('/');\n const path = '/' + pathParts.join('/');\n\n // Parse query parameters\n const params: Record<string, string> = {};\n if (queryString) {\n const searchParams = new URLSearchParams(queryString);\n searchParams.forEach((value, key) => {\n params[key] = value;\n });\n }\n\n return { scheme, host, path, params };\n } catch (error) {\n console.error('Failed to parse deep link:', error);\n return null;\n }\n}\n\n/**\n * Checks if a URL is a valid ZKProofport deep link.\n *\n * Performs a case-insensitive check to see if the URL starts with the\n * ZKProofport scheme. Does not validate the URL structure beyond the scheme.\n *\n * @param url - URL to check\n * @param scheme - Expected URL scheme (defaults to \"zkproofport\")\n * @returns True if the URL starts with the specified scheme\n *\n * @example\n * ```typescript\n * isProofportDeepLink(\"zkproofport://proof-request?data=...\"); // true\n * isProofportDeepLink(\"https://example.com\"); // false\n * isProofportDeepLink(\"ZKPROOFPORT://proof-request\"); // true (case-insensitive)\n * ```\n */\nexport function isProofportDeepLink(\n url: string,\n scheme: string = DEFAULT_SCHEME\n): boolean {\n return url.toLowerCase().startsWith(`${scheme.toLowerCase()}://`);\n}\n\n/**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Performs comprehensive validation including:\n * - Required fields (requestId, circuit, callbackUrl)\n * - Circuit type validity (must be a supported circuit)\n * - Circuit-specific input validation (e.g., userAddress format, countryList structure)\n * - Expiration check (if expiresAt is provided)\n *\n * Note: userAddress is optional for both circuits - the mobile app will prompt\n * for wallet connection if not provided.\n *\n * @param request - Proof request to validate\n * @returns Validation result with `valid` flag and optional `error` message\n */\n/**\n * Validates a free-text mDL input (scope / targetRegion).\n * Rejects empty or whitespace-only values, control characters (which break\n * deep-link query encoding and downstream logging), and values over 256 chars\n * (server-side length cap mirror). UTF-8 text such as Korean region names is\n * allowed.\n *\n * @returns Error message string, or null when valid.\n */\nfunction validateMdlTextInput(value: unknown, fieldName: string): string | null {\n if (typeof value !== 'string' || value.trim() === '') {\n return `${fieldName} is required and must be a non-empty string`;\n }\n if (value.length > 256) {\n return `${fieldName} must be 256 characters or fewer`;\n }\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001F\\u007F]/.test(value)) {\n return `${fieldName} must not contain control characters`;\n }\n return null;\n}\n\n/**\n * Validates dapp-supplied inputs for the Korea Mobile ID (mDL) circuits.\n * Shared by deep-link request validation and relay request creation so the\n * same guards apply on every request path.\n *\n * Rules:\n * - `scope` — required non-empty string, ≤256 chars, no control characters\n * - `mdl_kr_ownership.discloseFlags` — optional integer 0–15 (0x0F bitmask)\n * - `mdl_kr_age.ageThreshold` — required integer 1–150\n * - `mdl_kr_region.targetRegion` — required non-empty string (Korean si/do),\n * ≤256 chars, no control characters\n *\n * @param circuit - One of the three mDL circuit identifiers\n * @param inputs - Dapp-supplied circuit inputs\n * @returns Error message string, or null when the inputs are valid\n */\nexport function validateMdlInputs(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs\n): string | null {\n const scopeError = validateMdlTextInput((inputs as MdlKrOwnershipInputs).scope, 'scope');\n if (scopeError) {\n return scopeError;\n }\n\n if (circuit === 'mdl_kr_ownership') {\n const { discloseFlags } = inputs as MdlKrOwnershipInputs;\n if (discloseFlags !== undefined) {\n if (\n typeof discloseFlags !== 'number' ||\n !Number.isInteger(discloseFlags) ||\n discloseFlags < 0 ||\n discloseFlags > 0x0f\n ) {\n return 'discloseFlags must be an integer between 0 and 15';\n }\n }\n } else if (circuit === 'mdl_kr_age') {\n const { ageThreshold } = inputs as MdlKrAgeInputs;\n if (\n typeof ageThreshold !== 'number' ||\n !Number.isInteger(ageThreshold) ||\n ageThreshold < 1 ||\n ageThreshold > 150\n ) {\n return 'ageThreshold is required and must be an integer between 1 and 150';\n }\n } else {\n const { targetRegion } = inputs as MdlKrRegionInputs;\n const regionError = validateMdlTextInput(targetRegion, 'targetRegion');\n if (regionError) {\n return regionError;\n }\n }\n\n return null;\n}\n\n/**\n * Longest accepted `returnScheme` value.\n * Kept in sync with proofport-relay `src/returnScheme.ts`.\n */\nexport const MAX_RETURN_SCHEME_LENGTH = 128;\n\n/** RFC 3986 scheme (`ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )`) followed by exactly `://`. */\nconst BARE_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\\/\\/$/;\n\n/**\n * Schemes we refuse even in the bare `scheme://` shape.\n *\n * `http` and `https` are the back door the shape rule alone leaves open: with\n * no host, `https://` is shaped exactly like a bare custom scheme and would\n * otherwise pass. A browser pointed at nowhere is not a return target, and\n * accepting it would re-open the URL-shaped door this field just closed.\n * `googlechrome://` and `firefox://` are deliberately NOT denied — bare, they\n * foreground that browser without navigating, which is the whole point.\n */\nconst DENIED_RETURN_SCHEMES = new Set([\n 'about',\n 'blob',\n 'content',\n 'data',\n 'facetime',\n 'facetime-audio',\n 'file',\n 'ftp',\n 'http',\n 'https',\n 'intent',\n 'javascript',\n 'jar',\n 'mailto',\n 'sms',\n 'tel',\n 'vbscript',\n]);\n\n/**\n * Validates a `returnScheme` before it is sent to the relay, so a malformed\n * value fails fast in the integrator's own code instead of coming back as a\n * relay 400. The relay re-validates and is the authority.\n *\n * One shape is accepted: a bare custom scheme such as `mydapp://`. It names an\n * app to switch back to, never a page to visit — so hosts, paths and query\n * strings are rejected, and an https URL is not a valid value. A web page has\n * no app to return to and simply omits the field.\n *\n * @param value - Candidate return target\n * @returns `null` when acceptable, otherwise a human-readable error message\n *\n * @internal\n */\nexport function validateReturnScheme(value: unknown): string | null {\n if (typeof value !== 'string') {\n return 'returnScheme must be a string';\n }\n if (value.length === 0) {\n return 'returnScheme must not be empty';\n }\n // Length is checked before any regex so a huge string never reaches the matcher.\n if (value.length > MAX_RETURN_SCHEME_LENGTH) {\n return `returnScheme must be at most ${MAX_RETURN_SCHEME_LENGTH} characters`;\n }\n if (/\\s/.test(value)) {\n return 'returnScheme must not contain whitespace';\n }\n\n const normalized = value.toLowerCase();\n\n if (!BARE_SCHEME_RE.test(normalized)) {\n return 'returnScheme must be a bare custom scheme such as \"mydapp://\" — hosts, paths, query strings and fragments are not accepted, and an https URL is not a return target';\n }\n\n const schemeName = normalized.slice(0, normalized.indexOf(':'));\n if (DENIED_RETURN_SCHEMES.has(schemeName)) {\n return `returnScheme \"${schemeName}\" is not allowed`;\n }\n\n return null;\n}\n\n/**\n * The return target to use when the integrator named none.\n *\n * Only the requesting PAGE can answer \"which browser is this?\" — iOS gives the\n * ZKProofport app nothing to work with (`sourceApplication` is nil across team\n * identifiers, and there is no public API to foreground an app by bundle id).\n * So the detection has to happen here, in the SDK, and travel with the request.\n *\n * Two cases are detected, each from a POSITIVE token, and each verified in the\n * browser's own source to foreground WITHOUT navigating anywhere:\n *\n * Chrome for iOS (`CriOS/`) -> `googlechrome://`\n * Firefox for iOS (`FxiOS/`) -> `firefox://`\n *\n * The BARE scheme is the point in both cases: it carries no URL, so the browser\n * comes forward with nothing to open and the user lands on the tab they were\n * already reading — no new tab, no navigation, no reload, JS state intact.\n *\n * Chrome: `ios/chrome/app/startup/chrome_app_startup_parameters.mm` replaces\n * the scheme with `http`, producing `http://`, which fails GURL validation\n * (`if (!externalURL.is_valid()) return nil;`), so the startup parameters are\n * nil and there is nothing to open.\n *\n * Firefox: `firefox://` has an empty host, and\n * `Coordinators/Router/RouteBuilder.swift` resolves the host through\n * `DeeplinkInput.Host(rawValue: \"\")`, which is nil because no case has an empty\n * raw value (`Coordinators/Router/DeeplinkInput.swift`). The scheme is not http\n * either, so `makeRoute(url:)` falls to its final `else { return nil }`, and\n * `SceneDelegate.handleOpenURL` then hits `guard let route = ... else\n * { return }` and does nothing at all. Verified on the warm path — the browser\n * is already running, which is always true here, because the user came from a\n * page in it.\n *\n * Everything else deliberately returns undefined, and that is not a gap:\n *\n * - Safari has no equivalent. No scheme means \"just come forward\";\n * `https://<url>` navigates and opens a new tab, `x-web-search://` opens a\n * search page. Both lose the user's page.\n * - Brave and Arc for iOS are UNDETECTABLE. Brave ships no UA token and\n * identifies itself only via Client Hints, which WebKit does not implement,\n * so it looks exactly like Safari. Inferring \"Safari\" by elimination and\n * firing a Safari-ish scheme would throw Brave and Arc users into a browser\n * they were not using — strictly worse than doing nothing.\n * - In-app webviews (KakaoTalk, Naver, Line, Instagram) are not tabs at all.\n * Any scheme destroys the page; the system \"< Back to X\" breadcrumb is the\n * only thing that preserves it.\n * - Edge (`EdgiOS`) and Opera (`OPiOS` / `OPT`) for iOS are NOT included.\n * Both are closed source, so `microsoft-edge://` and `opera-http://` cannot\n * be checked the way Chrome's and Firefox's were. Their bare schemes are\n * plausible analogues, and that is exactly why they stay out: an unverified\n * guess that opens a new tab is the bug this field exists to avoid. Add one\n * only with evidence that it foregrounds WITHOUT navigating.\n * - Android needs nothing: the ZKProofport app brings itself to the back\n * (`moveTaskToBack`), which resumes the browser exactly as it was.\n *\n * When this returns undefined the field is omitted and the ZKProofport app\n * tells the user the proof was delivered and to switch back themselves.\n *\n * @param userAgent - override, for tests. Defaults to `navigator.userAgent`.\n * Returns undefined when there is no navigator at all (Node, SSR).\n * @returns a scheme that is safe to open, or undefined to send nothing\n *\n * @internal\n */\nexport function detectReturnScheme(userAgent?: string): string | undefined {\n const ua =\n userAgent ?? (typeof navigator === 'undefined' ? undefined : navigator.userAgent);\n if (typeof ua !== 'string' || ua.length === 0) {\n return undefined;\n }\n // A device token is required alongside the browser token. `CriOS` and `FxiOS`\n // are already iOS-only and unambiguous on their own, but pairing them with the\n // device token costs nothing and stops a synthetic or spoofed desktop user\n // agent from producing a mobile-only scheme.\n if (!/(iPhone|iPad|iPod)/.test(ua)) {\n return undefined;\n }\n if (/CriOS\\//.test(ua)) {\n return 'googlechrome://';\n }\n if (/FxiOS\\//.test(ua)) {\n return 'firefox://';\n }\n return undefined;\n}\n\nexport function validateProofRequest(request: ProofRequest): { valid: boolean; error?: string } {\n if (!request.requestId) {\n return { valid: false, error: 'Missing requestId' };\n }\n\n if (!request.circuit) {\n return { valid: false, error: 'Missing circuit type' };\n }\n\n // The list is the SDK's own, not a copy. The copy that used to sit here\n // had missed circuits, so a link for one was refused as an invalid type\n // while every other layer accepted it.\n if (!isCircuitId(request.circuit)) {\n return {\n valid: false,\n error: `Invalid circuit type: ${request.circuit}. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n };\n }\n\n if (!request.callbackUrl) {\n return { valid: false, error: 'Missing callbackUrl' };\n }\n\n // Validate circuit-specific inputs\n if (request.circuit === 'coinbase_attestation') {\n // Coinbase KYC: userAddress is optional - app will connect wallet if not provided\n const inputs = request.inputs as CoinbaseKycInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n // If userAddress is not provided, app will prompt wallet connection - this is valid\n } else if (request.circuit === 'coinbase_country_attestation') {\n const inputs = request.inputs as CoinbaseCountryInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n return { valid: false, error: 'countryList is required and must be a non-empty array' };\n }\n if (!inputs.countryList.every(c => typeof c === 'string')) {\n return { valid: false, error: 'countryList must contain only strings' };\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n return { valid: false, error: 'isIncluded is required and must be a boolean' };\n }\n } else if (request.circuit === 'oidc_domain_attestation') {\n const inputs = request.inputs as OidcDomainInputs;\n if (!inputs.domain || typeof inputs.domain !== 'string' || inputs.domain.trim() === '') {\n return { valid: false, error: 'domain is required and must be a non-empty string' };\n }\n if (!inputs.scope || typeof inputs.scope !== 'string' || inputs.scope.trim() === '') {\n return { valid: false, error: 'scope is required and must be a non-empty string' };\n }\n if (inputs.provider !== undefined && (typeof inputs.provider !== 'string' || inputs.provider.trim() === '')) {\n return { valid: false, error: 'provider must be a non-empty string when specified' };\n }\n } else if (\n request.circuit === 'mdl_kr_ownership' ||\n request.circuit === 'mdl_kr_age' ||\n request.circuit === 'mdl_kr_region'\n ) {\n const mdlError = validateMdlInputs(request.circuit, request.inputs);\n if (mdlError) {\n return { valid: false, error: mdlError };\n }\n }\n\n // The action, decided by the circuit's own entry rather than by naming a\n // circuit here, so every action-capable circuit is checked the same way.\n {\n const action = (request.inputs as { action?: unknown } | undefined)?.action;\n const binding = circuitActionBinding(request.circuit);\n if (binding === 'none') {\n if (action !== undefined) {\n return {\n valid: false,\n error: `${request.circuit} has no action inputs, so an action sent with it would not be proved. Refusing rather than dropping it.`,\n };\n }\n } else if (binding === 'required' || action !== undefined) {\n const actionError = validateTypedAction(action);\n if (actionError) {\n return { valid: false, error: actionError };\n }\n }\n }\n\n // Check expiry\n if (request.expiresAt && Date.now() > request.expiresAt) {\n return { valid: false, error: 'Request has expired' };\n }\n\n return { valid: true };\n}\n","/**\n * QR Code utilities for ZKProofport SDK\n */\n\nimport QRCode from 'qrcode';\nimport type { ProofRequest, QRCodeOptions } from './types';\nimport { buildProofRequestUrl } from './deeplink';\nimport { DEFAULT_SCHEME, MAX_QR_DATA_SIZE } from './constants';\n\n/**\n * Default QR code options\n */\nconst DEFAULT_QR_OPTIONS: QRCodeOptions = {\n width: 300,\n errorCorrectionLevel: 'M',\n margin: 2,\n darkColor: '#000000',\n lightColor: '#ffffff',\n};\n\n/**\n * Generates a QR code as a base64-encoded PNG data URL.\n *\n * Creates a scannable QR code image from a proof request or deep link URL.\n * The returned data URL can be used directly in HTML img src attributes.\n * Validates that the encoded data doesn't exceed the maximum QR code size.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to base64 PNG data URL (e.g., \"data:image/png;base64,...\")\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n *\n * const dataUrl = await generateQRCodeDataUrl(request, {\n * width: 400,\n * darkColor: '#000000',\n * lightColor: '#ffffff'\n * });\n *\n * // Use in HTML: <img src={dataUrl} alt=\"Scan to prove\" />\n * ```\n */\nexport async function generateQRCodeDataUrl(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n // Check data size\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toDataURL(url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Generates a QR code as an SVG string.\n *\n * Creates a scalable vector graphics QR code that can be embedded directly in HTML\n * or saved to a file. SVG QR codes scale perfectly at any size and have smaller\n * file sizes than raster formats.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to SVG markup string\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const svg = await generateQRCodeSVG(request, { width: 300 });\n *\n * // Embed directly: <div dangerouslySetInnerHTML={{ __html: svg }} />\n * // Or save to file: fs.writeFileSync('qr.svg', svg);\n * ```\n */\nexport async function generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toString(url, {\n type: 'svg',\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Browser-only function that draws a QR code onto an existing canvas element.\n * Useful for interactive applications or when you need direct canvas manipulation.\n * The canvas dimensions will be set automatically based on the width option.\n *\n * @param canvas - HTML canvas element to render to (must exist in DOM)\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise that resolves when rendering is complete\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n * @throws {Error} If canvas is not a valid HTMLCanvasElement (browser only)\n *\n * @example\n * ```typescript\n * // In a React component:\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n *\n * useEffect(() => {\n * if (canvasRef.current) {\n * generateQRCodeToCanvas(canvasRef.current, request, { width: 400 });\n * }\n * }, [request]);\n *\n * return <canvas ref={canvasRef} />;\n * ```\n */\nexport async function generateQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<void> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n await QRCode.toCanvas(canvas, url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Estimates the byte size of a QR code's encoded data.\n *\n * Calculates the size of the deep link URL that will be encoded in the QR code,\n * and checks if it's within the maximum supported size (2953 bytes for QR version 40\n * with medium error correction). Use this before generating QR codes to avoid errors.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Object with `size` in bytes and `withinLimit` boolean flag\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const { size, withinLimit } = estimateQRDataSize(request);\n *\n * if (!withinLimit) {\n * console.error(`QR code too large: ${size} bytes (max 2953)`);\n * // Consider reducing request data or splitting into multiple QR codes\n * }\n *\n * // Example output: { size: 384, withinLimit: true }\n * ```\n */\nexport function estimateQRDataSize(\n requestOrUrl: ProofRequest | string,\n scheme: string = DEFAULT_SCHEME\n): { size: number; withinLimit: boolean } {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n return {\n size: url.length,\n withinLimit: url.length <= MAX_QR_DATA_SIZE,\n };\n}\n","/**\n * Off-chain proof verification — checking a proof against its verification key,\n * with no chain, no RPC, and no gas.\n *\n * WHY THIS EXISTS. The SDK had only `verifyProofOnChain`, and every caller that\n * wanted an off-chain check called that instead and relabelled the result. The\n * demo page did exactly this from its first commit: pressing \"Off-Chain Verify\"\n * ran an on-chain verification and printed \"Off-Chain Verification Passed!\".\n * The answer was true and the label was a lie, which is the worst combination —\n * nothing looked broken. The mobile app has always verified off-chain properly\n * (through mopro's native Barretenberg); it was only the JavaScript side that\n * had no such thing.\n *\n * HOW IT WORKS. Proofs here are made for the EVM target (`bb prove -t evm`:\n * keccak transcript, ZK on), so the matching check is bb.js's\n * `UltraHonkVerifierBackend.verifyProof(..., { verifierTarget: 'evm' })`. Two\n * things have to line up:\n *\n * The version. `@aztec/bb.js` must be the WASM build of the same bb the\n * circuits are compiled with -- `BB_VERSION` in circuits/toolchain.env,\n * 4.2.0-aztecnr-rc.2 since the beta.19 toolchain. Versions are not\n * interchangeable: on the Korea Mobile ID age circuit the 2025 nightly wrote\n * a 16256-byte proof where bb 1.2.0 wrote 16224 for the identical circuit and\n * witness, with the SAME verification key, so the key cannot warn you. A\n * mismatch shows up only as verification failing.\n *\n * The target. Verifying an EVM proof as any other target is not a polite\n * false. With the 2025 nightly, keccak-without-ZK trapped the WebAssembly\n * with a bare \"unreachable\" and the poseidon flavour answered false for a\n * good proof.\n *\n * THE PROOF ARRIVES IN TWO PIECES. The mobile app splits what Barretenberg\n * produced into `proof` and `publicInputs` before sending it, because the\n * Solidity verifier takes them separately. bb.js 4.x's verifier takes the same\n * two pieces, so nothing is joined back here.\n */\nimport { CIRCUIT_VK_PATHS, type CircuitId } from './circuits';\n\n/**\n * Where verification keys are published.\n *\n * Not configurable, deliberately: a caller who could point this somewhere else\n * could point it at a key of their choosing, and \"the proof verified\" would\n * then mean nothing. Same repository the mobile app downloads circuit data\n * from.\n */\nconst CIRCUITS_VK_BASE =\n 'https://raw.githubusercontent.com/zkproofport/circuits/main';\n\n/** How long a fetched verification key is reused. Keys change only on a recompile. */\nconst VK_CACHE_TTL_MS = 60 * 60 * 1000;\n\nconst vkCache = new Map<string, { vk: Uint8Array; at: number }>();\n\nexport interface OffChainVerifyResult {\n valid: boolean;\n error?: string;\n}\n\nexport interface OffChainVerifyOptions {\n /**\n * Verification key bytes, if the caller already has them. Skips the fetch —\n * useful offline, in tests, and for anyone who would rather pin the key they\n * checked than trust a download.\n */\n verificationKey?: Uint8Array;\n /** Milliseconds before the fetch is abandoned. Default 30000. */\n timeoutMs?: number;\n}\n\n/**\n * Make sure a Node-shaped `Buffer` exists before Barretenberg is loaded.\n *\n * WHY THE SDK DOES THIS RATHER THAN THE CALLER. bb.js's own BROWSER build —\n * not just its node build — converts field elements through `Buffer.alloc` and\n * `buf.writeBigUInt64BE`. Browsers have no Buffer, and bundlers stopped\n * polyfilling Node globals years ago, so in a browser the first verification\n * dies with \"r.writeBigUInt64BE is not a function\" — a message that names\n * nothing a caller could act on. Measured on the demo page, 2026-09-04, against\n * a real GIWA proof.\n *\n * Leaving it to callers would mean every browser customer editing their\n * bundler config to make an SDK method work, which is the configuration this\n * SDK promises not to require.\n *\n * Deliberately narrow:\n * - It only fills a GAP. A real Buffer (Node, or a page that already has one)\n * is left alone, so nothing is shadowed by a lesser implementation.\n * - It checks for the METHOD, not just the global. A partial Buffer — which is\n * what several bundlers leave behind, and what the demo page actually had —\n * passes a `typeof Buffer` test and then fails inside Barretenberg.\n */\nasync function ensureBufferForBarretenberg(): Promise<void> {\n const existing = (globalThis as { Buffer?: { alloc?: (n: number) => unknown } }).Buffer;\n if (existing?.alloc) {\n const probe = existing.alloc(8) as { writeBigUInt64BE?: unknown };\n if (typeof probe.writeBigUInt64BE === 'function') return;\n }\n const { Buffer } = await import('buffer/');\n (globalThis as { Buffer?: unknown }).Buffer = Buffer;\n}\n\n/** @internal Hex string (with or without 0x) to bytes. */\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length === 0) return new Uint8Array(0);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has an odd length (${clean.length}); it cannot be bytes`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('Hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.substr(i * 2, 2), 16);\n }\n return out;\n}\n\n/**\n * @internal Public inputs as 32-byte big-endian field elements in hex, the\n * shape bb.js's verifier takes.\n *\n * The relay carries them as hex strings that are USUALLY already 32 bytes, but\n * a value that happens to have leading zeros can arrive short (`0x01`). Left-\n * padding here rather than trusting the sender is the difference between a\n * verification that works and one that fails on roughly one proof in a hundred,\n * for no reason the caller can see.\n */\nfunction normalisePublicInputs(publicInputs: string[]): string[] {\n return publicInputs.map((input, i) => {\n const bytes = hexToBytes(input);\n if (bytes.length > 32) {\n throw new Error(\n `Public input ${i} is ${bytes.length} bytes; a field element is at most 32`\n );\n }\n const padded = new Uint8Array(32);\n padded.set(bytes, 32 - bytes.length);\n return '0x' + Array.from(padded, b => b.toString(16).padStart(2, '0')).join('');\n });\n}\n\n/**\n * Fetch a circuit's verification key, with a small cache.\n *\n * @internal\n */\nasync function fetchVerificationKey(\n circuit: CircuitId,\n timeoutMs: number\n): Promise<Uint8Array> {\n const cached = vkCache.get(circuit);\n if (cached && Date.now() - cached.at < VK_CACHE_TTL_MS) return cached.vk;\n\n const vkPath = CIRCUIT_VK_PATHS[circuit];\n if (!vkPath) {\n throw new Error(\n `No verification key path for circuit '${circuit}'. ` +\n `Add it to CIRCUIT_VK_PATHS, or pass verificationKey directly.`\n );\n }\n\n const url = `${CIRCUITS_VK_BASE}/${vkPath}`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const resp = await fetch(url, { signal: controller.signal });\n if (!resp.ok) {\n throw new Error(`Could not fetch the verification key (HTTP ${resp.status}) from ${url}`);\n }\n const vk = new Uint8Array(await resp.arrayBuffer());\n // A 404 page or an HTML redirect arrives as a successful response full of\n // text, and would reach Barretenberg as a \"verification key\" that fails for\n // reasons no one could guess from the message.\n if (vk.length < 512) {\n throw new Error(\n `The verification key at ${url} is ${vk.length} bytes, far too small to be one. ` +\n `The path is probably wrong and something else was served.`\n );\n }\n vkCache.set(circuit, { vk, at: Date.now() });\n return vk;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Verify a proof off-chain, against its verification key.\n *\n * Needs no setup from the caller: the verifier ships with this SDK and is\n * loaded on first use.\n *\n * @param circuit - Canonical circuit identifier\n * @param proof - Proof bytes as hex, WITHOUT public inputs (as the relay sends it)\n * @param publicInputs - Public inputs as hex strings, in circuit order\n * @param options - Optional verification key and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` when the check could not run\n *\n * @example\n * ```typescript\n * const result = await verifyProofOffChain(\n * 'coinbase_attestation',\n * response.proof,\n * response.publicInputs\n * );\n * if (result.valid) console.log('Proof is valid, no chain involved');\n * ```\n */\nexport async function verifyProofOffChain(\n circuit: CircuitId,\n proof: string,\n publicInputs: string[],\n options: OffChainVerifyOptions = {}\n): Promise<OffChainVerifyResult> {\n const timeoutMs = options.timeoutMs ?? 30000;\n\n // A REQUIRED dependency, loaded lazily.\n //\n // It was briefly an optional peer dependency, on the reasoning that the WASM\n // is 16MB and most callers verify on-chain. That was wrong: it would have\n // meant a customer calling this method got an error telling them to install\n // something, and \"works with zero customer configuration\" is the SDK's rule.\n // A caller should never have to know this is implemented with Barretenberg.\n //\n // The dynamic import is what keeps the cost off everyone else — a bundler\n // splits it out, and a caller who never verifies off-chain never loads it.\n // Before bb.js, not after: its module-level code already reaches for Buffer.\n await ensureBufferForBarretenberg();\n\n let bb: typeof import('@aztec/bb.js');\n try {\n bb = await import('@aztec/bb.js');\n } catch (error) {\n // Reaching here means the install is broken, not that something is missing\n // by design. Say so, rather than sending the caller off to install a\n // package they should never have had to hear about.\n return {\n valid: false,\n error:\n 'Could not load the proof verifier (@aztec/bb.js), which ships with this ' +\n 'SDK. This usually means a broken or partial install — try reinstalling ' +\n `@zkproofport-app/sdk. Underlying error: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n let api: { destroy(): Promise<void> } | undefined;\n try {\n const proofBytes = hexToBytes(proof);\n if (proofBytes.length === 0) {\n return { valid: false, error: 'Proof is empty' };\n }\n // Normalised to 32-byte big-endian fields before handing them over: the\n // relay can deliver a short value (`0x01`), and the check below must see\n // exactly what the circuit committed to.\n const fields = normalisePublicInputs(publicInputs);\n\n const vk =\n options.verificationKey ?? (await fetchVerificationKey(circuit, timeoutMs));\n\n const barretenberg = await bb.Barretenberg.new({ threads: 1 });\n api = barretenberg;\n const verifier = new bb.UltraHonkVerifierBackend(barretenberg);\n const valid = await verifier.verifyProof(\n { proof: proofBytes, publicInputs: fields, verificationKey: vk },\n { verifierTarget: 'evm' }\n );\n return { valid };\n } catch (error) {\n return { valid: false, error: error instanceof Error ? error.message : String(error) };\n } finally {\n // The WASM instance holds worker threads; leaving them running keeps a Node\n // process alive after the check is done.\n if (api) {\n try {\n await api.destroy();\n } catch {\n /* nothing useful to do if teardown fails */\n }\n }\n }\n}\n\n/** @internal Test seam — lets a test start from a known-empty cache. */\nexport function clearVerificationKeyCache(): void {\n vkCache.clear();\n}\n","import type { RelayTerminalStatus } from './types';\n\n/**\n * The statuses a relay request ends in, as a runtime list. `satisfies` keeps it\n * in step with the `RelayTerminalStatus` type in both directions: a status\n * added to the type and not here, or here and not in the type, fails to compile.\n */\nexport const RELAY_TERMINAL_STATUSES = ['completed', 'error', 'failed', 'cancelled', 'expired'] as const satisfies readonly RelayTerminalStatus[];\n\ntype Missing = Exclude<RelayTerminalStatus, typeof RELAY_TERMINAL_STATUSES[number]>;\nconst everyStatusListed: Missing extends never ? true : Missing = true;\nvoid everyStatusListed;\n\n/** True when `status` is one a relay request ends in. */\nexport function isTerminalRelayStatus(status: string): status is RelayTerminalStatus {\n return (RELAY_TERMINAL_STATUSES as readonly string[]).includes(status);\n}\n","/**\n * Proofport SDK - Main class\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitType,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n ProofportConfig,\n QRCodeOptions,\n ParsedProof,\n VerifierContract,\n ChallengeResponse,\n WalletSigner,\n RelayProofRequest,\n RelayProofResult,\n} from './types';\nimport {\n generateRequestId,\n buildProofRequestUrl,\n buildCallbackUrl,\n parseProofRequestUrl,\n parseProofResponseUrl,\n validateProofRequest,\n validateMdlInputs,\n validateReturnScheme,\n detectReturnScheme,\n isProofportDeepLink,\n} from './deeplink';\nimport {\n generateQRCodeDataUrl,\n generateQRCodeSVG,\n generateQRCodeToCanvas,\n estimateQRDataSize,\n} from './qrcode';\nimport {\n verifyProofOnChain,\n parseProofForOnChain,\n getVerifierAddress,\n getVerifierChainId,\n getDefaultProvider,\n extractScopeFromPublicInputs,\n extractNullifierFromPublicInputs,\n extractDomainFromPublicInputs,\n} from './verifier';\nimport {\n verifyProofOffChain,\n type OffChainVerifyOptions,\n} from './offChainVerifier';\nimport {\n DEFAULT_SCHEME,\n DEFAULT_REQUEST_EXPIRY_MS,\n CIRCUIT_METADATA,\n RELAY_URLS,\n} from './constants';\nimport { CIRCUIT_NEEDS_WALLET_SIGNATURE, circuitActionBinding, type CircuitId } from './circuits';\nimport { validateTypedAction } from './typedAction';\nimport { isTerminalRelayStatus } from './relayStatus';\nimport type { SDKEnvironment } from './types';\n\n\n/**\n * Main SDK class for interacting with the ZKProofport mobile app.\n *\n * Provides methods for creating proof requests, generating QR codes and deep links,\n * verifying proofs on-chain, and handling proof responses from the mobile app.\n *\n * @example\n * ```typescript\n * import { ProofportSDK } from '@zkproofport-app/sdk';\n * import { BrowserProvider } from 'ethers';\n *\n * // Initialize SDK (uses production relay by default)\n * const sdk = ProofportSDK.create();\n *\n * // Set wallet signer for challenge-signature auth\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n *\n * // Create proof request via relay\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * });\n *\n * // Generate QR code for desktop users\n * const qrDataUrl = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof via WebSocket (primary) or polling (fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof received:', result.proof);\n * }\n * ```\n */\nexport class ProofportSDK {\n private config: Required<Omit<ProofportConfig, 'relayUrl'>>;\n private pendingRequests: Map<string, ProofRequest> = new Map();\n private signer: WalletSigner | null = null;\n private relayUrl: string;\n private socket: any = null;\n\n /**\n * Creates a new ProofportSDK instance.\n *\n * For most use cases, prefer the static factory with environment presets:\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * ```\n *\n * @param config - SDK configuration options\n * @param config.scheme - Custom deep link scheme (default: 'zkproofport')\n * @param config.relayUrl - Relay server URL (required for relay features)\n * @param config.verifiers - Custom verifier contract addresses per circuit\n *\n * @example\n * ```typescript\n * const sdk = new ProofportSDK({\n * relayUrl: 'https://relay.zkproofport.app',\n * verifiers: {\n * coinbase_attestation: {\n * verifierAddress: '0x...',\n * chainId: 1\n * }\n * }\n * });\n * ```\n */\n constructor(config: ProofportConfig = {}) {\n this.config = {\n scheme: config.scheme || DEFAULT_SCHEME,\n verifiers: config.verifiers || {},\n };\n this.relayUrl = config.relayUrl || '';\n }\n\n // ============ Request Creation ============\n\n /**\n * @internal\n * Creates a Coinbase KYC verification proof request.\n *\n * Generates a proof request for verifying Coinbase KYC status without revealing\n * the actual attestation data. The proof confirms the user has passed Coinbase KYC\n * while maintaining privacy through zero-knowledge proofs.\n *\n * @param inputs - Circuit inputs for Coinbase KYC\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your KYC status to access this feature'\n * });\n *\n * const deepLink = sdk.getDeepLinkUrl(request);\n * ```\n */\n private createCoinbaseKycRequest(\n inputs: CoinbaseKycInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!inputs.scope) {\n throw new Error('scope is required for coinbase_attestation circuit');\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit: 'coinbase_attestation',\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a Coinbase Country attestation proof request.\n *\n * Generates a proof request for verifying country eligibility through Coinbase\n * attestation without revealing the actual country data. The proof confirms the\n * user's country status while maintaining privacy through zero-knowledge proofs.\n *\n * @param inputs - Circuit inputs for Coinbase Country attestation\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseCountryRequest({\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your country eligibility'\n * });\n * ```\n */\n private createCoinbaseCountryRequest(\n inputs: CoinbaseCountryInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!inputs.scope) {\n throw new Error('scope is required for coinbase_country_attestation circuit');\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n throw new Error('countryList is required for coinbase_country_attestation circuit');\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n throw new Error('isIncluded is required for coinbase_country_attestation circuit');\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit: 'coinbase_country_attestation',\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a generic proof request for any supported circuit type.\n *\n * Routes to the appropriate circuit-specific request creation method based on\n * the circuit type. Use this for dynamic circuit selection or when the circuit\n * type is determined at runtime.\n *\n * @param circuit - Circuit type identifier ('coinbase_attestation' | 'coinbase_country_attestation')\n * @param inputs - Circuit-specific inputs\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 15 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if required inputs are missing for the specified circuit\n *\n * @example\n * ```typescript\n * const circuitType = userSelection; // Dynamic selection\n * const request = sdk.createProofRequest(\n * circuitType,\n * { scope: 'myapp.com' },\n * { dappName: 'My DApp' }\n * );\n * ```\n */\n private createProofRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (circuit === 'coinbase_country_attestation') {\n return this.createCoinbaseCountryRequest(inputs as CoinbaseCountryInputs, options);\n } else if (\n circuit === 'mdl_kr_ownership' ||\n circuit === 'mdl_kr_age' ||\n circuit === 'mdl_kr_region'\n ) {\n return this.createMdlKrRequest(circuit, inputs, options);\n } else {\n return this.createCoinbaseKycRequest(inputs as CoinbaseKycInputs, options);\n }\n }\n\n /**\n * @internal\n * Creates a Korea Mobile ID (mDL) proof request for any of the three\n * mDL predicate circuits (ownership / age / region).\n *\n * The mobile app collects the license data on-device; the dapp only\n * supplies the predicate parameters validated here. No wallet signature\n * is required for mDL circuits.\n *\n * @param circuit - 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region'\n * @param inputs - Predicate inputs (see MdlKr*Inputs types)\n * @param options - Request configuration options\n *\n * @throws Error if the predicate inputs fail validation\n */\n private createMdlKrRequest(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit,\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n // ============ Deep Link Generation ============\n\n /**\n * @internal\n * Generates a deep link URL for a proof request.\n *\n * Creates a zkproofport:// URL that opens the ZKProofport mobile app with the\n * specified proof request. The URL contains all request details encoded as query\n * parameters.\n *\n * @param request - ProofRequest object to encode as deep link\n *\n * @returns Deep link URL string (e.g., 'zkproofport://proof?requestId=...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const url = sdk.getDeepLinkUrl(request);\n * // url: 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...'\n * ```\n */\n private getDeepLinkUrl(request: ProofRequest): string {\n return buildProofRequestUrl(request, this.config.scheme);\n }\n\n /**\n * @internal\n * Opens the ZKProofport mobile app with a proof request.\n *\n * Redirects the browser to the deep link URL, which opens the ZKProofport app\n * if installed. Only works in mobile browser environments. For desktop, use\n * requestProof() to display a QR code instead.\n *\n * @param request - ProofRequest object to send to the app\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * if (ProofportSDK.isMobile()) {\n * sdk.openProofRequest(request); // Opens app directly\n * }\n * ```\n */\n private openProofRequest(request: ProofRequest): void {\n const url = this.getDeepLinkUrl(request);\n window.location.href = url;\n }\n\n /**\n * @internal\n * Requests a proof with automatic platform detection.\n *\n * Detects whether the user is on mobile or desktop and automatically chooses\n * the appropriate flow:\n * - Mobile: Opens the deep link directly to launch the ZKProofport app\n * - Desktop: Generates a QR code data URL for the user to scan\n *\n * @param request - ProofRequest object to send\n * @param qrOptions - QR code generation options (size, colors, logo) for desktop\n *\n * @returns Object containing deep link URL, optional QR code data URL, and platform detection result\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const result = await sdk.requestProof(request);\n *\n * if (result.mobile) {\n * console.log('Opening app directly');\n * } else {\n * // Display QR code for desktop users\n * document.getElementById('qr').src = result.qrDataUrl;\n * }\n * ```\n */\n private async requestProof(\n request: ProofRequest,\n qrOptions?: QRCodeOptions\n ): Promise<{ deepLink: string; qrDataUrl?: string; mobile: boolean }> {\n const deepLink = this.getDeepLinkUrl(request);\n const mobile = ProofportSDK.isMobile();\n\n if (mobile) {\n window.location.href = deepLink;\n return { deepLink, mobile: true };\n }\n\n const qrDataUrl = await this.generateQRCode(request, qrOptions);\n return { deepLink, qrDataUrl, mobile: false };\n }\n\n // ============ QR Code Generation ============\n\n /**\n * Generates a QR code as a data URL for a proof request.\n *\n * Creates a PNG image data URL that can be directly set as an img src attribute.\n * Suitable for embedding QR codes in web pages for desktop users to scan with\n * their mobile device.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n * @param options.logoUrl - Optional center logo image URL\n * @param options.logoSize - Logo size as fraction of QR code (default: 0.2)\n *\n * @returns Promise resolving to PNG data URL (e.g., 'data:image/png;base64,...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const qrUrl = await sdk.generateQRCode(request, {\n * size: 400,\n * darkColor: '#1a1a1a',\n * logoUrl: 'https://myapp.com/logo.png'\n * });\n * document.getElementById('qr-image').src = qrUrl;\n * ```\n */\n async generateQRCode(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeDataUrl(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Generates a QR code as an SVG string for a proof request.\n *\n * Creates a scalable vector graphics representation of the QR code, ideal for\n * high-resolution displays or when vector format is preferred over raster images.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise resolving to SVG string\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const svgString = await sdk.generateQRCodeSVG(request);\n * document.getElementById('qr-container').innerHTML = svgString;\n * ```\n */\n async generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeSVG(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Draws the QR code onto the provided canvas element, useful for custom\n * rendering workflows or when you need direct canvas manipulation.\n *\n * @param canvas - HTML canvas element to render to\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise that resolves when rendering is complete\n *\n * @example\n * ```typescript\n * const canvas = document.getElementById('qr-canvas') as HTMLCanvasElement;\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * await sdk.renderQRCodeToCanvas(canvas, request, { size: 400 });\n * ```\n */\n async renderQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<void> {\n return generateQRCodeToCanvas(canvas, requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Checks if a proof request fits within QR code size limits.\n *\n * Estimates the encoded data size and validates it against QR code capacity limits.\n * Useful for validating requests before generating QR codes, especially when\n * including large custom messages or metadata.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n *\n * @returns Object with size in bytes and whether it fits within limits\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const check = sdk.checkQRCodeSize(request);\n * if (!check.withinLimit) {\n * console.warn(`Request too large: ${check.size} bytes`);\n * }\n * ```\n */\n checkQRCodeSize(requestOrUrl: ProofRequest | string): { size: number; withinLimit: boolean } {\n return estimateQRDataSize(requestOrUrl, this.config.scheme);\n }\n\n // ============ Response Handling ============\n\n /**\n * @internal\n * Parses a proof response from a callback URL.\n *\n * Extracts and decodes proof response data from the callback URL query parameters\n * after the user completes proof generation in the ZKProofport app. The app\n * redirects to your callback URL with the proof data encoded as query parameters.\n *\n * @param url - Callback URL containing proof response data\n *\n * @returns ProofResponse object with status, proof data, and public inputs, or null if invalid\n *\n * @example\n * ```typescript\n * // In your callback endpoint handler\n * app.get('/callback', (req, res) => {\n * const callbackUrl = req.url;\n * const response = sdk.parseResponse(callbackUrl);\n *\n * if (response?.status === 'completed') {\n * console.log('Proof received:', response.proof);\n * console.log('Public inputs:', response.publicInputs);\n * } else if (response?.status === 'rejected') {\n * console.log('User rejected the request');\n * }\n * });\n * ```\n */\n private parseResponse(url: string): ProofResponse | null {\n return parseProofResponseUrl(url);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport proof response callback.\n *\n * Validates whether the given URL contains the required query parameters for a\n * proof response. Useful for filtering and routing callback requests.\n *\n * @param url - URL to check\n *\n * @returns True if the URL appears to be a ZKProofport response callback\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n * if (sdk.isProofportResponse(fullUrl)) {\n * const response = sdk.parseResponse(fullUrl);\n * // Handle proof response\n * }\n * });\n * ```\n */\n private isProofportResponse(url: string): boolean {\n try {\n const urlObj = new URL(url);\n return urlObj.searchParams.has('requestId') && urlObj.searchParams.has('status');\n } catch {\n return false;\n }\n }\n\n /**\n * @internal\n * Retrieves a pending proof request by its ID.\n *\n * Looks up a previously created proof request from the SDK's internal cache.\n * Useful for validating callback responses and maintaining request state.\n *\n * @param requestId - Unique request identifier\n *\n * @returns ProofRequest object if found, undefined otherwise\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * const originalRequest = sdk.getPendingRequest(response.requestId);\n *\n * if (originalRequest) {\n * console.log('Original request:', originalRequest);\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private getPendingRequest(requestId: string): ProofRequest | undefined {\n return this.pendingRequests.get(requestId);\n }\n\n /**\n * @internal\n * Clears a pending proof request from the internal cache.\n *\n * Removes a proof request from the SDK's pending requests map. Should be called\n * after successfully processing a proof response to prevent memory leaks.\n *\n * @param requestId - Unique request identifier to remove\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * if (response?.status === 'completed') {\n * // Process proof...\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private clearPendingRequest(requestId: string): void {\n this.pendingRequests.delete(requestId);\n }\n\n // ============ Verification ============\n\n /**\n * Verifies a zero-knowledge proof on-chain using the deployed verifier contract.\n *\n * Calls the Solidity verifier contract to cryptographically verify the proof's\n * validity. This ensures the proof was generated correctly and the public inputs\n * match the claimed values.\n *\n * @param circuit - Circuit type identifier\n * @param proof - Hex-encoded proof string from the ZKProofport app\n * @param publicInputs - Array of hex-encoded public input strings\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * const response = sdk.parseResponse(callbackUrl);\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyOnChain(\n * response.circuit,\n * response.proof,\n * response.publicInputs,\n * provider\n * );\n *\n * if (result.valid) {\n * console.log('Proof verified on-chain!');\n * } else {\n * console.error('Verification failed:', result.error);\n * }\n * }\n * ```\n */\n async verifyOnChain(\n circuit: CircuitType,\n proof: string,\n publicInputs: string[],\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n const parsedProof = parseProofForOnChain(\n proof,\n publicInputs,\n publicInputs.length\n );\n\n const customVerifier = this.config.verifiers[circuit];\n return verifyProofOnChain(circuit, parsedProof, providerOrSigner, customVerifier);\n }\n\n /**\n * Verifies a proof response on-chain using the deployed verifier contract.\n *\n * Convenience method that extracts proof data from a ProofResponse object and\n * verifies it on-chain. Automatically handles incomplete or rejected responses.\n *\n * @param response - ProofResponse object from parseResponse()\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * app.get('/callback', async (req, res) => {\n * const response = sdk.parseResponse(req.url);\n *\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyResponseOnChain(response, provider);\n *\n * if (result.valid) {\n * // Grant access to user\n * res.json({ success: true, verified: true });\n * } else {\n * res.status(400).json({ error: result.error });\n * }\n * } else {\n * res.status(400).json({ error: 'Proof generation failed or rejected' });\n * }\n * });\n * ```\n */\n async verifyResponseOnChain(\n response: ProofResponse,\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n\n const parsedProof = parseProofForOnChain(\n response.proof,\n response.publicInputs,\n response.publicInputs.length\n );\n\n const customVerifier = this.config.verifiers[response.circuit];\n const responseVerifier = {\n verifierAddress: response.verifierAddress,\n chainId: response.chainId,\n };\n return verifyProofOnChain(response.circuit, parsedProof, providerOrSigner, customVerifier, responseVerifier);\n }\n\n /**\n * Verifies a proof response off-chain, against the circuit's verification key.\n *\n * No chain, no RPC, no gas, and no verifier contract — so this works for a\n * circuit whose verifier has not been deployed anywhere, and it does not\n * depend on a network being reachable. What it does not give you is the\n * chain's own opinion: use {@link verifyResponseOnChain} when the answer has\n * to be one a contract will agree with.\n *\n * Needs no setup: the verifier ships with this SDK. It is loaded on first\n * use, so a caller who only verifies on-chain never pays for it.\n *\n * @param response - Proof response from the relay\n * @param options - Optional verification key (skips the fetch) and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` if the check could not run\n *\n * @example\n * ```typescript\n * const result = await sdk.verifyResponseOffChain(response);\n * if (result.valid) {\n * console.log('Valid, and nothing was asked of any chain');\n * }\n * ```\n */\n async verifyResponseOffChain(\n response: ProofResponse,\n options?: OffChainVerifyOptions\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n return verifyProofOffChain(\n response.circuit,\n response.proof,\n response.publicInputs,\n options\n );\n }\n\n // ============ Utility Methods ============\n\n /**\n * Gets the deployed verifier contract address for a circuit.\n *\n * Returns the Ethereum address of the Solidity verifier contract for the\n * specified circuit. Uses custom verifier if configured, otherwise returns\n * the default deployed address.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Ethereum address of the verifier contract (0x...)\n *\n * @example\n * ```typescript\n * const address = sdk.getVerifierAddress('coinbase_attestation');\n * console.log('Verifier deployed at:', address);\n * ```\n */\n getVerifierAddress(circuit: CircuitType): string {\n const customVerifier = this.config.verifiers[circuit];\n return getVerifierAddress(circuit, customVerifier);\n }\n\n /**\n * Gets the blockchain chain ID where the verifier contract is deployed.\n *\n * Returns the EIP-155 chain ID for the network where the verifier contract\n * is deployed. Uses custom verifier if configured, otherwise returns the\n * default chain ID (Base mainnet: 8453).\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Chain ID number (e.g., 8453 for Base mainnet)\n *\n * @example\n * ```typescript\n * const chainId = sdk.getVerifierChainId('coinbase_attestation');\n * console.log('Verifier on chain:', chainId); // 8453 (Base mainnet)\n * ```\n */\n getVerifierChainId(circuit: CircuitType): number {\n const customVerifier = this.config.verifiers[circuit];\n return getVerifierChainId(circuit, customVerifier);\n }\n\n /**\n * Gets metadata for a specific circuit type.\n *\n * Returns circuit metadata including display name, description, required inputs,\n * and other configuration details.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Circuit metadata object with name, description, and configuration\n *\n * @example\n * ```typescript\n * const metadata = sdk.getCircuitMetadata('coinbase_attestation');\n * console.log('Circuit name:', metadata.name);\n * console.log('Description:', metadata.description);\n * ```\n */\n getCircuitMetadata(circuit: CircuitType) {\n return CIRCUIT_METADATA[circuit];\n }\n\n /**\n * Gets all supported circuit types.\n *\n * Returns an array of all circuit type identifiers that are currently supported\n * by the SDK and ZKProofport app.\n *\n * @returns Array of supported circuit type identifiers\n *\n * @example\n * ```typescript\n * const circuits = sdk.getSupportedCircuits();\n * console.log('Supported circuits:', circuits);\n * // ['coinbase_attestation', 'coinbase_country_attestation']\n * ```\n */\n getSupportedCircuits(): CircuitType[] {\n return Object.keys(CIRCUIT_METADATA) as CircuitType[];\n }\n\n /**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Checks that the proof request contains all required fields and that the\n * circuit-specific inputs are valid. Useful for catching configuration errors\n * before generating QR codes or sending requests to users.\n *\n * @param request - ProofRequest object to validate\n *\n * @returns Validation result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const validation = sdk.validateRequest(request);\n *\n * if (!validation.valid) {\n * console.error('Invalid request:', validation.error);\n * }\n * ```\n */\n private validateRequest(request: ProofRequest): { valid: boolean; error?: string } {\n return validateProofRequest(request);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport deep link.\n *\n * Validates whether the given URL uses the ZKProofport deep link scheme\n * (zkproofport:// by default) and has the correct format for a proof request.\n *\n * @param url - URL string to check\n *\n * @returns True if the URL is a valid ZKProofport deep link\n *\n * @example\n * ```typescript\n * const url = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation';\n * if (sdk.isProofportDeepLink(url)) {\n * const request = sdk.parseDeepLink(url);\n * console.log('Parsed request:', request);\n * }\n * ```\n */\n private isProofportDeepLink(url: string): boolean {\n return isProofportDeepLink(url, this.config.scheme);\n }\n\n /**\n * @internal\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a zkproofport:// deep link URL.\n * Useful for handling deep link navigation in web applications or validating\n * deep link URLs before displaying QR codes.\n *\n * @param url - ZKProofport deep link URL string\n *\n * @returns ProofRequest object with all request details, or null if invalid\n *\n * @example\n * ```typescript\n * const deepLink = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...';\n * const request = sdk.parseDeepLink(deepLink);\n *\n * if (request) {\n * console.log('Request ID:', request.requestId);\n * console.log('Circuit:', request.circuit);\n * }\n * ```\n */\n private parseDeepLink(url: string): ProofRequest | null {\n return parseProofRequestUrl(url);\n }\n\n // ============ Static Factory ============\n\n /**\n * Creates a new ProofportSDK instance with environment preset or custom config.\n * Defaults to `'production'` if no argument is provided.\n *\n * **Recommended usage** — use the default production relay:\n * ```typescript\n * const sdk = ProofportSDK.create();\n * ```\n *\n * Environment presets:\n * - `'production'` — relay.zkproofport.app (default)\n * - `'staging'` — stg-relay.zkproofport.app\n * - `'local'` — localhost:4001\n *\n * @param envOrConfig - Environment name or custom SDK configuration\n *\n * @returns New ProofportSDK instance\n *\n * @example\n * ```typescript\n * // Environment preset (recommended)\n * const sdk = ProofportSDK.create(); // production (default)\n * const sdk = ProofportSDK.create('staging');\n *\n * // Custom config\n * const sdk = ProofportSDK.create({\n * relayUrl: 'https://my-custom-relay.example.com',\n * });\n * ```\n */\n static create(envOrConfig?: SDKEnvironment | ProofportConfig): ProofportSDK {\n if (typeof envOrConfig === 'undefined') {\n return new ProofportSDK({ relayUrl: RELAY_URLS.production });\n }\n if (typeof envOrConfig === 'string') {\n const relayUrl = RELAY_URLS[envOrConfig];\n if (!relayUrl) {\n throw new Error(`Unknown environment: ${envOrConfig}. Use 'production', 'staging', or 'local'.`);\n }\n return new ProofportSDK({ relayUrl });\n }\n return new ProofportSDK(envOrConfig);\n }\n\n /**\n * Detects if the code is running on a mobile device.\n *\n * Uses user agent detection to determine if the current environment is a mobile\n * browser. This helps the SDK automatically choose between direct deep link\n * navigation (mobile) and QR code display (desktop).\n *\n * @returns True if running on a mobile device (iOS, Android, etc.)\n *\n * @example\n * ```typescript\n * if (ProofportSDK.isMobile()) {\n * // Open deep link directly\n * sdk.openProofRequest(request);\n * } else {\n * // Show QR code\n * const qr = await sdk.generateQRCode(request);\n * displayQRCode(qr);\n * }\n * ```\n */\n static isMobile(): boolean {\n if (typeof navigator === 'undefined') return false;\n return /Android|iPhone|iPad|iPod|webOS|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n }\n\n // ============ Relay Integration ============\n\n /**\n * Sets the wallet signer for challenge-signature authentication.\n * The signer will be used to sign challenges from the relay server.\n *\n * @param signer - Wallet signer (ethers v6 Signer or compatible object with signMessage/getAddress)\n *\n * @example\n * ```typescript\n * import { BrowserProvider } from 'ethers';\n *\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n * ```\n */\n setSigner(signer: WalletSigner): void {\n this.signer = signer;\n }\n\n /**\n * Fetches a random challenge from the relay server.\n * The challenge must be signed and included in proof requests.\n *\n * @returns Promise resolving to ChallengeResponse with challenge hex and expiry\n * @throws Error if relayUrl is not configured\n */\n async getChallenge(): Promise<ChallengeResponse> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/challenge`);\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Failed to get challenge: HTTP ${response.status}`);\n }\n\n return await response.json() as ChallengeResponse;\n }\n\n /**\n * Creates a proof request through the relay server.\n *\n * This is the recommended way to create proof requests. The relay server:\n * - Issues a server-side requestId (validated by the mobile app)\n * - Tracks request status in Redis\n * - Builds the deep link with relay callback URL\n * - Stores inputs hash for deep link integrity verification\n *\n * @param circuit - Circuit type identifier\n * @param inputs - Circuit-specific inputs\n * @param options - Request options (message, dappName, dappIcon, nonce, returnScheme)\n * @param options.returnScheme - Which app the ZKProofport app should switch back\n * to once it has finished. Put **your own** deep link scheme here — the bare\n * scheme your app registers, e.g. `'mydapp://'`. Only a native app has an\n * answer to this question; a web app omits the option entirely, because\n * opening its https origin would launch a new browser tab on a fresh page\n * rather than return the user to the tab they started from.\n *\n * This is intentionally **not** a URL and not a return address: no path, query\n * string or fragment is accepted, and the ZKProofport app never sends the proof\n * there. The proof still comes back to you the same way it always did — over the\n * relay, via `waitForProof()` / `waitForResult()`. `returnScheme` only answers\n * \"which app should come back to the foreground\", exactly like the\n * `redirect.native` value a wallet uses to hand control back after signing.\n *\n * **Omit it and the SDK decides for you.** When the request is created from a\n * page running in Chrome for iOS (`CriOS`) or Firefox for iOS (`FxiOS`), the\n * SDK fills in `'googlechrome://'` or `'firefox://'` by itself: opening either\n * scheme bare brings that browser forward without navigating, so the user lands\n * back on the tab they were already reading. Every other browser sends nothing,\n * because nothing safe exists to send — Safari has no such scheme, and Brave\n * and Arc are indistinguishable from Safari on iOS, so guessing would eject the\n * user into the wrong browser.\n * On Android nothing is needed at all: the ZKProofport app brings itself to the\n * back and the browser resumes exactly as it was. When no target is sent and\n * none can be inferred, the ZKProofport app tells the user the proof was\n * delivered and lets them switch back themselves.\n *\n * There is no auto-switch on proof failure; only on success and on the user\n * declining the request.\n *\n * Rejected with an error before the request is sent: empty or whitespace values,\n * anything longer than 128 characters, values carrying a host/path/query/fragment\n * (including https origins such as `'https://myapp.com'`), and the `http:`,\n * `file:`, `data:`, `javascript:`, `intent:`, `tel:`, `sms:`, `mailto:` families.\n * @returns Promise resolving to RelayProofRequest with requestId, deepLink, pollUrl\n * @throws Error if signer not set, returnScheme is malformed, or the relay request fails\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create();\n * sdk.setSigner(signer);\n *\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * }, { dappName: 'My DApp', returnScheme: 'mydapp://' });\n *\n * // Generate QR code from relay deep link\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof (WebSocket primary, polling fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * ```\n */\n // Which circuits need a wallet signature, from the one record in\n // src/circuits.ts. A typed-out list here once missed a circuit, so a dapp\n // calling createRelayRequest() for it with no signer got no local error and\n // a relay 401 two round trips later.\n private static needsWalletSignature(circuit: CircuitType): boolean {\n return CIRCUIT_NEEDS_WALLET_SIGNATURE[circuit as CircuitId] === true;\n }\n\n async createRelayRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n nonce?: string;\n returnScheme?: string;\n } = {}\n ): Promise<RelayProofRequest> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const needsSignature = ProofportSDK.needsWalletSignature(circuit);\n\n if (needsSignature && !this.signer) {\n throw new Error('Signer not set. Call setSigner() first. Wallet signature is required for this circuit.');\n }\n\n // mDL circuits: validate predicate inputs client-side before hitting the\n // relay, so a bad ageThreshold / targetRegion fails fast with a clear error.\n if (circuit === 'mdl_kr_ownership' || circuit === 'mdl_kr_age' || circuit === 'mdl_kr_region') {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n }\n\n // The action, per the circuit's entry in CIRCUIT_ACTION_BINDING. Checked\n // here, before a challenge is burned, because the alternative is a refusal\n // from inside the mobile app -- a screen the dapp developer never sees,\n // reached after the person has already scanned a QR code.\n //\n // The circuit id belongs in the table, not in the check.\n {\n const action = (inputs as { action?: unknown }).action;\n const binding = circuitActionBinding(circuit);\n if (binding === 'none' && action !== undefined) {\n throw new Error(\n `${circuit} has no action inputs, so an action sent with it would not be proved. ` +\n 'Remove it, or use a circuit that binds one.'\n );\n }\n if (binding === 'required' || (binding === 'optional' && action !== undefined)) {\n const actionError = validateTypedAction(action);\n if (actionError) {\n throw new Error(`${actionError} (circuit: ${circuit})`);\n }\n }\n }\n\n // Return target: validated before we burn a challenge, so a typo surfaces\n // as a local error instead of a relay 400 on the second round trip.\n if (options.returnScheme !== undefined) {\n const returnSchemeError = validateReturnScheme(options.returnScheme);\n if (returnSchemeError) {\n throw new Error(returnSchemeError);\n }\n }\n\n // Get challenge + requestId from relay\n const { requestId, challenge } = await this.getChallenge();\n\n const body: Record<string, unknown> = {\n requestId,\n circuitId: circuit,\n inputs,\n challenge,\n };\n\n // The relay never reads `inputs`, so the scope is also sent on the envelope,\n // where the relay counts requests per scope. The app proves the scope inside\n // `inputs` and uses the envelope copy only when `inputs` has none; both are\n // the same string here.\n const scope = (inputs as { scope?: unknown }).scope;\n if (typeof scope === 'string' && scope.length > 0) body.scope = scope;\n\n // Sign challenge for circuits that require wallet signature\n if (needsSignature && this.signer) {\n body.signature = await this.signer.signMessage(challenge);\n }\n\n if (options.message) body.message = options.message;\n if (options.dappName) body.dappName = options.dappName;\n if (options.dappIcon) body.dappIcon = options.dappIcon;\n if (options.nonce) body.nonce = options.nonce;\n // An explicit value always wins. Otherwise ask the SDK to work one out from\n // the page's own user agent — the requesting page is the only side that can\n // (iOS tells the app nothing about who launched it). Both paths can end in\n // \"send nothing\", which is a legitimate outcome, not a failure.\n const returnScheme = options.returnScheme ?? detectReturnScheme();\n if (returnScheme) body.returnScheme = returnScheme;\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/request`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Relay request failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofRequest;\n }\n\n /**\n * Polls the relay for proof result status.\n *\n * @param requestId - The relay-issued request ID\n * @returns Promise resolving to RelayProofResult\n * @throws Error if relay URL not configured or request not found\n *\n * @example\n * ```typescript\n * const result = await sdk.pollResult(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof:', result.proof);\n * console.log('Public inputs:', result.publicInputs);\n * }\n * ```\n */\n async pollResult(requestId: string): Promise<RelayProofResult> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/${requestId}`);\n\n if (!response.ok) {\n if (response.status === 404) {\n throw new Error('Request not found or expired');\n }\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Poll failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofResult;\n }\n\n /**\n * Polls the relay until the request reaches a terminal status\n * (`completed`, `error`, `failed`, `cancelled` or `expired`), with\n * configurable interval and timeout. Branch on `result.status`.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Polling options\n * @param options.intervalMs - Polling interval in milliseconds (default: 2000)\n * @param options.timeoutMs - Maximum polling time in milliseconds (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback when status changes\n * @returns Promise resolving to final RelayProofResult\n * @throws Error if timeout or relay error\n */\n async waitForResult(\n requestId: string,\n options: {\n intervalMs?: number;\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const interval = options.intervalMs || 2000;\n const timeout = options.timeoutMs || 300000;\n const startTime = Date.now();\n let lastStatus = '';\n\n while (Date.now() - startTime < timeout) {\n const result = await this.pollResult(requestId);\n\n if (result.status !== lastStatus) {\n lastStatus = result.status;\n options.onStatusChange?.(result);\n }\n\n // Every terminal status ends the wait, not only success: an app error,\n // a cancellation and a relay-side timeout are answers too, and polling\n // past them would only end in this method's own timeout.\n if (isTerminalRelayStatus(result.status)) {\n return result;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Polling timed out after ${timeout}ms`);\n }\n\n /**\n * Subscribes to real-time proof status updates via Socket.IO.\n *\n * This is the recommended way to receive proof results. Uses WebSocket\n * connection for instant delivery instead of polling.\n *\n * Requires `socket.io-client` package: `npm install socket.io-client`\n *\n * @param requestId - The relay-issued request ID to subscribe to\n * @param callbacks - Event callbacks for status changes and results\n * @param callbacks.onStatus - Called on status updates (pending, generating)\n * @param callbacks.onResult - Called once with the terminal result: completed, error, failed, cancelled or expired\n * @param callbacks.onError - Called on errors\n * @returns Unsubscribe function to clean up the connection\n * @throws Error if relayUrl not set or socket.io-client not installed\n *\n * @example\n * ```typescript\n * const relay = await sdk.createRelayRequest('coinbase_attestation', { scope: 'myapp.com' });\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * const unsubscribe = await sdk.subscribe(relay.requestId, {\n * onResult: (result) => {\n * if (result.status === 'completed') {\n * console.log('Proof received!', result.proof);\n * }\n * },\n * onError: (error) => console.error('Error:', error),\n * });\n *\n * // Later: clean up\n * unsubscribe();\n * ```\n */\n async subscribe(\n requestId: string,\n callbacks: {\n onStatus?: (data: { requestId: string; status: string; deepLink?: string }) => void;\n onResult?: (result: RelayProofResult) => void;\n onError?: (error: { error: string; code?: number; requestId?: string }) => void;\n }\n ): Promise<() => void> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n let ioConnect: any;\n try {\n const mod: any = await import('socket.io-client');\n ioConnect = mod.io ?? mod.connect ?? mod.default;\n } catch {\n throw new Error(\n 'socket.io-client is required for real-time updates. Install it: npm install socket.io-client'\n );\n }\n\n if (typeof ioConnect !== 'function') {\n throw new Error('Failed to load socket.io-client: io function not found');\n }\n\n // Connect to relay /proof namespace (no JWT — open connections)\n const socket = ioConnect(`${this.relayUrl}/proof`, {\n path: '/socket.io',\n transports: ['websocket', 'polling'],\n });\n\n this.socket = socket;\n\n // Subscribe to the request room\n socket.on('connect', () => {\n socket.emit('proof:subscribe', { requestId });\n });\n\n // Handle connection errors (e.g. rejected by relay middleware)\n socket.on('connect_error', (err: Error) => {\n console.error(`[ProofportSDK] Socket.IO connect_error for requestId=${requestId}: ${err.message}`);\n callbacks.onError?.({ error: err.message, requestId });\n });\n\n // Listen for events\n if (callbacks.onStatus) {\n socket.on('proof:status', callbacks.onStatus);\n }\n if (callbacks.onResult) {\n socket.on('proof:result', callbacks.onResult);\n }\n if (callbacks.onError) {\n socket.on('proof:error', callbacks.onError);\n }\n\n // Return unsubscribe function\n return () => {\n socket.off('proof:status');\n socket.off('proof:result');\n socket.off('proof:error');\n socket.disconnect();\n if (this.socket === socket) {\n this.socket = null;\n }\n };\n }\n\n /**\n * Waits for a proof result using Socket.IO (primary) with polling fallback.\n *\n * Tries Socket.IO first for real-time delivery. If socket.io-client is not\n * installed or connection fails, automatically falls back to HTTP polling.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Configuration options\n * @param options.timeoutMs - Maximum wait time in ms (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback for status updates\n * @returns Promise resolving to final RelayProofResult\n */\n async waitForProof(\n requestId: string,\n options: {\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult | { requestId: string; status: string; deepLink?: string }) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const timeout = options.timeoutMs || 300000;\n\n // Try Socket.IO first\n if (this.relayUrl) {\n try {\n return await new Promise<RelayProofResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n unsubscribePromise?.then(fn => fn());\n reject(new Error(`Waiting for proof timed out after ${timeout}ms`));\n }, timeout);\n\n const unsubscribePromise = this.subscribe(requestId, {\n onStatus: (data) => {\n options.onStatusChange?.(data);\n },\n onResult: (result) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n resolve(result);\n },\n onError: (error) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n reject(new Error(error.error));\n },\n });\n });\n } catch (err: any) {\n // Re-throw timeout — that's a real failure the caller should handle\n if (err.message?.includes('timed out')) {\n throw err;\n }\n // socket.io-client missing or connection failed → fall back to polling silently\n console.warn('Socket.IO unavailable, falling back to HTTP polling:', err.message);\n }\n }\n\n // Fallback: HTTP polling\n return this.waitForResult(requestId, {\n timeoutMs: timeout,\n onStatusChange: options.onStatusChange as any,\n });\n }\n\n /**\n * Disconnects the Socket.IO connection if active.\n */\n disconnect(): void {\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n }\n\n // ============ Public Input Utilities ============\n\n /**\n * Extracts the scope from proof public inputs.\n *\n * The scope is an application-specific identifier (e.g., domain name) encoded\n * as bytes32 in the proof's public inputs.\n *\n * @param publicInputs - Array of public input hex strings from proof response\n * @param circuit - Circuit type to determine field positions\n * @returns Scope as hex string (0x...), or null if inputs are insufficient\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const scope = sdk.extractScope(result.publicInputs, result.circuit);\n * console.log('Scope:', scope);\n * }\n * ```\n */\n extractScope(publicInputs: string[], circuit: CircuitType): string | null {\n return extractScopeFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the nullifier (bytes32) from proof public inputs.\n *\n * The nullifier is a unique, deterministic hash derived from the user's attestation\n * and scope. It serves as a privacy-preserving user identifier — the same user\n * with the same scope always produces the same nullifier, enabling duplicate\n * detection without revealing the wallet address.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Nullifier as hex string (bytes32), or null if publicInputs too short\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const nullifier = sdk.extractNullifier(result.publicInputs, result.circuit);\n * console.log('Nullifier:', nullifier); // '0xabc123...'\n * }\n * ```\n */\n extractNullifier(publicInputs: string[], circuit: CircuitType): string | null {\n return extractNullifierFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the domain string from OIDC Domain Attestation proof public inputs.\n *\n * Only works with 'oidc_domain_attestation' circuit. Returns null for other circuits.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Domain as ASCII string (e.g., 'example.com'), or null if not applicable\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const domain = sdk.extractDomain(result.publicInputs, result.circuit);\n * console.log('Domain:', domain); // 'example.com'\n * }\n * ```\n */\n extractDomain(publicInputs: string[], circuit: CircuitType): string | null {\n return extractDomainFromPublicInputs(publicInputs, circuit);\n }\n\n}\n\nexport default ProofportSDK;\n"],"names":["isCircuitId","ALL_CIRCUIT_IDS","circuitActionBinding","validateTypedAction","CIRCUIT_VK_PATHS","parseProofForOnChain","verifyProofOnChain","getVerifierAddress","getVerifierChainId","CIRCUIT_NEEDS_WALLET_SIGNATURE","extractScopeFromPublicInputs","extractNullifierFromPublicInputs","extractDomainFromPublicInputs"],"mappings":";;;;;;;;;AAAA;;AAEG;AAIH;;;;;;;;;AASG;AACI,MAAM,UAAU,GAAmC;AACxD,IAAA,UAAU,EAAE,+BAA+B;AAC3C,IAAA,OAAO,EAAE,mCAAmC;AAC5C,IAAA,KAAK,EAAE,uBAAuB;CAC/B;AAED;;;;;;;;;AASG;AACI,MAAM,cAAc,GAAG,aAAa;AAE3C;;;;;;;;;AASG;AACI,MAAM,eAAe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AAU,EAAE;AACxB,YAAA,IAAI,CAAC,MAAM,GAAG,IAAI;QACpB;IACF;;AAIA;;;;;;;;;;;;;;;;;;AAkBG;IACH,YAAY,CAAC,YAAsB,EAAE,OAAoB,EAAA;AACvD,QAAA,OAAOO,iCAA4B,CAAC,YAAY,EAAE,OAAO,CAAC;IAC5D;AAEA;;;;;;;;;;;;;;;;;;;;AAoBG;IACH,gBAAgB,CAAC,YAAsB,EAAE,OAAoB,EAAA;AAC3D,QAAA,OAAOC,qCAAgC,CAAC,YAAY,EAAE,OAAO,CAAC;IAChE;AAEA;;;;;;;;;;;;;;;;;AAiBG;IACH,aAAa,CAAC,YAAsB,EAAE,OAAoB,EAAA;AACxD,QAAA,OAAOC,kCAA6B,CAAC,YAAY,EAAE,OAAO,CAAC;IAC7D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/constants.ts","../src/deeplink.ts","../src/qrcode.ts","../src/offChainVerifier.ts","../src/relayStatus.ts","../src/ProofportSDK.ts"],"sourcesContent":["/**\n * ZKProofport SDK Constants\n */\n\nimport type { CircuitType, SDKEnvironment } from './types';\n\n/**\n * Pre-configured relay server URLs for each environment.\n * Used by `ProofportSDK.create('production')` for zero-config initialization.\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * // Uses RELAY_URLS.production = 'https://relay.zkproofport.app'\n * ```\n */\nexport const RELAY_URLS: Record<SDKEnvironment, string> = {\n production: 'https://relay.zkproofport.app',\n staging: 'https://stg-relay.zkproofport.app',\n local: 'http://localhost:4001',\n};\n\n/**\n * The chain each circuit is verified on, per environment. Complete: a circuit\n * added to the SDK is a compile error here until somebody names its chain.\n *\n * Mirrors the mobile app's `CIRCUIT_NETWORKS` (proofport-app\n * src/config/contracts.ts), because a proof is checked where the app said its\n * verifier is: Base for the Coinbase and OIDC circuits, GIWA Sepolia for GIWA\n * and Dojang (testnet-only), Base Sepolia for Korea Mobile ID (testnet-only).\n * The ADDRESS on that chain always comes from core's pinned table, never from\n * a proof response.\n */\nexport const VERIFICATION_CHAINS = {\n production: {\n coinbase_attestation: 8453,\n coinbase_country_attestation: 8453,\n oidc_domain_attestation: 8453,\n giwa_attestation: 91342,\n dojang_playground: 91342,\n mdl_kr_ownership: 84532,\n mdl_kr_age: 84532,\n mdl_kr_region: 84532,\n },\n staging: {\n coinbase_attestation: 84532,\n coinbase_country_attestation: 84532,\n oidc_domain_attestation: 84532,\n giwa_attestation: 91342,\n dojang_playground: 91342,\n mdl_kr_ownership: 84532,\n mdl_kr_age: 84532,\n mdl_kr_region: 84532,\n },\n local: {\n coinbase_attestation: 84532,\n coinbase_country_attestation: 84532,\n oidc_domain_attestation: 84532,\n giwa_attestation: 91342,\n dojang_playground: 91342,\n mdl_kr_ownership: 84532,\n mdl_kr_age: 84532,\n mdl_kr_region: 84532,\n },\n} as const satisfies Record<SDKEnvironment, Record<CircuitType, number>>;\n\n/**\n * Default deep link URL scheme for ZKProofport mobile app.\n * Used to construct deep link URLs that open the mobile app.\n *\n * @example\n * ```typescript\n * const deepLink = `${DEFAULT_SCHEME}://proof-request?...`;\n * // Results in: zkproofport://proof-request?...\n * ```\n */\nexport const DEFAULT_SCHEME = 'zkproofport';\n\n/**\n * Deep link URL hosts for different proof request flows.\n * Used as the host component in deep link URLs.\n *\n * @example\n * ```typescript\n * const requestUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_REQUEST}`;\n * const responseUrl = `zkproofport://${DEEP_LINK_HOSTS.PROOF_RESPONSE}`;\n * ```\n */\nexport const DEEP_LINK_HOSTS = {\n /** Host for proof requests sent to mobile app */\n PROOF_REQUEST: 'proof-request',\n /** Host for proof responses returned from mobile app */\n PROOF_RESPONSE: 'proof-response',\n} as const;\n\n/**\n * Circuit metadata containing display names, descriptions, and public input specifications.\n * Each circuit has a defined number and layout of public inputs that must match\n * the Noir circuit definition.\n *\n * @example\n * ```typescript\n * const metadata = CIRCUIT_METADATA['coinbase_attestation'];\n * console.log(metadata.name); // \"Coinbase KYC\"\n * console.log(metadata.publicInputsCount); // 128\n * ```\n */\nexport const CIRCUIT_METADATA: Record<CircuitType, {\n name: string;\n description: string;\n publicInputsCount: number;\n publicInputNames: string[];\n}> = {\n coinbase_attestation: {\n name: 'Coinbase KYC',\n description: 'Prove Coinbase identity verification',\n // 4 x `pub [u8; 32]` in coinbase-attestation/src/main.nr, flattened to\n // bytes: signal_hash, signer_list_merkle_root, scope, nullifier.\n // Read 2 here until 2026-09-04, which was wrong under any reading —\n // the circuit has never had two public inputs, logical or flattened.\n publicInputsCount: 128,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root'],\n },\n coinbase_country_attestation: {\n name: 'Coinbase Country',\n description: 'Prove Coinbase country verification',\n // 32 + 32 + (10 x 2) + 1 + 1 + 32 + 32 = 150, counted off\n // coinbase-country-attestation/src/main.nr. Read 14 until 2026-09-04.\n publicInputsCount: 150,\n publicInputNames: ['signal_hash', 'signer_list_merkle_root', 'country_list', 'country_list_length', 'is_included'],\n },\n oidc_domain_attestation: {\n name: 'OIDC Domain',\n description: 'Prove email domain affiliation via OIDC JWT',\n publicInputsCount: 148,\n publicInputNames: ['pubkey_modulus_limbs', 'domain', 'scope', 'nullifier', 'provider'],\n },\n // Planned circuit — the identifier is reserved and the circuit exists, but it\n // is not officially supported yet. See CIRCUIT_SUPPORT_STATUS in ./circuits.\n // Forked from coinbase_attestation, then given the EIP-712 pair and a\n // branch: with an action the wallet signs the typed data and signal_hash is\n // zero; without one it signs signal_hash and the pair is zero. Read off the\n // compiled ABI (6 x [u8; 32] = 192): signal_hash 0-31, domain_separator\n // 32-63, action_hash 64-95, signer_list_merkle_root 96-127, scope 128-159,\n // nullifier 160-191.\n //\n // signal_hash is NOT part of this circuit's nullifier: a nullifier derived\n // from a public input nobody signs and nothing constrains would let one\n // wallet mint as many nullifiers as it likes; here the secret is the address\n // plus a constant compiled into the circuit.\n giwa_attestation: {\n name: 'GIWA Attestation',\n description: 'Prove GIWA identity verification, optionally authorizing one EIP-712 action (planned — not officially supported yet)',\n publicInputsCount: 192,\n publicInputNames: ['signal_hash', 'domain_separator', 'action_hash', 'signer_list_merkle_root', 'scope', 'nullifier'],\n },\n // Experimental, GIWA Sepolia only. The wallet signs the request (an EIP-712\n // action, or signal_hash when none is given -- the same branch as GIWA), and\n // the same key must have signed a payAndIssueEAS() call to the Playground\n // faucet. No issuer list, so no merkle root: 5 x [u8; 32] = 160, read off the\n // compiled ABI -- signal_hash 0-31, domain_separator 32-63, action_hash\n // 64-95, scope 96-127, nullifier 128-159.\n dojang_playground: {\n name: 'Dojang Playground',\n description: 'Prove this wallet issued itself a Dojang through the GIWA Playground, optionally authorizing one EIP-712 action',\n publicInputsCount: 160,\n publicInputNames: ['signal_hash', 'domain_separator', 'action_hash', 'scope', 'nullifier'],\n },\n // Korea Mobile ID (mDL) circuits. Planned — not officially supported yet.\n // Counts are byte-flattened field totals from the compiled circuit ABIs:\n // [u8; 32] arrays contribute 32 inputs each.\n mdl_kr_ownership: {\n name: 'Korea Mobile ID — Ownership',\n description: \"Prove valid Korean mobile driver's license ownership with selective disclosure\",\n publicInputsCount: 97,\n publicInputNames: ['scope', 'nullifier_value', 'disclose_flags', 'owner_commit'],\n },\n mdl_kr_age: {\n name: 'Korea Mobile ID — Age',\n description: \"Prove minimum age from Korean mobile driver's license without revealing birth date\",\n publicInputsCount: 66,\n publicInputNames: ['scope', 'nullifier_value', 'age_threshold', 'current_year'],\n },\n mdl_kr_region: {\n name: 'Korea Mobile ID — Region',\n description: \"Prove si/do residency from Korean mobile driver's license without revealing address\",\n publicInputsCount: 96,\n publicInputNames: ['scope', 'nullifier_value', 'region_code'],\n },\n};\n\n\n\n/**\n * Default proof request expiration time in milliseconds.\n * Requests older than this are considered expired and should not be processed.\n *\n * Default: 10 minutes (600,000 ms)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * // ...\n * createdAt: Date.now(),\n * expiresAt: Date.now() + DEFAULT_REQUEST_EXPIRY_MS\n * };\n * ```\n */\nexport const DEFAULT_REQUEST_EXPIRY_MS = 10 * 60 * 1000;\n\n/**\n * Maximum data size (in bytes) that can be encoded in a QR code.\n * Based on QR Code Version 40 with L (Low) error correction level.\n *\n * Requests exceeding this size should use alternative methods (HTTP, WebSocket).\n *\n * @example\n * ```typescript\n * const deepLinkUrl = generateDeepLink(request);\n * if (deepLinkUrl.length > MAX_QR_DATA_SIZE) {\n * console.warn('Request too large for QR code');\n * }\n * ```\n */\nexport const MAX_QR_DATA_SIZE = 2953; // Version 40 with L error correction\n\n// Moved to @zkproofport-app/core, re-exported so existing imports keep working.\nexport {\n VERIFIER_ABI,\n RPC_ENDPOINTS,\n COINBASE_ATTESTATION_PUBLIC_INPUT_LAYOUT,\n COINBASE_COUNTRY_PUBLIC_INPUT_LAYOUT,\n MDL_KR_PUBLIC_INPUT_LAYOUT,\n OIDC_DOMAIN_ATTESTATION_PUBLIC_INPUT_LAYOUT,\n} from '@zkproofport-app/core';\n","/**\n * Deep Link utilities for ZKProofport SDK\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n OidcDomainInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n DeepLinkComponents,\n CircuitType,\n} from './types';\nimport { DEFAULT_SCHEME, DEEP_LINK_HOSTS } from './constants';\nimport { isCircuitId, ALL_CIRCUIT_IDS } from './circuits';\nimport { validateTypedAction } from './typedAction';\nimport { circuitActionBinding } from './circuits';\n\n/**\n * Generates a unique request ID for proof requests.\n *\n * Creates an ID by combining a base36-encoded timestamp with a random string,\n * prefixed with \"req-\". This ensures uniqueness across concurrent requests.\n *\n * @returns A unique string identifier in the format \"req-{timestamp}-{random}\"\n *\n * @example\n * ```typescript\n * const id = generateRequestId();\n * // \"req-lh8k3f2g-a9b7c4d2\"\n * ```\n */\nexport function generateRequestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 10);\n return `req-${timestamp}-${random}`;\n}\n\n/**\n * Encodes an object into a URL-safe base64url string with UTF-8 support.\n *\n * Converts the input object to JSON, then encodes it using base64url format\n * (RFC 4648 §5) which replaces '+' with '-', '/' with '_', and removes padding.\n * Works in both browser and Node.js environments.\n *\n * @param data - The object to encode (will be JSON stringified)\n * @returns Base64url-encoded string safe for URL parameters\n *\n * @example\n * ```typescript\n * const encoded = encodeData({ circuit: 'coinbase_attestation', requestId: 'req-123' });\n * // \"eyJjaXJjdWl0IjoiY29pbmJhc2VfYXR0ZXN0YXRpb24iLCJyZXF1ZXN0SWQiOiJyZXEtMTIzIn0\"\n * ```\n */\nexport function encodeData(data: object): string {\n const json = JSON.stringify(data);\n // Use base64url encoding (URL-safe) with UTF-8 support\n if (typeof btoa === 'function') {\n // Browser: UTF-8 encode first, then base64\n const utf8Encoded = encodeURIComponent(json).replace(/%([0-9A-F]{2})/g, (_, p1) =>\n String.fromCharCode(parseInt(p1, 16))\n );\n return btoa(utf8Encoded)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n }\n // Node.js environment\n return Buffer.from(json, 'utf-8')\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Decodes a base64url-encoded string back into a typed object.\n *\n * Reverses the encoding process by converting base64url to standard base64,\n * decoding it, and parsing the resulting JSON. Handles UTF-8 correctly in\n * both browser and Node.js environments.\n *\n * @typeParam T - The expected type of the decoded object\n * @param encoded - Base64url-encoded string (from encodeData)\n * @returns Decoded and parsed object of type T\n *\n * @throws {SyntaxError} If the decoded string is not valid JSON\n *\n * @example\n * ```typescript\n * const request = decodeData<ProofRequest>(encodedString);\n * console.log(request.circuit); // \"coinbase_attestation\"\n * ```\n */\nexport function decodeData<T>(encoded: string): T {\n // Restore base64 padding\n let base64 = encoded.replace(/-/g, '+').replace(/_/g, '/');\n while (base64.length % 4) {\n base64 += '=';\n }\n\n let json: string;\n if (typeof atob === 'function') {\n // Browser: decode base64, then UTF-8 decode\n const decoded = atob(base64);\n json = decodeURIComponent(\n decoded.split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join('')\n );\n } else {\n json = Buffer.from(base64, 'base64').toString('utf-8');\n }\n\n return JSON.parse(json) as T;\n}\n\n/**\n * Builds a deep link URL for a proof request.\n *\n * Encodes the proof request and constructs a deep link URL that can be opened\n * by the ZKProofport mobile app. The URL format is:\n * `{scheme}://proof-request?data={encodedRequest}`\n *\n * @param request - The proof request to encode in the deep link\n * @param scheme - Custom URL scheme (defaults to \"zkproofport\")\n * @returns Complete deep link URL ready to be opened or embedded in a QR code\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n * const url = buildProofRequestUrl(request);\n * // \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\"\n * ```\n */\nexport function buildProofRequestUrl(\n request: ProofRequest,\n scheme: string = DEFAULT_SCHEME\n): string {\n const encodedRequest = encodeData(request);\n return `${scheme}://${DEEP_LINK_HOSTS.PROOF_REQUEST}?data=${encodedRequest}`;\n}\n\n/**\n * Builds a callback URL with proof response data as query parameters.\n *\n * Appends proof response fields to the provided callback URL. For completed proofs,\n * includes proof data, public inputs, and nullifier. For errors, includes error message.\n *\n * @internal Used by the mobile app to construct callback URLs — not intended for SDK consumers.\n *\n * @param callbackUrl - Base callback URL (from the original proof request)\n * @param response - Proof response containing status and optional proof data\n * @returns Complete callback URL with proof response as query parameters\n */\nexport function buildCallbackUrl(\n callbackUrl: string,\n response: ProofResponse\n): string {\n const url = new URL(callbackUrl);\n url.searchParams.set('requestId', response.requestId);\n url.searchParams.set('status', response.status);\n\n if (response.status === 'completed' && response.proof) {\n url.searchParams.set('proof', response.proof);\n if (response.publicInputs) {\n url.searchParams.set('publicInputs', response.publicInputs.join(','));\n }\n if (response.numPublicInputs !== undefined) {\n url.searchParams.set('numPublicInputs', response.numPublicInputs.toString());\n }\n if (response.timestamp) {\n url.searchParams.set('timestamp', response.timestamp.toString());\n }\n } else if (response.status === 'error' && response.error) {\n url.searchParams.set('error', response.error);\n }\n\n return url.toString();\n}\n\n/**\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a ZKProofport deep link URL.\n * Returns null if the URL is invalid or missing required parameters.\n *\n * @param url - Deep link URL (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Decoded ProofRequest object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request?data=eyJyZXF1ZXN0SWQi...\";\n * const request = parseProofRequestUrl(url);\n * if (request) {\n * console.log(request.circuit); // \"coinbase_attestation\"\n * }\n * ```\n */\nexport function parseProofRequestUrl(url: string): ProofRequest | null {\n try {\n const urlObj = new URL(url);\n const data = urlObj.searchParams.get('data');\n\n if (!data) {\n return null;\n }\n\n return decodeData<ProofRequest>(data);\n } catch (error) {\n console.error('Failed to parse proof request URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a proof response from a callback URL.\n *\n * Extracts proof response data from query parameters in a callback URL.\n * Handles both successful proof completions and error responses.\n * Returns null if required parameters (requestId, status) are missing.\n *\n * @param url - Callback URL with proof response query parameters\n * @returns Decoded ProofResponse object, or null if parsing fails\n *\n * @example\n * ```typescript\n * const callbackUrl = \"https://example.com/callback?requestId=req-123&status=completed&proof=0x...\";\n * const response = parseProofResponseUrl(callbackUrl);\n * if (response && response.status === 'completed') {\n * console.log(response.proof); // \"0x...\"\n * }\n * ```\n */\nexport function parseProofResponseUrl(url: string): ProofResponse | null {\n try {\n const urlObj = new URL(url);\n const requestId = urlObj.searchParams.get('requestId');\n const status = urlObj.searchParams.get('status') as ProofResponse['status'];\n\n if (!requestId || !status) {\n return null;\n }\n\n // A missing or unrecognised circuit is a REJECTION, not a default.\n //\n // This used to fall back to `coinbase_attestation`. A callback carrying a\n // country or OIDC proof, or a circuit this build has never heard of, was\n // then handed to the caller labelled Coinbase KYC -- the parse succeeded,\n // the label was wrong, and nothing downstream could tell. Whoever reads\n // `response.circuit` decides which verifier and which public-input layout\n // to use, so the wrong label is a proof checked against another circuit's\n // bytes.\n const circuit = urlObj.searchParams.get('circuit');\n if (!circuit || !isCircuitId(circuit)) {\n return null;\n }\n\n const response: ProofResponse = {\n requestId,\n circuit,\n status,\n };\n\n if (status === 'completed') {\n response.proof = urlObj.searchParams.get('proof') || undefined;\n const publicInputsStr = urlObj.searchParams.get('publicInputs');\n if (publicInputsStr) {\n response.publicInputs = publicInputsStr.split(',');\n }\n const numPublicInputs = urlObj.searchParams.get('numPublicInputs');\n if (numPublicInputs) {\n response.numPublicInputs = parseInt(numPublicInputs, 10);\n }\n const timestamp = urlObj.searchParams.get('timestamp');\n if (timestamp) {\n response.timestamp = parseInt(timestamp, 10);\n }\n } else if (status === 'error') {\n response.error = urlObj.searchParams.get('error') || undefined;\n }\n\n return response;\n } catch (error) {\n console.error('Failed to parse proof response URL:', error);\n return null;\n }\n}\n\n/**\n * Parses a deep link URL into its component parts.\n *\n * Breaks down a custom scheme URL into scheme, host, path, and query parameters.\n * Useful for routing and handling different types of deep links.\n *\n * @param url - Custom scheme URL to parse (e.g., \"zkproofport://proof-request?data=...\")\n * @returns Object containing scheme, host, path, and params, or null if invalid\n *\n * @example\n * ```typescript\n * const url = \"zkproofport://proof-request/verify?data=abc123\";\n * const components = parseDeepLink(url);\n * // {\n * // scheme: \"zkproofport\",\n * // host: \"proof-request\",\n * // path: \"/verify\",\n * // params: { data: \"abc123\" }\n * // }\n * ```\n */\nexport function parseDeepLink(url: string): DeepLinkComponents | null {\n try {\n // Handle custom scheme URLs\n const schemeMatch = url.match(/^([a-z][a-z0-9+.-]*):\\/\\/(.+)$/i);\n if (!schemeMatch) {\n return null;\n }\n\n const scheme = schemeMatch[1];\n const rest = schemeMatch[2];\n\n // Parse host and path\n const [hostPath, queryString] = rest.split('?');\n const [host, ...pathParts] = hostPath.split('/');\n const path = '/' + pathParts.join('/');\n\n // Parse query parameters\n const params: Record<string, string> = {};\n if (queryString) {\n const searchParams = new URLSearchParams(queryString);\n searchParams.forEach((value, key) => {\n params[key] = value;\n });\n }\n\n return { scheme, host, path, params };\n } catch (error) {\n console.error('Failed to parse deep link:', error);\n return null;\n }\n}\n\n/**\n * Checks if a URL is a valid ZKProofport deep link.\n *\n * Performs a case-insensitive check to see if the URL starts with the\n * ZKProofport scheme. Does not validate the URL structure beyond the scheme.\n *\n * @param url - URL to check\n * @param scheme - Expected URL scheme (defaults to \"zkproofport\")\n * @returns True if the URL starts with the specified scheme\n *\n * @example\n * ```typescript\n * isProofportDeepLink(\"zkproofport://proof-request?data=...\"); // true\n * isProofportDeepLink(\"https://example.com\"); // false\n * isProofportDeepLink(\"ZKPROOFPORT://proof-request\"); // true (case-insensitive)\n * ```\n */\nexport function isProofportDeepLink(\n url: string,\n scheme: string = DEFAULT_SCHEME\n): boolean {\n return url.toLowerCase().startsWith(`${scheme.toLowerCase()}://`);\n}\n\n/**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Performs comprehensive validation including:\n * - Required fields (requestId, circuit, callbackUrl)\n * - Circuit type validity (must be a supported circuit)\n * - Circuit-specific input validation (e.g., userAddress format, countryList structure)\n * - Expiration check (if expiresAt is provided)\n *\n * Note: userAddress is optional for both circuits - the mobile app will prompt\n * for wallet connection if not provided.\n *\n * @param request - Proof request to validate\n * @returns Validation result with `valid` flag and optional `error` message\n */\n/**\n * Validates a free-text mDL input (scope / targetRegion).\n * Rejects empty or whitespace-only values, control characters (which break\n * deep-link query encoding and downstream logging), and values over 256 chars\n * (server-side length cap mirror). UTF-8 text such as Korean region names is\n * allowed.\n *\n * @returns Error message string, or null when valid.\n */\nfunction validateMdlTextInput(value: unknown, fieldName: string): string | null {\n if (typeof value !== 'string' || value.trim() === '') {\n return `${fieldName} is required and must be a non-empty string`;\n }\n if (value.length > 256) {\n return `${fieldName} must be 256 characters or fewer`;\n }\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001F\\u007F]/.test(value)) {\n return `${fieldName} must not contain control characters`;\n }\n return null;\n}\n\n/**\n * Validates dapp-supplied inputs for the Korea Mobile ID (mDL) circuits.\n * Shared by deep-link request validation and relay request creation so the\n * same guards apply on every request path.\n *\n * Rules:\n * - `scope` — required non-empty string, ≤256 chars, no control characters\n * - `mdl_kr_ownership.discloseFlags` — optional integer 0–15 (0x0F bitmask)\n * - `mdl_kr_age.ageThreshold` — required integer 1–150\n * - `mdl_kr_region.targetRegion` — required non-empty string (Korean si/do),\n * ≤256 chars, no control characters\n *\n * @param circuit - One of the three mDL circuit identifiers\n * @param inputs - Dapp-supplied circuit inputs\n * @returns Error message string, or null when the inputs are valid\n */\nexport function validateMdlInputs(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs\n): string | null {\n const scopeError = validateMdlTextInput((inputs as MdlKrOwnershipInputs).scope, 'scope');\n if (scopeError) {\n return scopeError;\n }\n\n if (circuit === 'mdl_kr_ownership') {\n const { discloseFlags } = inputs as MdlKrOwnershipInputs;\n if (discloseFlags !== undefined) {\n if (\n typeof discloseFlags !== 'number' ||\n !Number.isInteger(discloseFlags) ||\n discloseFlags < 0 ||\n discloseFlags > 0x0f\n ) {\n return 'discloseFlags must be an integer between 0 and 15';\n }\n }\n } else if (circuit === 'mdl_kr_age') {\n const { ageThreshold } = inputs as MdlKrAgeInputs;\n if (\n typeof ageThreshold !== 'number' ||\n !Number.isInteger(ageThreshold) ||\n ageThreshold < 1 ||\n ageThreshold > 150\n ) {\n return 'ageThreshold is required and must be an integer between 1 and 150';\n }\n } else {\n const { targetRegion } = inputs as MdlKrRegionInputs;\n const regionError = validateMdlTextInput(targetRegion, 'targetRegion');\n if (regionError) {\n return regionError;\n }\n }\n\n return null;\n}\n\n/**\n * Longest accepted `returnScheme` value.\n * Kept in sync with proofport-relay `src/returnScheme.ts`.\n */\nexport const MAX_RETURN_SCHEME_LENGTH = 128;\n\n/** RFC 3986 scheme (`ALPHA *( ALPHA / DIGIT / \"+\" / \"-\" / \".\" )`) followed by exactly `://`. */\nconst BARE_SCHEME_RE = /^[a-z][a-z0-9+.-]*:\\/\\/$/;\n\n/**\n * Schemes we refuse even in the bare `scheme://` shape.\n *\n * `http` and `https` are the back door the shape rule alone leaves open: with\n * no host, `https://` is shaped exactly like a bare custom scheme and would\n * otherwise pass. A browser pointed at nowhere is not a return target, and\n * accepting it would re-open the URL-shaped door this field just closed.\n * `googlechrome://` and `firefox://` are deliberately NOT denied — bare, they\n * foreground that browser without navigating, which is the whole point.\n */\nconst DENIED_RETURN_SCHEMES = new Set([\n 'about',\n 'blob',\n 'content',\n 'data',\n 'facetime',\n 'facetime-audio',\n 'file',\n 'ftp',\n 'http',\n 'https',\n 'intent',\n 'javascript',\n 'jar',\n 'mailto',\n 'sms',\n 'tel',\n 'vbscript',\n]);\n\n/**\n * Validates a `returnScheme` before it is sent to the relay, so a malformed\n * value fails fast in the integrator's own code instead of coming back as a\n * relay 400. The relay re-validates and is the authority.\n *\n * One shape is accepted: a bare custom scheme such as `mydapp://`. It names an\n * app to switch back to, never a page to visit — so hosts, paths and query\n * strings are rejected, and an https URL is not a valid value. A web page has\n * no app to return to and simply omits the field.\n *\n * @param value - Candidate return target\n * @returns `null` when acceptable, otherwise a human-readable error message\n *\n * @internal\n */\nexport function validateReturnScheme(value: unknown): string | null {\n if (typeof value !== 'string') {\n return 'returnScheme must be a string';\n }\n if (value.length === 0) {\n return 'returnScheme must not be empty';\n }\n // Length is checked before any regex so a huge string never reaches the matcher.\n if (value.length > MAX_RETURN_SCHEME_LENGTH) {\n return `returnScheme must be at most ${MAX_RETURN_SCHEME_LENGTH} characters`;\n }\n if (/\\s/.test(value)) {\n return 'returnScheme must not contain whitespace';\n }\n\n const normalized = value.toLowerCase();\n\n if (!BARE_SCHEME_RE.test(normalized)) {\n return 'returnScheme must be a bare custom scheme such as \"mydapp://\" — hosts, paths, query strings and fragments are not accepted, and an https URL is not a return target';\n }\n\n const schemeName = normalized.slice(0, normalized.indexOf(':'));\n if (DENIED_RETURN_SCHEMES.has(schemeName)) {\n return `returnScheme \"${schemeName}\" is not allowed`;\n }\n\n return null;\n}\n\n/**\n * The return target to use when the integrator named none.\n *\n * Only the requesting PAGE can answer \"which browser is this?\" — iOS gives the\n * ZKProofport app nothing to work with (`sourceApplication` is nil across team\n * identifiers, and there is no public API to foreground an app by bundle id).\n * So the detection has to happen here, in the SDK, and travel with the request.\n *\n * Two cases are detected, each from a POSITIVE token, and each verified in the\n * browser's own source to foreground WITHOUT navigating anywhere:\n *\n * Chrome for iOS (`CriOS/`) -> `googlechrome://`\n * Firefox for iOS (`FxiOS/`) -> `firefox://`\n *\n * The BARE scheme is the point in both cases: it carries no URL, so the browser\n * comes forward with nothing to open and the user lands on the tab they were\n * already reading — no new tab, no navigation, no reload, JS state intact.\n *\n * Chrome: `ios/chrome/app/startup/chrome_app_startup_parameters.mm` replaces\n * the scheme with `http`, producing `http://`, which fails GURL validation\n * (`if (!externalURL.is_valid()) return nil;`), so the startup parameters are\n * nil and there is nothing to open.\n *\n * Firefox: `firefox://` has an empty host, and\n * `Coordinators/Router/RouteBuilder.swift` resolves the host through\n * `DeeplinkInput.Host(rawValue: \"\")`, which is nil because no case has an empty\n * raw value (`Coordinators/Router/DeeplinkInput.swift`). The scheme is not http\n * either, so `makeRoute(url:)` falls to its final `else { return nil }`, and\n * `SceneDelegate.handleOpenURL` then hits `guard let route = ... else\n * { return }` and does nothing at all. Verified on the warm path — the browser\n * is already running, which is always true here, because the user came from a\n * page in it.\n *\n * Everything else deliberately returns undefined, and that is not a gap:\n *\n * - Safari has no equivalent. No scheme means \"just come forward\";\n * `https://<url>` navigates and opens a new tab, `x-web-search://` opens a\n * search page. Both lose the user's page.\n * - Brave and Arc for iOS are UNDETECTABLE. Brave ships no UA token and\n * identifies itself only via Client Hints, which WebKit does not implement,\n * so it looks exactly like Safari. Inferring \"Safari\" by elimination and\n * firing a Safari-ish scheme would throw Brave and Arc users into a browser\n * they were not using — strictly worse than doing nothing.\n * - In-app webviews (KakaoTalk, Naver, Line, Instagram) are not tabs at all.\n * Any scheme destroys the page; the system \"< Back to X\" breadcrumb is the\n * only thing that preserves it.\n * - Edge (`EdgiOS`) and Opera (`OPiOS` / `OPT`) for iOS are NOT included.\n * Both are closed source, so `microsoft-edge://` and `opera-http://` cannot\n * be checked the way Chrome's and Firefox's were. Their bare schemes are\n * plausible analogues, and that is exactly why they stay out: an unverified\n * guess that opens a new tab is the bug this field exists to avoid. Add one\n * only with evidence that it foregrounds WITHOUT navigating.\n * - Android needs nothing: the ZKProofport app brings itself to the back\n * (`moveTaskToBack`), which resumes the browser exactly as it was.\n *\n * When this returns undefined the field is omitted and the ZKProofport app\n * tells the user the proof was delivered and to switch back themselves.\n *\n * @param userAgent - override, for tests. Defaults to `navigator.userAgent`.\n * Returns undefined when there is no navigator at all (Node, SSR).\n * @returns a scheme that is safe to open, or undefined to send nothing\n *\n * @internal\n */\nexport function detectReturnScheme(userAgent?: string): string | undefined {\n const ua =\n userAgent ?? (typeof navigator === 'undefined' ? undefined : navigator.userAgent);\n if (typeof ua !== 'string' || ua.length === 0) {\n return undefined;\n }\n // A device token is required alongside the browser token. `CriOS` and `FxiOS`\n // are already iOS-only and unambiguous on their own, but pairing them with the\n // device token costs nothing and stops a synthetic or spoofed desktop user\n // agent from producing a mobile-only scheme.\n if (!/(iPhone|iPad|iPod)/.test(ua)) {\n return undefined;\n }\n if (/CriOS\\//.test(ua)) {\n return 'googlechrome://';\n }\n if (/FxiOS\\//.test(ua)) {\n return 'firefox://';\n }\n return undefined;\n}\n\nexport function validateProofRequest(request: ProofRequest): { valid: boolean; error?: string } {\n if (!request.requestId) {\n return { valid: false, error: 'Missing requestId' };\n }\n\n if (!request.circuit) {\n return { valid: false, error: 'Missing circuit type' };\n }\n\n // The list is the SDK's own, not a copy. The copy that used to sit here\n // had missed circuits, so a link for one was refused as an invalid type\n // while every other layer accepted it.\n if (!isCircuitId(request.circuit)) {\n return {\n valid: false,\n error: `Invalid circuit type: ${request.circuit}. Expected one of: ${ALL_CIRCUIT_IDS.join(', ')}`,\n };\n }\n\n if (!request.callbackUrl) {\n return { valid: false, error: 'Missing callbackUrl' };\n }\n\n // Validate circuit-specific inputs\n if (request.circuit === 'coinbase_attestation') {\n // Coinbase KYC: userAddress is optional - app will connect wallet if not provided\n const inputs = request.inputs as CoinbaseKycInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n // If userAddress is not provided, app will prompt wallet connection - this is valid\n } else if (request.circuit === 'coinbase_country_attestation') {\n const inputs = request.inputs as CoinbaseCountryInputs;\n if (inputs.userAddress && !/^0x[a-fA-F0-9]{40}$/.test(inputs.userAddress)) {\n return { valid: false, error: 'Invalid userAddress format' };\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n return { valid: false, error: 'countryList is required and must be a non-empty array' };\n }\n if (!inputs.countryList.every(c => typeof c === 'string')) {\n return { valid: false, error: 'countryList must contain only strings' };\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n return { valid: false, error: 'isIncluded is required and must be a boolean' };\n }\n } else if (request.circuit === 'oidc_domain_attestation') {\n const inputs = request.inputs as OidcDomainInputs;\n if (!inputs.domain || typeof inputs.domain !== 'string' || inputs.domain.trim() === '') {\n return { valid: false, error: 'domain is required and must be a non-empty string' };\n }\n if (!inputs.scope || typeof inputs.scope !== 'string' || inputs.scope.trim() === '') {\n return { valid: false, error: 'scope is required and must be a non-empty string' };\n }\n if (inputs.provider !== undefined && (typeof inputs.provider !== 'string' || inputs.provider.trim() === '')) {\n return { valid: false, error: 'provider must be a non-empty string when specified' };\n }\n } else if (\n request.circuit === 'mdl_kr_ownership' ||\n request.circuit === 'mdl_kr_age' ||\n request.circuit === 'mdl_kr_region'\n ) {\n const mdlError = validateMdlInputs(request.circuit, request.inputs);\n if (mdlError) {\n return { valid: false, error: mdlError };\n }\n }\n\n // The action, decided by the circuit's own entry rather than by naming a\n // circuit here, so every action-capable circuit is checked the same way.\n {\n const action = (request.inputs as { action?: unknown } | undefined)?.action;\n const binding = circuitActionBinding(request.circuit);\n if (binding === 'none') {\n if (action !== undefined) {\n return {\n valid: false,\n error: `${request.circuit} has no action inputs, so an action sent with it would not be proved. Refusing rather than dropping it.`,\n };\n }\n } else if (binding === 'required' || action !== undefined) {\n const actionError = validateTypedAction(action);\n if (actionError) {\n return { valid: false, error: actionError };\n }\n }\n }\n\n // Check expiry\n if (request.expiresAt && Date.now() > request.expiresAt) {\n return { valid: false, error: 'Request has expired' };\n }\n\n return { valid: true };\n}\n","/**\n * QR Code utilities for ZKProofport SDK\n */\n\nimport QRCode from 'qrcode';\nimport type { ProofRequest, QRCodeOptions } from './types';\nimport { buildProofRequestUrl } from './deeplink';\nimport { DEFAULT_SCHEME, MAX_QR_DATA_SIZE } from './constants';\n\n/**\n * Default QR code options\n */\nconst DEFAULT_QR_OPTIONS: QRCodeOptions = {\n width: 300,\n errorCorrectionLevel: 'M',\n margin: 2,\n darkColor: '#000000',\n lightColor: '#ffffff',\n};\n\n/**\n * Generates a QR code as a base64-encoded PNG data URL.\n *\n * Creates a scannable QR code image from a proof request or deep link URL.\n * The returned data URL can be used directly in HTML img src attributes.\n * Validates that the encoded data doesn't exceed the maximum QR code size.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to base64 PNG data URL (e.g., \"data:image/png;base64,...\")\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = {\n * requestId: generateRequestId(),\n * circuit: 'coinbase_attestation',\n * inputs: { scope: 'myapp.com' },\n * createdAt: Date.now()\n * };\n *\n * const dataUrl = await generateQRCodeDataUrl(request, {\n * width: 400,\n * darkColor: '#000000',\n * lightColor: '#ffffff'\n * });\n *\n * // Use in HTML: <img src={dataUrl} alt=\"Scan to prove\" />\n * ```\n */\nexport async function generateQRCodeDataUrl(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n // Check data size\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toDataURL(url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Generates a QR code as an SVG string.\n *\n * Creates a scalable vector graphics QR code that can be embedded directly in HTML\n * or saved to a file. SVG QR codes scale perfectly at any size and have smaller\n * file sizes than raster formats.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise resolving to SVG markup string\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const svg = await generateQRCodeSVG(request, { width: 300 });\n *\n * // Embed directly: <div dangerouslySetInnerHTML={{ __html: svg }} />\n * // Or save to file: fs.writeFileSync('qr.svg', svg);\n * ```\n */\nexport async function generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<string> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n return QRCode.toString(url, {\n type: 'svg',\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Browser-only function that draws a QR code onto an existing canvas element.\n * Useful for interactive applications or when you need direct canvas manipulation.\n * The canvas dimensions will be set automatically based on the width option.\n *\n * @param canvas - HTML canvas element to render to (must exist in DOM)\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param options - QR code appearance options (width, colors, error correction)\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Promise that resolves when rendering is complete\n *\n * @throws {Error} If the URL exceeds MAX_QR_DATA_SIZE (2953 bytes)\n * @throws {Error} If canvas is not a valid HTMLCanvasElement (browser only)\n *\n * @example\n * ```typescript\n * // In a React component:\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n *\n * useEffect(() => {\n * if (canvasRef.current) {\n * generateQRCodeToCanvas(canvasRef.current, request, { width: 400 });\n * }\n * }, [request]);\n *\n * return <canvas ref={canvasRef} />;\n * ```\n */\nexport async function generateQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options: QRCodeOptions = {},\n scheme: string = DEFAULT_SCHEME\n): Promise<void> {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n\n if (url.length > MAX_QR_DATA_SIZE) {\n throw new Error(\n `QR code data too large (${url.length} bytes). Maximum is ${MAX_QR_DATA_SIZE} bytes.`\n );\n }\n\n const mergedOptions = { ...DEFAULT_QR_OPTIONS, ...options };\n\n await QRCode.toCanvas(canvas, url, {\n width: mergedOptions.width,\n errorCorrectionLevel: mergedOptions.errorCorrectionLevel,\n margin: mergedOptions.margin,\n color: {\n dark: mergedOptions.darkColor,\n light: mergedOptions.lightColor,\n },\n });\n}\n\n/**\n * Estimates the byte size of a QR code's encoded data.\n *\n * Calculates the size of the deep link URL that will be encoded in the QR code,\n * and checks if it's within the maximum supported size (2953 bytes for QR version 40\n * with medium error correction). Use this before generating QR codes to avoid errors.\n *\n * @param requestOrUrl - Proof request object or pre-built deep link URL\n * @param scheme - Custom URL scheme (only used if requestOrUrl is a ProofRequest)\n * @returns Object with `size` in bytes and `withinLimit` boolean flag\n *\n * @example\n * ```typescript\n * const request: ProofRequest = { ... };\n * const { size, withinLimit } = estimateQRDataSize(request);\n *\n * if (!withinLimit) {\n * console.error(`QR code too large: ${size} bytes (max 2953)`);\n * // Consider reducing request data or splitting into multiple QR codes\n * }\n *\n * // Example output: { size: 384, withinLimit: true }\n * ```\n */\nexport function estimateQRDataSize(\n requestOrUrl: ProofRequest | string,\n scheme: string = DEFAULT_SCHEME\n): { size: number; withinLimit: boolean } {\n const url = typeof requestOrUrl === 'string'\n ? requestOrUrl\n : buildProofRequestUrl(requestOrUrl, scheme);\n return {\n size: url.length,\n withinLimit: url.length <= MAX_QR_DATA_SIZE,\n };\n}\n","/**\n * Off-chain proof verification — checking a proof against its verification key,\n * with no chain, no RPC, and no gas.\n *\n * WHY THIS EXISTS. The SDK had only `verifyProofOnChain`, and every caller that\n * wanted an off-chain check called that instead and relabelled the result. The\n * demo page did exactly this from its first commit: pressing \"Off-Chain Verify\"\n * ran an on-chain verification and printed \"Off-Chain Verification Passed!\".\n * The answer was true and the label was a lie, which is the worst combination —\n * nothing looked broken. The mobile app has always verified off-chain properly\n * (through mopro's native Barretenberg); it was only the JavaScript side that\n * had no such thing.\n *\n * HOW IT WORKS. Proofs here are made for the EVM target (`bb prove -t evm`:\n * keccak transcript, ZK on), so the matching check is bb.js's\n * `UltraHonkVerifierBackend.verifyProof(..., { verifierTarget: 'evm' })`. Two\n * things have to line up:\n *\n * The version. `@aztec/bb.js` must be the WASM build of the same bb the\n * circuits are compiled with -- `BB_VERSION` in circuits/toolchain.env,\n * 4.2.0-aztecnr-rc.2 since the beta.19 toolchain. Versions are not\n * interchangeable: on the Korea Mobile ID age circuit the 2025 nightly wrote\n * a 16256-byte proof where bb 1.2.0 wrote 16224 for the identical circuit and\n * witness, with the SAME verification key, so the key cannot warn you. A\n * mismatch shows up only as verification failing.\n *\n * The target. Verifying an EVM proof as any other target is not a polite\n * false. With the 2025 nightly, keccak-without-ZK trapped the WebAssembly\n * with a bare \"unreachable\" and the poseidon flavour answered false for a\n * good proof.\n *\n * THE PROOF ARRIVES IN TWO PIECES. The mobile app splits what Barretenberg\n * produced into `proof` and `publicInputs` before sending it, because the\n * Solidity verifier takes them separately. bb.js 4.x's verifier takes the same\n * two pieces, so nothing is joined back here.\n */\nimport { ALL_CIRCUIT_IDS, CIRCUIT_VK_PATHS, isCircuitId, type CircuitId } from './circuits';\nimport { checkProofIssuer } from '@zkproofport-app/core';\n\n/**\n * Where verification keys are published.\n *\n * Not configurable, deliberately: a caller who could point this somewhere else\n * could point it at a key of their choosing, and \"the proof verified\" would\n * then mean nothing. Same repository the mobile app downloads circuit data\n * from.\n */\nconst CIRCUITS_VK_BASE =\n 'https://raw.githubusercontent.com/zkproofport/circuits/main';\n\n/** How long a fetched verification key is reused. Keys change only on a recompile. */\nconst VK_CACHE_TTL_MS = 60 * 60 * 1000;\n\nconst vkCache = new Map<string, { vk: Uint8Array; at: number }>();\n\nexport interface OffChainVerifyResult {\n valid: boolean;\n error?: string;\n}\n\nexport interface OffChainVerifyOptions {\n /**\n * Verification key bytes, if the caller already has them. Skips the fetch —\n * useful offline, in tests, and for anyone who would rather pin the key they\n * checked than trust a download.\n */\n verificationKey?: Uint8Array;\n /** Milliseconds before the fetch is abandoned. Default 30000. */\n timeoutMs?: number;\n}\n\n/**\n * Make sure a Node-shaped `Buffer` exists before Barretenberg is loaded.\n *\n * WHY THE SDK DOES THIS RATHER THAN THE CALLER. bb.js's own BROWSER build —\n * not just its node build — converts field elements through `Buffer.alloc` and\n * `buf.writeBigUInt64BE`. Browsers have no Buffer, and bundlers stopped\n * polyfilling Node globals years ago, so in a browser the first verification\n * dies with \"r.writeBigUInt64BE is not a function\" — a message that names\n * nothing a caller could act on. Measured on the demo page, 2026-09-04, against\n * a real GIWA proof.\n *\n * Leaving it to callers would mean every browser customer editing their\n * bundler config to make an SDK method work, which is the configuration this\n * SDK promises not to require.\n *\n * Deliberately narrow:\n * - It only fills a GAP. A real Buffer (Node, or a page that already has one)\n * is left alone, so nothing is shadowed by a lesser implementation.\n * - It checks for the METHOD, not just the global. A partial Buffer — which is\n * what several bundlers leave behind, and what the demo page actually had —\n * passes a `typeof Buffer` test and then fails inside Barretenberg.\n */\nasync function ensureBufferForBarretenberg(): Promise<void> {\n const existing = (globalThis as { Buffer?: { alloc?: (n: number) => unknown } }).Buffer;\n if (existing?.alloc) {\n const probe = existing.alloc(8) as { writeBigUInt64BE?: unknown };\n if (typeof probe.writeBigUInt64BE === 'function') return;\n }\n const { Buffer } = await import('buffer/');\n (globalThis as { Buffer?: unknown }).Buffer = Buffer;\n}\n\n/** @internal Hex string (with or without 0x) to bytes. */\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length === 0) return new Uint8Array(0);\n if (clean.length % 2 !== 0) {\n throw new Error(`Hex string has an odd length (${clean.length}); it cannot be bytes`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('Hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.substr(i * 2, 2), 16);\n }\n return out;\n}\n\n/**\n * @internal Public inputs as 32-byte big-endian field elements in hex, the\n * shape bb.js's verifier takes.\n *\n * The relay carries them as hex strings that are USUALLY already 32 bytes, but\n * a value that happens to have leading zeros can arrive short (`0x01`). Left-\n * padding here rather than trusting the sender is the difference between a\n * verification that works and one that fails on roughly one proof in a hundred,\n * for no reason the caller can see.\n */\nfunction normalisePublicInputs(publicInputs: string[]): string[] {\n return publicInputs.map((input, i) => {\n const bytes = hexToBytes(input);\n if (bytes.length > 32) {\n throw new Error(\n `Public input ${i} is ${bytes.length} bytes; a field element is at most 32`\n );\n }\n const padded = new Uint8Array(32);\n padded.set(bytes, 32 - bytes.length);\n return '0x' + Array.from(padded, b => b.toString(16).padStart(2, '0')).join('');\n });\n}\n\n/**\n * Fetch a circuit's verification key, with a small cache.\n *\n * @internal\n */\nasync function fetchVerificationKey(\n circuit: CircuitId,\n timeoutMs: number\n): Promise<Uint8Array> {\n const cached = vkCache.get(circuit);\n if (cached && Date.now() - cached.at < VK_CACHE_TTL_MS) return cached.vk;\n\n const vkPath = CIRCUIT_VK_PATHS[circuit];\n if (!vkPath) {\n throw new Error(\n `No verification key path for circuit '${circuit}'. ` +\n `Add it to CIRCUIT_VK_PATHS, or pass verificationKey directly.`\n );\n }\n\n const url = `${CIRCUITS_VK_BASE}/${vkPath}`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const resp = await fetch(url, { signal: controller.signal });\n if (!resp.ok) {\n throw new Error(`Could not fetch the verification key (HTTP ${resp.status}) from ${url}`);\n }\n const vk = new Uint8Array(await resp.arrayBuffer());\n // A 404 page or an HTML redirect arrives as a successful response full of\n // text, and would reach Barretenberg as a \"verification key\" that fails for\n // reasons no one could guess from the message.\n if (vk.length < 512) {\n throw new Error(\n `The verification key at ${url} is ${vk.length} bytes, far too small to be one. ` +\n `The path is probably wrong and something else was served.`\n );\n }\n vkCache.set(circuit, { vk, at: Date.now() });\n return vk;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Verify a proof off-chain, against its verification key.\n *\n * Needs no setup from the caller: the verifier ships with this SDK and is\n * loaded on first use.\n *\n * For `oidc_domain_attestation` it first checks the proof's RSA key against the\n * provider's published JWKS (core's `checkOidcProviderKey`); a key the provider\n * does not publish, or a JWKS that cannot be fetched, is `{ valid: false }`.\n *\n * @param circuit - Canonical circuit identifier\n * @param proof - Proof bytes as hex, WITHOUT public inputs (as the relay sends it)\n * @param publicInputs - Public inputs as hex strings, in circuit order\n * @param options - Optional verification key and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` when the check could not run\n *\n * @example\n * ```typescript\n * const result = await verifyProofOffChain(\n * 'coinbase_attestation',\n * response.proof,\n * response.publicInputs\n * );\n * if (result.valid) console.log('Proof is valid, no chain involved');\n * ```\n */\nexport async function verifyProofOffChain(\n circuit: CircuitId,\n proof: string,\n publicInputs: string[],\n options: OffChainVerifyOptions = {}\n): Promise<OffChainVerifyResult> {\n const timeoutMs = options.timeoutMs ?? 30000;\n\n if (!isCircuitId(circuit)) {\n return { valid: false, error: `Unknown circuit '${circuit}'. Known: ${ALL_CIRCUIT_IDS.join(', ')}.` };\n }\n\n // Before Barretenberg, and for the same reason as on-chain: a proof can be\n // mathematically valid and still mean nothing, because some circuits take\n // their trust anchor as a public input the prover chooses. For OIDC that is\n // the RSA key -- see core's oidcProviderKeys. Checked here so a dApp that\n // verifies off-chain gets the same answer as one that verifies on-chain.\n const issuer = await checkProofIssuer(circuit, publicInputs);\n if (!issuer.ok) {\n return { valid: false, error: issuer.error };\n }\n\n // A REQUIRED dependency, loaded lazily.\n //\n // It was briefly an optional peer dependency, on the reasoning that the WASM\n // is 16MB and most callers verify on-chain. That was wrong: it would have\n // meant a customer calling this method got an error telling them to install\n // something, and \"works with zero customer configuration\" is the SDK's rule.\n // A caller should never have to know this is implemented with Barretenberg.\n //\n // The dynamic import is what keeps the cost off everyone else — a bundler\n // splits it out, and a caller who never verifies off-chain never loads it.\n // Before bb.js, not after: its module-level code already reaches for Buffer.\n await ensureBufferForBarretenberg();\n\n let bb: typeof import('@aztec/bb.js');\n try {\n bb = await import('@aztec/bb.js');\n } catch (error) {\n // Reaching here means the install is broken, not that something is missing\n // by design. Say so, rather than sending the caller off to install a\n // package they should never have had to hear about.\n return {\n valid: false,\n error:\n 'Could not load the proof verifier (@aztec/bb.js), which ships with this ' +\n 'SDK. This usually means a broken or partial install — try reinstalling ' +\n `@zkproofport-app/sdk. Underlying error: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n let api: { destroy(): Promise<void> } | undefined;\n try {\n const proofBytes = hexToBytes(proof);\n if (proofBytes.length === 0) {\n return { valid: false, error: 'Proof is empty' };\n }\n // Normalised to 32-byte big-endian fields before handing them over: the\n // relay can deliver a short value (`0x01`), and the check below must see\n // exactly what the circuit committed to.\n const fields = normalisePublicInputs(publicInputs);\n\n const vk =\n options.verificationKey ?? (await fetchVerificationKey(circuit, timeoutMs));\n\n const barretenberg = await bb.Barretenberg.new({ threads: 1 });\n api = barretenberg;\n const verifier = new bb.UltraHonkVerifierBackend(barretenberg);\n const valid = await verifier.verifyProof(\n { proof: proofBytes, publicInputs: fields, verificationKey: vk },\n { verifierTarget: 'evm' }\n );\n return { valid };\n } catch (error) {\n return { valid: false, error: error instanceof Error ? error.message : String(error) };\n } finally {\n // The WASM instance holds worker threads; leaving them running keeps a Node\n // process alive after the check is done.\n if (api) {\n try {\n await api.destroy();\n } catch {\n /* nothing useful to do if teardown fails */\n }\n }\n }\n}\n\n/** @internal Test seam — lets a test start from a known-empty cache. */\nexport function clearVerificationKeyCache(): void {\n vkCache.clear();\n}\n","import type { RelayTerminalStatus } from './types';\n\n/**\n * The statuses a relay request ends in, as a runtime list. `satisfies` keeps it\n * in step with the `RelayTerminalStatus` type in both directions: a status\n * added to the type and not here, or here and not in the type, fails to compile.\n */\nexport const RELAY_TERMINAL_STATUSES = ['completed', 'error', 'failed', 'cancelled', 'expired'] as const satisfies readonly RelayTerminalStatus[];\n\ntype Missing = Exclude<RelayTerminalStatus, typeof RELAY_TERMINAL_STATUSES[number]>;\nconst everyStatusListed: Missing extends never ? true : Missing = true;\nvoid everyStatusListed;\n\n/** True when `status` is one a relay request ends in. */\nexport function isTerminalRelayStatus(status: string): status is RelayTerminalStatus {\n return (RELAY_TERMINAL_STATUSES as readonly string[]).includes(status);\n}\n","/**\n * Proofport SDK - Main class\n */\n\nimport type {\n ProofRequest,\n ProofResponse,\n CircuitType,\n CircuitInputs,\n CoinbaseKycInputs,\n CoinbaseCountryInputs,\n MdlKrOwnershipInputs,\n MdlKrAgeInputs,\n MdlKrRegionInputs,\n ProofportConfig,\n QRCodeOptions,\n ParsedProof,\n VerifierContract,\n ChallengeResponse,\n WalletSigner,\n RelayProofRequest,\n RelayProofResult,\n} from './types';\nimport {\n generateRequestId,\n buildProofRequestUrl,\n buildCallbackUrl,\n parseProofRequestUrl,\n parseProofResponseUrl,\n validateProofRequest,\n validateMdlInputs,\n validateReturnScheme,\n detectReturnScheme,\n isProofportDeepLink,\n} from './deeplink';\nimport {\n generateQRCodeDataUrl,\n generateQRCodeSVG,\n generateQRCodeToCanvas,\n estimateQRDataSize,\n} from './qrcode';\nimport {\n verifyProofOnChain,\n parseProofForOnChain,\n getDefaultProvider,\n extractScopeFromPublicInputs,\n extractNullifierFromPublicInputs,\n extractDomainFromPublicInputs,\n} from './verifier';\nimport {\n verifyProofOffChain,\n type OffChainVerifyOptions,\n} from './offChainVerifier';\nimport {\n DEFAULT_SCHEME,\n DEFAULT_REQUEST_EXPIRY_MS,\n CIRCUIT_METADATA,\n RELAY_URLS,\n VERIFICATION_CHAINS,\n} from './constants';\nimport { ALL_CIRCUIT_IDS, CIRCUIT_NEEDS_WALLET_SIGNATURE, circuitActionBinding, isCircuitId, type CircuitId } from './circuits';\nimport { getPinnedVerifier, type VerifierTarget } from './verifier';\nimport { validateTypedAction } from './typedAction';\nimport { isTerminalRelayStatus } from './relayStatus';\nimport type { SDKEnvironment } from './types';\n\n\n/**\n * Main SDK class for interacting with the ZKProofport mobile app.\n *\n * Provides methods for creating proof requests, generating QR codes and deep links,\n * verifying proofs on-chain, and handling proof responses from the mobile app.\n *\n * @example\n * ```typescript\n * import { ProofportSDK } from '@zkproofport-app/sdk';\n * import { BrowserProvider } from 'ethers';\n *\n * // Initialize SDK (uses production relay by default)\n * const sdk = ProofportSDK.create();\n *\n * // Set wallet signer for challenge-signature auth\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n *\n * // Create proof request via relay\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * });\n *\n * // Generate QR code for desktop users\n * const qrDataUrl = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof via WebSocket (primary) or polling (fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof received:', result.proof);\n * }\n * ```\n */\nexport class ProofportSDK {\n private config: Required<Omit<ProofportConfig, 'relayUrl' | 'environment'>>;\n private pendingRequests: Map<string, ProofRequest> = new Map();\n private signer: WalletSigner | null = null;\n private relayUrl: string;\n private socket: any = null;\n /**\n * Set by {@link ProofportSDK.create} from its environment preset. It decides\n * which chain a proof is verified on when the dApp configured no verifier\n * for the circuit; a custom-config SDK has none and must configure one.\n */\n private environment: SDKEnvironment | null = null;\n\n /**\n * Creates a new ProofportSDK instance.\n *\n * For most use cases, prefer the static factory with environment presets:\n * ```typescript\n * const sdk = ProofportSDK.create('production');\n * ```\n *\n * @param config - SDK configuration options\n * @param config.scheme - Custom deep link scheme (default: 'zkproofport')\n * @param config.relayUrl - Relay server URL (required for relay features)\n * @param config.verifiers - Custom verifier contract addresses per circuit\n *\n * @example\n * ```typescript\n * const sdk = new ProofportSDK({\n * relayUrl: 'https://relay.zkproofport.app',\n * verifiers: {\n * coinbase_attestation: {\n * verifierAddress: '0x...',\n * chainId: 1\n * }\n * }\n * });\n * ```\n */\n constructor(config: ProofportConfig = {}) {\n this.config = {\n scheme: config.scheme || DEFAULT_SCHEME,\n verifiers: config.verifiers || {},\n };\n this.relayUrl = config.relayUrl || '';\n if (config.environment !== undefined) {\n if (!Object.prototype.hasOwnProperty.call(VERIFICATION_CHAINS, config.environment)) {\n throw new Error(\n `Unknown environment '${config.environment}'. Known: ${Object.keys(VERIFICATION_CHAINS).join(', ')}.`,\n );\n }\n this.environment = config.environment;\n }\n }\n\n // ============ Request Creation ============\n\n /**\n * @internal\n * Creates a proof request for a circuit whose dapp-side input is a scope\n * (Coinbase KYC, OIDC domain, GIWA, Dojang), keeping that circuit's id.\n *\n * @param circuit - The circuit requested; it is the request's circuit\n * @param inputs - Circuit inputs; `scope` is required (and `domain` for OIDC)\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createScopedRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your KYC status to access this feature'\n * });\n *\n * const deepLink = sdk.getDeepLinkUrl(request);\n * ```\n */\n private createScopedRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n const scope = (inputs as { scope?: unknown }).scope;\n if (typeof scope !== 'string' || scope.trim() === '') {\n throw new Error(`scope is required for ${circuit} circuit`);\n }\n if (circuit === 'oidc_domain_attestation') {\n const domain = (inputs as { domain?: unknown }).domain;\n if (typeof domain !== 'string' || domain.trim() === '') {\n throw new Error('domain is required for oidc_domain_attestation circuit');\n }\n }\n const action = (inputs as { action?: unknown }).action;\n const binding = circuitActionBinding(circuit);\n if (binding === 'none' && action !== undefined) {\n throw new Error(`${circuit} has no action inputs, so an action sent with it would not be proved.`);\n }\n if (binding === 'required' || (binding === 'optional' && action !== undefined)) {\n const actionError = validateTypedAction(action);\n if (actionError) throw new Error(`${actionError} (circuit: ${circuit})`);\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n // The circuit asked for, always. This used to be the literal\n // 'coinbase_attestation', and every circuit that was not country or mDL\n // was routed here -- a GIWA, Dojang or OIDC request silently became a\n // Coinbase KYC request.\n circuit,\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a Coinbase Country attestation proof request.\n *\n * Generates a proof request for verifying country eligibility through Coinbase\n * attestation without revealing the actual country data. The proof confirms the\n * user's country status while maintaining privacy through zero-knowledge proofs.\n *\n * @param inputs - Circuit inputs for Coinbase Country attestation\n * @param inputs.scope - Application-specific scope (e.g., domain name)\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 10 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if scope is not provided\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseCountryRequest({\n * scope: 'myapp.com'\n * }, {\n * dappName: 'My DApp',\n * message: 'Verify your country eligibility'\n * });\n * ```\n */\n private createCoinbaseCountryRequest(\n inputs: CoinbaseCountryInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!inputs.scope) {\n throw new Error('scope is required for coinbase_country_attestation circuit');\n }\n if (!inputs.countryList || !Array.isArray(inputs.countryList) || inputs.countryList.length === 0) {\n throw new Error('countryList is required for coinbase_country_attestation circuit');\n }\n if (typeof inputs.isIncluded !== 'boolean') {\n throw new Error('isIncluded is required for coinbase_country_attestation circuit');\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit: 'coinbase_country_attestation',\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n /**\n * @internal\n * Creates a generic proof request for any supported circuit type.\n *\n * Routes to the appropriate circuit-specific request creation method based on\n * the circuit type. Use this for dynamic circuit selection or when the circuit\n * type is determined at runtime.\n *\n * @param circuit - Circuit type identifier ('coinbase_attestation' | 'coinbase_country_attestation')\n * @param inputs - Circuit-specific inputs\n * @param options - Request configuration options\n\n * @param options.message - Custom message to display to user\n * @param options.dappName - Application name shown in ZKProofport app\n * @param options.dappIcon - Application icon URL shown in ZKProofport app\n * @param options.expiresInMs - Request expiration time in milliseconds (default: 15 minutes)\n *\n * @returns ProofRequest object with unique requestId and all request details\n *\n * @throws Error if required inputs are missing for the specified circuit\n *\n * @example\n * ```typescript\n * const circuitType = userSelection; // Dynamic selection\n * const request = sdk.createProofRequest(\n * circuitType,\n * { scope: 'myapp.com' },\n * { dappName: 'My DApp' }\n * );\n * ```\n */\n private createProofRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n if (!isCircuitId(circuit)) {\n throw new Error(`Unknown circuit '${circuit}'. Known: ${ALL_CIRCUIT_IDS.join(', ')}.`);\n }\n const builder = ProofportSDK.REQUEST_BUILDERS[circuit];\n switch (builder) {\n case 'country':\n return this.createCoinbaseCountryRequest(inputs as CoinbaseCountryInputs, options);\n case 'mdl':\n return this.createMdlKrRequest(circuit as 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region', inputs, options);\n case 'scoped':\n return this.createScopedRequest(circuit, inputs, options);\n }\n }\n\n /**\n * How each circuit's request is built and checked. Keyed by circuit id and\n * exhaustive over it, so a new circuit is a compile error here instead of\n * falling through to another circuit's builder.\n */\n private static readonly REQUEST_BUILDERS = {\n coinbase_attestation: 'scoped',\n coinbase_country_attestation: 'country',\n oidc_domain_attestation: 'scoped',\n giwa_attestation: 'scoped',\n dojang_playground: 'scoped',\n mdl_kr_ownership: 'mdl',\n mdl_kr_age: 'mdl',\n mdl_kr_region: 'mdl',\n } as const satisfies Record<CircuitId, 'scoped' | 'country' | 'mdl'>;\n\n /**\n * @internal\n * Creates a Korea Mobile ID (mDL) proof request for any of the three\n * mDL predicate circuits (ownership / age / region).\n *\n * The mobile app collects the license data on-device; the dapp only\n * supplies the predicate parameters validated here. No wallet signature\n * is required for mDL circuits.\n *\n * @param circuit - 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region'\n * @param inputs - Predicate inputs (see MdlKr*Inputs types)\n * @param options - Request configuration options\n *\n * @throws Error if the predicate inputs fail validation\n */\n private createMdlKrRequest(\n circuit: 'mdl_kr_ownership' | 'mdl_kr_age' | 'mdl_kr_region',\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n expiresInMs?: number;\n } = {}\n ): ProofRequest {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n\n const request: ProofRequest = {\n requestId: generateRequestId(),\n circuit,\n inputs,\n message: options.message,\n dappName: options.dappName,\n dappIcon: options.dappIcon,\n createdAt: Date.now(),\n expiresAt: Date.now() + (options.expiresInMs || DEFAULT_REQUEST_EXPIRY_MS),\n };\n\n this.pendingRequests.set(request.requestId, request);\n return request;\n }\n\n // ============ Deep Link Generation ============\n\n /**\n * @internal\n * Generates a deep link URL for a proof request.\n *\n * Creates a zkproofport:// URL that opens the ZKProofport mobile app with the\n * specified proof request. The URL contains all request details encoded as query\n * parameters.\n *\n * @param request - ProofRequest object to encode as deep link\n *\n * @returns Deep link URL string (e.g., 'zkproofport://proof?requestId=...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const url = sdk.getDeepLinkUrl(request);\n * // url: 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...'\n * ```\n */\n private getDeepLinkUrl(request: ProofRequest): string {\n return buildProofRequestUrl(request, this.config.scheme);\n }\n\n /**\n * @internal\n * Opens the ZKProofport mobile app with a proof request.\n *\n * Redirects the browser to the deep link URL, which opens the ZKProofport app\n * if installed. Only works in mobile browser environments. For desktop, use\n * requestProof() to display a QR code instead.\n *\n * @param request - ProofRequest object to send to the app\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * if (ProofportSDK.isMobile()) {\n * sdk.openProofRequest(request); // Opens app directly\n * }\n * ```\n */\n private openProofRequest(request: ProofRequest): void {\n const url = this.getDeepLinkUrl(request);\n window.location.href = url;\n }\n\n /**\n * @internal\n * Requests a proof with automatic platform detection.\n *\n * Detects whether the user is on mobile or desktop and automatically chooses\n * the appropriate flow:\n * - Mobile: Opens the deep link directly to launch the ZKProofport app\n * - Desktop: Generates a QR code data URL for the user to scan\n *\n * @param request - ProofRequest object to send\n * @param qrOptions - QR code generation options (size, colors, logo) for desktop\n *\n * @returns Object containing deep link URL, optional QR code data URL, and platform detection result\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const result = await sdk.requestProof(request);\n *\n * if (result.mobile) {\n * console.log('Opening app directly');\n * } else {\n * // Display QR code for desktop users\n * document.getElementById('qr').src = result.qrDataUrl;\n * }\n * ```\n */\n private async requestProof(\n request: ProofRequest,\n qrOptions?: QRCodeOptions\n ): Promise<{ deepLink: string; qrDataUrl?: string; mobile: boolean }> {\n const deepLink = this.getDeepLinkUrl(request);\n const mobile = ProofportSDK.isMobile();\n\n if (mobile) {\n window.location.href = deepLink;\n return { deepLink, mobile: true };\n }\n\n const qrDataUrl = await this.generateQRCode(request, qrOptions);\n return { deepLink, qrDataUrl, mobile: false };\n }\n\n // ============ QR Code Generation ============\n\n /**\n * Generates a QR code as a data URL for a proof request.\n *\n * Creates a PNG image data URL that can be directly set as an img src attribute.\n * Suitable for embedding QR codes in web pages for desktop users to scan with\n * their mobile device.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n * @param options.logoUrl - Optional center logo image URL\n * @param options.logoSize - Logo size as fraction of QR code (default: 0.2)\n *\n * @returns Promise resolving to PNG data URL (e.g., 'data:image/png;base64,...')\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const qrUrl = await sdk.generateQRCode(request, {\n * size: 400,\n * darkColor: '#1a1a1a',\n * logoUrl: 'https://myapp.com/logo.png'\n * });\n * document.getElementById('qr-image').src = qrUrl;\n * ```\n */\n async generateQRCode(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeDataUrl(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Generates a QR code as an SVG string for a proof request.\n *\n * Creates a scalable vector graphics representation of the QR code, ideal for\n * high-resolution displays or when vector format is preferred over raster images.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise resolving to SVG string\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const svgString = await sdk.generateQRCodeSVG(request);\n * document.getElementById('qr-container').innerHTML = svgString;\n * ```\n */\n async generateQRCodeSVG(\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<string> {\n return generateQRCodeSVG(requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Renders a QR code directly to an HTML canvas element.\n *\n * Draws the QR code onto the provided canvas element, useful for custom\n * rendering workflows or when you need direct canvas manipulation.\n *\n * @param canvas - HTML canvas element to render to\n * @param requestOrUrl - ProofRequest object or deep link URL string\n * @param options - QR code customization options\n * @param options.size - QR code size in pixels (default: 256)\n * @param options.margin - Quiet zone margin in modules (default: 4)\n * @param options.darkColor - Color for dark modules (default: '#000000')\n * @param options.lightColor - Color for light modules (default: '#ffffff')\n *\n * @returns Promise that resolves when rendering is complete\n *\n * @example\n * ```typescript\n * const canvas = document.getElementById('qr-canvas') as HTMLCanvasElement;\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * await sdk.renderQRCodeToCanvas(canvas, request, { size: 400 });\n * ```\n */\n async renderQRCodeToCanvas(\n canvas: HTMLCanvasElement,\n requestOrUrl: ProofRequest | string,\n options?: QRCodeOptions\n ): Promise<void> {\n return generateQRCodeToCanvas(canvas, requestOrUrl, options, this.config.scheme);\n }\n\n /**\n * Checks if a proof request fits within QR code size limits.\n *\n * Estimates the encoded data size and validates it against QR code capacity limits.\n * Useful for validating requests before generating QR codes, especially when\n * including large custom messages or metadata.\n *\n * @param requestOrUrl - ProofRequest object or deep link URL string\n *\n * @returns Object with size in bytes and whether it fits within limits\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const check = sdk.checkQRCodeSize(request);\n * if (!check.withinLimit) {\n * console.warn(`Request too large: ${check.size} bytes`);\n * }\n * ```\n */\n checkQRCodeSize(requestOrUrl: ProofRequest | string): { size: number; withinLimit: boolean } {\n return estimateQRDataSize(requestOrUrl, this.config.scheme);\n }\n\n // ============ Response Handling ============\n\n /**\n * @internal\n * Parses a proof response from a callback URL.\n *\n * Extracts and decodes proof response data from the callback URL query parameters\n * after the user completes proof generation in the ZKProofport app. The app\n * redirects to your callback URL with the proof data encoded as query parameters.\n *\n * @param url - Callback URL containing proof response data\n *\n * @returns ProofResponse object with status, proof data, and public inputs, or null if invalid\n *\n * @example\n * ```typescript\n * // In your callback endpoint handler\n * app.get('/callback', (req, res) => {\n * const callbackUrl = req.url;\n * const response = sdk.parseResponse(callbackUrl);\n *\n * if (response?.status === 'completed') {\n * console.log('Proof received:', response.proof);\n * console.log('Public inputs:', response.publicInputs);\n * } else if (response?.status === 'rejected') {\n * console.log('User rejected the request');\n * }\n * });\n * ```\n */\n private parseResponse(url: string): ProofResponse | null {\n return parseProofResponseUrl(url);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport proof response callback.\n *\n * Validates whether the given URL contains the required query parameters for a\n * proof response. Useful for filtering and routing callback requests.\n *\n * @param url - URL to check\n *\n * @returns True if the URL appears to be a ZKProofport response callback\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n * if (sdk.isProofportResponse(fullUrl)) {\n * const response = sdk.parseResponse(fullUrl);\n * // Handle proof response\n * }\n * });\n * ```\n */\n private isProofportResponse(url: string): boolean {\n try {\n const urlObj = new URL(url);\n return urlObj.searchParams.has('requestId') && urlObj.searchParams.has('status');\n } catch {\n return false;\n }\n }\n\n /**\n * @internal\n * Retrieves a pending proof request by its ID.\n *\n * Looks up a previously created proof request from the SDK's internal cache.\n * Useful for validating callback responses and maintaining request state.\n *\n * @param requestId - Unique request identifier\n *\n * @returns ProofRequest object if found, undefined otherwise\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * const originalRequest = sdk.getPendingRequest(response.requestId);\n *\n * if (originalRequest) {\n * console.log('Original request:', originalRequest);\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private getPendingRequest(requestId: string): ProofRequest | undefined {\n return this.pendingRequests.get(requestId);\n }\n\n /**\n * @internal\n * Clears a pending proof request from the internal cache.\n *\n * Removes a proof request from the SDK's pending requests map. Should be called\n * after successfully processing a proof response to prevent memory leaks.\n *\n * @param requestId - Unique request identifier to remove\n *\n * @example\n * ```typescript\n * app.get('/callback', (req, res) => {\n * const response = sdk.parseResponse(req.url);\n * if (response?.status === 'completed') {\n * // Process proof...\n * sdk.clearPendingRequest(response.requestId);\n * }\n * });\n * ```\n */\n private clearPendingRequest(requestId: string): void {\n this.pendingRequests.delete(requestId);\n }\n\n // ============ Verification ============\n\n /**\n * Verifies a zero-knowledge proof on-chain using the deployed verifier contract.\n *\n * Calls the Solidity verifier contract to cryptographically verify the proof's\n * validity. This ensures the proof was generated correctly and the public inputs\n * match the claimed values.\n *\n * @param circuit - Circuit type identifier\n * @param proof - Hex-encoded proof string from the ZKProofport app\n * @param publicInputs - Array of hex-encoded public input strings\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * const response = sdk.parseResponse(callbackUrl);\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyOnChain(\n * response.circuit,\n * response.proof,\n * response.publicInputs,\n * provider\n * );\n *\n * if (result.valid) {\n * console.log('Proof verified on-chain!');\n * } else {\n * console.error('Verification failed:', result.error);\n * }\n * }\n * ```\n */\n async verifyOnChain(\n circuit: CircuitType,\n proof: string,\n publicInputs: string[],\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n const parsedProof = parseProofForOnChain(\n proof,\n publicInputs,\n publicInputs.length\n );\n\n return verifyProofOnChain(circuit, parsedProof, providerOrSigner, this.verifierTarget(circuit));\n }\n\n /**\n * The verifier for a circuit: the one the dApp configured, otherwise the\n * pinned deployment on the chain this SDK's environment verifies that\n * circuit on. `undefined` when neither exists, which core reports as an\n * error. Never anything a proof response said.\n */\n private verifierTarget(circuit: CircuitType): VerifierTarget | undefined {\n const configured = this.config.verifiers[circuit];\n if (configured) return configured;\n if (this.environment === null) return undefined;\n const chains: Record<string, number> = VERIFICATION_CHAINS[this.environment];\n if (!Object.prototype.hasOwnProperty.call(chains, circuit)) return undefined;\n return { chainId: chains[circuit] };\n }\n\n /**\n * Verifies a proof response on-chain using the deployed verifier contract.\n *\n * Convenience method that extracts proof data from a ProofResponse object and\n * verifies it on-chain. Automatically handles incomplete or rejected responses.\n *\n * @param response - ProofResponse object from parseResponse()\n * @param providerOrSigner - ethers v6 Provider or Signer (defaults to base mainnet public RPC)\n *\n * @returns Promise resolving to verification result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * import { ethers } from 'ethers';\n *\n * app.get('/callback', async (req, res) => {\n * const response = sdk.parseResponse(req.url);\n *\n * if (response?.status === 'completed') {\n * const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');\n * const result = await sdk.verifyResponseOnChain(response, provider);\n *\n * if (result.valid) {\n * // Grant access to user\n * res.json({ success: true, verified: true });\n * } else {\n * res.status(400).json({ error: result.error });\n * }\n * } else {\n * res.status(400).json({ error: 'Proof generation failed or rejected' });\n * }\n * });\n * ```\n */\n async verifyResponseOnChain(\n response: ProofResponse,\n providerOrSigner?: any\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n\n const parsedProof = parseProofForOnChain(\n response.proof,\n response.publicInputs,\n response.publicInputs.length\n );\n\n // The response's verifierAddress and chainId are a claim to check, never\n // the contract to call: whoever wrote the response would otherwise pick\n // the judge. A claim that differs from the pinned or configured verifier\n // is refused.\n return verifyProofOnChain(response.circuit, parsedProof, providerOrSigner, this.verifierTarget(response.circuit), {\n verifierAddress: response.verifierAddress,\n chainId: response.chainId,\n });\n }\n\n /**\n * Verifies a proof response off-chain, against the circuit's verification key.\n *\n * No chain, no RPC, no gas, and no verifier contract — so this works for a\n * circuit whose verifier has not been deployed anywhere, and it does not\n * depend on a network being reachable. What it does not give you is the\n * chain's own opinion: use {@link verifyResponseOnChain} when the answer has\n * to be one a contract will agree with.\n *\n * Needs no setup: the verifier ships with this SDK. It is loaded on first\n * use, so a caller who only verifies on-chain never pays for it.\n *\n * @param response - Proof response from the relay\n * @param options - Optional verification key (skips the fetch) and timeout\n * @returns `{ valid }`, or `{ valid: false, error }` if the check could not run\n *\n * @example\n * ```typescript\n * const result = await sdk.verifyResponseOffChain(response);\n * if (result.valid) {\n * console.log('Valid, and nothing was asked of any chain');\n * }\n * ```\n */\n async verifyResponseOffChain(\n response: ProofResponse,\n options?: OffChainVerifyOptions\n ): Promise<{ valid: boolean; error?: string }> {\n if (response.status !== 'completed' || !response.proof || !response.publicInputs) {\n return { valid: false, error: 'Invalid or incomplete response' };\n }\n return verifyProofOffChain(\n response.circuit,\n response.proof,\n response.publicInputs,\n options\n );\n }\n\n // ============ Utility Methods ============\n\n /**\n * Gets the deployed verifier contract address for a circuit.\n *\n * Returns the Ethereum address of the Solidity verifier contract for the\n * specified circuit. Uses custom verifier if configured, otherwise returns\n * the default deployed address.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Ethereum address of the verifier contract (0x...)\n *\n * @example\n * ```typescript\n * const address = sdk.getVerifierAddress('coinbase_attestation');\n * console.log('Verifier deployed at:', address);\n * ```\n */\n getVerifierAddress(circuit: CircuitType): string {\n return this.requireVerifier(circuit).address;\n }\n\n /** The configured or pinned verifier, or an error saying why there is none. */\n private requireVerifier(circuit: CircuitType): { address: string; chainId: number } {\n const target = this.verifierTarget(circuit);\n if (!target) {\n throw new Error(\n `No verifier configured for circuit '${circuit}'. Configure one in the SDK's verifiers option, or create the SDK with ProofportSDK.create() to use the pinned deployment.`,\n );\n }\n if ('address' in target) return { address: target.address, chainId: target.chainId };\n return { address: getPinnedVerifier(circuit, target.chainId).address, chainId: target.chainId };\n }\n\n /**\n * Gets the blockchain chain ID where the verifier contract is deployed.\n *\n * Returns the EIP-155 chain ID for the network where the verifier contract\n * is deployed. Uses custom verifier if configured, otherwise returns the\n * default chain ID (Base mainnet: 8453).\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Chain ID number (e.g., 8453 for Base mainnet)\n *\n * @example\n * ```typescript\n * const chainId = sdk.getVerifierChainId('coinbase_attestation');\n * console.log('Verifier on chain:', chainId); // 8453 (Base mainnet)\n * ```\n */\n getVerifierChainId(circuit: CircuitType): number {\n return this.requireVerifier(circuit).chainId;\n }\n\n /**\n * Gets metadata for a specific circuit type.\n *\n * Returns circuit metadata including display name, description, required inputs,\n * and other configuration details.\n *\n * @param circuit - Circuit type identifier\n *\n * @returns Circuit metadata object with name, description, and configuration\n *\n * @example\n * ```typescript\n * const metadata = sdk.getCircuitMetadata('coinbase_attestation');\n * console.log('Circuit name:', metadata.name);\n * console.log('Description:', metadata.description);\n * ```\n */\n getCircuitMetadata(circuit: CircuitType) {\n return CIRCUIT_METADATA[circuit];\n }\n\n /**\n * Gets all supported circuit types.\n *\n * Returns an array of all circuit type identifiers that are currently supported\n * by the SDK and ZKProofport app.\n *\n * @returns Array of supported circuit type identifiers\n *\n * @example\n * ```typescript\n * const circuits = sdk.getSupportedCircuits();\n * console.log('Supported circuits:', circuits);\n * // ['coinbase_attestation', 'coinbase_country_attestation']\n * ```\n */\n getSupportedCircuits(): CircuitType[] {\n return Object.keys(CIRCUIT_METADATA) as CircuitType[];\n }\n\n /**\n * @internal\n * Validates a proof request for completeness and correctness.\n *\n * Checks that the proof request contains all required fields and that the\n * circuit-specific inputs are valid. Useful for catching configuration errors\n * before generating QR codes or sending requests to users.\n *\n * @param request - ProofRequest object to validate\n *\n * @returns Validation result with valid boolean and optional error message\n *\n * @example\n * ```typescript\n * const request = sdk.createCoinbaseKycRequest({ scope: 'myapp.com' });\n * const validation = sdk.validateRequest(request);\n *\n * if (!validation.valid) {\n * console.error('Invalid request:', validation.error);\n * }\n * ```\n */\n private validateRequest(request: ProofRequest): { valid: boolean; error?: string } {\n return validateProofRequest(request);\n }\n\n /**\n * @internal\n * Checks if a URL is a ZKProofport deep link.\n *\n * Validates whether the given URL uses the ZKProofport deep link scheme\n * (zkproofport:// by default) and has the correct format for a proof request.\n *\n * @param url - URL string to check\n *\n * @returns True if the URL is a valid ZKProofport deep link\n *\n * @example\n * ```typescript\n * const url = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation';\n * if (sdk.isProofportDeepLink(url)) {\n * const request = sdk.parseDeepLink(url);\n * console.log('Parsed request:', request);\n * }\n * ```\n */\n private isProofportDeepLink(url: string): boolean {\n return isProofportDeepLink(url, this.config.scheme);\n }\n\n /**\n * @internal\n * Parses a proof request from a deep link URL.\n *\n * Extracts and decodes the proof request data from a zkproofport:// deep link URL.\n * Useful for handling deep link navigation in web applications or validating\n * deep link URLs before displaying QR codes.\n *\n * @param url - ZKProofport deep link URL string\n *\n * @returns ProofRequest object with all request details, or null if invalid\n *\n * @example\n * ```typescript\n * const deepLink = 'zkproofport://proof?requestId=abc123&circuit=coinbase_attestation&...';\n * const request = sdk.parseDeepLink(deepLink);\n *\n * if (request) {\n * console.log('Request ID:', request.requestId);\n * console.log('Circuit:', request.circuit);\n * }\n * ```\n */\n private parseDeepLink(url: string): ProofRequest | null {\n return parseProofRequestUrl(url);\n }\n\n // ============ Static Factory ============\n\n /**\n * Creates a new ProofportSDK instance with environment preset or custom config.\n * Defaults to `'production'` if no argument is provided.\n *\n * **Recommended usage** — use the default production relay:\n * ```typescript\n * const sdk = ProofportSDK.create();\n * ```\n *\n * Environment presets:\n * - `'production'` — relay.zkproofport.app (default)\n * - `'staging'` — stg-relay.zkproofport.app\n * - `'local'` — localhost:4001\n *\n * @param envOrConfig - Environment name or custom SDK configuration\n *\n * @returns New ProofportSDK instance\n *\n * @example\n * ```typescript\n * // Environment preset (recommended)\n * const sdk = ProofportSDK.create(); // production (default)\n * const sdk = ProofportSDK.create('staging');\n *\n * // Custom config\n * const sdk = ProofportSDK.create({\n * relayUrl: 'https://my-custom-relay.example.com',\n * });\n * ```\n */\n static create(envOrConfig?: SDKEnvironment | ProofportConfig): ProofportSDK {\n if (typeof envOrConfig === 'undefined') {\n return ProofportSDK.forEnvironment('production');\n }\n if (typeof envOrConfig === 'string') {\n return ProofportSDK.forEnvironment(envOrConfig);\n }\n return new ProofportSDK(envOrConfig);\n }\n\n /** @internal An SDK on an environment preset's relay, verifying on that environment's chains. */\n private static forEnvironment(env: SDKEnvironment): ProofportSDK {\n if (!Object.prototype.hasOwnProperty.call(RELAY_URLS, env)) {\n throw new Error(`Unknown environment: ${env}. Use 'production', 'staging', or 'local'.`);\n }\n return new ProofportSDK({ relayUrl: RELAY_URLS[env], environment: env });\n }\n\n /**\n * Detects if the code is running on a mobile device.\n *\n * Uses user agent detection to determine if the current environment is a mobile\n * browser. This helps the SDK automatically choose between direct deep link\n * navigation (mobile) and QR code display (desktop).\n *\n * @returns True if running on a mobile device (iOS, Android, etc.)\n *\n * @example\n * ```typescript\n * if (ProofportSDK.isMobile()) {\n * // Open deep link directly\n * sdk.openProofRequest(request);\n * } else {\n * // Show QR code\n * const qr = await sdk.generateQRCode(request);\n * displayQRCode(qr);\n * }\n * ```\n */\n static isMobile(): boolean {\n if (typeof navigator === 'undefined') return false;\n return /Android|iPhone|iPad|iPod|webOS|BlackBerry|IEMobile|Opera Mini/i.test(\n navigator.userAgent\n );\n }\n\n // ============ Relay Integration ============\n\n /**\n * Sets the wallet signer for challenge-signature authentication.\n * The signer will be used to sign challenges from the relay server.\n *\n * @param signer - Wallet signer (ethers v6 Signer or compatible object with signMessage/getAddress)\n *\n * @example\n * ```typescript\n * import { BrowserProvider } from 'ethers';\n *\n * const provider = new BrowserProvider(window.ethereum);\n * const signer = await provider.getSigner();\n * sdk.setSigner(signer);\n * ```\n */\n setSigner(signer: WalletSigner): void {\n this.signer = signer;\n }\n\n /**\n * Fetches a random challenge from the relay server.\n * The challenge must be signed and included in proof requests.\n *\n * @returns Promise resolving to ChallengeResponse with challenge hex and expiry\n * @throws Error if relayUrl is not configured\n */\n async getChallenge(): Promise<ChallengeResponse> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/challenge`);\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Failed to get challenge: HTTP ${response.status}`);\n }\n\n return await response.json() as ChallengeResponse;\n }\n\n /**\n * Creates a proof request through the relay server.\n *\n * This is the recommended way to create proof requests. The relay server:\n * - Issues a server-side requestId (validated by the mobile app)\n * - Tracks request status in Redis\n * - Builds the deep link with relay callback URL\n * - Stores inputs hash for deep link integrity verification\n *\n * @param circuit - Circuit type identifier\n * @param inputs - Circuit-specific inputs\n * @param options - Request options (message, dappName, dappIcon, nonce, returnScheme)\n * @param options.returnScheme - Which app the ZKProofport app should switch back\n * to once it has finished. Put **your own** deep link scheme here — the bare\n * scheme your app registers, e.g. `'mydapp://'`. Only a native app has an\n * answer to this question; a web app omits the option entirely, because\n * opening its https origin would launch a new browser tab on a fresh page\n * rather than return the user to the tab they started from.\n *\n * This is intentionally **not** a URL and not a return address: no path, query\n * string or fragment is accepted, and the ZKProofport app never sends the proof\n * there. The proof still comes back to you the same way it always did — over the\n * relay, via `waitForProof()` / `waitForResult()`. `returnScheme` only answers\n * \"which app should come back to the foreground\", exactly like the\n * `redirect.native` value a wallet uses to hand control back after signing.\n *\n * **Omit it and the SDK decides for you.** When the request is created from a\n * page running in Chrome for iOS (`CriOS`) or Firefox for iOS (`FxiOS`), the\n * SDK fills in `'googlechrome://'` or `'firefox://'` by itself: opening either\n * scheme bare brings that browser forward without navigating, so the user lands\n * back on the tab they were already reading. Every other browser sends nothing,\n * because nothing safe exists to send — Safari has no such scheme, and Brave\n * and Arc are indistinguishable from Safari on iOS, so guessing would eject the\n * user into the wrong browser.\n * On Android nothing is needed at all: the ZKProofport app brings itself to the\n * back and the browser resumes exactly as it was. When no target is sent and\n * none can be inferred, the ZKProofport app tells the user the proof was\n * delivered and lets them switch back themselves.\n *\n * There is no auto-switch on proof failure; only on success and on the user\n * declining the request.\n *\n * Rejected with an error before the request is sent: empty or whitespace values,\n * anything longer than 128 characters, values carrying a host/path/query/fragment\n * (including https origins such as `'https://myapp.com'`), and the `http:`,\n * `file:`, `data:`, `javascript:`, `intent:`, `tel:`, `sms:`, `mailto:` families.\n * @returns Promise resolving to RelayProofRequest with requestId, deepLink, pollUrl\n * @throws Error if signer not set, returnScheme is malformed, or the relay request fails\n *\n * @example\n * ```typescript\n * const sdk = ProofportSDK.create();\n * sdk.setSigner(signer);\n *\n * const relay = await sdk.createRelayRequest('coinbase_attestation', {\n * scope: 'myapp.com'\n * }, { dappName: 'My DApp', returnScheme: 'mydapp://' });\n *\n * // Generate QR code from relay deep link\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * // Wait for proof (WebSocket primary, polling fallback)\n * const result = await sdk.waitForProof(relay.requestId);\n * ```\n */\n // Which circuits need a wallet signature, from the one record in\n // src/circuits.ts. A typed-out list here once missed a circuit, so a dapp\n // calling createRelayRequest() for it with no signer got no local error and\n // a relay 401 two round trips later.\n private static needsWalletSignature(circuit: CircuitType): boolean {\n if (!isCircuitId(circuit)) {\n throw new Error(`Unknown circuit '${circuit}'. Expected: ${ALL_CIRCUIT_IDS.join(', ')}`);\n }\n return CIRCUIT_NEEDS_WALLET_SIGNATURE[circuit];\n }\n\n async createRelayRequest(\n circuit: CircuitType,\n inputs: CircuitInputs,\n options: {\n message?: string;\n dappName?: string;\n dappIcon?: string;\n nonce?: string;\n returnScheme?: string;\n } = {}\n ): Promise<RelayProofRequest> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const needsSignature = ProofportSDK.needsWalletSignature(circuit);\n\n if (needsSignature && !this.signer) {\n throw new Error('Signer not set. Call setSigner() first. Wallet signature is required for this circuit.');\n }\n\n // mDL circuits: validate predicate inputs client-side before hitting the\n // relay, so a bad ageThreshold / targetRegion fails fast with a clear error.\n if (circuit === 'mdl_kr_ownership' || circuit === 'mdl_kr_age' || circuit === 'mdl_kr_region') {\n const mdlError = validateMdlInputs(circuit, inputs);\n if (mdlError) {\n throw new Error(`${mdlError} (circuit: ${circuit})`);\n }\n }\n\n // The action, per the circuit's entry in CIRCUIT_ACTION_BINDING. Checked\n // here, before a challenge is burned, because the alternative is a refusal\n // from inside the mobile app -- a screen the dapp developer never sees,\n // reached after the person has already scanned a QR code.\n //\n // The circuit id belongs in the table, not in the check.\n {\n const action = (inputs as { action?: unknown }).action;\n const binding = circuitActionBinding(circuit);\n if (binding === 'none' && action !== undefined) {\n throw new Error(\n `${circuit} has no action inputs, so an action sent with it would not be proved. ` +\n 'Remove it, or use a circuit that binds one.'\n );\n }\n if (binding === 'required' || (binding === 'optional' && action !== undefined)) {\n const actionError = validateTypedAction(action);\n if (actionError) {\n throw new Error(`${actionError} (circuit: ${circuit})`);\n }\n }\n }\n\n // Return target: validated before we burn a challenge, so a typo surfaces\n // as a local error instead of a relay 400 on the second round trip.\n if (options.returnScheme !== undefined) {\n const returnSchemeError = validateReturnScheme(options.returnScheme);\n if (returnSchemeError) {\n throw new Error(returnSchemeError);\n }\n }\n\n // Get challenge + requestId from relay\n const { requestId, challenge } = await this.getChallenge();\n\n const body: Record<string, unknown> = {\n requestId,\n circuitId: circuit,\n inputs,\n challenge,\n };\n\n // The relay never reads `inputs`, so the scope is also sent on the envelope,\n // where the relay counts requests per scope. The app proves the scope inside\n // `inputs` and uses the envelope copy only when `inputs` has none; both are\n // the same string here.\n const scope = (inputs as { scope?: unknown }).scope;\n if (typeof scope === 'string' && scope.length > 0) body.scope = scope;\n\n // Sign challenge for circuits that require wallet signature\n if (needsSignature && this.signer) {\n body.signature = await this.signer.signMessage(challenge);\n }\n\n if (options.message) body.message = options.message;\n if (options.dappName) body.dappName = options.dappName;\n if (options.dappIcon) body.dappIcon = options.dappIcon;\n if (options.nonce) body.nonce = options.nonce;\n // An explicit value always wins. Otherwise ask the SDK to work one out from\n // the page's own user agent — the requesting page is the only side that can\n // (iOS tells the app nothing about who launched it). Both paths can end in\n // \"send nothing\", which is a legitimate outcome, not a failure.\n const returnScheme = options.returnScheme ?? detectReturnScheme();\n if (returnScheme) body.returnScheme = returnScheme;\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/request`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Relay request failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofRequest;\n }\n\n /**\n * Polls the relay for proof result status.\n *\n * @param requestId - The relay-issued request ID\n * @returns Promise resolving to RelayProofResult\n * @throws Error if relay URL not configured or request not found\n *\n * @example\n * ```typescript\n * const result = await sdk.pollResult(relay.requestId);\n * if (result.status === 'completed') {\n * console.log('Proof:', result.proof);\n * console.log('Public inputs:', result.publicInputs);\n * }\n * ```\n */\n async pollResult(requestId: string): Promise<RelayProofResult> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n const response = await fetch(`${this.relayUrl}/api/v1/proof/${requestId}`);\n\n if (!response.ok) {\n if (response.status === 404) {\n throw new Error('Request not found or expired');\n }\n const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));\n throw new Error(error.error || `Poll failed: HTTP ${response.status}`);\n }\n\n return await response.json() as RelayProofResult;\n }\n\n /**\n * Polls the relay until the request reaches a terminal status\n * (`completed`, `error`, `failed`, `cancelled` or `expired`), with\n * configurable interval and timeout. Branch on `result.status`.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Polling options\n * @param options.intervalMs - Polling interval in milliseconds (default: 2000)\n * @param options.timeoutMs - Maximum polling time in milliseconds (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback when status changes\n * @returns Promise resolving to final RelayProofResult\n * @throws Error if timeout or relay error\n */\n async waitForResult(\n requestId: string,\n options: {\n intervalMs?: number;\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const interval = options.intervalMs || 2000;\n const timeout = options.timeoutMs || 300000;\n const startTime = Date.now();\n let lastStatus = '';\n\n while (Date.now() - startTime < timeout) {\n const result = await this.pollResult(requestId);\n\n if (result.status !== lastStatus) {\n lastStatus = result.status;\n options.onStatusChange?.(result);\n }\n\n // Every terminal status ends the wait, not only success: an app error,\n // a cancellation and a relay-side timeout are answers too, and polling\n // past them would only end in this method's own timeout.\n if (isTerminalRelayStatus(result.status)) {\n return result;\n }\n\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n\n throw new Error(`Polling timed out after ${timeout}ms`);\n }\n\n /**\n * Subscribes to real-time proof status updates via Socket.IO.\n *\n * This is the recommended way to receive proof results. Uses WebSocket\n * connection for instant delivery instead of polling.\n *\n * Requires `socket.io-client` package: `npm install socket.io-client`\n *\n * @param requestId - The relay-issued request ID to subscribe to\n * @param callbacks - Event callbacks for status changes and results\n * @param callbacks.onStatus - Called on status updates (pending, generating)\n * @param callbacks.onResult - Called once with the terminal result: completed, error, failed, cancelled or expired\n * @param callbacks.onError - Called on errors\n * @returns Unsubscribe function to clean up the connection\n * @throws Error if relayUrl not set or socket.io-client not installed\n *\n * @example\n * ```typescript\n * const relay = await sdk.createRelayRequest('coinbase_attestation', { scope: 'myapp.com' });\n * const qr = await sdk.generateQRCode(relay.deepLink);\n *\n * const unsubscribe = await sdk.subscribe(relay.requestId, {\n * onResult: (result) => {\n * if (result.status === 'completed') {\n * console.log('Proof received!', result.proof);\n * }\n * },\n * onError: (error) => console.error('Error:', error),\n * });\n *\n * // Later: clean up\n * unsubscribe();\n * ```\n */\n async subscribe(\n requestId: string,\n callbacks: {\n onStatus?: (data: { requestId: string; status: string; deepLink?: string }) => void;\n onResult?: (result: RelayProofResult) => void;\n onError?: (error: { error: string; code?: number; requestId?: string }) => void;\n }\n ): Promise<() => void> {\n if (!this.relayUrl) {\n throw new Error('relayUrl is required. Set it in ProofportSDK config.');\n }\n\n let ioConnect: any;\n try {\n const mod: any = await import('socket.io-client');\n ioConnect = mod.io ?? mod.connect ?? mod.default;\n } catch {\n throw new Error(\n 'socket.io-client is required for real-time updates. Install it: npm install socket.io-client'\n );\n }\n\n if (typeof ioConnect !== 'function') {\n throw new Error('Failed to load socket.io-client: io function not found');\n }\n\n // Connect to relay /proof namespace (no JWT — open connections)\n const socket = ioConnect(`${this.relayUrl}/proof`, {\n path: '/socket.io',\n transports: ['websocket', 'polling'],\n });\n\n this.socket = socket;\n\n // Subscribe to the request room\n socket.on('connect', () => {\n socket.emit('proof:subscribe', { requestId });\n });\n\n // Handle connection errors (e.g. rejected by relay middleware)\n socket.on('connect_error', (err: Error) => {\n console.error(`[ProofportSDK] Socket.IO connect_error for requestId=${requestId}: ${err.message}`);\n callbacks.onError?.({ error: err.message, requestId });\n });\n\n // Listen for events\n if (callbacks.onStatus) {\n socket.on('proof:status', callbacks.onStatus);\n }\n if (callbacks.onResult) {\n socket.on('proof:result', callbacks.onResult);\n }\n if (callbacks.onError) {\n socket.on('proof:error', callbacks.onError);\n }\n\n // Return unsubscribe function\n return () => {\n socket.off('proof:status');\n socket.off('proof:result');\n socket.off('proof:error');\n socket.disconnect();\n if (this.socket === socket) {\n this.socket = null;\n }\n };\n }\n\n /**\n * Waits for a proof result using Socket.IO (primary) with polling fallback.\n *\n * Tries Socket.IO first for real-time delivery. If socket.io-client is not\n * installed or connection fails, automatically falls back to HTTP polling.\n *\n * @param requestId - The relay-issued request ID\n * @param options - Configuration options\n * @param options.timeoutMs - Maximum wait time in ms (default: 300000 = 5 min)\n * @param options.onStatusChange - Callback for status updates\n * @returns Promise resolving to final RelayProofResult\n */\n async waitForProof(\n requestId: string,\n options: {\n timeoutMs?: number;\n onStatusChange?: (result: RelayProofResult | { requestId: string; status: string; deepLink?: string }) => void;\n } = {}\n ): Promise<RelayProofResult> {\n const timeout = options.timeoutMs || 300000;\n\n // Try Socket.IO first\n if (this.relayUrl) {\n try {\n return await new Promise<RelayProofResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n unsubscribePromise?.then(fn => fn());\n reject(new Error(`Waiting for proof timed out after ${timeout}ms`));\n }, timeout);\n\n const unsubscribePromise = this.subscribe(requestId, {\n onStatus: (data) => {\n options.onStatusChange?.(data);\n },\n onResult: (result) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n resolve(result);\n },\n onError: (error) => {\n clearTimeout(timer);\n unsubscribePromise?.then(fn => fn());\n reject(new Error(error.error));\n },\n });\n });\n } catch (err: any) {\n // Re-throw timeout — that's a real failure the caller should handle\n if (err.message?.includes('timed out')) {\n throw err;\n }\n // socket.io-client missing or connection failed → fall back to polling silently\n console.warn('Socket.IO unavailable, falling back to HTTP polling:', err.message);\n }\n }\n\n // Fallback: HTTP polling\n return this.waitForResult(requestId, {\n timeoutMs: timeout,\n onStatusChange: options.onStatusChange as any,\n });\n }\n\n /**\n * Disconnects the Socket.IO connection if active.\n */\n disconnect(): void {\n if (this.socket) {\n this.socket.disconnect();\n this.socket = null;\n }\n }\n\n // ============ Public Input Utilities ============\n\n /**\n * Extracts the scope from proof public inputs.\n *\n * The scope is an application-specific identifier (e.g., domain name) encoded\n * as bytes32 in the proof's public inputs.\n *\n * @param publicInputs - Array of public input hex strings from proof response\n * @param circuit - Circuit type to determine field positions\n * @returns Scope as hex string (0x...), or null if inputs are insufficient\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const scope = sdk.extractScope(result.publicInputs, result.circuit);\n * console.log('Scope:', scope);\n * }\n * ```\n */\n extractScope(publicInputs: string[], circuit: CircuitType): string | null {\n return extractScopeFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the nullifier (bytes32) from proof public inputs.\n *\n * The nullifier is a unique, deterministic hash derived from the user's attestation\n * and scope. It serves as a privacy-preserving user identifier — the same user\n * with the same scope always produces the same nullifier, enabling duplicate\n * detection without revealing the wallet address.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Nullifier as hex string (bytes32), or null if publicInputs too short\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const nullifier = sdk.extractNullifier(result.publicInputs, result.circuit);\n * console.log('Nullifier:', nullifier); // '0xabc123...'\n * }\n * ```\n */\n extractNullifier(publicInputs: string[], circuit: CircuitType): string | null {\n return extractNullifierFromPublicInputs(publicInputs, circuit);\n }\n\n /**\n * Extracts the domain string from OIDC Domain Attestation proof public inputs.\n *\n * Only works with 'oidc_domain_attestation' circuit. Returns null for other circuits.\n *\n * @param publicInputs - Array of hex-encoded field elements from proof result\n * @param circuit - Circuit type that produced the public inputs\n * @returns Domain as ASCII string (e.g., 'example.com'), or null if not applicable\n *\n * @example\n * ```typescript\n * const result = await sdk.waitForProof(relay.requestId);\n * if (result.status === 'completed') {\n * const domain = sdk.extractDomain(result.publicInputs, result.circuit);\n * console.log('Domain:', domain); // 'example.com'\n * }\n * ```\n */\n extractDomain(publicInputs: string[], circuit: CircuitType): string | null {\n return extractDomainFromPublicInputs(publicInputs, circuit);\n }\n\n}\n\nexport default ProofportSDK;\n"],"names":["isCircuitId","ALL_CIRCUIT_IDS","circuitActionBinding","validateTypedAction","CIRCUIT_VK_PATHS","checkProofIssuer","parseProofForOnChain","verifyProofOnChain","getPinnedVerifier","CIRCUIT_NEEDS_WALLET_SIGNATURE","extractScopeFromPublicInputs","extractNullifierFromPublicInputs","extractDomainFromPublicInputs"],"mappings":";;;;;;;;;AAAA;;AAEG;AAIH;;;;;;;;;AASG;AACI,MAAM,UAAU,GAAmC;AACxD,IAAA,UAAU,EAAE,+BAA+B;AAC3C,IAAA,OAAO,EAAE,mC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