@velion-la/onboarding-sdk-web 1.2.0-beta.3 → 1.2.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"velion-sdk.es.js","sources":["../../packages/types/src/index.ts","../../node_modules/@noble/ed25519/index.js","../src/manifest.ts","../src/velion-loader.ts","../src/index.ts"],"sourcesContent":["/**\n * @fileoverview Public TypeScript contracts for the Velion Onboarding SDK.\n *\n * Design principle: All types exported from this file constitute the public API.\n * Internal implementation types should live alongside their respective modules.\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// STEP & FLOW TYPES\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The complete set of onboarding steps the backend can require.\n * The SDK dynamically receives the active subset for each session.\n *\n * @remarks\n * - `DEVICE_FINGERPRINT`: Silently collects device entropy via FingerprintJS.\n * - `DOCUMENTS_OCR`: Renders a UI for ID document image capture and upload.\n * - `LIVENESS_MATCH`: Drives the Velion Iris active-liveness flow over WebSocket (HUMAN only).\n * - `EMAIL_OTP` / `PHONE_OTP`: Contact verification via one-time passwords.\n * - `HUMAN_BASIC_INFO`: Natural-person identification data (HUMAN only).\n * - `LEGAL_BASIC_INFO`: Legal-entity identification data (LEGAL only).\n * - `EMAIL_CONTACT` / `PHONE_CONTACT`: contact collection without OTP.\n * - `TAX_INFO`, `HUMAN_EXTENDED_INFO`, `LEGAL_EXTENDED_INFO`, `ADDRESS_INFO`, `SWORN_DECLARATION`: form steps.\n * - `ECONOMIC_ACTIVITY_DECLARATION`: pick exactly one economic activity from a searchable list.\n * - `TERMS_AND_CONDITIONS`: accept configured T&amp;C items.\n * - `FACE_MATCH`: server-side face comparison after liveness (no user input; SDK waits).\n * - `AML_SCREENING`: server-side PEP / sanctions screening (no user input; never routed to\n * the SDK as `NEXT_STEP`, only visible in `steps[]` and `STEP_UPDATED`).\n */\nexport type OnboardingStep =\n | 'DEVICE_FINGERPRINT'\n | 'HUMAN_BASIC_INFO'\n | 'LEGAL_BASIC_INFO'\n | 'EMAIL_OTP'\n | 'EMAIL_CONTACT'\n | 'PHONE_OTP'\n | 'PHONE_CONTACT'\n | 'TAX_INFO'\n | 'HUMAN_EXTENDED_INFO'\n | 'LEGAL_EXTENDED_INFO'\n | 'ADDRESS_INFO'\n | 'SWORN_DECLARATION'\n | 'ECONOMIC_ACTIVITY_DECLARATION'\n | 'DOCUMENTS_OCR'\n | 'LIVENESS_MATCH'\n | 'FACE_MATCH'\n | 'AML_SCREENING'\n | 'TERMS_AND_CONDITIONS';\n\n/**\n * Status of an individual onboarding step (matches backend OnboardingStepStatus).\n */\nexport type OnboardingStepStatus =\n | 'PENDING'\n | 'IN_PROGRESS'\n | 'COMPLETED'\n | 'SKIPPED'\n | 'FAILED';\n\n/**\n * Type of onboarding session (matches backend OnboardingType).\n * Constrains which steps are valid: HUMAN allows biometric steps, LEGAL uses entity data.\n */\nexport type OnboardingType = 'HUMAN' | 'LEGAL';\n\n/** Which face of the ID document is being captured. */\nexport type DocumentSide = 'FRONT' | 'BACK';\n\n/**\n * How the user can provide document images in the DOCUMENTS_OCR step.\n * - `'camera'`: Only \"Take photo\" (opens camera on supported devices).\n * - `'file'`: Only \"Choose file\" (file picker).\n * - `'both'`: Both options; implementer can style via theme.\n *\n * @default 'both'\n */\nexport type DocumentCaptureMode = 'camera' | 'file' | 'both';\n\n/**\n * Orientation of the document capture cutout / crop frame.\n * - `'landscape'`: Horizontal card (default — standard ID-1 cards).\n * - `'portrait'`: Vertical card (e.g. some passports, residence permits).\n *\n * @default 'landscape'\n */\nexport type DocumentOrientation = 'landscape' | 'portrait';\n\n/**\n * Optional overrides for document OCR UI (not part of `VelionConfig`; used internally).\n */\nexport interface DocumentsConfig {\n /**\n * When true (default), the document camera preview is mirrored (like selfie mode).\n * Set to false if the back camera shows the document inverted.\n *\n * @default true\n */\n mirrorDocumentVideo?: boolean;\n\n /**\n * Orientation of the document capture frame and crop.\n * - `'landscape'`: Horizontal card (default — standard ID-1 cards).\n * - `'portrait'`: Vertical card.\n *\n * @default 'landscape'\n */\n documentOrientation?: DocumentOrientation;\n}\n\n/** Generic visible/required field toggle used by workflow step configs. */\nexport interface StepFieldRule {\n visible: boolean;\n required: boolean;\n}\n\n/** Select option used by configurable step fields (e.g. HUMAN_EXTENDED_INFO gender/civil_status). */\nexport interface StepFieldOption {\n id: string;\n display_value?: string;\n}\n\n/** Field rule with optional selectable options. */\nexport interface StepFieldRuleWithOptions extends StepFieldRule {\n options?: StepFieldOption[];\n}\n\n/** STEP config for HUMAN_BASIC_INFO. */\nexport interface HumanBasicInfoStepConfig {\n accepted_country_documents?: Array<{\n country_code: string;\n document_types: Array<{ id: string; display_value?: string }>;\n }>;\n}\n\n/**\n * One selectable option row from TAX_INFO `accepted_tax_information` (backend GET session).\n * Prefer `code` as the value sent in POST tax-info; `id` is supported for older payloads.\n */\nexport interface TaxInfoConfigOptionRow {\n code?: string;\n id?: string;\n display_value?: string;\n tax_code?: string;\n}\n\n/** One country block in TAX_INFO step config (GET session `current_step.config`). */\nexport interface TaxInfoAcceptedCountryRow {\n country_code: string;\n identification_types?: TaxInfoConfigOptionRow[];\n /** Options for the \"Categoría fiscal\" / taxpayer category select. */\n taxpayer_categories?: TaxInfoConfigOptionRow[];\n}\n\n/** STEP config for TAX_INFO. */\nexport interface TaxInfoStepConfig {\n /** Identification types + taxpayer categories per country. */\n accepted_tax_information?: TaxInfoAcceptedCountryRow[];\n}\n\n/** STEP config for HUMAN_EXTENDED_INFO. */\nexport interface HumanExtendedInfoStepConfig {\n /** Optional top-level lists sent by backend for select fields. */\n gender_options?: StepFieldOption[];\n civil_status_options?: StepFieldOption[];\n fields?: Partial<\n Record<\n 'gender' | 'civil_status' | 'birth_date' | 'birth_country' | 'citizenship' | 'residence_country',\n StepFieldRuleWithOptions\n >\n >;\n}\n\n/** STEP config for ADDRESS_INFO. */\nexport interface AddressInfoStepConfig {\n address_type?: { id?: string; display_value?: string };\n fields?: Partial<\n Record<\n 'state' | 'city' | 'district' | 'neighborhood' | 'postal_code' | 'street' | 'number',\n StepFieldRule\n >\n >;\n /**\n * Optional ISO 3166-1 alpha-2 allowlist for the country selector. Only\n * consumed by the manual-entry form (when the SDK is configured without a\n * Google Maps key). When unset, every country is offered.\n */\n country_allow?: string[];\n}\n\n/** STEP config for SWORN_DECLARATION. */\nexport interface SwornDeclarationStepConfig {\n ask_pep?: boolean;\n ask_obligated_subject?: boolean;\n ask_fatca?: boolean;\n ask_ocde?: boolean;\n on_declared_pep?: string;\n on_declared_obligated_subject?: string;\n on_declared_fatca?: string;\n on_declared_ocde?: string;\n}\n\n/**\n * A single selectable economic activity presented in the\n * `ECONOMIC_ACTIVITY_DECLARATION` step. Mirrors the backend `EconomicActivityItem`\n * (`code` + `display_name`); `code` is unique within the list and is what the SDK\n * submits. There is no global catalog — each workflow declares its own list.\n */\nexport interface EconomicActivityItem {\n /** Machine-readable activity code (e.g. an AFIP/CLAE code) — unique within the list. */\n code: string;\n /** Human-readable label shown to the user. */\n display_name: string;\n}\n\n/** STEP config for ECONOMIC_ACTIVITY_DECLARATION (`current_step.config`). */\nexport interface EconomicActivityStepConfig {\n /** Selectable activities; always non-empty when the step is active. */\n items?: EconomicActivityItem[];\n}\n\n/** STEP config for DOCUMENTS_OCR. */\nexport interface DocumentsOcrStepConfig {\n country_allow?: string[];\n capture_methods?: {\n camera_scan?: boolean;\n upload?: boolean;\n };\n /** Crop frame orientation for document camera capture. */\n document_orientation?: DocumentOrientation;\n /**\n * Force the document camera preview mirroring. When absent the SDK decides\n * from the camera the browser opened: front mirrored, rear not. Only the\n * preview is affected; the uploaded crop is never mirrored.\n */\n mirror_document_video?: boolean;\n}\n\n/** STEP config for TERMS_AND_CONDITIONS. */\nexport interface TermsAndConditionsStepConfig {\n terms?: Array<{ title?: string; url?: string }>;\n}\n\n/** Generic per-step runtime config map carried by session state and SSE. */\nexport type StepConfigMap = Partial<Record<OnboardingStep, Record<string, unknown>>>;\n\n/**\n * Request body for POST /sessions/:sessionId/documents-init.\n * Allowed values are defined by the backend; the SDK currently sends a fixed type until\n * the session exposes selectable document types.\n */\nexport interface DocumentsInitRequest {\n document_type: string;\n}\n\n/**\n * Response from POST /sessions/:sessionId/documents-init.\n * Backend returns signed upload URLs so the SDK can PUT each document side\n * directly to storage (e.g. GCS) without routing bytes through the backend.\n */\n/**\n * Response of `POST /sessions/:id/documents-init`.\n *\n * Each URL is a GCS V4 signed PUT issued by the Velion CDN, valid for about\n * two minutes, and signed over `host`, `content-type` and\n * `x-goog-content-length-range`. The PUT must therefore send\n * `Content-Type: image/jpeg` **and** `x-goog-content-length-range:\n * 0,<max_file_size_bytes>` byte for byte, or GCS answers 400\n * `MalformedSecurityHeader` (OSDKW-5). Request the URLs right before the\n * upload, never ahead of the capture.\n */\nexport interface DocumentsInitResponse {\n /** Pre-signed URL to upload the front side (PUT, see the interface docs for the required headers). */\n front_side_upload_url: string;\n /** Pre-signed URL to upload the back side (PUT, see the interface docs for the required headers). */\n back_side_upload_url: string;\n /**\n * Upper bound the URLs were signed for; the exact number that goes into the\n * `x-goog-content-length-range` header. Also usable to reject oversize\n * captures before the PUT.\n */\n max_file_size_bytes?: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// ERROR TYPES\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Granular error codes for camera/hardware failures.\n * Allows consumers to display localized, actionable messages to end-users.\n */\nexport enum CameraErrorCode {\n /** User explicitly denied camera access in the browser permission dialog. */\n PERMISSION_DENIED = 'CAMERA_PERMISSION_DENIED',\n /** No camera device was detected on the system. */\n DEVICE_NOT_FOUND = 'CAMERA_DEVICE_NOT_FOUND',\n /**\n * The camera could not be opened for reading (often in use by another app,\n * or blocked at the OS level). Maps to `NotReadableError` / `TrackStartError`.\n */\n DEVICE_NOT_READABLE = 'CAMERA_DEVICE_NOT_READABLE',\n /**\n * The page is served over HTTP (not HTTPS) in a production environment.\n * `getUserMedia` is blocked by the browser's Secure Context policy.\n */\n INSECURE_CONTEXT = 'CAMERA_INSECURE_CONTEXT',\n /**\n * Browser policy blocked camera (e.g. cross-origin iframe without permission,\n * or `Permissions-Policy` / Feature-Policy denying camera). Maps to `SecurityError`\n * from `getUserMedia` — distinct from {@link INSECURE_CONTEXT} (non-HTTPS).\n */\n POLICY_BLOCKED = 'CAMERA_POLICY_BLOCKED',\n /** The browser or WebView does not support the `getUserMedia` API. */\n NOT_SUPPORTED = 'CAMERA_NOT_SUPPORTED',\n /**\n * Camera access is blocked by a WebView policy (common in in-app browsers\n * on iOS/Android that restrict hardware access).\n */\n WEBVIEW_BLOCKED = 'CAMERA_WEBVIEW_BLOCKED',\n /** The requested video constraints (resolution, facing mode) are not satisfiable. */\n CONSTRAINT_ERROR = 'CAMERA_CONSTRAINT_ERROR',\n /** An unclassified camera error occurred. Check `cause` for details. */\n UNKNOWN = 'CAMERA_UNKNOWN_ERROR',\n}\n\n/**\n * Top-level SDK error codes covering all failure scenarios in the onboarding flow.\n */\nexport enum SdkErrorCode {\n // ── Session ──────────────────────────────────────────────────────────────\n /** The sessionToken was rejected by the backend (401/403). */\n SESSION_INVALID = 'SESSION_INVALID',\n /** The sessionToken has expired (typically a 401 after initial validation). */\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n /** Could not fetch the initial session state from the backend. */\n SESSION_FETCH_FAILED = 'SESSION_FETCH_FAILED',\n /** Backend sent SESSION_DECLINED over SSE; session ended before completion. */\n SESSION_DECLINED = 'SESSION_DECLINED',\n /**\n * A step was completed but the backend did not route the session to the\n * next one within `routingTimeoutMs` (default 120 s): no `ROUTING_COMMAND`\n * arrived over SSE and `GET /sessions/:id` kept reporting the completed\n * step. The session is still alive on the backend; `stepCode` names the\n * completed step. Typical cause: a delayed or stalled onboarding worker.\n */\n ROUTING_TIMEOUT = 'ROUTING_TIMEOUT',\n\n // ── Modules ──────────────────────────────────────────────────────────────\n /** FingerprintJS failed to generate the visitor ID. */\n FINGERPRINT_FAILED = 'FINGERPRINT_FAILED',\n /** One or more document images failed to upload successfully. */\n DOCUMENT_UPLOAD_FAILED = 'DOCUMENT_UPLOAD_FAILED',\n /** The liveness check did not pass or returned an unexpected result. */\n LIVENESS_FAILED = 'LIVENESS_FAILED',\n /** The Liveness module failed to initialize (e.g., could not create the Iris session). */\n LIVENESS_INIT_FAILED = 'LIVENESS_INIT_FAILED',\n /**\n * The recorded liveness session video could not be uploaded to storage.\n * Best-effort only: this never fails the liveness step — it is logged so the\n * back-office knows the playback evidence is missing for the session.\n */\n LIVENESS_VIDEO_UPLOAD_FAILED = 'LIVENESS_VIDEO_UPLOAD_FAILED',\n\n // ── Camera ───────────────────────────────────────────────────────────────\n /**\n * A camera-related error occurred. Inspect `cameraCode` for the specific reason.\n * @see CameraErrorCode\n */\n CAMERA_ERROR = 'CAMERA_ERROR',\n\n // ── Network & API ────────────────────────────────────────────────────────\n /** A network-level failure (no internet, CORS, DNS). */\n NETWORK_ERROR = 'NETWORK_ERROR',\n /** The backend returned a non-2xx HTTP status. */\n API_ERROR = 'API_ERROR',\n\n // ── Configuration ────────────────────────────────────────────────────────\n /** The `containerId` provided in the config does not exist in the DOM. */\n CONTAINER_NOT_FOUND = 'CONTAINER_NOT_FOUND',\n /** `start()` was called on an SDK instance that is already running. */\n ALREADY_STARTED = 'ALREADY_STARTED',\n /** `start()` was called after `destroy()`. The instance is no longer usable. */\n INSTANCE_DESTROYED = 'INSTANCE_DESTROYED',\n\n /**\n * The page is running inside an iframe and embedding was not explicitly allowed.\n * Configure Content-Security-Policy: frame-ancestors or X-Frame-Options on the\n * page that hosts the SDK, or set allowEmbedded: true if embedding is intentional.\n */\n INSECURE_EMBED = 'INSECURE_EMBED',\n\n /**\n * The CDN-served runtime failed verification: the manifest could not be\n * downloaded or its Ed25519 signature did not verify against the loader's\n * embedded public key; the signed manifest is for another major, older than the\n * minimum runtime the loader accepts (rollback) or does not name its entry\n * digest; or the entry HTML or one of its scripts does not match the manifest.\n * The loader refuses to mount the iframe to prevent execution of\n * tampered/unsigned bundles. Also raised by the mounted runtime when data it\n * reads from its CDN after boot (the country subdivisions of `ADDRESS_INFO`)\n * does not match the digest pinned in its bundle; the flow then stops.\n */\n INTEGRITY_FAILED = 'INTEGRITY_FAILED',\n /**\n * The browser cannot verify the CDN manifest signature at all (no WebCrypto\n * `crypto.subtle`, typically an insecure `http://` context). Unlike\n * `INTEGRITY_FAILED` this is not a tampering signal; the loader still refuses\n * to mount the iframe because the runtime cannot be verified.\n */\n UNSUPPORTED_BROWSER = 'UNSUPPORTED_BROWSER',\n /**\n * The runtime could not be started or was lost:\n * - the iframe loaded but the runtime never reported `VELION_READY` within\n * `runtimeReadyTimeoutMs` (default 30 s). Typical causes: the CDN serves an\n * `index.html` whose hashed assets are missing (deploy under the wrong\n * prefix), a Content-Security-Policy on the host blocking the runtime's\n * scripts, or the runtime crashing before it could boot. Without this the\n * host saw a blank iframe and no callback at all;\n * - the loader could not download the entry or its scripts to verify them;\n * - the iframe reloaded after the session started. The loader does not resend\n * the session token to a document it did not verify; a new instance resumes\n * from the backend's current step.\n */\n RUNTIME_LOAD_FAILED = 'RUNTIME_LOAD_FAILED',\n\n UNKNOWN = 'UNKNOWN',\n}\n\n/**\n * A structured, machine-readable error object emitted by the SDK.\n *\n * @example\n * ```typescript\n * const sdk = new VelionOnboarding({\n * onError: (err) => {\n * if (err.code === SdkErrorCode.CAMERA_ERROR &&\n * err.cameraCode === CameraErrorCode.PERMISSION_DENIED) {\n * showCameraPermissionDialog();\n * }\n * }\n * });\n * ```\n */\nexport interface SdkError {\n /** Primary SDK-level error classification. */\n readonly code: SdkErrorCode;\n /** Human-readable English description for developer logging. */\n readonly message: string;\n /** Present when `code === SdkErrorCode.SESSION_DECLINED` (SSE `reason`). */\n readonly declineReason?: string;\n /**\n * Step the error refers to. For `SESSION_DECLINED` it is the SSE `step_code`;\n * for `ROUTING_TIMEOUT` it is the step that was completed and never routed.\n */\n readonly stepCode?: string;\n /**\n * Localized headline resolved by the SDK for SESSION_DECLINED.\n * Useful when hosts hide the built-in final result screen but still want\n * the same user-facing text in custom UI.\n */\n readonly declineTitle?: string;\n /**\n * Localized body message resolved by the SDK for SESSION_DECLINED.\n * Mirrors the text shown in the built-in final result screen.\n */\n readonly declineMessage?: string;\n /** Present when `code === SdkErrorCode.CAMERA_ERROR`. Provides camera-specific detail. */\n readonly cameraCode?: CameraErrorCode;\n /** HTTP status code when the error originated from an API call. */\n readonly httpStatus?: number;\n /**\n * The original caught value for debugging.\n * Not guaranteed to be an `Error` instance — could be a DOMException or string.\n */\n readonly cause?: unknown;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// THEMING\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * White-labeling theme configuration.\n * Each property maps to a CSS custom property injected on the SDK container,\n * making all SDK UI elements styleable via `--vl-*` variables.\n *\n * @example\n * ```typescript\n * const theme: VelionTheme = {\n * primaryColor: '#0052CC', // → --vl-primary-color\n * borderRadius: '12px', // → --vl-border-radius\n * fontFamily: 'Inter, sans-serif'// → --vl-font-family\n * };\n * ```\n */\nexport interface VelionTheme {\n /** Primary brand color. Used for buttons, progress indicators, and accents. */\n primaryColor?: string;\n /** Secondary color. Used for hover states and secondary actions. */\n secondaryColor?: string;\n /** Background color of the SDK container. */\n backgroundColor?: string;\n /** Main body text color. */\n textColor?: string;\n /** Secondary text color for subtitles, captions, and de-emphasized copy. */\n textSecondaryColor?: string;\n /** Border radius for cards, buttons, and inputs. */\n borderRadius?: string;\n /** Font family string. Must be available in the host page's CSS context. */\n fontFamily?: string;\n /** Color used for error states and destructive actions. */\n errorColor?: string;\n /** Color used for success confirmations. */\n successColor?: string;\n /** Color used for warnings and informational alerts. */\n warningColor?: string;\n /** Border color for input fields and separators. */\n borderColor?: string;\n /** Box shadow definition for elevated elements (cards, modals). */\n cardShadow?: string;\n\n /**\n * When `true`, the round icon that sits above each step's title is hidden.\n * Only the title and subtitle are rendered. Useful when the host UI already\n * provides its own visual identity per step or when a denser layout is\n * preferred.\n *\n * @default false\n */\n hideStepIcons?: boolean;\n\n /**\n * When `true`, the thin progress bar at the top of the SDK container is\n * hidden. Equivalent to setting `VelionConfig.showProgressBar: false` —\n * either flag is enough to disable it (whichever is more convenient given\n * how the host configures the SDK). Disable when your host UI already\n * surfaces its own progress indicator.\n *\n * @default false\n */\n hideProgressBar?: boolean;\n}\n\n/**\n * Optional title and body for one terminal verdict on the final result screen.\n */\nexport interface VelionFinalResultStatusCopy {\n title?: string;\n message?: string;\n}\n\n/**\n * Configurable copy for the built-in final result screen (`showFinalResultScreen`).\n * Omitted fields fall back to SDK defaults for the active `locale`.\n */\nexport interface VelionFinalResultScreenTexts {\n approved?: VelionFinalResultStatusCopy;\n manualReview?: VelionFinalResultStatusCopy;\n rejected?: VelionFinalResultStatusCopy;\n /** Copy when {@link OnboardingResult.status} is `DECLINED`. */\n declined?: VelionFinalResultStatusCopy;\n /** Primary button label (e.g. \"Entendido\" / \"Got it\"). */\n dismissLabel?: string;\n}\n\n/**\n * Localized title/body for one `reason` on the SESSION_DECLINED screen.\n * Keys match backend `reason` (e.g. `TAX_INFO_FAILED`).\n */\nexport interface VelionSessionDeclinedReasonMessages {\n en?: VelionFinalResultStatusCopy;\n es?: VelionFinalResultStatusCopy;\n}\n\n/**\n * Per-reason overrides for the built-in SESSION_DECLINED screen (`showFinalResultScreen` not false).\n * Unspecified reasons fall back to SDK defaults when available, then generic copy.\n */\nexport type VelionSessionDeclinedReasonTexts = Record<\n string,\n VelionSessionDeclinedReasonMessages\n>;\n\n/**\n * Per-step overrides for the retry dialog shown when the backend emits a\n * `ROUTING_COMMAND / RETRY_STEP` (the step failed but the retry quota is not\n * exhausted). Keyed by step code (e.g. `LIVENESS_MATCH`, `DOCUMENTS_OCR`).\n * Unspecified steps fall back to SDK per-step defaults, then generic copy.\n *\n * Note: the SDK intentionally ignores the backend `reason` for this dialog —\n * it is a diagnostic string (e.g. `\"STEP_FAILED_RETRY_ALLOWED (attempt 1/3)\"`),\n * not user-facing localized copy. The copy is derived from the step instead.\n */\nexport type VelionRetryStepTexts = Record<\n string,\n VelionSessionDeclinedReasonMessages\n>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// CALLBACKS\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The complete set of lifecycle callbacks the host application can subscribe to.\n * All callbacks are optional. The SDK is still functional without any of them,\n * but `onError` and `onSuccess` are strongly recommended for production.\n */\nexport interface VelionCallbacks {\n /**\n * Fires when the entire onboarding flow has been completed successfully\n * and the backend has confirmed the session as resolved.\n *\n * @param result - Final onboarding verdict from the backend.\n */\n onSuccess?: (result: OnboardingResult) => void;\n\n /**\n * Fires when an unrecoverable error terminates the onboarding flow.\n * Any terminal failure (camera error, document capture failure, upload failure,\n * liveness failure, API error, etc.) is delivered here so the host can notify the user.\n * After this callback, the SDK instance is in an error state.\n * Call `sdk.destroy()` and re-instantiate to retry.\n *\n * @param error - Structured error with a machine-readable code (e.g. CAMERA_ERROR, DOCUMENT_UPLOAD_FAILED).\n */\n onError?: (error: SdkError) => void;\n\n /**\n * Fires each time the active step changes during the flow.\n * Useful for updating a custom step indicator in the host UI.\n *\n * The required step list is resolved dynamically by the backend, so the SDK\n * does not know the total step count up front. Callers that need a progress\n * indicator should rely on the SDK's built-in progress bar (or the trickling\n * counter in `stepIndex`).\n *\n * @param step - The step that just became active.\n * @param stepIndex - Zero-based index of the current step.\n */\n onStepChange?: (step: OnboardingStep, stepIndex: number) => void;\n\n /**\n * Fires immediately after a step succeeds, before advancing to the next one.\n * Useful for analytics or triggering intermediate UI transitions.\n *\n * @param step - The step that was just completed.\n */\n onStepComplete?: (step: OnboardingStep) => void;\n\n /**\n * Fires for each SSE event from GET /sessions/:sessionId/events\n * (e.g. STEP_UPDATED, SESSION_APPROVED).\n */\n onSessionEvent?: (event: OnboardingSessionEvent) => void;\n\n /**\n * Called when the user taps the dismiss control on the final result screen\n * (only when the final result screen is shown). `onSuccess` has already run.\n */\n onFinalResultScreenDismiss?: () => void;\n\n /**\n * Fires when the LIVENESS_MATCH step successfully uploaded the recorded\n * session video to the onboarding storage (GCS PUT returned 200). Best-effort:\n * if the upload failed, timed out, or the session had no `video_upload` URL,\n * the callback is not invoked — liveness still completes normally.\n *\n * @param ref - URL and metadata of the uploaded video.\n */\n onLivenessVideoUploaded?: (ref: LivenessVideoRef) => void;\n\n /**\n * Fires when the user leaves the onboarding flow without a terminal verdict —\n * either by tapping \"back\" on the first reversible step (`BACK_EXIT`) or\n * \"Cancel\" on the retry dialog shown after a `RETRY_STEP` (`RETRY_CANCELLED`).\n * In both cases the backend told the SDK to leave the flow and hand control\n * back to the host; the SDK has already torn down its UI.\n *\n * Distinct from `onSuccess` (a terminal verdict) and `onError` (a failure):\n * the host should typically dismiss/close the SDK surface when this fires.\n *\n * @param exit - Why the flow exited and the step it exited from.\n */\n onExit?: (exit: OnboardingExit) => void;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// MAIN CONFIGURATION\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root configuration object for the `VelionOnboarding` class.\n *\n * @example\n * ```typescript\n * const sdk = new VelionOnboarding({\n * containerId: 'velion-root',\n * sessionId: 'ses_abc123',\n * sessionToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',\n * apiUrl: 'https://api.velion.la/v1',\n * theme: { primaryColor: '#0052CC' },\n * onSuccess: (result) => console.log('Done!', result),\n * onError: (err) => console.error('SDK Error:', err),\n * });\n *\n * await sdk.start();\n * ```\n */\nexport interface VelionConfig extends VelionCallbacks {\n /**\n * The `id` of an existing DOM element where the SDK will render its UI.\n * The element **must** be present in the document at the time `start()` is called.\n *\n * @example `'velion-kyc-container'`\n */\n containerId: string;\n\n /**\n * The unique session identifier generated by your backend for this\n * onboarding session. Used to scope all API calls.\n *\n * @example `'ses_9f8d7c6b5a4e3f2d'`\n */\n sessionId: string;\n\n /**\n * A short-lived, opaque authorization token (e.g. HS256 JWT) issued by your\n * backend when creating the session. Sent as `Authorization: Bearer <sessionToken>`\n * on every SDK request. Required for all endpoints behind the gateway.\n *\n * **Security note:** This token is held in memory only (never in localStorage\n * or cookies) and is automatically discarded on `destroy()`.\n */\n sessionToken: string;\n\n /**\n * ISO-8601 expiry timestamp of the sessionToken. If provided, the SDK may\n * check expiration before requests and emit SESSION_EXPIRED without a round-trip.\n * When the backend returns 401/403, the SDK emits SESSION_EXPIRED anyway.\n */\n expiresAt?: string;\n\n /**\n * Base URL of the Velion onboarding edge. Must **not** include a trailing slash.\n * SDK paths are relative to this (e.g. GET `/sessions/{sessionId}`).\n *\n * Defaults to the public production edge `https://sdk.velion.la/onboarding`.\n * Override only for staging or self-hosted environments.\n */\n apiUrl?: string;\n\n /**\n * Optional white-labeling theme. If omitted, SDK renders with Velion defaults.\n */\n theme?: VelionTheme;\n\n /**\n * Global visual mode for SDK overlays and controls.\n * - `'light'`: Light translucent surfaces.\n * - `'dark'`: Dark translucent surfaces.\n *\n * @default 'light'\n */\n colorMode?: 'light' | 'dark';\n\n /**\n * BCP 47 locale tag for SDK UI copy (labels, instructions, error messages).\n *\n * @default 'es'\n */\n locale?: string;\n\n /**\n * When `true`, after the backend returns a terminal verdict the SDK shows a\n * full-screen summary (APPROVED, MANUAL_REVIEW, REJECTED) inside the container,\n * styled with `theme` and `colorMode`. `onSuccess` still fires with the result.\n *\n * @default true\n */\n showFinalResultScreen?: boolean;\n\n /**\n * When `true` (default), the SDK renders a thin progress bar at the top of\n * the container that advances as the user moves through steps. Disable for\n * embedded experiences that already provide their own progress UI.\n *\n * @default true\n */\n showProgressBar?: boolean;\n\n /**\n * Overrides for default titles, messages, and dismiss button on the final result screen.\n * Only used when the final result screen is shown (`showFinalResultScreen` is not `false`).\n */\n finalResultScreenTexts?: VelionFinalResultScreenTexts;\n\n /**\n * Optional copy for SESSION_DECLINED SSE screens, keyed by backend `reason`.\n * Merged with SDK defaults (e.g. `TAX_INFO_FAILED`) for `locale` `en` / `es`.\n */\n sessionDeclinedReasonTexts?: VelionSessionDeclinedReasonTexts;\n\n /**\n * Optional copy for the retry dialog (`ROUTING_COMMAND / RETRY_STEP`), keyed by\n * step code (e.g. `LIVENESS_MATCH`). Merged with SDK per-step defaults for\n * `locale` `en` / `es`; unspecified steps fall back to generic retry copy.\n */\n retryStepTexts?: VelionRetryStepTexts;\n\n /**\n * When `true` (default), shows the Velion preparation screen (face icon, tips,\n * \"Start verification\") before connecting to Iris. When `false`, skips it and\n * starts the camera + Iris session immediately on step entry.\n *\n * @default true\n */\n livenessShowIntro?: boolean;\n\n /**\n * When `false`, hides the \"Atrás\" / \"Back\" button on the liveness preparation\n * screen. The button is only present in the intro; once the camera capture\n * begins the user must complete the Iris challenges to leave the step.\n *\n * @default true\n */\n livenessShowBackButton?: boolean;\n\n /**\n * If true, allows the SDK to run when the page is inside an iframe.\n * Only set to true if you have configured Content-Security-Policy: frame-ancestors\n * or X-Frame-Options on the HTTP response of the page that hosts the SDK.\n * If false (default) and the page is embedded in an iframe, the SDK emits\n * INSECURE_EMBED and does not start.\n *\n * @default false\n */\n allowEmbedded?: boolean;\n\n /**\n * Internal — set by the Velion CDN entry (`cdn-main.ts`) to the `event.origin`\n * captured from the loader's first VELION_INIT message. The SDK validates it\n * against `allowed_parent_origins` returned by the backend and refuses to start\n * if the origin is not in the customer's registered allowlist.\n *\n * Direct integrators (running VelionOnboarding without the loader iframe)\n * should leave this unset.\n *\n * @internal\n */\n iframeParentOrigin?: string;\n\n /**\n * Fingerprint Pro API endpoint (custom subdomain). Used by the DEVICE_FINGERPRINT\n * step to load and identify visitors. Only set this when using a custom Fingerprint\n * subdomain or proxy; otherwise the default Velion endpoint is used.\n *\n * @default 'https://fp.velion.la'\n */\n fingerprintEndpoint?: string;\n\n /**\n * Fingerprint Pro public API key. Used by the DEVICE_FINGERPRINT step to\n * identify visitors. Defaults to the shared Velion public key — set this\n * only when your tenant has its own Fingerprint workspace.\n *\n * @default Velion's shared public key\n */\n fingerprintApiKey?: string;\n\n /**\n * Hard ceiling, in milliseconds, for the DEVICE_FINGERPRINT step (agent\n * load + identification). The Fingerprint agent has its own internal\n * timeout, but with tracker blockers or a blackholed endpoint it can hang\n * well past it; the SDK races against this value so the step fails with\n * `FINGERPRINT_FAILED` instead of leaving the user on a blank screen.\n *\n * @default 15000\n */\n fingerprintTimeoutMs?: number;\n\n /**\n * Total wait, in milliseconds, for the backend to route the session after a\n * step is completed. The SDK waits for the SSE `ROUTING_COMMAND` and falls\n * back to `GET /sessions/:id` every 30 s; when the backend keeps reporting\n * the completed step (delayed or stalled worker) those cycles used to repeat\n * for ever. Past this bound the flow fails with `ROUTING_TIMEOUT` so the host\n * gets a callback instead of an endless spinner.\n *\n * @default 120000\n */\n routingTimeoutMs?: number;\n\n /**\n * Google Maps Platform API key (Maps JavaScript API + Places). Required for the\n * {@code ADDRESS_INFO} step to show the map, search, and geocoding. Omit only if\n * your flow never reaches that step.\n */\n googleMapsApiKey?: string;\n\n /**\n * Optional calibration tag forwarded to Iris for the LIVENESS_MATCH step.\n * When the Iris worker is running with `CALIBRATION_BACKEND=fs|gcs`, every\n * frame of this session is mirrored to the dataset bucket with the tag in\n * `metadata.json`, so we can build labeled training sets for the spoof /\n * liveness models. Does NOT affect the score.\n *\n * Suggested values (must match the worker's known labels — see\n * `iris-worker` README): `REAL_GOOD_LIGHT`, `REAL_BAD_LIGHT`, `REAL_BACKLIT`,\n * `REAL_BUSY_BG`, `REAL_NEUTRAL_BG`, `REAL_GLASSES`, `REAL_OUTDOOR`,\n * `FAKE_PHONE_PHOTO`, `FAKE_PHONE_VIDEO`, `FAKE_TABLET_VIDEO`,\n * `FAKE_MONITOR_VIDEO`, `FAKE_PRINT`, `FAKE_MASK`, `UNKNOWN`, `EDGE_CASE`.\n *\n * Leave undefined for normal user-facing sessions.\n */\n livenessCalibrationLabel?: string;\n\n /**\n * When true, the SDK enables verbose `console.info` logging at runtime even in\n * production builds. Useful when reproducing customer issues. Independent of the\n * build-time `__DEBUG__` flag, which already gates dev-server logs.\n *\n * @default false\n */\n debug?: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// BACKEND RESPONSE SHAPES\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Backend step DTO (OnboardingStepDto). GET session returns an array of these.\n */\nexport interface OnboardingStepDto {\n code: string;\n name?: string;\n description?: string;\n order?: number;\n status?: string;\n /**\n * Machine-readable cause of the current `status` when it is `FAILED` or\n * `MANUAL_REVIEW` (backend `StepStatusDetailCode`, VON-54 / VON-56). Examples:\n * `DOC_UNREADABLE`, `DOC_MRZ_NOT_READABLE`, `DOC_EXPIRED`, `DOC_AGE_EXCLUSION`,\n * `LIVENESS_BELOW_THRESHOLD`, `LIVENESS_SPOOF_SUSPECTED`,\n * `FACE_MATCH_BELOW_THRESHOLD`, `FINGERPRINT_BOT_DETECTED`,\n * `TAX_ARCA_VALIDATION_FAILED`, `TERMS_NOT_ACCEPTED`,\n * `ECONOMIC_ACTIVITY_INVALID_SELECTION`, `STEP_UNEXPECTED_ERROR`. Hosts may\n * use it for analytics or support tooling; the SDK derives its user-facing\n * copy from the step, never from this code.\n */\n status_detail?: string;\n required?: boolean;\n /** Step-specific payload (e.g. OCR fields, fingerprint, T&amp;C items). */\n result?: Record<string, unknown>;\n /** Raw workflow config for this step (thresholds, accepted documents, …). */\n config?: Record<string, unknown>;\n /**\n * Whether the user may navigate back INTO this step after completing it\n * (intrinsic per-step flag the backend stamps from the workflow). Used only\n * to derive `can_go_back` for steps reached via SSE (which doesn't carry the\n * flag) and for prefill — NOT to decide whether to render the back button.\n * @see OnboardingDtoResponse.can_go_back\n */\n reversible?: boolean;\n}\n\n/**\n * Backend session/onboarding DTO (OnboardingDto). Returned by GET /sessions/:sessionId.\n * The SDK maps this to SessionState for the step machine.\n */\nexport interface OnboardingDtoResponse {\n id?: string;\n related_id?: string;\n onboarding_type?: string;\n status?: string;\n current_step?: {\n code?: string;\n status?: string;\n config?: Record<string, unknown>;\n /**\n * Previously-captured data for this step, present when a reverse navigation\n * re-opened a completed step. The SDK uses it as editable prefill.\n */\n result?: Record<string, unknown>;\n /** Intrinsic per-step reversibility (prefill / SSE-derivation only). */\n reversible?: boolean;\n };\n steps?: OnboardingStepDto[];\n created_at?: string;\n updated_at?: string;\n completed_at?: string;\n metadata?: Record<string, unknown>;\n /**\n * Whether the SDK should render the \"back\" control on the current step.\n * Computed server-side from the workflow graph (barrier model): `true` when\n * there is a previous reversible step to re-open, OR when the current step is\n * the first reversible step (back exits the flow via `BACK_EXIT`). The SDK\n * uses **this** — not a step's intrinsic `reversible` flag — to decide whether\n * to show the back button.\n */\n can_go_back?: boolean;\n /**\n * Origins (scheme + host + port) authorized by the customer to embed the SDK.\n * The iframe validates `event.origin` of the loader's first VELION_INIT against\n * this list and aborts with INSECURE_EMBED otherwise. Backend must also enforce\n * server-side via the `Origin` header on every API call.\n */\n allowed_parent_origins?: string[];\n}\n\n/**\n * Session state used by the SDK step machine. Derived from GET /sessions/:sessionId\n * (OnboardingDto): steps sorted by order → requiredSteps, first non-completed index → currentStepIndex.\n */\nexport interface SessionState {\n /** Current runnable step reported by backend session state. */\n currentStep?: OnboardingStep;\n /** Step-specific config for `currentStep` from GET /sessions/:id `current_step.config`. */\n currentStepConfig?: Record<string, unknown>;\n /** Cached configs discovered from GET session and SSE `step_config`. */\n stepConfigs?: StepConfigMap;\n /** Session type (HUMAN or LEGAL). Constrains which steps are applicable. */\n onboardingType?: OnboardingType;\n /**\n * Whether the SDK should render the \"back\" control on `currentStep`. Mapped\n * from GET `can_go_back` (workflow-graph computed). When absent (e.g. a step\n * reached via SSE, which doesn't carry the flag) the orchestrator derives it\n * from {@link stepReversibility}.\n */\n canGoBack?: boolean;\n /**\n * Per-step intrinsic reversibility in workflow order, cached from the initial\n * GET so the orchestrator can derive `can_go_back` for steps reached via SSE:\n * a step can go back when any earlier step is reversible, or the step itself\n * is the first reversible one (back exits the flow).\n */\n stepReversibility?: Array<{ code: OnboardingStep; reversible: boolean }>;\n /**\n * Previously-captured data for `currentStep`, present when a reverse\n * navigation re-opened a completed step (GET reflects it on\n * `current_step.result`). Applied by the SDK as editable prefill.\n */\n currentStepResult?: Record<string, unknown>;\n /** Arbitrary session metadata the backend may attach. */\n metadata?: Record<string, unknown>;\n /**\n * Customer-registered allowlist of origins authorized to embed the SDK.\n * When provided, the SDK validates the loader's parent origin against this list.\n */\n allowedParentOrigins?: string[];\n}\n\n/**\n * Why the onboarding flow ended without a terminal verdict, delivered to\n * {@link VelionCallbacks.onExit}.\n *\n * Triggers:\n * - `BACK_EXIT`: the user tapped \"back\" on the first reversible step, where\n * there is no earlier step to return to, so the SDK left the flow and\n * returned control to the host.\n * - `RETRY_CANCELLED`: the user tapped \"Cancel\" on the retry dialog shown after\n * a `ROUTING_COMMAND / RETRY_STEP`. The backend session stays `IN_PROGRESS`\n * (there is no cancellation endpoint); the host may re-open it later via\n * `GET /sessions/:id`.\n */\nexport interface OnboardingExit {\n /** The reason the flow exited. */\n reason: 'BACK_EXIT' | 'RETRY_CANCELLED';\n /** The step the user exited from (when the backend provides `step_code`). */\n step?: OnboardingStep;\n}\n\n/**\n * A single T&amp;C line item (matches backend TermsAndConditionsItemDto / domain record).\n */\nexport interface TermsAndConditionsItem {\n id: string;\n description: string;\n /** Optional URL to the full document. */\n link?: string;\n}\n\n/**\n * Response from session creation (POST from your backend). Use sessionId and\n * sessionToken when instantiating VelionOnboarding; pass expiresAt for optional\n * client-side expiration checks.\n */\nexport interface SessionCreationResponse {\n session_id: string;\n session_token: string;\n expires_at: string;\n status?: string;\n}\n\n/**\n * Shape of the final result the SDK hands to `onSuccess` once the session\n * reaches a terminal status. Built from the terminal SSE event and the\n * `GET /sessions/:sessionId` snapshot (the backend exposes no separate\n * `/result` endpoint).\n */\nexport interface OnboardingResult {\n /** The session ID that was completed. Matches `VelionConfig.sessionId`. */\n sessionId: string;\n /** ISO 8601 timestamp of when the backend finalized the session. */\n completedAt: string;\n /**\n * The final KYC verdict.\n * - `APPROVED`: All checks passed automatically.\n * - `MANUAL_REVIEW`: Flagged for human review (common in AML flows). Backend `IN_REVIEW` maps here.\n * - `REJECTED`: Automatically rejected (fraud signals, liveness failure, etc.).\n * - `DECLINED`: Session ended in a declined state (matches GET session `status: DECLINED`).\n */\n status: 'APPROVED' | 'MANUAL_REVIEW' | 'REJECTED' | 'DECLINED';\n /** An optional tracking reference for support and audit trails. */\n referenceId?: string;\n /**\n * When the terminal outcome came from SSE, optional backend `reason` (e.g.\n * `LIVENESS_SCORE_IN_REVIEW_RANGE` on SESSION_MANUAL_REVIEW) for localized final-screen copy.\n */\n terminalReason?: string;\n}\n\n/**\n * Response from `POST /sessions/:sessionId/liveness-init`.\n * The backend returns the Iris session details the SDK needs to open the WebSocket\n * and stream frames. Credentials are not used: Iris owns the session lifecycle.\n */\nexport interface LivenessSessionResponse {\n /** Iris session identifier. */\n liveness_session_id?: string;\n /** Full WebSocket URL the SDK must connect to (e.g. wss://iris.host/ws/iris/{id}). */\n websocket_url?: string;\n /** ISO-8601 expiry of the Iris session. */\n expires_at?: string;\n /** Effective Iris challenge identifiers in order (TURN_LEFT, SMILE, …). */\n challenges?: string[];\n /** Optional JWT for the WebSocket handshake when Iris auth is enabled. */\n connection_token?: string;\n /**\n * Optional base64 HMAC-SHA256 key. When present, the SDK signs every JPEG\n * frame in a JSON envelope (canonical line: `sessionId\\nframeId\\nts\\nsha256hex(jpeg)`).\n */\n frame_integrity_key_base64?: string;\n /**\n * Signed PUT URL the SDK uses to upload the locally-recorded liveness video\n * directly to the onboarding GCS bucket. `null` (or absent) when video\n * recording is disabled or the signing failed — the SDK skips the upload\n * silently (liveness still works without the video; only the back-office\n * loses the playback evidence).\n */\n video_upload?: VideoUpload | null;\n}\n\n/**\n * Signed-upload payload returned by `POST /liveness-init`. Mirrors the backend\n * `LivenessInitResponseDto.VideoUpload`. The SDK PUTs the recorded video bytes\n * to `upload_url` (Content-Type matching the recorded container) before calling\n * `POST /liveness-verify` with the resulting metadata.\n */\nexport interface VideoUpload {\n /** Absolute https://storage.googleapis.com/... URL with V4 signature params. */\n upload_url: string;\n /** ISO-8601 instant after which GCS rejects the signature. */\n expires_at: string;\n /** HTTP method to use. Always `\"PUT\"` today; future-proofing. */\n method: 'PUT' | string;\n}\n\n/**\n * Optional body of `POST /liveness-verify`. The SDK only includes it when the\n * recorded video uploaded successfully (HTTP 200 from GCS). When omitted, the\n * backend completes liveness based on the Iris score only.\n */\nexport interface LivenessVerifyVideoMeta {\n /** MIME type that was sent in the PUT `Content-Type` header (e.g. `video/mp4`, `video/webm`). */\n content_type: string;\n /** Recorded video duration in milliseconds, or `null` if it could not be determined. */\n duration_ms: number | null;\n}\n\n/**\n * Payload delivered to the optional `onLivenessVideoUploaded` callback after a\n * successful upload of the liveness video. Best-effort: the callback only\n * fires when the GCS PUT returned 200.\n */\nexport interface LivenessVideoRef {\n /** Signed `upload_url` the SDK PUT the video to. */\n upload_url: string;\n /** MIME type used in the PUT. */\n content_type: string;\n /** Recorded video duration in milliseconds, or `null` when unknown. */\n duration_ms: number | null;\n /** Recorded file size in bytes, or `null` when unknown. */\n size_bytes: number | null;\n}\n\n/**\n * Payload for POST /sessions/:sessionId/basic-info/human (HUMAN_BASIC_INFO step).\n * Matches backend SubmitHumanBasicInfoRequestDto (snake_case in JSON).\n */\nexport interface HumanBasicInfoPayload {\n first_name: string;\n middle_name?: string;\n last_name: string;\n second_last_name?: string;\n identification_type: string;\n identification_id: string;\n}\n\n/**\n * Payload for POST /sessions/:sessionId/basic-info/legal (LEGAL_BASIC_INFO step).\n * Matches backend SubmitLegalBasicInfoRequestDto (snake_case in JSON).\n */\nexport interface LegalBasicInfoPayload {\n legal_name: string;\n legal_form: string;\n identification_type: string;\n identification_id: string;\n}\n\n/**\n * Single selectable option for tax category or fiscal identifier type (TAX_INFO step).\n * `id` is submitted to the API; `description` is the user-visible label.\n */\nexport interface TaxInfoOption {\n id: string;\n description: string;\n}\n\n/**\n * Resolved selectable lists for the TAX_INFO step UI (from `accepted_tax_information` only; no SDK defaults).\n */\nexport interface TaxInfoConfig {\n /**\n * Fiscal regime / category options (e.g. Monotributo). The chosen `id` is sent as `taxpayer_type`.\n */\n taxpayerCategories: TaxInfoOption[];\n /**\n * Tax identification scheme options (e.g. CUIT). The chosen `id` is sent as `taxpayer_id_type`.\n */\n fiscalIdentifierTypes: TaxInfoOption[];\n}\n\n/** POST /sessions/:id/tax-info — SubmitTaxInfoRequestDto. */\nexport interface TaxInfoPayload {\n /** Selected fiscal category value (`code` from step config `taxpayer_categories`). */\n taxpayer_type: string;\n /** Selected fiscal identifier kind id (e.g. `CUIT` from step config `identification_types`). */\n taxpayer_id_type: string;\n /** Tax identification number for the chosen type. */\n taxpayer_id: string;\n}\n\n/** POST /sessions/:id/extended-info/human — SubmitHumanExtendedInfoRequestDto. */\nexport interface HumanExtendedInfoPayload {\n gender?: string;\n civil_status?: string;\n birth_date?: string;\n birth_country?: string;\n citizenship?: string;\n residence_country?: string;\n}\n\n/** POST /sessions/:id/extended-info/legal — SubmitLegalExtendedInfoRequestDto. */\nexport interface LegalExtendedInfoPayload {\n incorporation_date: string;\n incorporation_country: string;\n}\n\n/** POST /sessions/:id/address-info — SubmitAddressInfoRequestDto. */\nexport interface AddressInfoPayload {\n type: string;\n country: string;\n state: string;\n city: string;\n district?: string;\n neighborhood?: string;\n street: string;\n number: string;\n floor?: string;\n apartment?: string;\n details?: string;\n zip_code: string;\n latitude?: number;\n longitude?: number;\n}\n\n/** POST /sessions/:id/sworn-declaration — SubmitSwornDeclarationRequestDto. */\nexport interface SwornDeclarationPayload {\n is_pep: boolean;\n is_ssoo: boolean;\n is_fatca: boolean;\n is_ocde: boolean;\n}\n\n/**\n * POST /sessions/:id/economic-activity — EconomicActivitySelectionDto.\n *\n * Carries the `code` of the single economic activity the user selected for the\n * `ECONOMIC_ACTIVITY_DECLARATION` step. The Worker validates it asynchronously\n * against the configured items; an invalid code surfaces over SSE as\n * `RETRY_STEP` (re-mounts the step) or `SESSION_DECLINED`, never as an HTTP error.\n */\nexport interface EconomicActivitySelectionPayload {\n /** `code` of the selected EconomicActivityItem. */\n code: string;\n}\n\n/** POST /sessions/:id/contact/email — SubmitEmailContactRequestDto. */\nexport interface EmailContactPayload {\n email: string;\n}\n\n/** POST /sessions/:id/contact/phone — SubmitPhoneContactRequestDto. */\nexport interface PhoneContactPayload {\n phone: string;\n}\n\n/** POST /sessions/:id/terms-and-conditions — SubmitTermsAndConditionsRequestDto. */\nexport interface TermsAndConditionsAcceptancePayload {\n item_id: string;\n accepted: boolean;\n}\n\nexport interface TermsAndConditionsSubmitPayload {\n acceptances: TermsAndConditionsAcceptancePayload[];\n}\n\n/**\n * SSE event payload (OnboardingSessionEvent). Matches the backend record\n * la.velion.onboarding.api...sdk.OnboardingSessionEventDto (snake_case in JSON).\n *\n * Received on GET /public/sdk/sessions/:sessionId/events. The backend sends\n * ServerSentEvent with id = event_id (epoch millis) for Last-Event-ID replay.\n *\n * Event types (event_type):\n * - STEP_UPDATED — a workflow step changed status (step_code, step_status)\n * - ROUTING_COMMAND — next/retry/terminate instruction (action: NEXT_STEP | RETRY_STEP | TERMINATE)\n * - SESSION_APPROVED — all checks passed; session_status = APPROVED\n * - SESSION_MANUAL_REVIEW — manual review required; session_status = MANUAL_REVIEW\n * - SESSION_DECLINED — session ended with decline (step_code, session_status DECLINED, reason)\n */\nexport interface OnboardingSessionEvent {\n /** Onboarding session identifier (Long in backend). */\n session_id?: number;\n /** Discriminator: STEP_UPDATED | ROUTING_COMMAND | SESSION_APPROVED | SESSION_MANUAL_REVIEW | SESSION_DECLINED */\n event_type?: string;\n /** Present for STEP_UPDATED or ROUTING_COMMAND (next step code). */\n step_code?: string;\n /** Present for STEP_UPDATED; e.g. COMPLETED. */\n step_status?: string;\n /** Present for terminal events; e.g. APPROVED | MANUAL_REVIEW | REJECTED. */\n session_status?: string;\n /**\n * For ROUTING_COMMAND: NEXT_STEP | RETRY_STEP (render step_code), TERMINATE\n * (end flow), PREVIOUS_STEP (reverse navigation — re-open step_code with\n * step_result as prefill), or BACK_EXIT (user backed out of the first\n * reversible step — leave the flow and notify the host via `onExit`).\n */\n action?: string;\n /** For SESSION_DECLINED / SESSION_MANUAL_REVIEW or ROUTING_COMMAND TERMINATE; e.g. UNREADABLE_DOCUMENT. */\n reason?: string;\n /** Step-specific config sent with ROUTING_COMMAND NEXT_STEP / PREVIOUS_STEP. */\n step_config?: Record<string, unknown>;\n /**\n * Previously-captured data for the re-opened step, sent with ROUTING_COMMAND\n * PREVIOUS_STEP. Applied by the SDK as editable prefill.\n */\n step_result?: Record<string, unknown>;\n /**\n * Whether the step the user is landing on can itself go back further. Carried\n * on ROUTING_COMMAND when the backend computes it; when absent the SDK derives\n * it from the cached workflow reversibility map.\n */\n can_go_back?: boolean;\n /** Epoch millis; used as SSE id for Last-Event-ID on reconnect. */\n event_id?: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// BACKEND COMMANDS (Listen & Obey)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Backend command: advance to a specific step. The SDK must render that step's\n * screen without evaluating business rules locally.\n */\nexport interface BackendCommandGoToStep {\n action: 'GO_TO_STEP';\n stepCode: OnboardingStep;\n}\n\n/**\n * Backend command: show an error message to the user. The SDK displays the\n * message and does not advance (backend owns the decision).\n */\nexport interface BackendCommandShowError {\n action: 'SHOW_ERROR';\n message: string;\n}\n\n/**\n * Backend command: flow is complete. SDK should fetch final result and fire onSuccess.\n */\nexport interface BackendCommandFlowComplete {\n action: 'FLOW_COMPLETE';\n}\n\n/**\n * Backend command: retry the current step (e.g. after transient failure).\n */\nexport interface BackendCommandRetry {\n action: 'RETRY';\n}\n\n/**\n * Strict command payload the backend may return in a synchronous HTTP response\n * or send via SSE. The SDK never makes routing decisions; it only obeys these commands.\n */\nexport type BackendCommand =\n | BackendCommandGoToStep\n | BackendCommandShowError\n | BackendCommandFlowComplete\n | BackendCommandRetry;\n\n/**\n * Raw response body that may contain a backend command (e.g. POST submit response).\n */\nexport interface BackendCommandResponse {\n action?: string;\n stepCode?: string;\n message?: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// INTERNAL STATE MACHINE TYPES (exported for module authors)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * All possible states of the SDK's internal lifecycle.\n * Transitions are strictly unidirectional (no going back to IDLE once started).\n *\n * @internal\n */\nexport type SdkStatus =\n | 'IDLE' // Instantiated, not yet started\n | 'INITIALIZING' // Fetching session state from backend\n | 'RUNNING' // Orchestrating steps\n | 'STEP_PROCESSING'// A module is actively running\n | 'COMPLETED' // All steps done, onSuccess fired\n | 'EXITED' // User left the flow via back on the first step, onExit fired\n | 'ERROR' // Unrecoverable error, onError fired\n | 'DESTROYED'; // destroy() was called, instance is a no-op\n\n/**\n * Internal event bus event names. Typed via `SdkEventMap`.\n * @internal\n */\nexport type SdkEventName =\n | 'step:change'\n | 'step:complete'\n | 'session:loaded'\n | 'flow:complete'\n | 'flow:exit'\n | 'error'\n | 'status:change';\n\n/**\n * Maps each internal event name to its payload type.\n * Used by the `TypedEventEmitter` for compile-time safety.\n * @internal\n */\nexport interface SdkEventMap extends Record<string, unknown> {\n 'step:change': { step: OnboardingStep; index: number };\n 'step:complete': { step: OnboardingStep };\n 'session:loaded': SessionState;\n 'flow:complete': OnboardingResult;\n 'flow:exit': OnboardingExit;\n 'error': SdkError;\n 'status:change': SdkStatus;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LOADER ↔ CDN APP POSTMESSAGE PROTOCOL (Sumsub-style)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Message type: parent (loader) sends config to iframe (CDN app). */\nexport const VELION_MSG_INIT = 'VELION_INIT' as const;\n\n/** Message types: iframe (CDN app) sends to parent (loader). */\nexport const VELION_MSG_READY = 'VELION_READY' as const;\nexport const VELION_MSG_SUCCESS = 'VELION_SUCCESS' as const;\nexport const VELION_MSG_ERROR = 'VELION_ERROR' as const;\nexport const VELION_MSG_STEP_CHANGE = 'VELION_STEP_CHANGE' as const;\nexport const VELION_MSG_STEP_COMPLETE = 'VELION_STEP_COMPLETE' as const;\nexport const VELION_MSG_TOKEN_EXPIRED = 'VELION_TOKEN_EXPIRED' as const;\n/**\n * Iframe → parent: the user left the flow via back on the first reversible step\n * (`ROUTING_COMMAND / BACK_EXIT`). The loader forwards this to the host's\n * `onExit` callback so it can dismiss the SDK surface.\n */\nexport const VELION_MSG_EXIT = 'VELION_EXIT' as const;\n/**\n * Iframe → parent: the LIVENESS_MATCH step uploaded the recorded session video\n * (GCS PUT returned 200). The loader forwards the {@link LivenessVideoRef} to\n * the host's `onLivenessVideoUploaded` callback. Best-effort: never sent when\n * recording was disabled or the upload failed.\n */\nexport const VELION_MSG_LIVENESS_VIDEO_UPLOADED = 'VELION_LIVENESS_VIDEO_UPLOADED' as const;\n\n/** Message type: parent sends new token to iframe after VELION_TOKEN_EXPIRED. */\nexport const VELION_MSG_TOKEN = 'VELION_TOKEN' as const;\n\nexport type VelionMessageType =\n | typeof VELION_MSG_INIT\n | typeof VELION_MSG_READY\n | typeof VELION_MSG_SUCCESS\n | typeof VELION_MSG_ERROR\n | typeof VELION_MSG_STEP_CHANGE\n | typeof VELION_MSG_STEP_COMPLETE\n | typeof VELION_MSG_TOKEN_EXPIRED\n | typeof VELION_MSG_EXIT\n | typeof VELION_MSG_LIVENESS_VIDEO_UPLOADED\n | typeof VELION_MSG_TOKEN;\n\n/** Envelope for all loader ↔ iframe messages. Both sides must validate origin. */\nexport interface VelionMessage<T = unknown> {\n type: VelionMessageType;\n payload: T;\n}\n\n/** Payload for VELION_INIT: full config (iframe runs with containerId overwritten to root id). */\nexport type VelionInitPayload = VelionConfig;\n\n/** Payload for VELION_STEP_CHANGE. */\nexport interface VelionStepChangePayload {\n step: OnboardingStep;\n stepIndex: number;\n}\n\n/** Payload for VELION_STEP_COMPLETE. */\nexport interface VelionStepCompletePayload {\n step: OnboardingStep;\n}\n\n/** Payload for VELION_EXIT (mirrors {@link OnboardingExit}). */\nexport type VelionExitPayload = OnboardingExit;\n\n/** Payload for VELION_LIVENESS_VIDEO_UPLOADED (mirrors {@link LivenessVideoRef}). */\nexport type VelionLivenessVideoUploadedPayload = LivenessVideoRef;\n\n/** Payload for VELION_TOKEN (token refresh response from parent to iframe). */\nexport interface VelionTokenPayload {\n sessionToken: string;\n expiresAt?: string;\n}\n","/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 5KB JS implementation of ed25519 EdDSA signatures.\n * Targets RFC8032, FIPS 186-5, and ZIP215 behavior.\n * @module\n * @example\n * ```js\nimport * as ed from '@noble/ed25519';\n(async () => {\n const secretKey = ed.utils.randomSecretKey();\n const message = Uint8Array.from([0xab, 0xbc, 0xcd, 0xde]);\n const pubKey = await ed.getPublicKeyAsync(secretKey); // Sync methods are also present\n const signature = await ed.signAsync(message, secretKey);\n const isValid = await ed.verifyAsync(signature, message, pubKey);\n})();\n```\n */\n/**\n * Curve params. edwards25519 uses the RFC equation `-x² + y² = 1 + dx²y²`.\n * The stored `a` literal below is `p - 1`, i.e. the field-element encoding of RFC `a = -1`.\n * * P = `2n**255n - 19n` // field over which calculations are done\n * * N = `2n**252n + 27742317777372353535851937790883648493n` // prime-order subgroup order\n * * h = 8 // cofactor\n * * a = `Fp.create(BigInt(-1))` // equation param, stored here as `p - 1`\n * * d = -121665/121666 a.k.a. `Fp.neg(121665 * Fp.inv(121666))` // equation param\n * * Gx, Gy are coordinates of Generator / base point\n *\n * Mirror noble-curves: Point.CURVE() exposes shared params, but callers must not be able to mutate\n * that shared view and desynchronize it from the arithmetic constants captured below.\n */\nconst freeze = Object.freeze;\nconst P = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn;\nconst N = 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn;\nconst _d = 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n;\nconst Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an;\nconst Gy = 0x6666666666666666666666666666666666666666666666666666666666666658n;\nconst _a = P - 1n; // field-element encoding of RFC `a = -1`\nconst ed25519_CURVE = freeze({\n p: P,\n n: N,\n h: 8n,\n a: _a,\n d: _d,\n Gx,\n Gy,\n});\n// Shared 32-byte encoded width for Ed25519 points, scalars, signatures/2, and keys. Named LEN\n// rather than RFC 8032's `L`, which names the group order (stored here as `N`).\nconst LEN = 32;\n// Helpers and Precomputes sections are reused between libraries\n// ## Helpers\n// ----------\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nconst isBytes = (a) => {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n a.BYTES_PER_ELEMENT === 1));\n};\n/** Asserts something is Bytes. */\nconst abytes = (value, length, title = '') => {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = (title ? `\"${title}\" ` : '') + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n};\n// Validate, then take one owned copy, so later caller mutation cannot be observed — e.g. cannot\n// make sign()'s nonce derivation and challenge derivation see different messages.\nconst snapshotBytes = (value, title = '', length) => Uint8Array.from(abytes(value, length, title));\n// Callers keep values non-negative and within the requested width; padStart() won't truncate over-wide inputs.\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\n/** Convert byte array to hex string. */\nconst bytesToHex = (bytes) => {\n let hex = '';\n for (const byte of abytes(bytes))\n hex += padh(byte, 2);\n return hex;\n};\n/** Convert hex string to byte array. */\nconst hexToBytes = (hex) => {\n const e = 'hex invalid'; // Strict ASCII hex only, with one generic error for parse failures.\n if (typeof hex !== 'string')\n throw new TypeError(e);\n if (hex.length % 2 || !/^[\\da-f]*$/i.test(hex))\n throw new RangeError(e);\n const array = new Uint8Array(hex.length / 2);\n for (let ai = 0, hi = 0; ai < array.length; ai++, hi += 2) {\n const n1 = hex.charCodeAt(hi);\n const n2 = hex.charCodeAt(hi + 1);\n // Regex guarantees ASCII. For 0..9/A..F/a..f, this maps char codes to 0..15.\n array[ai] = ((n1 & 15) + (n1 >> 6) * 9) * 16 + (n2 & 15) + (n2 >> 6) * 9;\n }\n return array;\n};\n// WebCrypto is available in all modern environments\n/** Copies several Uint8Arrays into one. */\nconst concatBytes = (...arrays) => {\n let sum = 0;\n for (const a of arrays)\n sum += abytes(a).length;\n const res = new Uint8Array(sum);\n let pad = 0;\n for (const a of arrays) {\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n};\n/**\n * WebCrypto OS-level CSPRNG (random number generator).\n * Will throw when not available; large-request ceilings are delegated to getRandomValues().\n */\nconst randomBytes = (len = LEN) => {\n const c = globalThis?.crypto;\n if (typeof c?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined, consider polyfill');\n return c.getRandomValues(new Uint8Array(len));\n};\n/** Inclusive-lower, exclusive-upper bigint range assertion. */\nconst arange = (n, min, max, msg = 'bad number: out of range') => {\n if (typeof n !== 'bigint')\n throw new TypeError(msg);\n if (min <= n && n < max)\n return n;\n throw new RangeError(msg);\n};\n/** Canonical modular reduction. Callers must provide a positive modulus. */\nconst mod = (a, b = P) => ((a %= b) >= 0n ? a : b + a);\n// Low-255-bit mask used by the `2^255 - 19` fast reduction in `modP(...)`.\nconst P_MASK = (1n << 255n) - 1n;\n// Fast reduction for the special prime `2^255 - 19`. This path assumes nonnegative inputs; the\n// generic fallback would simply be `mod(num, P)`.\nconst modP = (num) => {\n if (num < 0n)\n throw new RangeError('negative coordinate');\n let r = (num >> 255n) * 19n + (num & P_MASK);\n r = (r >> 255n) * 19n + (r & P_MASK);\n return r % P;\n};\n// Reduce modulo the subgroup order stored in implementation constant `N` (RFC 8032's `L`).\nconst modN = (a) => mod(a, N);\n/** Modular inversion using extended euclidean GCD. Variable-time (non-CT). */\nconst invert = (number, modulo) => {\n if (number === 0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= 1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`.\n let a = mod(number, modulo);\n let b = modulo;\n // Only the Bézout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = 0n, u = 1n;\n while (a !== 0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== 1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n};\n// Dynamic lookup keeps sync/async hash providers configurable at runtime. Both exported slots are\n// caller-owned and may be unset; wrapper helpers use this lookup first and then enforce the digest\n// contract instead of trusting provider output.\nconst _hash = (name) => {\n // @ts-ignore\n const fn = hashes[name];\n if (typeof fn !== 'function')\n throw new Error('hashes.' + name + ' not set');\n return fn;\n};\n// All exported provider slots are caller-configurable and may be unset or return arbitrary values,\n// so wrapper helpers must enforce the exact 64-byte SHA-512 digest contract instead of trusting providers.\nconst callHash = (name, ...m) => abytes(_hash(name)(concatBytes(...m)), 64, 'digest');\nconst callHashAsync = async (name, ...m) => abytes(await _hash(name)(concatBytes(...m)), 64, 'digest');\n/**\n * SHA-512 helper used by the synchronous API.\n * @param msg - Message bytes to hash.\n * @returns 64-byte SHA-512 digest.\n * @example\n * Hash message bytes after wiring the synchronous SHA-512 implementation.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const digest = ed.hash(new Uint8Array([1, 2, 3]));\n * ```\n */\n// Public helper validates the message boundary explicitly; the configured provider is still looked\n// up dynamically and its output is checked with `callHash(...)`.\nconst hash = (msg) => callHash('sha512', abytes(msg, undefined, 'message'));\n// Runtime class guard: this is `instanceof Point`, so cross-realm / duplicate-bundle Point objects\n// are rejected even if they are structurally identical.\nconst apoint = (p) => {\n if (p instanceof Point)\n return p;\n throw new TypeError('Point expected');\n};\n// ## End of Helpers\n// -----------------\n// Exclusive upper bound `2^256` used by 32-byte decode/serialization range checks.\nconst B256 = 2n ** 256n;\n/**\n * Point in XYZT extended coordinates.\n * @param X - X coordinate.\n * @param Y - Y coordinate.\n * @param Z - Projective Z coordinate.\n * @param T - Cached cross-product term.\n * @example\n * Do point arithmetic with the built-in base point and encode the result as hex.\n *\n * ```ts\n * const hex = Point.BASE.double().toHex();\n * ```\n */\nclass Point {\n static BASE;\n static ZERO;\n X;\n Y;\n Z;\n T;\n // Constructor only bounds-checks and freezes XYZT coordinates; it does not prove the point is\n // on-curve or that T matches X*Y/Z.\n constructor(X, Y, Z, T) {\n const max = B256;\n this.X = arange(X, 0n, max);\n this.Y = arange(Y, 0n, max);\n this.Z = arange(Z, 1n, max);\n this.T = arange(T, 0n, max);\n freeze(this);\n }\n static CURVE() {\n return ed25519_CURVE;\n }\n static fromAffine(p) {\n return new Point(p.x, p.y, 1n, modP(p.x * p.y));\n }\n /** RFC8032 5.1.3: Uint8Array to Point. */\n static fromBytes(bytes, zip215 = false) {\n const normed = snapshotBytes(bytes, 'point', LEN); // owned copy: sign-bit mask below mutates it\n // adjust first LE byte = last BE byte\n const lastByte = normed[31];\n normed[31] = lastByte & ~0x80;\n const y = bytesToNumberLE(normed);\n // After clearing the sign bit, parsed `y` is always < 2^255. ZIP-215 still accepts the full\n // post-mask range here, while strict RFC8032 decoding further requires `y < p`.\n if (!zip215)\n arange(y, 0n, P);\n const y2 = modP(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = modP(_d * y2 + 1n); // v=dy²+1\n let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (!isValid)\n throw new Error('bad point: y not sqrt'); // not square root: bad point\n const isLastByteOdd = !!(lastByte & 0x80); // x_0, last bit\n // ZIP-215-compatible decoding keeps the x=0 / sign-bit=1 encoding accepted; strict RFC 8032\n // rejects it, but the vendored ZIP-215 compliance vectors include this form in A/R bytes.\n if (!zip215 && x === 0n && isLastByteOdd)\n throw new Error('bad point: x==0, isLastByteOdd'); // x=0, x_0=1\n if (isLastByteOdd !== !!(x & 1n))\n x = mod(-x); // adjust sign of x coordinate\n return new Point(x, y, 1n, modP(x * y)); // Z=1, T=xy\n }\n static fromHex(hex, zip215) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /** Checks if the point is valid and on-curve. */\n assertValidity() {\n const a = _a;\n const d = _d;\n const p = this;\n // Intentional stricter-than-on-curve policy: reject ZERO by default because many protocols\n // require a non-zero point, and silently accepting identity points is a common caller mistake.\n if (p.is0())\n throw new Error('bad point: ZERO');\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * (aX2 + Y2)); // (aX² + Y²)Z²\n const right = mod(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return this;\n }\n /** Equality check: compare points P&Q. */\n equals(other) {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = apoint(other); // checks class equality\n return modP(X1 * Z2) === modP(X2 * Z1) && modP(Y1 * Z2) === modP(Y2 * Z1);\n }\n is0() {\n return this.equals(I);\n }\n /** Flip point over y coordinate. */\n negate() {\n return new Point(mod(-this.X), this.Y, this.Z, mod(-this.T));\n }\n /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */\n double() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const a = _a;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n const A = modP(X1 * X1);\n const B = modP(Y1 * Y1);\n const C = modP(2n * Z1 * Z1);\n const D = modP(a * A);\n const x1y1 = mod(X1 + Y1);\n const E = mod(modP(x1y1 * x1y1) - A - B);\n const G = mod(D + B);\n const F = mod(G - C);\n const H = mod(D - B);\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n /** Point addition. Complete formula. Cost: `9M + 1*a + 1*d + 7add`. */\n add(other) {\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other); // doesn't check if other on-curve\n const a = _a;\n const d = _d;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n const A = modP(X1 * X2);\n const B = modP(Y1 * Y2);\n const C = modP(modP(T1 * d) * T2);\n const D = modP(Z1 * Z2);\n const E = mod(modP(mod(X1 + Y1) * mod(X2 + Y2)) - A - B);\n const F = mod(D - C);\n const G = mod(D + C);\n const H = mod(B - modP(a * A));\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(apoint(other).negate());\n }\n /**\n * Point-by-scalar multiplication. Safe mode requires `1 <= n < CURVE.n`.\n * Unsafe mode additionally permits `n = 0` and returns the identity point for that case.\n * Uses {@link wNAF} for base point.\n * Uses fake point to mitigate side-channel leakage.\n * @param n - scalar by which point is multiplied\n * @param safe - safe mode guards against timing attacks; unsafe mode is faster\n */\n multiply(n, safe = true) {\n // Mirror noble-curves: unsafe mode still validates scalar range first, but intentionally keeps\n // `n = 0` as the one extra accepted case used by verification-style callers.\n if (!safe && n === 0n)\n return I;\n arange(n, 1n, N);\n if (!safe && this.is0())\n return I;\n if (n === 1n)\n return this;\n if (this.equals(G))\n return wNAF(n).p;\n // init result point & fake point\n let p = I;\n let f = G;\n let d = this;\n // Safe mode always runs 256 iterations so ladder length can't leak the scalar's\n // leading zero bits; unsafe mode stops at the top set bit for speed.\n for (let i = 0; safe ? i < 256 : n > 0n; i++) {\n // if bit is present, add to point\n // if not present, add to fake, for timing safety\n if (n & 1n)\n p = p.add(d);\n else if (safe)\n f = f.add(d);\n d = d.double();\n n >>= 1n;\n }\n return p;\n }\n multiplyUnsafe(scalar) {\n return this.multiply(scalar, false);\n }\n /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */\n toAffine() {\n const { X, Y, Z } = this;\n // Fast-path only for the identity point; all other inputs still go through inversion.\n if (this.equals(I))\n return { x: 0n, y: 1n };\n const iz = invert(Z, P);\n // (Z * Z^-1) must be 1, otherwise bad math\n if (modP(Z * iz) !== 1n)\n throw new Error('invalid inverse');\n // x = X*Z^-1; y = Y*Z^-1\n return { x: modP(X * iz), y: modP(Y * iz) };\n }\n toBytes() {\n const { x, y } = this.toAffine();\n const b = numTo32bLE(y);\n // store sign in first LE byte\n b[31] |= x & 1n ? 0x80 : 0;\n return b;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n clearCofactor() {\n return this.multiply(8n, false); // h = 8\n }\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n isTorsionFree() {\n // Multiply by big number N. We can't `mul(N)` because of checks. Instead, we `mul(N/2)*2+1`;\n // N is odd, so N/2 truncates and the final `add(this)` is always needed.\n return this.multiply(N / 2n, false)\n .double()\n .add(this)\n .is0();\n }\n}\n/** Generator / base point */\nconst G = new Point(Gx, Gy, 1n, mod(Gx * Gy));\n/** Identity / zero point */\nconst I = new Point(0n, 1n, 1n, 0n);\n// Static aliases\nPoint.BASE = G;\nPoint.ZERO = I;\nconst numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), 64)).reverse();\n// Caller-enforced width: some sites require 32-byte RFC encodings, while others intentionally feed\n// wider SHA-512 output chunks through the same little-endian parser.\nconst bytesToNumberLE = (b) => BigInt('0x' + bytesToHex(Uint8Array.from(abytes(b)).reverse()));\nconst pow2 = (x, power) => {\n // pow2(x, 4) == x^(2^4)\n // Negative `power` values are not rejected here and currently leave `x` unchanged.\n let r = x;\n while (power-- > 0) {\n r = modP(r * r);\n }\n return r;\n};\n// prettier-ignore\nconst pow_2_252_3 = (x) => {\n const x2 = modP(x * x); // x^2, bits 1\n const b2 = modP(x2 * x); // x^3, bits 11\n const b4 = modP(pow2(b2, 2) * b2); // x^(2^4-1), bits 1111\n const b5 = modP(pow2(b4, 1) * x); // x^(2^5-1), bits 11111\n const b10 = modP(pow2(b5, 5) * b5); // x^(2^10-1)\n const b20 = modP(pow2(b10, 10) * b10); // x^(2^20-1)\n const b40 = modP(pow2(b20, 20) * b20); // x^(2^40-1)\n const b80 = modP(pow2(b40, 40) * b40); // x^(2^80-1)\n const b160 = modP(pow2(b80, 80) * b80); // x^(2^160-1)\n const b240 = modP(pow2(b160, 80) * b80); // x^(2^240-1)\n const b250 = modP(pow2(b240, 10) * b10); // x^(2^250-1)\n return modP(pow2(b250, 2) * x); // x^((p-5)/8), used by RFC8032 point decode\n};\nconst RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n; // 2^((p-1)/4) = sqrt(-1)\n// RFC8032 §5.1.3 square-root helper for point decompression. `value` is only meaningful when\n// `isValid` is true; callers are also expected to pass canonical field elements with non-zero `v`.\n// prettier-ignore\nconst uvRatio = (u, v) => {\n const v3 = modP(v * modP(v * v)); // v³\n const v7 = modP(modP(v3 * v3) * v); // v⁷\n const pow = pow_2_252_3(modP(u * v7)); // (uv⁷)^(p-5)/8\n let x = modP(u * modP(v3 * pow)); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = modP(v * modP(x * x)); // vx²\n const root1 = x; // First root candidate\n const root2 = modP(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n)\n x = mod(-x); // edIsNegative\n return { isValid: useRoot1 || useRoot2, value: x };\n};\n// Reduce a little-endian byte string modulo the subgroup order `N` (RFC 8032's `L`); the `hash`\n// param name reflects the common caller shape, not an input restriction.\nconst modL_LE = (hash) => modN(bytesToNumberLE(hash));\n// RFC8032 5.1.5. Split the 64-byte hashed seed into the clamped scalar half and nonce prefix.\nconst hashedToExtK = (hashed) => {\n // slice creates a copy, unlike subarray\n const copy = snapshotBytes(hashed);\n const head = copy.slice(0, 32);\n head[0] &= 248; // Clamp bits: 0b1111_1000\n head[31] &= 127; // 0b0111_1111\n head[31] |= 64; // 0b0100_0000\n const prefix = copy.slice(32); // secret key \"prefix\"\n // RFC words this as `[s]B`; reducing the clamped little-endian scalar modulo `N` is equivalent\n // for base-point multiplication because `G` already has subgroup order `N`.\n const scalar = modL_LE(head);\n const point = G.multiply(scalar); // public key point\n const pointBytes = point.toBytes(); // point serialized to Uint8Array\n return { head, prefix, scalar, point, pointBytes };\n};\n// RFC8032 5.1.5; getPublicKey async, sync. Hash secret key and extract point.\nconst getExtendedPublicKeyAsync = (secretKey) => callHashAsync('sha512Async', abytes(secretKey, LEN, 'secretKey')).then(hashedToExtK);\nconst getExtendedPublicKey = (secretKey) => hashedToExtK(callHash('sha512', abytes(secretKey, LEN, 'secretKey')));\n/**\n * Creates a 32-byte Ed25519 public key from the RFC 8032 32-byte secret-key seed. Async.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 32-byte public key.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Derive the public key bytes for a newly generated signer secret.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const publicKey = await ed.getPublicKeyAsync(secretKey);\n * ```\n */\nconst getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);\n/**\n * Creates a 32-byte Ed25519 public key from the RFC 8032 32-byte secret-key seed.\n * To use, set `hashes.sha512` first.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 32-byte public key.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Derive the public key entirely through the synchronous API.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const secretKey = ed.utils.randomSecretKey();\n * const publicKey = ed.getPublicKey(secretKey);\n * ```\n */\nconst getPublicKey = (secretKey) => getExtendedPublicKey(secretKey).pointBytes;\nconst hashFinishAsync = async (res) => res[1](await callHashAsync('sha512Async', res[0]));\nconst hashFinishSync = (res) => res[1](callHash('sha512', res[0]));\n// Code, shared between sync & async sign\nconst _sign = (e, rBytes, msg) => {\n const { pointBytes: A, scalar: s } = e;\n const r = modL_LE(rBytes); // r was created outside, reduce it modulo L\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero SHA-512 provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = G.multiply(r).toBytes(); // R = [r]B\n const hashable = concatBytes(R, A, msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n const S = modN(r + modL_LE(hashed) * s); // S = (r + k * s) mod L; 0 <= s < l\n return abytes(concatBytes(R, numTo32bLE(S)), 64); // 64-byte sig: 32-byte encoded R point || 32-byte LE(S)\n };\n return [hashable, finish];\n};\n/**\n * Signs message using secret key. Async.\n * Follows RFC8032 5.1.6.\n * @param message - Message bytes to sign.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 64-byte Ed25519 signature.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Sign an arbitrary message with a fresh Ed25519 secret key.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const signature = await ed.signAsync(message, secretKey);\n * ```\n */\nconst signAsync = async (message, secretKey) => {\n const m = snapshotBytes(message, 'message');\n const e = await getExtendedPublicKeyAsync(secretKey);\n // r = SHA512(dom2(F, C) || prefix || PH(M)); then generate R, k, S and the signature.\n return hashFinishAsync(_sign(e, await callHashAsync('sha512Async', e.prefix, m), m));\n};\n/**\n * Signs message using secret key. To use, set `hashes.sha512` first.\n * Follows RFC8032 5.1.6.\n * @param message - Message bytes to sign.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 64-byte Ed25519 signature.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Use the sync API when you've wired a SHA-512 implementation yourself.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const secretKey = ed.utils.randomSecretKey();\n * const signature = ed.sign(new Uint8Array([1, 2, 3]), secretKey);\n * ```\n */\nconst sign = (message, secretKey) => {\n const m = snapshotBytes(message, 'message');\n const e = getExtendedPublicKey(secretKey);\n // r = SHA512(dom2(F, C) || prefix || PH(M)); then generate R, k, S and the signature.\n return hashFinishSync(_sign(e, callHash('sha512', e.prefix, m), m));\n};\n// Exported defaults favor ZIP-215 interoperability semantics; callers must opt into the stricter\n// branch with `{ zip215: false }`.\n// Preserves the exported ZIP-215 default for `{}` / `{ zip215: undefined }`, not just omitted opts.\nconst getZip215 = (options) => {\n if (options === null || typeof options !== 'object')\n throw new TypeError('expected valid options object');\n return options.zip215 ?? true;\n};\nconst _verify = (sig, msg, publicKey, options) => {\n sig = abytes(sig, 64, 'signature'); // Signature hex str/Bytes, must be 64 bytes\n msg = abytes(msg, undefined, 'message'); // Message hex str/Bytes\n publicKey = abytes(publicKey, LEN, 'publicKey');\n const zip215 = getZip215(options);\n // zip215=false keeps the library's stricter branch, which still canonicalizes `R` / `A` before\n // hashing and rejects small-order public keys earlier than pure RFC8032 text would require.\n const r = sig.subarray(0, LEN);\n const s = bytesToNumberLE(sig.subarray(LEN, 64)); // Decode second half as an integer S;\n let A, R, SB;\n let hashable = Uint8Array.of();\n let finished = false;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = G.multiply(s, false); // 0 <= s < l is done inside\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n hashable = concatBytes(r, publicKey, msg); // dom2(F, C) || R || A || PH(M)\n finished = true;\n }\n catch (error) { }\n const finish = (hashed) => {\n if (!finished)\n return false;\n // Policy: strict mode intentionally rejects all small-order public keys, even though the raw RFC\n // equation text is looser here. This matches libsodium and avoids weak / ambiguous verification\n // outcomes where unusual low-order public keys can make distinct key/signature combinations verify.\n if (!zip215 && A.isSmallOrder())\n return false;\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n const k = modL_LE(hashed);\n const RkA = R.add(A.multiply(k, false));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n };\n return [hashable, finish];\n};\n/**\n * Verifies a signature on message and public key. Async.\n * The implementation is based on RFC8032 5.1.7, but default opts use ZIP-215 semantics; pass\n * `{ zip215: false }` for the library's stricter branch.\n * @param signature - 64-byte signature.\n * @param message - Signed message bytes.\n * @param publicKey - 32-byte public key.\n * @param opts - Verification options. Defaults to ZIP-215 semantics. See {@link EdDSAVerifyOpts}.\n * @returns `true` when the signature is valid.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Verify the signature against the same message and derived public key.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const publicKey = await ed.getPublicKeyAsync(secretKey);\n * const signature = await ed.signAsync(message, secretKey);\n * const isValid = await ed.verifyAsync(signature, message, publicKey);\n * ```\n */\nconst verifyAsync = async (signature, message, publicKey, opts = {}) => hashFinishAsync(_verify(signature, message, publicKey, opts));\n/**\n * Verifies a signature on message and public key using the synchronous hash path.\n * The implementation is based on RFC8032 5.1.7, but default opts use ZIP-215 semantics; pass\n * `{ zip215: false }` for the library's stricter branch.\n * @param signature - 64-byte signature.\n * @param message - Signed message bytes.\n * @param publicKey - 32-byte public key.\n * @param opts - Verification options. Defaults to ZIP-215 semantics. See {@link EdDSAVerifyOpts}.\n * @returns `true` when the signature is valid.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Verify a signature entirely through the synchronous API.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const secretKey = ed.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const publicKey = ed.getPublicKey(secretKey);\n * const signature = ed.sign(message, secretKey);\n * const isValid = ed.verify(signature, message, publicKey);\n * ```\n */\nconst verify = (signature, message, publicKey, opts = {}) => hashFinishSync(_verify(signature, message, publicKey, opts));\n/**\n * Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves.\n * Exposes the same low-level field-default `mod` reducer and non-CT `invert` helper used\n * internally.\n * @example\n * Convert bytes to a hex string with the low-level helper namespace.\n *\n * ```ts\n * const hex = etc.bytesToHex(new Uint8Array([1, 2, 3]));\n * ```\n */\nconst etc = /* @__PURE__ */ freeze({\n bytesToHex,\n hexToBytes,\n concatBytes,\n mod,\n invert,\n randomBytes,\n});\n/**\n * Hash implementations used by the synchronous API plus the default async WebCrypto provider.\n * Both slots are configurable API surface; wrapper helpers revalidate that providers still return\n * 64-byte SHA-512 digests.\n * @example\n * Provide a SHA-512 implementation before calling synchronous helpers.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const { publicKey } = ed.keygen();\n * ```\n */\nconst hashes = {\n sha512Async: async (message) => {\n const s = globalThis?.crypto?.subtle;\n if (!s)\n throw new Error('crypto.subtle must be defined, consider polyfill');\n return new Uint8Array(await s.digest('SHA-512', concatBytes(message)));\n },\n sha512: undefined,\n};\n// Returns the final 32-byte Ed25519 secret-key seed verbatim, generating fresh random bytes only\n// when omitted.\nconst randomSecretKey = (seed) => {\n return abytes(seed === undefined ? randomBytes() : seed, LEN, 'seed');\n};\n/**\n * Generates a secret/public keypair.\n * @param seed - Optional 32-byte Ed25519 secret-key seed, returned verbatim as `secretKey`.\n * @returns Keypair with `secretKey` and `publicKey`.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new keypair through the synchronous API after wiring SHA-512.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const { secretKey, publicKey } = ed.keygen();\n * ```\n */\nconst keygen = (seed) => {\n const secretKey = randomSecretKey(seed);\n const publicKey = getPublicKey(secretKey);\n return { secretKey, publicKey };\n};\n/**\n * Generates a secret/public keypair asynchronously.\n * @param seed - Optional 32-byte Ed25519 secret-key seed, returned verbatim as `secretKey`.\n * @returns Keypair with `secretKey` and `publicKey`.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new keypair through the asynchronous WebCrypto-backed path.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const { secretKey, publicKey } = await ed.keygenAsync();\n * ```\n */\nconst keygenAsync = async (seed) => {\n const secretKey = randomSecretKey(seed);\n const publicKey = await getPublicKeyAsync(secretKey);\n return { secretKey, publicKey };\n};\n/**\n * Ed25519-specific key utilities.\n * `utils.getExtendedPublicKey*` expose secret-derived internals (`head`, `prefix`, `scalar`, and\n * point objects), not just public-key bytes.\n * @example\n * Generate a new Ed25519 secret key and derive the matching public key.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const publicKey = await ed.getPublicKeyAsync(secretKey);\n * ```\n */\nconst utils = /* @__PURE__ */ freeze({\n getExtendedPublicKeyAsync,\n getExtendedPublicKey,\n randomSecretKey,\n});\n// ## Precomputes\n// --------------\n// Fixed W=8 window: 33 windows (ceil(256/8) + 1, NOT 32 - see wNAF loop), 128 points per window.\n// Layout is grouped by window: each block stores the positive multiples `1*base .. 128*base` for\n// that window, and the extra `+1` window absorbs carries from signed-digit recoding.\nconst precompute = () => {\n const points = [];\n let p = G;\n let b;\n for (let w = 0; w < 33; w++) {\n b = p;\n points.push(b);\n for (let i = 1; i < 128; i++) {\n b = b.add(p);\n points.push(b);\n } // i=1, bc we skip 0\n p = b.double();\n }\n return points;\n};\nlet Gpows = undefined; // shared process-wide cache of base-point precomputes\n// Branch-based negate helper used for JS/JIT mitigation symmetry, not a strict constant-time claim.\nconst ctneg = (cnd, p) => {\n const n = p.negate();\n return cnd ? n : p;\n};\n/**\n * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by\n * caching multiples of G (base point). Cache is stored in 32MB of RAM.\n * Any time `G.multiply` is done, precomputes are used.\n * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.\n *\n * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,\n * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.\n * Returns the real accumulator `p` plus a fake accumulator `f`; callers only care about `p`, while\n * `f` exists to keep similar work in zero-digit branches as a JS/JIT side-channel mitigation.\n *\n * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().\n */\nconst wNAF = (n) => {\n const comp = Gpows || (Gpows = precompute());\n let p = I;\n let f = G; // f must be G, or could become I in the end\n for (let w = 0; w < 33; w++) {\n let wbits = Number(n & 255n); // extract W=8 bits.\n n >>= 8n; // shift number by W=8 bits.\n // We use negative indexes to reduce size of precomputed table by 2x.\n // Instead of needing precomputes 0..256, we only calculate them for 0..128.\n // If an index > 128 is found, we do (256-index) - where 256 is next window.\n // Naive: index +127 => 127, +224 => 224\n // Optimized: index +127 => 127, +224 => 256-32\n if (wbits > 128) {\n wbits -= 256;\n n += 1n;\n }\n const off = w * 128; // offset of this window's block; also the fake-add index\n const offP = off + Math.abs(wbits) - 1; // real-add index; both offsets always evaluated\n const isOddW = w % 2 !== 0; // conditions, evaluate both; alternates fake-add sign per window\n const isNeg = wbits < 0;\n if (wbits === 0) {\n // wbits == 0 means the real index would be I: can't add it. Add window offset `off` instead.\n f = f.add(ctneg(isOddW, comp[off])); // bits are 0: add garbage to fake point\n }\n else {\n p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point\n }\n }\n if (n !== 0n)\n throw new Error('invalid wnaf');\n return { p, f }; // return both real and fake points for JIT/leakage-shape symmetry\n};\n// !! Remove the export to easily use in REPL / browser console\nexport { etc, getPublicKey, getPublicKeyAsync, hash, hashes, keygen, keygenAsync, Point, sign, signAsync, utils, verify, verifyAsync, };\n","/**\n * @fileoverview Signed-manifest verification for the Velion CDN bundle.\n *\n * Threat model:\n * The loader is published on npm and embedded in customer pages. The full SDK\n * ships from a CDN at runtime. If the CDN is compromised (BGP hijack, bucket\n * takeover, supply-chain on the build pipeline), an attacker could swap the\n * iframe HTML / JS and exfiltrate KYC documents, selfies, and session tokens.\n *\n * Mitigation: every CDN release ships a `manifest.json` that names the\n * entry HTML with its SHA-384 (`entryIntegrity`) and lists every asset with\n * its SHA-384, plus a detached `manifest.sig` (Ed25519 signature over the\n * exact bytes of `manifest.json`). The loader carries the corresponding\n * Ed25519 *public* key and, before letting the iframe load:\n * 1. verifies the signature;\n * 2. refuses a manifest for another loader major or older than\n * `MIN_RUNTIME_VERSION` (anti-rollback: an old, validly signed release\n * cannot be replayed);\n * 3. downloads the entry HTML and the scripts it references and checks them\n * against `entryIntegrity` and the HTML's own SRI attributes.\n * A compromised CDN cannot forge a manifest without the private key, which\n * lives in Cloud KMS and is only usable by the release workflow through\n * Workload Identity Federation.\n *\n * Residual: the iframe navigates to the entry URL itself, so a CDN that serves\n * different bytes to the loader's verification fetch and to the iframe\n * navigation is not caught here. Loading the verified bytes through `srcdoc` or\n * a `blob:` URL would close that gap but would run the runtime with the HOST\n * page's origin (sandbox `allow-same-origin`) or an opaque one, breaking the\n * origin isolation, the API's CORS/Origin checks and camera permissions. See\n * docs/THREAT_MODEL.md (T1).\n *\n * Rotation:\n * The public key is embedded in the loader bundle published to npm. Rotation\n * means publishing a new loader version with the new public key. Old loaders\n * still verify against the previous key while customers upgrade.\n *\n * Browser support:\n * WebCrypto Ed25519 ships enabled by default only in Chrome/Edge 137+,\n * Firefox 130+ and Safari 17+. On older engines `importKey` rejects the\n * algorithm, so the loader falls back to `@noble/ed25519` (pure JS, SHA-512\n * via `crypto.subtle.digest`) with the same key, bytes and verdict. The\n * fallback swaps the verifier, never the policy: a signature that does not\n * verify is still fatal. Only when neither path can run (no `crypto.subtle`,\n * e.g. an insecure context) is the result `unsupported_browser`.\n */\n\nimport { verifyAsync as nobleVerifyAsync } from '@noble/ed25519';\n\n/**\n * Ed25519 public key used to verify `manifest.sig`, base64-encoded raw bytes.\n *\n * Empty string means \"verification disabled\" — accepted only as a transitional\n * mode while the signing pipeline is being deployed. Production loaders MUST\n * ship with this populated before being published to npm.\n *\n * Each environment signs with its own Cloud KMS key. `DEV_MANIFEST_PUBKEY_B64` is\n * the development key (`VELION_MANIFEST_PUBKEY_B64_DEV`), so a local build verifies\n * the dev CDN; CI always injects the environment's key at build time. Update it\n * when the development key is rotated, or local builds and the e2e suite fail\n * with `INTEGRITY_FAILED`.\n */\nconst DEV_MANIFEST_PUBKEY_B64 = 'oX1GwUEjM7Zj9ShtUekgNRXuAUhwgQP5Gf5yYn/xpx4=';\n\ndeclare const __VELION_MANIFEST_PUBKEY__: string | undefined;\n\nexport const VELION_MANIFEST_PUBKEY_B64: string =\n (typeof __VELION_MANIFEST_PUBKEY__ === 'string' && __VELION_MANIFEST_PUBKEY__) ||\n DEV_MANIFEST_PUBKEY_B64;\n\n/**\n * Oldest runtime (`manifest.appVersion`) this loader accepts from a signed manifest.\n *\n * Anti-rollback floor: a signed manifest stays valid forever, so without a floor an\n * attacker who controls the CDN could serve an old release with a known flaw. Raise\n * it whenever a runtime release fixes a security issue; every loader published\n * afterwards then refuses the vulnerable runtimes. `1.1.0-beta.7` is the first\n * runtime whose manifest carries `entryIntegrity` and whose entry pins its scripts\n * with SRI (OSDKW-32).\n */\nexport const MIN_RUNTIME_VERSION = '1.1.0-beta.7';\n\n/** Schema of the signed `manifest.json` emitted by the CDN build pipeline. */\nexport interface VelionCdnManifest {\n /** Loader-major path token, e.g. `\"v1\"`. Must match the loader's `LOADER_MAJOR_VERSION`. */\n version: string;\n /** ISO-8601 timestamp of the build. */\n buildTime: string;\n /** Path to the iframe entry HTML, relative to `cdnUrl`. */\n entry: string;\n /**\n * SHA-384 of the entry HTML (`sha384-<base64>`). Required in a signed manifest:\n * the loader checks the downloaded entry against it before mounting the iframe.\n */\n entryIntegrity?: string;\n /** Runtime version (the app's `package.json`). Required in a signed manifest (anti-rollback). */\n appVersion?: string;\n /** Every shipped asset with its SHA-384 digest. */\n assets?: Array<{ url: string; integrity: string }>;\n}\n\n/** Why a well-signed manifest is still refused, or why the entry did not verify. */\nexport type IntegrityFailure = {\n ok: false;\n reason: 'policy' | 'integrity' | 'unavailable';\n detail: string;\n};\n\n/**\n * Distinguishes \"manifest absent\" (legacy CDN) from \"manifest invalid\" (compromised),\n * and both from \"this browser cannot verify a signature at all\" (`unsupported_browser`).\n */\nexport type ManifestLoadResult =\n | { ok: true; manifest: VelionCdnManifest; signed: boolean }\n | {\n ok: false;\n reason: 'unavailable' | 'invalid_signature' | 'malformed' | 'unsupported_browser';\n detail?: string;\n };\n\nfunction base64ToArrayBuffer(b64: string): ArrayBuffer {\n const bin = atob(b64);\n const buf = new ArrayBuffer(bin.length);\n const view = new Uint8Array(buf);\n for (let i = 0; i < bin.length; i++) {\n view[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n/**\n * Whether a WebCrypto rejection means \"algorithm not implemented\" rather than a bad\n * key or signature. Chromium throws `NotSupportedError` (\"Algorithm: Unrecognized\n * name\"); Firefox and Safari throw `NotSupportedError` too.\n */\nfunction isAlgorithmUnsupported(err: unknown): boolean {\n if (err instanceof Error && err.name === 'NotSupportedError') return true;\n const message = err instanceof Error ? err.message : String(err);\n return /unrecognized|not supported|unsupported/i.test(message);\n}\n\n/** Outcome of the native attempt: a verdict, \"engine lacks Ed25519\", or a hard error. */\ntype WebCryptoOutcome =\n | { kind: 'verdict'; valid: boolean }\n | { kind: 'unsupported' }\n | { kind: 'error'; detail: string };\n\nasync function verifyWithWebCrypto(\n pubKey: ArrayBuffer,\n signature: ArrayBuffer,\n data: ArrayBuffer,\n): Promise<WebCryptoOutcome> {\n let key: CryptoKey;\n try {\n key = await crypto.subtle.importKey(\n 'raw',\n pubKey,\n { name: 'Ed25519' } as AlgorithmIdentifier,\n false,\n ['verify'],\n );\n } catch (err) {\n if (isAlgorithmUnsupported(err)) return { kind: 'unsupported' };\n return { kind: 'error', detail: `pubkey import failed: ${(err as Error).message}` };\n }\n try {\n const valid = await crypto.subtle.verify(\n { name: 'Ed25519' } as AlgorithmIdentifier,\n key,\n signature,\n data,\n );\n return { kind: 'verdict', valid };\n } catch (err) {\n if (isAlgorithmUnsupported(err)) return { kind: 'unsupported' };\n return { kind: 'error', detail: (err as Error).message };\n }\n}\n\n/**\n * Pure-JS Ed25519 verification for engines without WebCrypto Ed25519. Uses RFC 8032\n * strict semantics (`zip215: false`) to match what WebCrypto accepts.\n */\nasync function verifyWithNoble(\n pubKey: ArrayBuffer,\n signature: ArrayBuffer,\n data: ArrayBuffer,\n): Promise<boolean> {\n return nobleVerifyAsync(new Uint8Array(signature), new Uint8Array(data), new Uint8Array(pubKey), {\n zip215: false,\n });\n}\n\n/**\n * Verifies with native WebCrypto when available, otherwise with the JS fallback.\n * Either way a signature that does not verify returns `invalid_signature`.\n */\nasync function verifySignature(\n pubKeyB64: string,\n signature: ArrayBuffer,\n data: ArrayBuffer,\n): Promise<ManifestLoadResult | null> {\n if (typeof globalThis.crypto?.subtle?.digest !== 'function') {\n return {\n ok: false,\n reason: 'unsupported_browser',\n detail:\n 'crypto.subtle is unavailable (insecure context or very old browser); ' +\n 'the manifest signature cannot be verified.',\n };\n }\n const pubKey = base64ToArrayBuffer(pubKeyB64);\n\n const native = await verifyWithWebCrypto(pubKey, signature, data);\n if (native.kind === 'error') {\n return { ok: false, reason: 'invalid_signature', detail: native.detail };\n }\n let valid: boolean;\n if (native.kind === 'verdict') {\n valid = native.valid;\n } else {\n try {\n valid = await verifyWithNoble(pubKey, signature, data);\n } catch (err) {\n // noble throws on malformed input (wrong signature / key length), i.e. a bad signature.\n return { ok: false, reason: 'invalid_signature', detail: (err as Error).message };\n }\n }\n return valid ? null : { ok: false, reason: 'invalid_signature' };\n}\n\n/**\n * Fetches `${cdnUrl}/manifest.json` (and `manifest.sig` when verification is enabled).\n *\n * Returns:\n * - `{ ok:true, signed:true }` when the signature verifies against the embedded pubkey.\n * - `{ ok:true, signed:false }` when the manifest exists but verification is disabled\n * (transitional dev/staging mode where `VELION_MANIFEST_PUBKEY_B64` is empty).\n * - `{ ok:false, reason:'unavailable' }` when the CDN has no manifest yet — the\n * loader treats this as legacy mode and may proceed if explicitly allowed.\n * - `{ ok:false, reason:'invalid_signature' | 'malformed' }` when the manifest\n * is present but tampered or syntactically invalid. The loader MUST refuse\n * to mount the iframe in this case.\n * - `{ ok:false, reason:'unsupported_browser' }` when the browser cannot verify\n * any signature (no `crypto.subtle`). Also fatal, but not a tampering signal.\n */\nexport async function loadAndVerifyManifest(\n cdnUrl: string,\n pubKeyB64: string = VELION_MANIFEST_PUBKEY_B64,\n): Promise<ManifestLoadResult> {\n let manifestBuffer: ArrayBuffer;\n let manifestText: string;\n try {\n const resp = await fetch(`${cdnUrl}/manifest.json`, {\n credentials: 'omit',\n cache: 'no-cache',\n redirect: 'error',\n });\n if (resp.status === 404) {\n return { ok: false, reason: 'unavailable' };\n }\n if (!resp.ok) {\n return { ok: false, reason: 'unavailable', detail: `HTTP ${resp.status}` };\n }\n manifestBuffer = await resp.arrayBuffer();\n manifestText = new TextDecoder().decode(manifestBuffer);\n } catch (err) {\n return { ok: false, reason: 'unavailable', detail: (err as Error).message };\n }\n\n let manifest: VelionCdnManifest;\n try {\n manifest = JSON.parse(manifestText) as VelionCdnManifest;\n if (\n typeof manifest.version !== 'string' ||\n typeof manifest.entry !== 'string' ||\n typeof manifest.buildTime !== 'string'\n ) {\n return { ok: false, reason: 'malformed' };\n }\n } catch (err) {\n return { ok: false, reason: 'malformed', detail: (err as Error).message };\n }\n\n if (!pubKeyB64) {\n // Pubkey not yet provisioned on this loader release. Accept the manifest\n // unsigned but flag it so the caller can decide whether to proceed.\n return { ok: true, manifest, signed: false };\n }\n\n let sigBuffer: ArrayBuffer;\n try {\n const sigResp = await fetch(`${cdnUrl}/manifest.sig`, {\n credentials: 'omit',\n cache: 'no-cache',\n redirect: 'error',\n });\n if (!sigResp.ok) {\n return { ok: false, reason: 'invalid_signature', detail: `sig HTTP ${sigResp.status}` };\n }\n const sigText = (await sigResp.text()).trim();\n sigBuffer = base64ToArrayBuffer(sigText);\n } catch (err) {\n return { ok: false, reason: 'invalid_signature', detail: (err as Error).message };\n }\n\n const failure = await verifySignature(pubKeyB64, sigBuffer, manifestBuffer);\n if (failure) {\n return failure;\n }\n\n return { ok: true, manifest, signed: true };\n}\n\n/** Numeric-aware comparison of SemVer strings, including pre-release identifiers. */\nexport function compareVersions(a: string, b: string): number {\n const parse = (v: string): { core: number[]; pre: string[] } | null => {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/.exec(v.trim());\n if (!m) return null;\n return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split('.') : [] };\n };\n const pa = parse(a);\n const pb = parse(b);\n if (!pa || !pb) return Number.NaN;\n for (let i = 0; i < 3; i++) {\n const d = (pa.core[i] ?? 0) - (pb.core[i] ?? 0);\n if (d !== 0) return Math.sign(d);\n }\n // A release ranks above any of its pre-releases.\n if (pa.pre.length === 0 || pb.pre.length === 0) return Math.sign(pb.pre.length - pa.pre.length);\n for (let i = 0; i < Math.max(pa.pre.length, pb.pre.length); i++) {\n const x = pa.pre[i];\n const y = pb.pre[i];\n if (x === undefined) return -1;\n if (y === undefined) return 1;\n const xn = /^\\d+$/.test(x);\n const yn = /^\\d+$/.test(y);\n if (xn && yn) {\n const d = Number(x) - Number(y);\n if (d !== 0) return Math.sign(d);\n } else if (xn !== yn) {\n return xn ? -1 : 1;\n } else if (x !== y) {\n return x < y ? -1 : 1;\n }\n }\n return 0;\n}\n\n/**\n * Policy a SIGNED manifest must satisfy on top of a valid signature: built for this\n * loader's major, not older than `minRuntimeVersion`, and naming its entry's digest.\n * Returns `null` when the manifest is acceptable.\n */\nexport function checkSignedManifestPolicy(\n manifest: VelionCdnManifest,\n expectedMajor: string,\n minRuntimeVersion: string = MIN_RUNTIME_VERSION,\n): IntegrityFailure | null {\n if (manifest.version !== expectedMajor) {\n return {\n ok: false,\n reason: 'policy',\n detail: `manifest is for loader major \"${manifest.version}\", this loader is \"${expectedMajor}\"`,\n };\n }\n if (typeof manifest.appVersion !== 'string') {\n return { ok: false, reason: 'policy', detail: 'manifest has no appVersion' };\n }\n const cmp = compareVersions(manifest.appVersion, minRuntimeVersion);\n if (Number.isNaN(cmp)) {\n return { ok: false, reason: 'policy', detail: `unparseable appVersion \"${manifest.appVersion}\"` };\n }\n if (cmp < 0) {\n return {\n ok: false,\n reason: 'policy',\n detail: `runtime ${manifest.appVersion} is older than the minimum ${minRuntimeVersion} (rollback refused)`,\n };\n }\n if (typeof manifest.entryIntegrity !== 'string' || !manifest.entryIntegrity.startsWith('sha384-')) {\n return { ok: false, reason: 'policy', detail: 'manifest does not name the entry digest (entryIntegrity)' };\n }\n return null;\n}\n\nasync function sha384Base64(buf: ArrayBuffer): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-384', buf));\n let bin = '';\n for (let i = 0; i < digest.length; i++) bin += String.fromCharCode(digest[i] ?? 0);\n return `sha384-${btoa(bin)}`;\n}\n\n/** True when `actual` (`sha384-…`) is one of the SHA-384 values of an SRI attribute. */\nfunction matchesIntegrity(expected: string, actual: string): boolean {\n return expected\n .trim()\n .split(/\\s+/)\n .some((token) => token.split('?')[0] === actual);\n}\n\nasync function fetchBytes(url: string, noCache: boolean): Promise<ArrayBuffer | IntegrityFailure> {\n try {\n const resp = await fetch(url, {\n credentials: 'omit',\n redirect: 'error',\n ...(noCache && { cache: 'no-cache' as RequestCache }),\n });\n if (!resp.ok) return { ok: false, reason: 'unavailable', detail: `HTTP ${resp.status} for ${url}` };\n return await resp.arrayBuffer();\n } catch (err) {\n return { ok: false, reason: 'unavailable', detail: `${url}: ${(err as Error).message}` };\n }\n}\n\n/**\n * Downloads the iframe entry and every script / stylesheet / modulepreload it\n * references, and checks them before the iframe is pointed at the entry:\n *\n * - the entry HTML must hash to `manifest.entryIntegrity`;\n * - every referenced resource must be same-origin with the CDN and carry an SRI\n * `integrity` attribute (the build adds them), and its bytes must match it.\n *\n * The browser enforces the same SRI attributes again when the iframe loads, so this\n * is what turns a tampered script into an immediate `INTEGRITY_FAILED` instead of a\n * runtime that silently never boots.\n *\n * Returns `null` when everything matches, `reason: 'integrity'` on any mismatch and\n * `reason: 'unavailable'` when a file could not be downloaded.\n */\nexport async function verifyEntry(\n cdnUrl: string,\n manifest: VelionCdnManifest,\n): Promise<IntegrityFailure | null> {\n if (typeof manifest.entryIntegrity !== 'string') {\n return { ok: false, reason: 'integrity', detail: 'manifest does not name the entry digest' };\n }\n if (typeof globalThis.crypto?.subtle?.digest !== 'function') {\n return { ok: false, reason: 'unavailable', detail: 'crypto.subtle is unavailable' };\n }\n const entryPath = manifest.entry.startsWith('/') ? manifest.entry : `/${manifest.entry}`;\n const entryUrl = `${cdnUrl}${entryPath}`;\n const cdnOrigin = new URL(cdnUrl).origin;\n\n const html = await fetchBytes(entryUrl, true);\n if (!(html instanceof ArrayBuffer)) return html;\n const htmlDigest = await sha384Base64(html);\n if (!matchesIntegrity(manifest.entryIntegrity, htmlDigest)) {\n return {\n ok: false,\n reason: 'integrity',\n detail: `${entryPath} does not match the signed manifest (got ${htmlDigest})`,\n };\n }\n\n // Parsed only after its digest matched, so this is the signed document.\n const doc = new DOMParser().parseFromString(new TextDecoder().decode(html), 'text/html');\n const refs: Array<{ url: string; integrity: string | null }> = [];\n doc.querySelectorAll('script[src]').forEach((el) => {\n refs.push({ url: el.getAttribute('src') ?? '', integrity: el.getAttribute('integrity') });\n });\n doc.querySelectorAll('link[href]').forEach((el) => {\n const rel = (el.getAttribute('rel') ?? '').toLowerCase().split(/\\s+/);\n if (rel.includes('modulepreload') || rel.includes('stylesheet') || rel.includes('preload')) {\n refs.push({ url: el.getAttribute('href') ?? '', integrity: el.getAttribute('integrity') });\n }\n });\n\n for (const ref of refs) {\n let url: URL;\n try {\n url = new URL(ref.url, entryUrl);\n } catch {\n return { ok: false, reason: 'integrity', detail: `invalid resource URL \"${ref.url}\" in the entry` };\n }\n if (url.origin !== cdnOrigin) {\n return { ok: false, reason: 'integrity', detail: `entry loads ${url.href} from another origin` };\n }\n if (!ref.integrity) {\n return { ok: false, reason: 'integrity', detail: `entry loads ${url.pathname} without SRI` };\n }\n const bytes = await fetchBytes(url.href, false);\n if (!(bytes instanceof ArrayBuffer)) return bytes;\n const digest = await sha384Base64(bytes);\n if (!matchesIntegrity(ref.integrity, digest)) {\n return {\n ok: false,\n reason: 'integrity',\n detail: `${url.pathname} does not match its SRI digest (got ${digest})`,\n };\n }\n }\n return null;\n}\n","/**\n * Thin client (loader) for Velion Onboarding.\n * Creates an iframe pointing to the CDN app and bridges config/events via postMessage.\n * Follows the same pattern as Sumsub WebSDK: init → iframe loads → postMessage config → events.\n *\n * Before the iframe is pointed at the CDN the loader verifies the signed manifest, the\n * anti-rollback floor and the entry HTML + scripts (see `manifest.ts`). `VELION_INIT`,\n * which carries the session token, is posted exactly once, to the document that\n * loaded after that verification.\n */\n\nimport type {\n VelionConfig,\n OnboardingResult,\n SdkError,\n SdkStatus,\n OnboardingStep,\n} from './types';\nimport {\n SdkErrorCode,\n VELION_MSG_INIT,\n VELION_MSG_READY,\n VELION_MSG_SUCCESS,\n VELION_MSG_ERROR,\n VELION_MSG_STEP_CHANGE,\n VELION_MSG_STEP_COMPLETE,\n VELION_MSG_TOKEN_EXPIRED,\n VELION_MSG_EXIT,\n VELION_MSG_LIVENESS_VIDEO_UPLOADED,\n VELION_MSG_TOKEN,\n type VelionMessage,\n type OnboardingExit,\n type LivenessVideoRef,\n} from './types';\nimport {\n checkSignedManifestPolicy,\n loadAndVerifyManifest,\n verifyEntry,\n VELION_MANIFEST_PUBKEY_B64,\n type VelionCdnManifest,\n} from './manifest';\n\n/**\n * Product slug under the shared `static.velion.la/sdk/` namespace. This identity\n * SDK lives at `sdk/onboarding/`; future Velion SDKs (e.g. payments, auth) get\n * their own slug so they can be deployed independently from the same CDN.\n */\nexport const LOADER_PRODUCT = 'onboarding' as const;\n\n/**\n * Major version of this loader. Locked into the CDN path so a breaking change\n * to the loader↔app postMessage contract requires publishing loader-`v2`\n * against `/sdk/onboarding/v2/`. Customers can keep older loaders for as long\n * as the matching CDN path is served.\n */\nexport const LOADER_MAJOR_VERSION = 'v1' as const;\n\n/** Default CDN base URL for the onboarding app (no trailing slash). */\nexport const DEFAULT_CDN_URL =\n `https://static.velion.la/sdk/${LOADER_PRODUCT}/${LOADER_MAJOR_VERSION}`;\n\n/**\n * Used only while the host container has no laid-out height yet (e.g. `display: none`\n * or first paint). Replaced by a pixel height as soon as `container.clientHeight > 0`.\n */\nconst IFRAME_FALLBACK_HEIGHT_CSS = 'min(85vh, 880px)';\n\n/** Loader config: VelionConfig plus optional CDN URL and token refresh callback. */\nexport interface VelionLoaderConfig extends VelionConfig {\n /**\n * Base URL of the CDN where the onboarding app is served (e.g. https://static.velion.la/sdk).\n * The loader fetches `${cdnUrl}/manifest.json` (signed with Ed25519), verifies the\n * signature against the loader's embedded public key, and only then loads the\n * iframe entry named in the manifest.\n * @default 'https://static.velion.la/sdk'\n */\n cdnUrl?: string;\n\n /**\n * When `true`, lets the loader proceed against a CDN that does not yet expose a\n * signed `manifest.json` — for staging or migration windows. Has NO effect when\n * the loader carries an embedded pubkey AND the manifest exists but signature\n * verification fails (that case is always fatal).\n *\n * Default `false`: production loaders refuse to mount the iframe without a\n * verified manifest once the pubkey has been provisioned.\n *\n * @default false\n */\n allowUnverifiedCdn?: boolean;\n\n /**\n * Called when the iframe requests a new session token (e.g. after SESSION_EXPIRED).\n * Return the new token and optional expiresAt; the CDN app will continue the flow.\n */\n onTokenExpired?: () => Promise<{ sessionToken: string; expiresAt?: string }>;\n\n /**\n * How long to wait, after the iframe document loaded, for the runtime to\n * report `VELION_READY`. Past it the loader emits `RUNTIME_LOAD_FAILED`\n * instead of leaving the host with a blank iframe and no callback (e.g.\n * when the CDN entry points at assets that 404).\n *\n * @default 30000\n */\n runtimeReadyTimeoutMs?: number;\n}\n\nconst DEFAULT_RUNTIME_READY_TIMEOUT_MS = 30_000;\n\nfunction parseOriginFromUrl(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return '';\n }\n}\n\n/**\n * Allows `https:` and `wss:` everywhere, plus plain `http:`/`ws:` only when the host\n * is a loopback / `.local` address (developer machines and CI). Used to prevent\n * accidental cleartext bearer-token transmission to a misconfigured `apiUrl`/`cdnUrl`.\n */\nfunction isLocalhostHost(host: string): boolean {\n return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.local');\n}\n\nexport function isSecureHttpUrl(url: string): boolean {\n try {\n const u = new URL(url);\n if (u.protocol === 'https:') return true;\n if (u.protocol === 'http:') return isLocalhostHost(u.hostname);\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * True while the iframe still holds the `about:blank` document it was created with.\n * That document is same-origin with the host, so its location is readable; the CDN\n * runtime is cross-origin and reading its location throws.\n */\nfunction isInitialBlankDocument(iframe: HTMLIFrameElement): boolean {\n try {\n return iframe.contentWindow?.location.href === 'about:blank';\n } catch {\n return false;\n }\n}\n\n/** Keys of VelionConfig that are safe to send via postMessage (no functions). */\nconst SERIALIZABLE_CONFIG_KEYS: (keyof VelionConfig)[] = [\n 'containerId',\n 'sessionId',\n 'sessionToken',\n 'apiUrl',\n 'expiresAt',\n 'theme',\n 'colorMode',\n 'locale',\n 'allowEmbedded',\n 'livenessShowIntro',\n 'livenessShowBackButton',\n 'fingerprintEndpoint',\n 'debug',\n 'googleMapsApiKey',\n 'showFinalResultScreen',\n 'showProgressBar',\n 'finalResultScreenTexts',\n 'routingTimeoutMs',\n];\n\nfunction buildSerializableConfig(\n config: Readonly<VelionLoaderConfig>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {\n containerId: 'velion-sdk-root',\n allowEmbedded: true,\n };\n for (const key of SERIALIZABLE_CONFIG_KEYS) {\n if (key === 'containerId' || key === 'allowEmbedded') continue;\n const value = config[key as keyof typeof config];\n if (value !== undefined && typeof value !== 'function') {\n out[key] = value;\n }\n }\n return out;\n}\n\nexport class VelionOnboarding {\n private readonly config: Readonly<VelionLoaderConfig>;\n private status: SdkStatus = 'IDLE';\n private iframe: HTMLIFrameElement | null = null;\n private container: HTMLElement | null = null;\n private messageHandler: ((e: MessageEvent) => void) | null = null;\n private containerResizeObserver: ResizeObserver | null = null;\n private iframeHeightWindowResizeHandler: (() => void) | null = null;\n private cdnOrigin = '';\n /** Armed when VELION_INIT is sent; cleared by VELION_READY or destroy(). */\n private readyTimer: ReturnType<typeof setTimeout> | null = null;\n /** Set once VELION_INIT (and with it the session token) has been posted. */\n private initSent = false;\n /**\n * Set when the iframe loads a second document after INIT. From then on nothing\n * from the iframe is trusted: it is no longer the document the loader verified.\n */\n private iframeReloaded = false;\n\n private clearReadyTimer(): void {\n if (this.readyTimer !== null) {\n clearTimeout(this.readyTimer);\n this.readyTimer = null;\n }\n }\n\n private armReadyTimer(cdnUrl: string): void {\n this.clearReadyTimer();\n const ms = this.config.runtimeReadyTimeoutMs ?? DEFAULT_RUNTIME_READY_TIMEOUT_MS;\n if (!(ms > 0)) return;\n this.readyTimer = setTimeout(() => {\n this.readyTimer = null;\n if (this.status !== 'RUNNING') return; // already READY-progressed, errored or destroyed\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.RUNTIME_LOAD_FAILED,\n message:\n `The onboarding runtime at ${cdnUrl} did not become ready within ${ms} ms. ` +\n 'Check that the CDN serves the assets referenced by its index.html and that the host ' +\n \"page's Content-Security-Policy allows the runtime scripts.\",\n });\n }, ms);\n }\n\n constructor(config: VelionLoaderConfig) {\n this.config = Object.freeze({ ...config });\n }\n\n async start(): Promise<void> {\n if (this.status === 'DESTROYED') {\n this.config.onError?.({\n code: SdkErrorCode.INSTANCE_DESTROYED,\n message:\n 'This VelionOnboarding instance has been destroyed. Create a new instance to retry.',\n });\n return;\n }\n\n if (this.status !== 'IDLE') {\n this.config.onError?.({\n code: SdkErrorCode.ALREADY_STARTED,\n message:\n 'start() was called on an already-running SDK instance. Call destroy() before re-starting.',\n });\n return;\n }\n\n const container = document.getElementById(this.config.containerId);\n if (!container) {\n this.config.onError?.({\n code: SdkErrorCode.CONTAINER_NOT_FOUND,\n message: `No DOM element found with id=\"${this.config.containerId}\". Ensure the element exists before calling start().`,\n });\n return;\n }\n\n const cdnUrl = (this.config.cdnUrl ?? DEFAULT_CDN_URL).replace(/\\/$/, '');\n if (!isSecureHttpUrl(cdnUrl)) {\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Insecure cdnUrl: \"${cdnUrl}\". Must be https:// (http:// is allowed only for localhost).`,\n });\n return;\n }\n if (this.config.apiUrl && !isSecureHttpUrl(this.config.apiUrl)) {\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Insecure apiUrl: \"${this.config.apiUrl}\". Must be https:// (http:// is allowed only for localhost).`,\n });\n return;\n }\n this.cdnOrigin = parseOriginFromUrl(cdnUrl);\n if (!this.cdnOrigin) {\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Invalid cdnUrl: ${cdnUrl}. Must be a valid absolute URL.`,\n });\n return;\n }\n\n this.container = container;\n this.status = 'INITIALIZING';\n\n const iframe = document.createElement('iframe');\n iframe.setAttribute('title', 'Velion Onboarding');\n // The SDK only needs the camera. Microphone and geolocation are intentionally not granted.\n iframe.setAttribute('allow', 'camera');\n // Sandbox limits blast radius of a CDN compromise. Tokens we keep:\n // allow-scripts — the iframe is a JS app\n // allow-same-origin — needed for fetch to same-origin assets and for postMessage to behave\n // allow-forms — file pickers and form submissions for OCR upload flows\n // allow-popups — Google Maps / Places attribution links open in new tab\n // allow-modals — getUserMedia permission prompts and document picker\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-modals',\n );\n // Avoid leaking host page paths to the CDN logs.\n iframe.setAttribute('referrerpolicy', 'no-referrer');\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n iframe.style.display = 'block';\n /* Height is applied in attachIframeHeightSync (pixel match + internal fallback). */\n\n const messageHandler = (e: MessageEvent): void => {\n // Origin AND source must match: a sibling iframe from the same CDN origin\n // (e.g. opened by the host page) must not be able to spoof events.\n if (e.origin !== this.cdnOrigin) return;\n if (e.source !== this.iframe?.contentWindow) return;\n if (this.iframeReloaded) return;\n const msg = e.data as VelionMessage | undefined;\n if (!msg || typeof msg.type !== 'string') return;\n\n // Any message that passed the origin+source check came from a running\n // runtime, so none of them may be followed by RUNTIME_LOAD_FAILED. READY is\n // the expected first message, but a runtime that reports a step or an\n // error first is alive just the same.\n this.clearReadyTimer();\n\n switch (msg.type) {\n case VELION_MSG_READY:\n this.status = 'RUNNING';\n break;\n case VELION_MSG_SUCCESS:\n this.status = 'COMPLETED';\n this.config.onSuccess?.(msg.payload as OnboardingResult);\n break;\n case VELION_MSG_ERROR:\n this.status = 'ERROR';\n this.config.onError?.(msg.payload as SdkError);\n break;\n case VELION_MSG_STEP_CHANGE: {\n const p = msg.payload as { step: OnboardingStep; stepIndex: number };\n this.config.onStepChange?.(p.step, p.stepIndex);\n break;\n }\n case VELION_MSG_STEP_COMPLETE: {\n const p = msg.payload as { step: OnboardingStep };\n this.config.onStepComplete?.(p.step);\n break;\n }\n case VELION_MSG_EXIT: {\n // User backed out of the first reversible step: the flow ended without\n // a verdict. Forward to the host so it can dismiss the SDK surface.\n this.status = 'EXITED';\n this.config.onExit?.(msg.payload as OnboardingExit);\n break;\n }\n case VELION_MSG_LIVENESS_VIDEO_UPLOADED: {\n // Evidence signal from the LIVENESS_MATCH step (OSDKW-11). Informational\n // only: the flow never depends on it, so no status change.\n this.config.onLivenessVideoUploaded?.(msg.payload as LivenessVideoRef);\n break;\n }\n case VELION_MSG_TOKEN_EXPIRED: {\n const refresh = this.config.onTokenExpired;\n if (refresh) {\n refresh().then(\n (t) => this.sendToIframe({ type: VELION_MSG_TOKEN, payload: t }),\n () => {\n this.config.onError?.({\n code: SdkErrorCode.SESSION_EXPIRED,\n message: 'Token refresh failed.',\n });\n }\n );\n } else {\n this.config.onError?.({\n code: SdkErrorCode.SESSION_EXPIRED,\n message: 'Session token expired. Provide onTokenExpired in config to refresh.',\n });\n }\n break;\n }\n default:\n break;\n }\n };\n\n window.addEventListener('message', messageHandler);\n this.messageHandler = messageHandler;\n this.iframe = iframe;\n\n container.replaceChildren(iframe);\n this.attachIframeHeightSync(container, iframe);\n\n // ── Verify the CDN manifest and the entry before mounting the iframe ───\n const resolved = await this.resolveManifest(cdnUrl);\n if (!resolved) {\n // resolveManifest already invoked onError. Stop here so we don't load\n // an unverified bundle.\n return;\n }\n const { manifest } = resolved;\n if (!(await this.verifyRuntime(cdnUrl, resolved))) return;\n if (this.status !== 'INITIALIZING') return; // destroyed while verifying\n const entryPath = manifest.entry.startsWith('/') ? manifest.entry : `/${manifest.entry}`;\n\n return new Promise<void>((resolve) => {\n iframe.onload = (): void => {\n if (isInitialBlankDocument(iframe)) {\n // The empty document a freshly inserted iframe starts with. Some engines\n // fire its `load` asynchronously, after `src` is already set; it is not\n // the runtime and must neither receive INIT nor count as a reload.\n return;\n }\n if (this.initSent) {\n // A second document loaded in the iframe (reload, or the runtime\n // navigated away). It was not verified, so it does not get the token.\n this.handleIframeReload();\n return;\n }\n if (!this.iframe?.contentWindow) {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: 'Iframe failed to load.',\n });\n resolve();\n return;\n }\n // postMessage cannot clone functions. Sumsub-style: send only JSON-serializable config.\n // Clone via JSON so no function can slip through (e.g. from cached bundle or nested props).\n const initPayload = buildSerializableConfig(this.config);\n let payloadForPostMessage: unknown;\n try {\n payloadForPostMessage = JSON.parse(JSON.stringify(initPayload));\n } catch {\n payloadForPostMessage = initPayload;\n }\n this.sendToIframe({ type: VELION_MSG_INIT, payload: payloadForPostMessage });\n this.initSent = true;\n this.status = 'RUNNING';\n // The document loaded, but a 200 index.html whose scripts 404 (or a CSP\n // that blocks them) never answers VELION_INIT. Bound the wait so the\n // host gets an error instead of a silent blank iframe.\n this.armReadyTimer(cdnUrl);\n resolve();\n };\n\n iframe.onerror = (): void => {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Failed to load onboarding app from ${cdnUrl}. Check cdnUrl and network.`,\n });\n resolve();\n };\n\n iframe.src = `${cdnUrl}${entryPath}`;\n });\n }\n\n /**\n * Reacts to a second `load` of the iframe after `VELION_INIT` was posted.\n *\n * The session is not restarted: that would mean posting the session token to a\n * document the loader never verified (the integrity check covers the bytes it\n * downloaded before the first navigation, not whatever a reload brings). Failing\n * costs little, because the backend owns the session state: a new instance\n * re-verifies the CDN and resumes from the current step.\n */\n private handleIframeReload(): void {\n this.iframeReloaded = true;\n this.clearReadyTimer();\n if (this.status !== 'RUNNING') return; // already finished, failed or destroyed\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.RUNTIME_LOAD_FAILED,\n message:\n 'The onboarding iframe reloaded after the session started. The loader does not resend ' +\n 'the session token to a document it did not verify; call destroy() and start a new ' +\n 'instance to resume from the current step.',\n });\n }\n\n /**\n * Applies the anti-rollback policy to a signed manifest and verifies the entry HTML\n * and its scripts. Emits onError and returns `false` when the runtime must not be\n * mounted.\n */\n private async verifyRuntime(\n cdnUrl: string,\n resolved: { manifest: VelionCdnManifest; signed: boolean; synthesized: boolean },\n ): Promise<boolean> {\n const { manifest, signed, synthesized } = resolved;\n if (synthesized) return true; // legacy CDN without manifest, explicitly tolerated\n if (signed) {\n const policy = checkSignedManifestPolicy(manifest, LOADER_MAJOR_VERSION);\n if (policy) {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `CDN manifest at \"${cdnUrl}/manifest.json\" is signed but not acceptable: ${policy.detail}. ` +\n 'Refusing to load the iframe.',\n });\n return false;\n }\n } else if (typeof manifest.entryIntegrity !== 'string') {\n return true; // unsigned transitional mode and nothing to check against\n }\n let failure;\n try {\n failure = await verifyEntry(cdnUrl, manifest);\n } catch (err) {\n failure = { ok: false as const, reason: 'integrity' as const, detail: (err as Error).message };\n }\n if (!failure) return true;\n this.status = 'ERROR';\n if (failure.reason === 'unavailable') {\n this.config.onError?.({\n code: SdkErrorCode.RUNTIME_LOAD_FAILED,\n message:\n `Could not download the onboarding runtime from ${cdnUrl} to verify it (${failure.detail}). ` +\n 'Check the CDN deploy and the network.',\n });\n } else {\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `The onboarding runtime at ${cdnUrl} failed its integrity check: ${failure.detail}. ` +\n 'Refusing to load the iframe to protect the user.',\n });\n }\n return false;\n }\n\n /**\n * Fetches and verifies the CDN manifest. Returns `null` and emits onError when\n * the manifest is missing in production mode, or when the signature is invalid.\n * `synthesized` marks the stand-in used for a legacy CDN without a manifest.\n */\n private async resolveManifest(\n cdnUrl: string,\n ): Promise<{ manifest: VelionCdnManifest; signed: boolean; synthesized: boolean } | null> {\n let result;\n try {\n result = await loadAndVerifyManifest(cdnUrl);\n } catch (err) {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message: `Manifest verification crashed unexpectedly: ${(err as Error).message}`,\n });\n return null;\n }\n if (result.ok) {\n if (!result.signed && VELION_MANIFEST_PUBKEY_B64) {\n // Should not happen — pubkey is set, manifest exists, yet not signed.\n // loadAndVerifyManifest only marks `signed:false` when pubkey is empty.\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message: 'Internal: manifest reported as unsigned despite pubkey being set.',\n });\n return null;\n }\n return { manifest: result.manifest, signed: result.signed, synthesized: false };\n }\n if (result.reason === 'unavailable') {\n // Manifest endpoint is missing. Permitted only when the loader is configured\n // to tolerate it OR when the loader was published without a pubkey (transitional).\n const tolerateMissing =\n this.config.allowUnverifiedCdn === true || !VELION_MANIFEST_PUBKEY_B64;\n if (tolerateMissing) {\n return {\n manifest: {\n version: 'legacy',\n buildTime: new Date().toISOString(),\n entry: '/index.html',\n },\n signed: false,\n synthesized: true,\n };\n }\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `CDN at \"${cdnUrl}\" did not expose /manifest.json. The loader is configured ` +\n 'to require a signed manifest. If the CDN is migrating, set `allowUnverifiedCdn: true` ' +\n 'on the loader config — but only as a temporary measure.',\n });\n return null;\n }\n if (result.reason === 'unsupported_browser') {\n // Fatal too, but reported apart: nothing was tampered with, the browser just\n // cannot verify a signature. allowUnverifiedCdn does not bypass it.\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.UNSUPPORTED_BROWSER,\n message:\n 'This browser cannot verify the signature of the Velion CDN manifest, so the ' +\n 'onboarding cannot start. It needs a secure context (https) and WebCrypto ' +\n '(Chrome/Edge 67+, Firefox 68+, Safari 14+). ' +\n (result.detail ? `Detail: ${result.detail}` : ''),\n });\n return null;\n }\n // 'invalid_signature' or 'malformed' — always fatal, even when allowUnverifiedCdn is true.\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `CDN manifest at \"${cdnUrl}/manifest.json\" failed integrity check (${result.reason}). ` +\n 'Refusing to load the iframe to protect the user. ' +\n ('detail' in result && result.detail ? `Detail: ${result.detail}` : ''),\n });\n return null;\n }\n\n /**\n * Keep the iframe exactly as tall as the host container so integrators do not need\n * `height: 100%` on the iframe or flex hacks—only a definite block-size on the\n * container (e.g. `height: 700px` or `height: 100vh`), similar to Sumsub WebSDK.\n *\n * Until the container has a non-zero `clientHeight`, apply an internal fallback\n * height so the SDK is usable even before layout or if only `min-height` is set.\n */\n private attachIframeHeightSync(\n container: HTMLElement,\n iframe: HTMLIFrameElement,\n ): void {\n const sync = (): void => {\n if (this.iframe !== iframe || this.container !== container) return;\n const h = container.clientHeight;\n if (h > 0) {\n iframe.style.height = `${h}px`;\n iframe.style.minHeight = '';\n } else {\n iframe.style.height = IFRAME_FALLBACK_HEIGHT_CSS;\n iframe.style.minHeight = '';\n }\n };\n sync();\n requestAnimationFrame(sync);\n requestAnimationFrame(() => {\n requestAnimationFrame(sync);\n });\n if (typeof ResizeObserver !== 'undefined') {\n this.containerResizeObserver = new ResizeObserver(sync);\n this.containerResizeObserver.observe(container);\n } else {\n this.iframeHeightWindowResizeHandler = sync;\n window.addEventListener('resize', sync);\n }\n }\n\n private detachIframeHeightSync(): void {\n if (this.containerResizeObserver) {\n this.containerResizeObserver.disconnect();\n this.containerResizeObserver = null;\n }\n if (this.iframeHeightWindowResizeHandler) {\n window.removeEventListener('resize', this.iframeHeightWindowResizeHandler);\n this.iframeHeightWindowResizeHandler = null;\n }\n }\n\n private sendToIframe(msg: VelionMessage): void {\n if (this.iframe?.contentWindow) {\n this.iframe.contentWindow.postMessage(msg, this.cdnOrigin);\n }\n }\n\n getStatus(): SdkStatus {\n return this.status;\n }\n\n static getVersion(): string {\n return typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0';\n }\n\n destroy(): void {\n if (this.status === 'DESTROYED') return;\n this.clearReadyTimer();\n this.detachIframeHeightSync();\n if (this.messageHandler) {\n window.removeEventListener('message', this.messageHandler);\n this.messageHandler = null;\n }\n if (this.iframe && this.container) {\n this.iframe.remove();\n this.container.replaceChildren();\n }\n this.iframe = null;\n this.container = null;\n this.status = 'DESTROYED';\n }\n}\n","/**\n * @fileoverview Public API of the Velion Onboarding SDK (thin client / loader).\n *\n * This package is the loader only: it creates an iframe that loads the full\n * onboarding app from the CDN (e.g. https://static.velion.la/sdk) and bridges\n * config and events via postMessage. No React, OpenCV, or Fingerprint\n * are bundled here — minimal size, same API as before.\n */\n\nexport { VelionOnboarding, DEFAULT_CDN_URL, type VelionLoaderConfig } from './velion-loader';\n\n/**\n * No-op when using the loader: OpenCV is loaded inside the CDN app.\n * Kept for API compatibility; configure OpenCV in the CDN app build if needed.\n */\nexport function setOpenCVBaseUrl(_url: string): void {}\n\nexport {\n SdkErrorCode,\n CameraErrorCode,\n VELION_MSG_INIT,\n VELION_MSG_READY,\n VELION_MSG_SUCCESS,\n VELION_MSG_ERROR,\n VELION_MSG_STEP_CHANGE,\n VELION_MSG_STEP_COMPLETE,\n VELION_MSG_TOKEN_EXPIRED,\n VELION_MSG_EXIT,\n VELION_MSG_LIVENESS_VIDEO_UPLOADED,\n VELION_MSG_TOKEN,\n type VelionConfig,\n type VelionTheme,\n type VelionFinalResultStatusCopy,\n type VelionFinalResultScreenTexts,\n type VelionSessionDeclinedReasonMessages,\n type VelionSessionDeclinedReasonTexts,\n type VelionRetryStepTexts,\n type VelionCallbacks,\n type OnboardingExit,\n type OnboardingStep,\n type OnboardingStepStatus,\n type OnboardingType,\n type DocumentSide,\n type DocumentCaptureMode,\n type DocumentsConfig,\n type TaxInfoConfig,\n type TaxInfoOption,\n type DocumentsInitRequest,\n type DocumentsInitResponse,\n type SessionState,\n type OnboardingResult,\n type OnboardingStepDto,\n type StepFieldRule,\n type HumanBasicInfoStepConfig,\n type HumanExtendedInfoStepConfig,\n type TaxInfoStepConfig,\n type AddressInfoStepConfig,\n type SwornDeclarationStepConfig,\n type DocumentsOcrStepConfig,\n type TermsAndConditionsStepConfig,\n type StepConfigMap,\n type SdkError,\n type SdkStatus,\n type LivenessSessionResponse,\n type VideoUpload,\n type LivenessVerifyVideoMeta,\n type LivenessVideoRef,\n type SessionCreationResponse,\n type HumanBasicInfoPayload,\n type LegalBasicInfoPayload,\n type TermsAndConditionsItem,\n type TaxInfoPayload,\n type HumanExtendedInfoPayload,\n type LegalExtendedInfoPayload,\n type AddressInfoPayload,\n type SwornDeclarationPayload,\n type EconomicActivityItem,\n type EconomicActivityStepConfig,\n type EconomicActivitySelectionPayload,\n type EmailContactPayload,\n type PhoneContactPayload,\n type TermsAndConditionsSubmitPayload,\n type TermsAndConditionsAcceptancePayload,\n type OnboardingSessionEvent,\n type OnboardingDtoResponse,\n type VelionMessage,\n type VelionMessageType,\n type VelionInitPayload,\n type VelionStepChangePayload,\n type VelionStepCompletePayload,\n type VelionExitPayload,\n type VelionLivenessVideoUploadedPayload,\n type VelionTokenPayload,\n} from './types';\n"],"names":["CameraErrorCode","SdkErrorCode","VELION_MSG_INIT","VELION_MSG_READY","VELION_MSG_SUCCESS","VELION_MSG_ERROR","VELION_MSG_STEP_CHANGE","VELION_MSG_STEP_COMPLETE","VELION_MSG_TOKEN_EXPIRED","VELION_MSG_EXIT","VELION_MSG_LIVENESS_VIDEO_UPLOADED","VELION_MSG_TOKEN","freeze","Object","P","N","_d","Gx","Gy","_a","ed25519_CURVE","p","n","h","a","d","isBytes","Uint8Array","ArrayBuffer","isView","constructor","name","BYTES_PER_ELEMENT","abytes","value","length","title","bytes","message","TypeError","RangeError","padh","pad","toString","padStart","bytesToHex","hex","byte","hexToBytes","e","test","array","ai","hi","n1","charCodeAt","n2","concatBytes","arrays","sum","res","set","arange","min","max","msg","mod","b","P_MASK","modP","num","r","callHashAsync","async","m","fn","hashes","Error","_hash","apoint","Point","B256","_Point","X","Y","Z","T","__publicField","this","CURVE","fromAffine","x","y","fromBytes","zip215","normed","from","snapshotBytes","lastByte","bytesToNumberLE","y2","u","v","isValid","uvRatio","isLastByteOdd","fromHex","toAffine","assertValidity","is0","X2","Y2","Z2","Z4","aX2","equals","other","X1","Y1","Z1","I","negate","double","A","B","C","D","x1y1","E","G","F","H","X3","Y3","T3","Z3","add","T1","T2","subtract","multiply","safe","wNAF","f","i","multiplyUnsafe","scalar","iz","number","modulo","q","invert","toBytes","numTo32bLE","toHex","clearCofactor","isSmallOrder","isTorsionFree","BASE","ZERO","reverse","BigInt","pow2","power","RM1","v3","v7","pow","x2","b2","b4","b5","b10","b20","b40","b80","b160","b240","b250","pow_2_252_3","vx2","root1","root2","useRoot1","useRoot2","noRoot","modL_LE","hash","modN","_verify","sig","publicKey","options","getZip215","subarray","s","R","SB","hashable","of","finished","error","hashed","k","verifyAsync","signature","opts","hashFinishAsync","sha512Async","globalThis","crypto","subtle","digest","sha512","Gpows","ctneg","cnd","comp","points","w","push","precompute","wbits","Number","off","offP","Math","abs","isOddW","isNeg","VELION_MANIFEST_PUBKEY_B64","base64ToArrayBuffer","b64","bin","atob","buf","view","isAlgorithmUnsupported","err","String","verifySignature","pubKeyB64","data","ok","reason","detail","pubKey","native","key","importKey","kind","valid","verify","verifyWithWebCrypto","nobleVerifyAsync","verifyWithNoble","checkSignedManifestPolicy","manifest","expectedMajor","minRuntimeVersion","version","appVersion","cmp","parse","exec","trim","core","pre","split","pa","pb","NaN","sign","xn","yn","compareVersions","isNaN","entryIntegrity","startsWith","sha384Base64","fromCharCode","btoa","matchesIntegrity","expected","actual","some","token","fetchBytes","url","noCache","resp","fetch","credentials","redirect","cache","arrayBuffer","status","DEFAULT_CDN_URL","isSecureHttpUrl","URL","protocol","host","hostname","endsWith","SERIALIZABLE_CONFIG_KEYS","VelionOnboarding","config","iframe","container","messageHandler","containerResizeObserver","iframeHeightWindowResizeHandler","cdnOrigin","readyTimer","initSent","iframeReloaded","clearReadyTimer","clearTimeout","armReadyTimer","cdnUrl","ms","runtimeReadyTimeoutMs","setTimeout","onError","code","RUNTIME_LOAD_FAILED","start","INSTANCE_DESTROYED","ALREADY_STARTED","document","getElementById","containerId","CONTAINER_NOT_FOUND","replace","UNKNOWN","apiUrl","origin","parseOriginFromUrl","createElement","setAttribute","style","width","border","display","source","contentWindow","type","onSuccess","payload","onStepChange","step","stepIndex","onStepComplete","onExit","onLivenessVideoUploaded","refresh","onTokenExpired","then","t","sendToIframe","SESSION_EXPIRED","window","addEventListener","replaceChildren","attachIframeHeightSync","resolved","resolveManifest","verifyRuntime","entryPath","entry","Promise","resolve","onload","location","href","isInitialBlankDocument","handleIframeReload","initPayload","out","allowEmbedded","buildSerializableConfig","payloadForPostMessage","JSON","stringify","onerror","src","signed","synthesized","policy","INTEGRITY_FAILED","failure","entryUrl","html","htmlDigest","doc","DOMParser","parseFromString","TextDecoder","decode","refs","querySelectorAll","forEach","el","getAttribute","integrity","rel","toLowerCase","includes","ref","pathname","verifyEntry","result","manifestBuffer","manifestText","sigBuffer","buildTime","sigResp","text","loadAndVerifyManifest","allowUnverifiedCdn","Date","toISOString","UNSUPPORTED_BROWSER","sync","clientHeight","height","minHeight","requestAnimationFrame","ResizeObserver","observe","detachIframeHeightSync","disconnect","removeEventListener","postMessage","getStatus","getVersion","destroy","remove","setOpenCVBaseUrl","_url"],"mappings":"0JAoSYA,kBAAAA,IAEVA,EAAA,kBAAoB,2BAEpBA,EAAA,iBAAmB,0BAKnBA,EAAA,oBAAsB,6BAKtBA,EAAA,iBAAmB,0BAMnBA,EAAA,eAAiB,wBAEjBA,EAAA,cAAgB,uBAKhBA,EAAA,gBAAkB,yBAElBA,EAAA,iBAAmB,0BAEnBA,EAAA,QAAU,uBA/BAA,IAAAA,GAAA,CAAA,GAqCAC,kBAAAA,IAGVA,EAAA,gBAAkB,kBAElBA,EAAA,gBAAkB,kBAElBA,EAAA,qBAAuB,uBAEvBA,EAAA,iBAAmB,mBAQnBA,EAAA,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AAK+N,iCAC1C/N,KAAK+N,gCAAkC,KAE3C,CAEQ,YAAAgD,CAAatS,GACfuB,KAAK2N,QAAQsC,eACfjQ,KAAK2N,OAAOsC,cAAcwF,YAAYhX,EAAKuB,KAAKgO,UAEpD,CAEA,SAAA0H,GACE,OAAO1V,KAAKgN,MACd,CAEA,iBAAO2I,GACL,MAAgD,cAClD,CAEA,OAAAC,GACsB,cAAhB5V,KAAKgN,SACThN,KAAKoO,kBACLpO,KAAKsV,yBACDtV,KAAK6N,iBACPoD,OAAOuE,oBAAoB,UAAWxV,KAAK6N,gBAC3C7N,KAAK6N,eAAiB,MAEpB7N,KAAK2N,QAAU3N,KAAK4N,YACtB5N,KAAK2N,OAAOkI,SACZ7V,KAAK4N,UAAUuD,mBAEjBnR,KAAK2N,OAAS,KACd3N,KAAK4N,UAAY,KACjB5N,KAAKgN,OAAS,YAChB,EC5qBK,SAAS8I,GAAiBC,GAAqB","x_google_ignoreList":[1]}
1
+ {"version":3,"file":"velion-sdk.es.js","sources":["../../packages/types/src/index.ts","../../node_modules/@noble/ed25519/index.js","../src/manifest.ts","../src/velion-loader.ts","../src/index.ts"],"sourcesContent":["/**\n * @fileoverview Public TypeScript contracts for the Velion Onboarding SDK.\n *\n * Design principle: All types exported from this file constitute the public API.\n * Internal implementation types should live alongside their respective modules.\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// STEP & FLOW TYPES\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The complete set of onboarding steps the backend can require.\n * The SDK dynamically receives the active subset for each session.\n *\n * @remarks\n * - `DEVICE_FINGERPRINT`: Silently collects device entropy via FingerprintJS.\n * - `DOCUMENTS_OCR`: Renders a UI for ID document image capture and upload.\n * - `LIVENESS_MATCH`: Drives the Velion Iris active-liveness flow over WebSocket (HUMAN only).\n * - `EMAIL_OTP` / `PHONE_OTP`: Contact verification via one-time passwords.\n * - `HUMAN_BASIC_INFO`: Natural-person identification data (HUMAN only).\n * - `LEGAL_BASIC_INFO`: Legal-entity identification data (LEGAL only).\n * - `EMAIL_CONTACT` / `PHONE_CONTACT`: contact collection without OTP.\n * - `TAX_INFO`, `HUMAN_EXTENDED_INFO`, `LEGAL_EXTENDED_INFO`, `ADDRESS_INFO`, `SWORN_DECLARATION`: form steps.\n * - `ECONOMIC_ACTIVITY_DECLARATION`: pick exactly one economic activity from a searchable list.\n * - `TERMS_AND_CONDITIONS`: accept configured T&amp;C items.\n * - `FACE_MATCH`: server-side face comparison after liveness (no user input; SDK waits).\n * - `AML_SCREENING`: server-side PEP / sanctions screening (no user input; never routed to\n * the SDK as `NEXT_STEP`, only visible in `steps[]` and `STEP_UPDATED`).\n */\nexport type OnboardingStep =\n | 'DEVICE_FINGERPRINT'\n | 'HUMAN_BASIC_INFO'\n | 'LEGAL_BASIC_INFO'\n | 'EMAIL_OTP'\n | 'EMAIL_CONTACT'\n | 'PHONE_OTP'\n | 'PHONE_CONTACT'\n | 'TAX_INFO'\n | 'HUMAN_EXTENDED_INFO'\n | 'LEGAL_EXTENDED_INFO'\n | 'ADDRESS_INFO'\n | 'SWORN_DECLARATION'\n | 'ECONOMIC_ACTIVITY_DECLARATION'\n | 'DOCUMENTS_OCR'\n | 'LIVENESS_MATCH'\n | 'FACE_MATCH'\n | 'AML_SCREENING'\n | 'TERMS_AND_CONDITIONS';\n\n/**\n * Status of an individual onboarding step (matches backend OnboardingStepStatus).\n */\nexport type OnboardingStepStatus =\n | 'PENDING'\n | 'IN_PROGRESS'\n | 'COMPLETED'\n | 'SKIPPED'\n | 'FAILED';\n\n/**\n * Type of onboarding session (matches backend OnboardingType).\n * Constrains which steps are valid: HUMAN allows biometric steps, LEGAL uses entity data.\n */\nexport type OnboardingType = 'HUMAN' | 'LEGAL';\n\n/** Which face of the ID document is being captured. */\nexport type DocumentSide = 'FRONT' | 'BACK';\n\n/**\n * How the user can provide document images in the DOCUMENTS_OCR step.\n * - `'camera'`: Only \"Take photo\" (opens camera on supported devices).\n * - `'file'`: Only \"Choose file\" (file picker).\n * - `'both'`: Both options; implementer can style via theme.\n *\n * @default 'both'\n */\nexport type DocumentCaptureMode = 'camera' | 'file' | 'both';\n\n/**\n * Orientation of the document capture cutout / crop frame.\n * - `'landscape'`: Horizontal card (default — standard ID-1 cards).\n * - `'portrait'`: Vertical card (e.g. some passports, residence permits).\n *\n * @default 'landscape'\n */\nexport type DocumentOrientation = 'landscape' | 'portrait';\n\n/**\n * Optional overrides for document OCR UI (not part of `VelionConfig`; used internally).\n */\nexport interface DocumentsConfig {\n /**\n * When true (default), the document camera preview is mirrored (like selfie mode).\n * Set to false if the back camera shows the document inverted.\n *\n * @default true\n */\n mirrorDocumentVideo?: boolean;\n\n /**\n * Orientation of the document capture frame and crop.\n * - `'landscape'`: Horizontal card (default — standard ID-1 cards).\n * - `'portrait'`: Vertical card.\n *\n * @default 'landscape'\n */\n documentOrientation?: DocumentOrientation;\n}\n\n/** Generic visible/required field toggle used by workflow step configs. */\nexport interface StepFieldRule {\n visible: boolean;\n required: boolean;\n}\n\n/** Select option used by configurable step fields (e.g. HUMAN_EXTENDED_INFO gender/civil_status). */\nexport interface StepFieldOption {\n id: string;\n display_value?: string;\n}\n\n/** Field rule with optional selectable options. */\nexport interface StepFieldRuleWithOptions extends StepFieldRule {\n options?: StepFieldOption[];\n}\n\n/** STEP config for HUMAN_BASIC_INFO. */\nexport interface HumanBasicInfoStepConfig {\n accepted_country_documents?: Array<{\n country_code: string;\n document_types: Array<{ id: string; display_value?: string }>;\n }>;\n}\n\n/**\n * One selectable option row from TAX_INFO `accepted_tax_information` (backend GET session).\n * Prefer `code` as the value sent in POST tax-info; `id` is supported for older payloads.\n */\nexport interface TaxInfoConfigOptionRow {\n code?: string;\n id?: string;\n display_value?: string;\n tax_code?: string;\n}\n\n/** One country block in TAX_INFO step config (GET session `current_step.config`). */\nexport interface TaxInfoAcceptedCountryRow {\n country_code: string;\n identification_types?: TaxInfoConfigOptionRow[];\n /** Options for the \"Categoría fiscal\" / taxpayer category select. */\n taxpayer_categories?: TaxInfoConfigOptionRow[];\n}\n\n/** STEP config for TAX_INFO. */\nexport interface TaxInfoStepConfig {\n /** Identification types + taxpayer categories per country. */\n accepted_tax_information?: TaxInfoAcceptedCountryRow[];\n}\n\n/** STEP config for HUMAN_EXTENDED_INFO. */\nexport interface HumanExtendedInfoStepConfig {\n /** Optional top-level lists sent by backend for select fields. */\n gender_options?: StepFieldOption[];\n civil_status_options?: StepFieldOption[];\n fields?: Partial<\n Record<\n 'gender' | 'civil_status' | 'birth_date' | 'birth_country' | 'citizenship' | 'residence_country',\n StepFieldRuleWithOptions\n >\n >;\n}\n\n/** STEP config for ADDRESS_INFO. */\nexport interface AddressInfoStepConfig {\n address_type?: { id?: string; display_value?: string };\n fields?: Partial<\n Record<\n 'state' | 'city' | 'district' | 'neighborhood' | 'postal_code' | 'street' | 'number',\n StepFieldRule\n >\n >;\n /**\n * Optional ISO 3166-1 alpha-2 allowlist for the country selector. Only\n * consumed by the manual-entry form (when the SDK is configured without a\n * Google Maps key). When unset, every country is offered.\n */\n country_allow?: string[];\n}\n\n/** STEP config for SWORN_DECLARATION. */\nexport interface SwornDeclarationStepConfig {\n ask_pep?: boolean;\n ask_obligated_subject?: boolean;\n ask_fatca?: boolean;\n ask_ocde?: boolean;\n on_declared_pep?: string;\n on_declared_obligated_subject?: string;\n on_declared_fatca?: string;\n on_declared_ocde?: string;\n}\n\n/**\n * A single selectable economic activity presented in the\n * `ECONOMIC_ACTIVITY_DECLARATION` step. Mirrors the backend `EconomicActivityItem`\n * (`code` + `display_name`); `code` is unique within the list and is what the SDK\n * submits. There is no global catalog — each workflow declares its own list.\n */\nexport interface EconomicActivityItem {\n /** Machine-readable activity code (e.g. an AFIP/CLAE code) — unique within the list. */\n code: string;\n /** Human-readable label shown to the user. */\n display_name: string;\n}\n\n/** STEP config for ECONOMIC_ACTIVITY_DECLARATION (`current_step.config`). */\nexport interface EconomicActivityStepConfig {\n /** Selectable activities; always non-empty when the step is active. */\n items?: EconomicActivityItem[];\n}\n\n/** STEP config for DOCUMENTS_OCR. */\nexport interface DocumentsOcrStepConfig {\n country_allow?: string[];\n capture_methods?: {\n camera_scan?: boolean;\n upload?: boolean;\n };\n /** Crop frame orientation for document camera capture. */\n document_orientation?: DocumentOrientation;\n /**\n * Force the document camera preview mirroring. When absent the SDK decides\n * from the camera the browser opened: front mirrored, rear not. Only the\n * preview is affected; the uploaded crop is never mirrored.\n */\n mirror_document_video?: boolean;\n}\n\n/** STEP config for TERMS_AND_CONDITIONS. */\nexport interface TermsAndConditionsStepConfig {\n terms?: Array<{ title?: string; url?: string }>;\n}\n\n/** Generic per-step runtime config map carried by session state and SSE. */\nexport type StepConfigMap = Partial<Record<OnboardingStep, Record<string, unknown>>>;\n\n/**\n * Request body for POST /sessions/:sessionId/documents-init.\n * Allowed values are defined by the backend; the SDK currently sends a fixed type until\n * the session exposes selectable document types.\n */\nexport interface DocumentsInitRequest {\n document_type: string;\n}\n\n/**\n * Response from POST /sessions/:sessionId/documents-init.\n * Backend returns signed upload URLs so the SDK can PUT each document side\n * directly to storage (e.g. GCS) without routing bytes through the backend.\n */\n/**\n * Response of `POST /sessions/:id/documents-init`.\n *\n * Each URL is a GCS V4 signed PUT issued by the Velion CDN, valid for about\n * two minutes, and signed over `host`, `content-type` and\n * `x-goog-content-length-range`. The PUT must therefore send\n * `Content-Type: image/jpeg` **and** `x-goog-content-length-range:\n * 0,<max_file_size_bytes>` byte for byte, or GCS answers 400\n * `MalformedSecurityHeader` (OSDKW-5). Request the URLs right before the\n * upload, never ahead of the capture.\n */\nexport interface DocumentsInitResponse {\n /** Pre-signed URL to upload the front side (PUT, see the interface docs for the required headers). */\n front_side_upload_url: string;\n /** Pre-signed URL to upload the back side (PUT, see the interface docs for the required headers). */\n back_side_upload_url: string;\n /**\n * Upper bound the URLs were signed for; the exact number that goes into the\n * `x-goog-content-length-range` header. Also usable to reject oversize\n * captures before the PUT.\n */\n max_file_size_bytes?: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// ERROR TYPES\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Granular error codes for camera/hardware failures.\n * Allows consumers to display localized, actionable messages to end-users.\n */\nexport enum CameraErrorCode {\n /** User explicitly denied camera access in the browser permission dialog. */\n PERMISSION_DENIED = 'CAMERA_PERMISSION_DENIED',\n /** No camera device was detected on the system. */\n DEVICE_NOT_FOUND = 'CAMERA_DEVICE_NOT_FOUND',\n /**\n * The camera could not be opened for reading (often in use by another app,\n * or blocked at the OS level). Maps to `NotReadableError` / `TrackStartError`.\n */\n DEVICE_NOT_READABLE = 'CAMERA_DEVICE_NOT_READABLE',\n /**\n * The page is served over HTTP (not HTTPS) in a production environment.\n * `getUserMedia` is blocked by the browser's Secure Context policy.\n */\n INSECURE_CONTEXT = 'CAMERA_INSECURE_CONTEXT',\n /**\n * Browser policy blocked camera (e.g. cross-origin iframe without permission,\n * or `Permissions-Policy` / Feature-Policy denying camera). Maps to `SecurityError`\n * from `getUserMedia` — distinct from {@link INSECURE_CONTEXT} (non-HTTPS).\n */\n POLICY_BLOCKED = 'CAMERA_POLICY_BLOCKED',\n /** The browser or WebView does not support the `getUserMedia` API. */\n NOT_SUPPORTED = 'CAMERA_NOT_SUPPORTED',\n /**\n * Camera access is blocked by a WebView policy (common in in-app browsers\n * on iOS/Android that restrict hardware access).\n */\n WEBVIEW_BLOCKED = 'CAMERA_WEBVIEW_BLOCKED',\n /** The requested video constraints (resolution, facing mode) are not satisfiable. */\n CONSTRAINT_ERROR = 'CAMERA_CONSTRAINT_ERROR',\n /** An unclassified camera error occurred. Check `cause` for details. */\n UNKNOWN = 'CAMERA_UNKNOWN_ERROR',\n}\n\n/**\n * Top-level SDK error codes covering all failure scenarios in the onboarding flow.\n */\nexport enum SdkErrorCode {\n // ── Session ──────────────────────────────────────────────────────────────\n /** The sessionToken was rejected by the backend (401/403). */\n SESSION_INVALID = 'SESSION_INVALID',\n /** The sessionToken has expired (typically a 401 after initial validation). */\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n /** Could not fetch the initial session state from the backend. */\n SESSION_FETCH_FAILED = 'SESSION_FETCH_FAILED',\n /** Backend sent SESSION_DECLINED over SSE; session ended before completion. */\n SESSION_DECLINED = 'SESSION_DECLINED',\n /**\n * The backend cancelled the session (`SESSION_CANCELLED` over SSE, or\n * `status: CANCELLED` on `GET /sessions/:id`). Not a verdict on the person:\n * the session was closed on Velion's side (e.g. `WORKFLOW_VERSION_RETIRED`\n * when a new workflow version is published forcing it). The session token\n * is revoked and the SDK sends no further requests; create a new session\n * to let the person start again. `cancelReason` carries the backend reason.\n */\n SESSION_CANCELLED = 'SESSION_CANCELLED',\n /**\n * A step was completed but the backend did not route the session to the\n * next one within `routingTimeoutMs` (default 120 s): no `ROUTING_COMMAND`\n * arrived over SSE and `GET /sessions/:id` kept reporting the completed\n * step. The session is still alive on the backend; `stepCode` names the\n * completed step. Typical cause: a delayed or stalled onboarding worker.\n */\n ROUTING_TIMEOUT = 'ROUTING_TIMEOUT',\n\n // ── Modules ──────────────────────────────────────────────────────────────\n /** FingerprintJS failed to generate the visitor ID. */\n FINGERPRINT_FAILED = 'FINGERPRINT_FAILED',\n /** One or more document images failed to upload successfully. */\n DOCUMENT_UPLOAD_FAILED = 'DOCUMENT_UPLOAD_FAILED',\n /** The liveness check did not pass or returned an unexpected result. */\n LIVENESS_FAILED = 'LIVENESS_FAILED',\n /** The Liveness module failed to initialize (e.g., could not create the Iris session). */\n LIVENESS_INIT_FAILED = 'LIVENESS_INIT_FAILED',\n /**\n * The recorded liveness session video could not be uploaded to storage.\n * Best-effort only: this never fails the liveness step — it is logged so the\n * back-office knows the playback evidence is missing for the session.\n */\n LIVENESS_VIDEO_UPLOAD_FAILED = 'LIVENESS_VIDEO_UPLOAD_FAILED',\n\n // ── Camera ───────────────────────────────────────────────────────────────\n /**\n * A camera-related error occurred. Inspect `cameraCode` for the specific reason.\n * @see CameraErrorCode\n */\n CAMERA_ERROR = 'CAMERA_ERROR',\n\n // ── Network & API ────────────────────────────────────────────────────────\n /** A network-level failure (no internet, CORS, DNS). */\n NETWORK_ERROR = 'NETWORK_ERROR',\n /** The backend returned a non-2xx HTTP status. */\n API_ERROR = 'API_ERROR',\n\n // ── Configuration ────────────────────────────────────────────────────────\n /** The `containerId` provided in the config does not exist in the DOM. */\n CONTAINER_NOT_FOUND = 'CONTAINER_NOT_FOUND',\n /** `start()` was called on an SDK instance that is already running. */\n ALREADY_STARTED = 'ALREADY_STARTED',\n /** `start()` was called after `destroy()`. The instance is no longer usable. */\n INSTANCE_DESTROYED = 'INSTANCE_DESTROYED',\n\n /**\n * The page is running inside an iframe and embedding was not explicitly allowed.\n * Configure Content-Security-Policy: frame-ancestors or X-Frame-Options on the\n * page that hosts the SDK, or set allowEmbedded: true if embedding is intentional.\n */\n INSECURE_EMBED = 'INSECURE_EMBED',\n\n /**\n * The CDN-served runtime failed verification: the manifest could not be\n * downloaded or its Ed25519 signature did not verify against the loader's\n * embedded public key; the signed manifest is for another major, older than the\n * minimum runtime the loader accepts (rollback) or does not name its entry\n * digest; or the entry HTML or one of its scripts does not match the manifest.\n * The loader refuses to mount the iframe to prevent execution of\n * tampered/unsigned bundles. Also raised by the mounted runtime when data it\n * reads from its CDN after boot (the country subdivisions of `ADDRESS_INFO`)\n * does not match the digest pinned in its bundle; the flow then stops.\n */\n INTEGRITY_FAILED = 'INTEGRITY_FAILED',\n /**\n * The browser cannot verify the CDN manifest signature at all (no WebCrypto\n * `crypto.subtle`, typically an insecure `http://` context). Unlike\n * `INTEGRITY_FAILED` this is not a tampering signal; the loader still refuses\n * to mount the iframe because the runtime cannot be verified.\n */\n UNSUPPORTED_BROWSER = 'UNSUPPORTED_BROWSER',\n /**\n * The runtime could not be started or was lost:\n * - the iframe loaded but the runtime never reported `VELION_READY` within\n * `runtimeReadyTimeoutMs` (default 30 s). Typical causes: the CDN serves an\n * `index.html` whose hashed assets are missing (deploy under the wrong\n * prefix), a Content-Security-Policy on the host blocking the runtime's\n * scripts, or the runtime crashing before it could boot. Without this the\n * host saw a blank iframe and no callback at all;\n * - the loader could not download the entry or its scripts to verify them;\n * - the iframe reloaded after the session started. The loader does not resend\n * the session token to a document it did not verify; a new instance resumes\n * from the backend's current step.\n */\n RUNTIME_LOAD_FAILED = 'RUNTIME_LOAD_FAILED',\n\n UNKNOWN = 'UNKNOWN',\n}\n\n/**\n * A structured, machine-readable error object emitted by the SDK.\n *\n * @example\n * ```typescript\n * const sdk = new VelionOnboarding({\n * onError: (err) => {\n * if (err.code === SdkErrorCode.CAMERA_ERROR &&\n * err.cameraCode === CameraErrorCode.PERMISSION_DENIED) {\n * showCameraPermissionDialog();\n * }\n * }\n * });\n * ```\n */\nexport interface SdkError {\n /** Primary SDK-level error classification. */\n readonly code: SdkErrorCode;\n /** Human-readable English description for developer logging. */\n readonly message: string;\n /** Present when `code === SdkErrorCode.SESSION_DECLINED` (SSE `reason`). */\n readonly declineReason?: string;\n /**\n * Step the error refers to. For `SESSION_DECLINED` it is the SSE `step_code`;\n * for `ROUTING_TIMEOUT` it is the step that was completed and never routed.\n */\n readonly stepCode?: string;\n /**\n * Localized headline resolved by the SDK for SESSION_DECLINED.\n * Useful when hosts hide the built-in final result screen but still want\n * the same user-facing text in custom UI.\n */\n readonly declineTitle?: string;\n /**\n * Localized body message resolved by the SDK for SESSION_DECLINED.\n * Mirrors the text shown in the built-in final result screen.\n */\n readonly declineMessage?: string;\n /** Present when `code === SdkErrorCode.SESSION_CANCELLED` (backend `reason`, e.g. `WORKFLOW_VERSION_RETIRED`). */\n readonly cancelReason?: string;\n /** Present when `code === SdkErrorCode.CAMERA_ERROR`. Provides camera-specific detail. */\n readonly cameraCode?: CameraErrorCode;\n /** HTTP status code when the error originated from an API call. */\n readonly httpStatus?: number;\n /**\n * The original caught value for debugging.\n * Not guaranteed to be an `Error` instance — could be a DOMException or string.\n */\n readonly cause?: unknown;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// THEMING\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * White-labeling theme configuration.\n * Each property maps to a CSS custom property injected on the SDK container,\n * making all SDK UI elements styleable via `--vl-*` variables.\n *\n * @example\n * ```typescript\n * const theme: VelionTheme = {\n * primaryColor: '#0052CC', // → --vl-primary-color\n * borderRadius: '12px', // → --vl-border-radius\n * fontFamily: 'Inter, sans-serif'// → --vl-font-family\n * };\n * ```\n */\nexport interface VelionTheme {\n /** Primary brand color. Used for buttons, progress indicators, and accents. */\n primaryColor?: string;\n /** Secondary color. Used for hover states and secondary actions. */\n secondaryColor?: string;\n /** Background color of the SDK container. */\n backgroundColor?: string;\n /** Main body text color. */\n textColor?: string;\n /** Secondary text color for subtitles, captions, and de-emphasized copy. */\n textSecondaryColor?: string;\n /** Border radius for cards, buttons, and inputs. */\n borderRadius?: string;\n /** Font family string. Must be available in the host page's CSS context. */\n fontFamily?: string;\n /** Color used for error states and destructive actions. */\n errorColor?: string;\n /** Color used for success confirmations. */\n successColor?: string;\n /** Color used for warnings and informational alerts. */\n warningColor?: string;\n /** Border color for input fields and separators. */\n borderColor?: string;\n /** Box shadow definition for elevated elements (cards, modals). */\n cardShadow?: string;\n\n /**\n * When `true`, the round icon that sits above each step's title is hidden.\n * Only the title and subtitle are rendered. Useful when the host UI already\n * provides its own visual identity per step or when a denser layout is\n * preferred.\n *\n * @default false\n */\n hideStepIcons?: boolean;\n\n /**\n * When `true`, the thin progress bar at the top of the SDK container is\n * hidden. Equivalent to setting `VelionConfig.showProgressBar: false` —\n * either flag is enough to disable it (whichever is more convenient given\n * how the host configures the SDK). Disable when your host UI already\n * surfaces its own progress indicator.\n *\n * @default false\n */\n hideProgressBar?: boolean;\n}\n\n/**\n * Optional title and body for one terminal verdict on the final result screen.\n */\nexport interface VelionFinalResultStatusCopy {\n title?: string;\n message?: string;\n}\n\n/**\n * Configurable copy for the built-in final result screen (`showFinalResultScreen`).\n * Omitted fields fall back to SDK defaults for the active `locale`.\n */\nexport interface VelionFinalResultScreenTexts {\n approved?: VelionFinalResultStatusCopy;\n manualReview?: VelionFinalResultStatusCopy;\n rejected?: VelionFinalResultStatusCopy;\n /** Copy when {@link OnboardingResult.status} is `DECLINED`. */\n declined?: VelionFinalResultStatusCopy;\n /** Copy for the screen shown when the backend cancels the session (`SESSION_CANCELLED`). */\n cancelled?: VelionFinalResultStatusCopy;\n /** Primary button label (e.g. \"Entendido\" / \"Got it\"). */\n dismissLabel?: string;\n}\n\n/**\n * Localized title/body for one `reason` on the SESSION_DECLINED screen.\n * Keys match backend `reason` (e.g. `TAX_INFO_FAILED`).\n */\nexport interface VelionSessionDeclinedReasonMessages {\n en?: VelionFinalResultStatusCopy;\n es?: VelionFinalResultStatusCopy;\n}\n\n/**\n * Per-reason overrides for the built-in SESSION_DECLINED screen (`showFinalResultScreen` not false).\n * Unspecified reasons fall back to SDK defaults when available, then generic copy.\n */\nexport type VelionSessionDeclinedReasonTexts = Record<\n string,\n VelionSessionDeclinedReasonMessages\n>;\n\n/**\n * Per-step overrides for the retry dialog shown when the backend emits a\n * `ROUTING_COMMAND / RETRY_STEP` (the step failed but the retry quota is not\n * exhausted). Keyed by step code (e.g. `LIVENESS_MATCH`, `DOCUMENTS_OCR`).\n * Unspecified steps fall back to SDK per-step defaults, then generic copy.\n *\n * Note: the SDK intentionally ignores the backend `reason` for this dialog —\n * it is a diagnostic string (e.g. `\"STEP_FAILED_RETRY_ALLOWED (attempt 1/3)\"`),\n * not user-facing localized copy. The copy is derived from the step instead.\n */\nexport type VelionRetryStepTexts = Record<\n string,\n VelionSessionDeclinedReasonMessages\n>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// CALLBACKS\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The complete set of lifecycle callbacks the host application can subscribe to.\n * All callbacks are optional. The SDK is still functional without any of them,\n * but `onError` and `onSuccess` are strongly recommended for production.\n */\nexport interface VelionCallbacks {\n /**\n * Fires when the entire onboarding flow has been completed successfully\n * and the backend has confirmed the session as resolved.\n *\n * @param result - Final onboarding verdict from the backend.\n */\n onSuccess?: (result: OnboardingResult) => void;\n\n /**\n * Fires when an unrecoverable error terminates the onboarding flow.\n * Any terminal failure (camera error, document capture failure, upload failure,\n * liveness failure, API error, etc.) is delivered here so the host can notify the user.\n * After this callback, the SDK instance is in an error state.\n * Call `sdk.destroy()` and re-instantiate to retry.\n *\n * @param error - Structured error with a machine-readable code (e.g. CAMERA_ERROR, DOCUMENT_UPLOAD_FAILED).\n */\n onError?: (error: SdkError) => void;\n\n /**\n * Fires each time the active step changes during the flow.\n * Useful for updating a custom step indicator in the host UI.\n *\n * The required step list is resolved dynamically by the backend, so the SDK\n * does not know the total step count up front. Callers that need a progress\n * indicator should rely on the SDK's built-in progress bar (or the trickling\n * counter in `stepIndex`).\n *\n * @param step - The step that just became active.\n * @param stepIndex - Zero-based index of the current step.\n */\n onStepChange?: (step: OnboardingStep, stepIndex: number) => void;\n\n /**\n * Fires immediately after a step succeeds, before advancing to the next one.\n * Useful for analytics or triggering intermediate UI transitions.\n *\n * @param step - The step that was just completed.\n */\n onStepComplete?: (step: OnboardingStep) => void;\n\n /**\n * Fires for each SSE event from GET /sessions/:sessionId/events\n * (e.g. STEP_UPDATED, SESSION_APPROVED).\n */\n onSessionEvent?: (event: OnboardingSessionEvent) => void;\n\n /**\n * Called when the user taps the dismiss control on the final result screen\n * (only when the final result screen is shown). `onSuccess` has already run.\n */\n onFinalResultScreenDismiss?: () => void;\n\n /**\n * Fires when the LIVENESS_MATCH step successfully uploaded the recorded\n * session video to the onboarding storage (GCS PUT returned 200). Best-effort:\n * if the upload failed, timed out, or the session had no `video_upload` URL,\n * the callback is not invoked — liveness still completes normally.\n *\n * @param ref - URL and metadata of the uploaded video.\n */\n onLivenessVideoUploaded?: (ref: LivenessVideoRef) => void;\n\n /**\n * Fires when the user leaves the onboarding flow without a terminal verdict —\n * either by tapping \"back\" on the first reversible step (`BACK_EXIT`) or\n * \"Cancel\" on the retry dialog shown after a `RETRY_STEP` (`RETRY_CANCELLED`).\n * In both cases the backend told the SDK to leave the flow and hand control\n * back to the host; the SDK has already torn down its UI.\n *\n * Distinct from `onSuccess` (a terminal verdict) and `onError` (a failure):\n * the host should typically dismiss/close the SDK surface when this fires.\n *\n * @param exit - Why the flow exited and the step it exited from.\n */\n onExit?: (exit: OnboardingExit) => void;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// MAIN CONFIGURATION\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Root configuration object for the `VelionOnboarding` class.\n *\n * @example\n * ```typescript\n * const sdk = new VelionOnboarding({\n * containerId: 'velion-root',\n * sessionId: 'ses_abc123',\n * sessionToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',\n * apiUrl: 'https://api.velion.la/v1',\n * theme: { primaryColor: '#0052CC' },\n * onSuccess: (result) => console.log('Done!', result),\n * onError: (err) => console.error('SDK Error:', err),\n * });\n *\n * await sdk.start();\n * ```\n */\nexport interface VelionConfig extends VelionCallbacks {\n /**\n * The `id` of an existing DOM element where the SDK will render its UI.\n * The element **must** be present in the document at the time `start()` is called.\n *\n * @example `'velion-kyc-container'`\n */\n containerId: string;\n\n /**\n * The unique session identifier generated by your backend for this\n * onboarding session. Used to scope all API calls.\n *\n * @example `'ses_9f8d7c6b5a4e3f2d'`\n */\n sessionId: string;\n\n /**\n * A short-lived, opaque authorization token (e.g. HS256 JWT) issued by your\n * backend when creating the session. Sent as `Authorization: Bearer <sessionToken>`\n * on every SDK request. Required for all endpoints behind the gateway.\n *\n * **Security note:** This token is held in memory only (never in localStorage\n * or cookies) and is automatically discarded on `destroy()`.\n */\n sessionToken: string;\n\n /**\n * ISO-8601 expiry timestamp of the sessionToken. If provided, the SDK may\n * check expiration before requests and emit SESSION_EXPIRED without a round-trip.\n * When the backend returns 401/403, the SDK emits SESSION_EXPIRED anyway.\n */\n expiresAt?: string;\n\n /**\n * Base URL of the Velion onboarding edge. Must **not** include a trailing slash.\n * SDK paths are relative to this (e.g. GET `/sessions/{sessionId}`).\n *\n * Defaults to the public production edge `https://sdk.velion.la/onboarding`.\n * Override only for staging or self-hosted environments.\n */\n apiUrl?: string;\n\n /**\n * Optional white-labeling theme. If omitted, SDK renders with Velion defaults.\n */\n theme?: VelionTheme;\n\n /**\n * Global visual mode for SDK overlays and controls.\n * - `'light'`: Light translucent surfaces.\n * - `'dark'`: Dark translucent surfaces.\n *\n * @default 'light'\n */\n colorMode?: 'light' | 'dark';\n\n /**\n * BCP 47 locale tag for SDK UI copy (labels, instructions, error messages).\n *\n * @default 'es'\n */\n locale?: string;\n\n /**\n * When `true`, after the backend returns a terminal verdict the SDK shows a\n * full-screen summary (APPROVED, MANUAL_REVIEW, REJECTED) inside the container,\n * styled with `theme` and `colorMode`. `onSuccess` still fires with the result.\n *\n * @default true\n */\n showFinalResultScreen?: boolean;\n\n /**\n * When `true` (default), the SDK renders a thin progress bar at the top of\n * the container that advances as the user moves through steps. Disable for\n * embedded experiences that already provide their own progress UI.\n *\n * @default true\n */\n showProgressBar?: boolean;\n\n /**\n * Overrides for default titles, messages, and dismiss button on the final result screen.\n * Only used when the final result screen is shown (`showFinalResultScreen` is not `false`).\n */\n finalResultScreenTexts?: VelionFinalResultScreenTexts;\n\n /**\n * Optional copy for SESSION_DECLINED SSE screens, keyed by backend `reason`.\n * Merged with SDK defaults (e.g. `TAX_INFO_FAILED`) for `locale` `en` / `es`.\n */\n sessionDeclinedReasonTexts?: VelionSessionDeclinedReasonTexts;\n\n /**\n * Optional copy for the retry dialog (`ROUTING_COMMAND / RETRY_STEP`), keyed by\n * step code (e.g. `LIVENESS_MATCH`). Merged with SDK per-step defaults for\n * `locale` `en` / `es`; unspecified steps fall back to generic retry copy.\n */\n retryStepTexts?: VelionRetryStepTexts;\n\n /**\n * When `true` (default), shows the Velion preparation screen (face icon, tips,\n * \"Start verification\") before connecting to Iris. When `false`, skips it and\n * starts the camera + Iris session immediately on step entry.\n *\n * @default true\n */\n livenessShowIntro?: boolean;\n\n /**\n * When `false`, hides the \"Atrás\" / \"Back\" button on the liveness preparation\n * screen. The button is only present in the intro; once the camera capture\n * begins the user must complete the Iris challenges to leave the step.\n *\n * @default true\n */\n livenessShowBackButton?: boolean;\n\n /**\n * If true, allows the SDK to run when the page is inside an iframe.\n * Only set to true if you have configured Content-Security-Policy: frame-ancestors\n * or X-Frame-Options on the HTTP response of the page that hosts the SDK.\n * If false (default) and the page is embedded in an iframe, the SDK emits\n * INSECURE_EMBED and does not start.\n *\n * @default false\n */\n allowEmbedded?: boolean;\n\n /**\n * Internal — set by the Velion CDN entry (`cdn-main.ts`) to the `event.origin`\n * captured from the loader's first VELION_INIT message. The SDK validates it\n * against `allowed_parent_origins` returned by the backend and refuses to start\n * if the origin is not in the customer's registered allowlist.\n *\n * Direct integrators (running VelionOnboarding without the loader iframe)\n * should leave this unset.\n *\n * @internal\n */\n iframeParentOrigin?: string;\n\n /**\n * Fingerprint Pro API endpoint (custom subdomain). Used by the DEVICE_FINGERPRINT\n * step to load and identify visitors. Only set this when using a custom Fingerprint\n * subdomain or proxy; otherwise the default Velion endpoint is used.\n *\n * @default 'https://fp.velion.la'\n */\n fingerprintEndpoint?: string;\n\n /**\n * Fingerprint Pro public API key. Used by the DEVICE_FINGERPRINT step to\n * identify visitors. Defaults to the shared Velion public key — set this\n * only when your tenant has its own Fingerprint workspace.\n *\n * @default Velion's shared public key\n */\n fingerprintApiKey?: string;\n\n /**\n * Hard ceiling, in milliseconds, for the DEVICE_FINGERPRINT step (agent\n * load + identification). The Fingerprint agent has its own internal\n * timeout, but with tracker blockers or a blackholed endpoint it can hang\n * well past it; the SDK races against this value so the step fails with\n * `FINGERPRINT_FAILED` instead of leaving the user on a blank screen.\n *\n * @default 15000\n */\n fingerprintTimeoutMs?: number;\n\n /**\n * Total wait, in milliseconds, for the backend to route the session after a\n * step is completed. The SDK waits for the SSE `ROUTING_COMMAND` and falls\n * back to `GET /sessions/:id` every 30 s; when the backend keeps reporting\n * the completed step (delayed or stalled worker) those cycles used to repeat\n * for ever. Past this bound the flow fails with `ROUTING_TIMEOUT` so the host\n * gets a callback instead of an endless spinner.\n *\n * @default 120000\n */\n routingTimeoutMs?: number;\n\n /**\n * Google Maps Platform API key (Maps JavaScript API + Places). Required for the\n * {@code ADDRESS_INFO} step to show the map, search, and geocoding. Omit only if\n * your flow never reaches that step.\n */\n googleMapsApiKey?: string;\n\n /**\n * Optional calibration tag forwarded to Iris for the LIVENESS_MATCH step.\n * When the Iris worker is running with `CALIBRATION_BACKEND=fs|gcs`, every\n * frame of this session is mirrored to the dataset bucket with the tag in\n * `metadata.json`, so we can build labeled training sets for the spoof /\n * liveness models. Does NOT affect the score.\n *\n * Suggested values (must match the worker's known labels — see\n * `iris-worker` README): `REAL_GOOD_LIGHT`, `REAL_BAD_LIGHT`, `REAL_BACKLIT`,\n * `REAL_BUSY_BG`, `REAL_NEUTRAL_BG`, `REAL_GLASSES`, `REAL_OUTDOOR`,\n * `FAKE_PHONE_PHOTO`, `FAKE_PHONE_VIDEO`, `FAKE_TABLET_VIDEO`,\n * `FAKE_MONITOR_VIDEO`, `FAKE_PRINT`, `FAKE_MASK`, `UNKNOWN`, `EDGE_CASE`.\n *\n * Leave undefined for normal user-facing sessions.\n */\n livenessCalibrationLabel?: string;\n\n /**\n * When true, the SDK enables verbose `console.info` logging at runtime even in\n * production builds. Useful when reproducing customer issues. Independent of the\n * build-time `__DEBUG__` flag, which already gates dev-server logs.\n *\n * @default false\n */\n debug?: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// BACKEND RESPONSE SHAPES\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Backend step DTO (OnboardingStepDto). GET session returns an array of these.\n */\nexport interface OnboardingStepDto {\n code: string;\n name?: string;\n description?: string;\n order?: number;\n status?: string;\n /**\n * Machine-readable cause of the current `status` when it is `FAILED` or\n * `MANUAL_REVIEW` (backend `StepStatusDetailCode`, VON-54 / VON-56). Examples:\n * `DOC_UNREADABLE`, `DOC_MRZ_NOT_READABLE`, `DOC_EXPIRED`, `DOC_AGE_EXCLUSION`,\n * `LIVENESS_BELOW_THRESHOLD`, `LIVENESS_SPOOF_SUSPECTED`,\n * `FACE_MATCH_BELOW_THRESHOLD`, `FINGERPRINT_BOT_DETECTED`,\n * `TAX_ARCA_VALIDATION_FAILED`, `TERMS_NOT_ACCEPTED`,\n * `ECONOMIC_ACTIVITY_INVALID_SELECTION`, `STEP_UNEXPECTED_ERROR`. Hosts may\n * use it for analytics or support tooling; the SDK derives its user-facing\n * copy from the step, never from this code.\n */\n status_detail?: string;\n required?: boolean;\n /** Step-specific payload (e.g. OCR fields, fingerprint, T&amp;C items). */\n result?: Record<string, unknown>;\n /** Raw workflow config for this step (thresholds, accepted documents, …). */\n config?: Record<string, unknown>;\n /**\n * Whether the user may navigate back INTO this step after completing it\n * (intrinsic per-step flag the backend stamps from the workflow). Used only\n * to derive `can_go_back` for steps reached via SSE (which doesn't carry the\n * flag) and for prefill — NOT to decide whether to render the back button.\n * @see OnboardingDtoResponse.can_go_back\n */\n reversible?: boolean;\n}\n\n/**\n * Backend session/onboarding DTO (OnboardingDto). Returned by GET /sessions/:sessionId.\n * The SDK maps this to SessionState for the step machine.\n */\nexport interface OnboardingDtoResponse {\n id?: string;\n related_id?: string;\n onboarding_type?: string;\n status?: string;\n current_step?: {\n code?: string;\n status?: string;\n config?: Record<string, unknown>;\n /**\n * Previously-captured data for this step, present when a reverse navigation\n * re-opened a completed step. The SDK uses it as editable prefill.\n */\n result?: Record<string, unknown>;\n /** Intrinsic per-step reversibility (prefill / SSE-derivation only). */\n reversible?: boolean;\n };\n steps?: OnboardingStepDto[];\n created_at?: string;\n updated_at?: string;\n completed_at?: string;\n metadata?: Record<string, unknown>;\n /**\n * Whether the SDK should render the \"back\" control on the current step.\n * Computed server-side from the workflow graph (barrier model): `true` when\n * there is a previous reversible step to re-open, OR when the current step is\n * the first reversible step (back exits the flow via `BACK_EXIT`). The SDK\n * uses **this** — not a step's intrinsic `reversible` flag — to decide whether\n * to show the back button.\n */\n can_go_back?: boolean;\n /**\n * Origins (scheme + host + port) authorized by the customer to embed the SDK.\n * The iframe validates `event.origin` of the loader's first VELION_INIT against\n * this list and aborts with INSECURE_EMBED otherwise. Backend must also enforce\n * server-side via the `Origin` header on every API call.\n */\n allowed_parent_origins?: string[];\n}\n\n/**\n * Session state used by the SDK step machine. Derived from GET /sessions/:sessionId\n * (OnboardingDto): steps sorted by order → requiredSteps, first non-completed index → currentStepIndex.\n */\nexport interface SessionState {\n /** Current runnable step reported by backend session state. */\n currentStep?: OnboardingStep;\n /** Step-specific config for `currentStep` from GET /sessions/:id `current_step.config`. */\n currentStepConfig?: Record<string, unknown>;\n /** Cached configs discovered from GET session and SSE `step_config`. */\n stepConfigs?: StepConfigMap;\n /** Session type (HUMAN or LEGAL). Constrains which steps are applicable. */\n onboardingType?: OnboardingType;\n /**\n * Whether the SDK should render the \"back\" control on `currentStep`. Mapped\n * from GET `can_go_back` (workflow-graph computed). When absent (e.g. a step\n * reached via SSE, which doesn't carry the flag) the orchestrator derives it\n * from {@link stepReversibility}.\n */\n canGoBack?: boolean;\n /**\n * Per-step intrinsic reversibility in workflow order, cached from the initial\n * GET so the orchestrator can derive `can_go_back` for steps reached via SSE:\n * a step can go back when any earlier step is reversible, or the step itself\n * is the first reversible one (back exits the flow).\n */\n stepReversibility?: Array<{ code: OnboardingStep; reversible: boolean }>;\n /**\n * Previously-captured data for `currentStep`, present when a reverse\n * navigation re-opened a completed step (GET reflects it on\n * `current_step.result`). Applied by the SDK as editable prefill.\n */\n currentStepResult?: Record<string, unknown>;\n /** Arbitrary session metadata the backend may attach. */\n metadata?: Record<string, unknown>;\n /**\n * Customer-registered allowlist of origins authorized to embed the SDK.\n * When provided, the SDK validates the loader's parent origin against this list.\n */\n allowedParentOrigins?: string[];\n}\n\n/**\n * Why the onboarding flow ended without a terminal verdict, delivered to\n * {@link VelionCallbacks.onExit}.\n *\n * Triggers:\n * - `BACK_EXIT`: the user tapped \"back\" on the first reversible step, where\n * there is no earlier step to return to, so the SDK left the flow and\n * returned control to the host.\n * - `RETRY_CANCELLED`: the user tapped \"Cancel\" on the retry dialog shown after\n * a `ROUTING_COMMAND / RETRY_STEP`. The backend session stays `IN_PROGRESS`\n * (there is no cancellation endpoint); the host may re-open it later via\n * `GET /sessions/:id`.\n */\nexport interface OnboardingExit {\n /** The reason the flow exited. */\n reason: 'BACK_EXIT' | 'RETRY_CANCELLED';\n /** The step the user exited from (when the backend provides `step_code`). */\n step?: OnboardingStep;\n}\n\n/**\n * A single T&amp;C line item (matches backend TermsAndConditionsItemDto / domain record).\n */\nexport interface TermsAndConditionsItem {\n id: string;\n description: string;\n /** Optional URL to the full document. */\n link?: string;\n}\n\n/**\n * Response from session creation (POST from your backend). Use sessionId and\n * sessionToken when instantiating VelionOnboarding; pass expiresAt for optional\n * client-side expiration checks.\n */\nexport interface SessionCreationResponse {\n session_id: string;\n session_token: string;\n expires_at: string;\n status?: string;\n}\n\n/**\n * Shape of the final result the SDK hands to `onSuccess` once the session\n * reaches a terminal status. Built from the terminal SSE event and the\n * `GET /sessions/:sessionId` snapshot (the backend exposes no separate\n * `/result` endpoint).\n */\nexport interface OnboardingResult {\n /** The session ID that was completed. Matches `VelionConfig.sessionId`. */\n sessionId: string;\n /** ISO 8601 timestamp of when the backend finalized the session. */\n completedAt: string;\n /**\n * The final KYC verdict.\n * - `APPROVED`: All checks passed automatically.\n * - `MANUAL_REVIEW`: Flagged for human review (common in AML flows). Backend `IN_REVIEW` maps here.\n * - `REJECTED`: Automatically rejected (fraud signals, liveness failure, etc.).\n * - `DECLINED`: Session ended in a declined state (matches GET session `status: DECLINED`).\n */\n status: 'APPROVED' | 'MANUAL_REVIEW' | 'REJECTED' | 'DECLINED';\n /** An optional tracking reference for support and audit trails. */\n referenceId?: string;\n /**\n * When the terminal outcome came from SSE, optional backend `reason` (e.g.\n * `LIVENESS_SCORE_IN_REVIEW_RANGE` on SESSION_MANUAL_REVIEW) for localized final-screen copy.\n */\n terminalReason?: string;\n}\n\n/**\n * Response from `POST /sessions/:sessionId/liveness-init`.\n * The backend returns the Iris session details the SDK needs to open the WebSocket\n * and stream frames. Credentials are not used: Iris owns the session lifecycle.\n */\nexport interface LivenessSessionResponse {\n /** Iris session identifier. */\n liveness_session_id?: string;\n /** Full WebSocket URL the SDK must connect to (e.g. wss://iris.host/ws/iris/{id}). */\n websocket_url?: string;\n /** ISO-8601 expiry of the Iris session. */\n expires_at?: string;\n /** Effective Iris challenge identifiers in order (TURN_LEFT, SMILE, …). */\n challenges?: string[];\n /** Optional JWT for the WebSocket handshake when Iris auth is enabled. */\n connection_token?: string;\n /**\n * Optional base64 HMAC-SHA256 key. When present, the SDK signs every JPEG\n * frame in a JSON envelope (canonical line: `sessionId\\nframeId\\nts\\nsha256hex(jpeg)`).\n */\n frame_integrity_key_base64?: string;\n /**\n * Signed PUT URL the SDK uses to upload the locally-recorded liveness video\n * directly to the onboarding GCS bucket. `null` (or absent) when video\n * recording is disabled or the signing failed — the SDK skips the upload\n * silently (liveness still works without the video; only the back-office\n * loses the playback evidence).\n */\n video_upload?: VideoUpload | null;\n}\n\n/**\n * Signed-upload payload returned by `POST /liveness-init`. Mirrors the backend\n * `LivenessInitResponseDto.VideoUpload`. The SDK PUTs the recorded video bytes\n * to `upload_url` (Content-Type matching the recorded container) before calling\n * `POST /liveness-verify` with the resulting metadata.\n */\nexport interface VideoUpload {\n /** Absolute https://storage.googleapis.com/... URL with V4 signature params. */\n upload_url: string;\n /** ISO-8601 instant after which GCS rejects the signature. */\n expires_at: string;\n /** HTTP method to use. Always `\"PUT\"` today; future-proofing. */\n method: 'PUT' | string;\n}\n\n/**\n * Optional body of `POST /liveness-verify`. The SDK only includes it when the\n * recorded video uploaded successfully (HTTP 200 from GCS). When omitted, the\n * backend completes liveness based on the Iris score only.\n */\nexport interface LivenessVerifyVideoMeta {\n /** MIME type that was sent in the PUT `Content-Type` header (e.g. `video/mp4`, `video/webm`). */\n content_type: string;\n /** Recorded video duration in milliseconds, or `null` if it could not be determined. */\n duration_ms: number | null;\n}\n\n/**\n * Payload delivered to the optional `onLivenessVideoUploaded` callback after a\n * successful upload of the liveness video. Best-effort: the callback only\n * fires when the GCS PUT returned 200.\n */\nexport interface LivenessVideoRef {\n /** Signed `upload_url` the SDK PUT the video to. */\n upload_url: string;\n /** MIME type used in the PUT. */\n content_type: string;\n /** Recorded video duration in milliseconds, or `null` when unknown. */\n duration_ms: number | null;\n /** Recorded file size in bytes, or `null` when unknown. */\n size_bytes: number | null;\n}\n\n/**\n * Payload for POST /sessions/:sessionId/basic-info/human (HUMAN_BASIC_INFO step).\n * Matches backend SubmitHumanBasicInfoRequestDto (snake_case in JSON).\n */\nexport interface HumanBasicInfoPayload {\n first_name: string;\n middle_name?: string;\n last_name: string;\n second_last_name?: string;\n identification_type: string;\n identification_id: string;\n}\n\n/**\n * Payload for POST /sessions/:sessionId/basic-info/legal (LEGAL_BASIC_INFO step).\n * Matches backend SubmitLegalBasicInfoRequestDto (snake_case in JSON).\n */\nexport interface LegalBasicInfoPayload {\n legal_name: string;\n legal_form: string;\n identification_type: string;\n identification_id: string;\n}\n\n/**\n * Single selectable option for tax category or fiscal identifier type (TAX_INFO step).\n * `id` is submitted to the API; `description` is the user-visible label.\n */\nexport interface TaxInfoOption {\n id: string;\n description: string;\n}\n\n/**\n * Resolved selectable lists for the TAX_INFO step UI (from `accepted_tax_information` only; no SDK defaults).\n */\nexport interface TaxInfoConfig {\n /**\n * Fiscal regime / category options (e.g. Monotributo). The chosen `id` is sent as `taxpayer_type`.\n */\n taxpayerCategories: TaxInfoOption[];\n /**\n * Tax identification scheme options (e.g. CUIT). The chosen `id` is sent as `taxpayer_id_type`.\n */\n fiscalIdentifierTypes: TaxInfoOption[];\n}\n\n/** POST /sessions/:id/tax-info — SubmitTaxInfoRequestDto. */\nexport interface TaxInfoPayload {\n /** Selected fiscal category value (`code` from step config `taxpayer_categories`). */\n taxpayer_type: string;\n /** Selected fiscal identifier kind id (e.g. `CUIT` from step config `identification_types`). */\n taxpayer_id_type: string;\n /** Tax identification number for the chosen type. */\n taxpayer_id: string;\n}\n\n/** POST /sessions/:id/extended-info/human — SubmitHumanExtendedInfoRequestDto. */\nexport interface HumanExtendedInfoPayload {\n gender?: string;\n civil_status?: string;\n birth_date?: string;\n birth_country?: string;\n citizenship?: string;\n residence_country?: string;\n}\n\n/** POST /sessions/:id/extended-info/legal — SubmitLegalExtendedInfoRequestDto. */\nexport interface LegalExtendedInfoPayload {\n incorporation_date: string;\n incorporation_country: string;\n}\n\n/** POST /sessions/:id/address-info — SubmitAddressInfoRequestDto. */\nexport interface AddressInfoPayload {\n type: string;\n country: string;\n state: string;\n city: string;\n district?: string;\n neighborhood?: string;\n street: string;\n number: string;\n floor?: string;\n apartment?: string;\n details?: string;\n zip_code: string;\n latitude?: number;\n longitude?: number;\n}\n\n/** POST /sessions/:id/sworn-declaration — SubmitSwornDeclarationRequestDto. */\nexport interface SwornDeclarationPayload {\n is_pep: boolean;\n is_ssoo: boolean;\n is_fatca: boolean;\n is_ocde: boolean;\n}\n\n/**\n * POST /sessions/:id/economic-activity — EconomicActivitySelectionDto.\n *\n * Carries the `code` of the single economic activity the user selected for the\n * `ECONOMIC_ACTIVITY_DECLARATION` step. The Worker validates it asynchronously\n * against the configured items; an invalid code surfaces over SSE as\n * `RETRY_STEP` (re-mounts the step) or `SESSION_DECLINED`, never as an HTTP error.\n */\nexport interface EconomicActivitySelectionPayload {\n /** `code` of the selected EconomicActivityItem. */\n code: string;\n}\n\n/** POST /sessions/:id/contact/email — SubmitEmailContactRequestDto. */\nexport interface EmailContactPayload {\n email: string;\n}\n\n/** POST /sessions/:id/contact/phone — SubmitPhoneContactRequestDto. */\nexport interface PhoneContactPayload {\n phone: string;\n}\n\n/** POST /sessions/:id/terms-and-conditions — SubmitTermsAndConditionsRequestDto. */\nexport interface TermsAndConditionsAcceptancePayload {\n item_id: string;\n accepted: boolean;\n}\n\nexport interface TermsAndConditionsSubmitPayload {\n acceptances: TermsAndConditionsAcceptancePayload[];\n}\n\n/**\n * SSE event payload (OnboardingSessionEvent). Matches the backend record\n * la.velion.onboarding.api...sdk.OnboardingSessionEventDto (snake_case in JSON).\n *\n * Received on GET /public/sdk/sessions/:sessionId/events. The backend sends\n * ServerSentEvent with id = event_id (epoch millis) for Last-Event-ID replay.\n *\n * Event types (event_type):\n * - STEP_UPDATED — a workflow step changed status (step_code, step_status)\n * - ROUTING_COMMAND — next/retry/terminate instruction (action: NEXT_STEP | RETRY_STEP | TERMINATE)\n * - SESSION_APPROVED — all checks passed; session_status = APPROVED\n * - SESSION_MANUAL_REVIEW — manual review required; session_status = MANUAL_REVIEW\n * - SESSION_DECLINED — session ended with decline (step_code, session_status DECLINED, reason)\n * - SESSION_CANCELLED — session cancelled by the backend, not a verdict (session_status CANCELLED,\n * reason e.g. WORKFLOW_VERSION_RETIRED). The stream closes and the session token is revoked.\n */\nexport interface OnboardingSessionEvent {\n /** Onboarding session identifier (Long in backend). */\n session_id?: number;\n /** Discriminator: STEP_UPDATED | ROUTING_COMMAND | SESSION_APPROVED | SESSION_MANUAL_REVIEW | SESSION_DECLINED | SESSION_CANCELLED */\n event_type?: string;\n /** Present for STEP_UPDATED or ROUTING_COMMAND (next step code). */\n step_code?: string;\n /** Present for STEP_UPDATED; e.g. COMPLETED. */\n step_status?: string;\n /** Present for terminal events; e.g. APPROVED | MANUAL_REVIEW | DECLINED | CANCELLED. */\n session_status?: string;\n /**\n * For ROUTING_COMMAND: NEXT_STEP | RETRY_STEP (render step_code), TERMINATE\n * (end flow), PREVIOUS_STEP (reverse navigation — re-open step_code with\n * step_result as prefill), or BACK_EXIT (user backed out of the first\n * reversible step — leave the flow and notify the host via `onExit`).\n */\n action?: string;\n /** For SESSION_DECLINED / SESSION_MANUAL_REVIEW / SESSION_CANCELLED or ROUTING_COMMAND TERMINATE; e.g. UNREADABLE_DOCUMENT. */\n reason?: string;\n /** Step-specific config sent with ROUTING_COMMAND NEXT_STEP / PREVIOUS_STEP. */\n step_config?: Record<string, unknown>;\n /**\n * Previously-captured data for the re-opened step, sent with ROUTING_COMMAND\n * PREVIOUS_STEP. Applied by the SDK as editable prefill.\n */\n step_result?: Record<string, unknown>;\n /**\n * Whether the step the user is landing on can itself go back further. Carried\n * on ROUTING_COMMAND when the backend computes it; when absent the SDK derives\n * it from the cached workflow reversibility map.\n */\n can_go_back?: boolean;\n /** Epoch millis; used as SSE id for Last-Event-ID on reconnect. */\n event_id?: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// BACKEND COMMANDS (Listen & Obey)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Backend command: advance to a specific step. The SDK must render that step's\n * screen without evaluating business rules locally.\n */\nexport interface BackendCommandGoToStep {\n action: 'GO_TO_STEP';\n stepCode: OnboardingStep;\n}\n\n/**\n * Backend command: show an error message to the user. The SDK displays the\n * message and does not advance (backend owns the decision).\n */\nexport interface BackendCommandShowError {\n action: 'SHOW_ERROR';\n message: string;\n}\n\n/**\n * Backend command: flow is complete. SDK should fetch final result and fire onSuccess.\n */\nexport interface BackendCommandFlowComplete {\n action: 'FLOW_COMPLETE';\n}\n\n/**\n * Backend command: retry the current step (e.g. after transient failure).\n */\nexport interface BackendCommandRetry {\n action: 'RETRY';\n}\n\n/**\n * Strict command payload the backend may return in a synchronous HTTP response\n * or send via SSE. The SDK never makes routing decisions; it only obeys these commands.\n */\nexport type BackendCommand =\n | BackendCommandGoToStep\n | BackendCommandShowError\n | BackendCommandFlowComplete\n | BackendCommandRetry;\n\n/**\n * Raw response body that may contain a backend command (e.g. POST submit response).\n */\nexport interface BackendCommandResponse {\n action?: string;\n stepCode?: string;\n message?: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// INTERNAL STATE MACHINE TYPES (exported for module authors)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * All possible states of the SDK's internal lifecycle.\n * Transitions are strictly unidirectional (no going back to IDLE once started).\n *\n * @internal\n */\nexport type SdkStatus =\n | 'IDLE' // Instantiated, not yet started\n | 'INITIALIZING' // Fetching session state from backend\n | 'RUNNING' // Orchestrating steps\n | 'STEP_PROCESSING'// A module is actively running\n | 'COMPLETED' // All steps done, onSuccess fired\n | 'EXITED' // User left the flow via back on the first step, onExit fired\n | 'ERROR' // Unrecoverable error, onError fired\n | 'DESTROYED'; // destroy() was called, instance is a no-op\n\n/**\n * Internal event bus event names. Typed via `SdkEventMap`.\n * @internal\n */\nexport type SdkEventName =\n | 'step:change'\n | 'step:complete'\n | 'session:loaded'\n | 'flow:complete'\n | 'flow:exit'\n | 'error'\n | 'status:change';\n\n/**\n * Maps each internal event name to its payload type.\n * Used by the `TypedEventEmitter` for compile-time safety.\n * @internal\n */\nexport interface SdkEventMap extends Record<string, unknown> {\n 'step:change': { step: OnboardingStep; index: number };\n 'step:complete': { step: OnboardingStep };\n 'session:loaded': SessionState;\n 'flow:complete': OnboardingResult;\n 'flow:exit': OnboardingExit;\n 'error': SdkError;\n 'status:change': SdkStatus;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LOADER ↔ CDN APP POSTMESSAGE PROTOCOL (Sumsub-style)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Message type: parent (loader) sends config to iframe (CDN app). */\nexport const VELION_MSG_INIT = 'VELION_INIT' as const;\n\n/** Message types: iframe (CDN app) sends to parent (loader). */\nexport const VELION_MSG_READY = 'VELION_READY' as const;\nexport const VELION_MSG_SUCCESS = 'VELION_SUCCESS' as const;\nexport const VELION_MSG_ERROR = 'VELION_ERROR' as const;\nexport const VELION_MSG_STEP_CHANGE = 'VELION_STEP_CHANGE' as const;\nexport const VELION_MSG_STEP_COMPLETE = 'VELION_STEP_COMPLETE' as const;\nexport const VELION_MSG_TOKEN_EXPIRED = 'VELION_TOKEN_EXPIRED' as const;\n/**\n * Iframe → parent: the user left the flow via back on the first reversible step\n * (`ROUTING_COMMAND / BACK_EXIT`). The loader forwards this to the host's\n * `onExit` callback so it can dismiss the SDK surface.\n */\nexport const VELION_MSG_EXIT = 'VELION_EXIT' as const;\n/**\n * Iframe → parent: the LIVENESS_MATCH step uploaded the recorded session video\n * (GCS PUT returned 200). The loader forwards the {@link LivenessVideoRef} to\n * the host's `onLivenessVideoUploaded` callback. Best-effort: never sent when\n * recording was disabled or the upload failed.\n */\nexport const VELION_MSG_LIVENESS_VIDEO_UPLOADED = 'VELION_LIVENESS_VIDEO_UPLOADED' as const;\n\n/** Message type: parent sends new token to iframe after VELION_TOKEN_EXPIRED. */\nexport const VELION_MSG_TOKEN = 'VELION_TOKEN' as const;\n\nexport type VelionMessageType =\n | typeof VELION_MSG_INIT\n | typeof VELION_MSG_READY\n | typeof VELION_MSG_SUCCESS\n | typeof VELION_MSG_ERROR\n | typeof VELION_MSG_STEP_CHANGE\n | typeof VELION_MSG_STEP_COMPLETE\n | typeof VELION_MSG_TOKEN_EXPIRED\n | typeof VELION_MSG_EXIT\n | typeof VELION_MSG_LIVENESS_VIDEO_UPLOADED\n | typeof VELION_MSG_TOKEN;\n\n/** Envelope for all loader ↔ iframe messages. Both sides must validate origin. */\nexport interface VelionMessage<T = unknown> {\n type: VelionMessageType;\n payload: T;\n}\n\n/** Payload for VELION_INIT: full config (iframe runs with containerId overwritten to root id). */\nexport type VelionInitPayload = VelionConfig;\n\n/** Payload for VELION_STEP_CHANGE. */\nexport interface VelionStepChangePayload {\n step: OnboardingStep;\n stepIndex: number;\n}\n\n/** Payload for VELION_STEP_COMPLETE. */\nexport interface VelionStepCompletePayload {\n step: OnboardingStep;\n}\n\n/** Payload for VELION_EXIT (mirrors {@link OnboardingExit}). */\nexport type VelionExitPayload = OnboardingExit;\n\n/** Payload for VELION_LIVENESS_VIDEO_UPLOADED (mirrors {@link LivenessVideoRef}). */\nexport type VelionLivenessVideoUploadedPayload = LivenessVideoRef;\n\n/** Payload for VELION_TOKEN (token refresh response from parent to iframe). */\nexport interface VelionTokenPayload {\n sessionToken: string;\n expiresAt?: string;\n}\n","/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 5KB JS implementation of ed25519 EdDSA signatures.\n * Targets RFC8032, FIPS 186-5, and ZIP215 behavior.\n * @module\n * @example\n * ```js\nimport * as ed from '@noble/ed25519';\n(async () => {\n const secretKey = ed.utils.randomSecretKey();\n const message = Uint8Array.from([0xab, 0xbc, 0xcd, 0xde]);\n const pubKey = await ed.getPublicKeyAsync(secretKey); // Sync methods are also present\n const signature = await ed.signAsync(message, secretKey);\n const isValid = await ed.verifyAsync(signature, message, pubKey);\n})();\n```\n */\n/**\n * Curve params. edwards25519 uses the RFC equation `-x² + y² = 1 + dx²y²`.\n * The stored `a` literal below is `p - 1`, i.e. the field-element encoding of RFC `a = -1`.\n * * P = `2n**255n - 19n` // field over which calculations are done\n * * N = `2n**252n + 27742317777372353535851937790883648493n` // prime-order subgroup order\n * * h = 8 // cofactor\n * * a = `Fp.create(BigInt(-1))` // equation param, stored here as `p - 1`\n * * d = -121665/121666 a.k.a. `Fp.neg(121665 * Fp.inv(121666))` // equation param\n * * Gx, Gy are coordinates of Generator / base point\n *\n * Mirror noble-curves: Point.CURVE() exposes shared params, but callers must not be able to mutate\n * that shared view and desynchronize it from the arithmetic constants captured below.\n */\nconst freeze = Object.freeze;\nconst P = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn;\nconst N = 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn;\nconst _d = 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n;\nconst Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an;\nconst Gy = 0x6666666666666666666666666666666666666666666666666666666666666658n;\nconst _a = P - 1n; // field-element encoding of RFC `a = -1`\nconst ed25519_CURVE = freeze({\n p: P,\n n: N,\n h: 8n,\n a: _a,\n d: _d,\n Gx,\n Gy,\n});\n// Shared 32-byte encoded width for Ed25519 points, scalars, signatures/2, and keys. Named LEN\n// rather than RFC 8032's `L`, which names the group order (stored here as `N`).\nconst LEN = 32;\n// Helpers and Precomputes sections are reused between libraries\n// ## Helpers\n// ----------\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nconst isBytes = (a) => {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n a.BYTES_PER_ELEMENT === 1));\n};\n/** Asserts something is Bytes. */\nconst abytes = (value, length, title = '') => {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = (title ? `\"${title}\" ` : '') + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n};\n// Validate, then take one owned copy, so later caller mutation cannot be observed — e.g. cannot\n// make sign()'s nonce derivation and challenge derivation see different messages.\nconst snapshotBytes = (value, title = '', length) => Uint8Array.from(abytes(value, length, title));\n// Callers keep values non-negative and within the requested width; padStart() won't truncate over-wide inputs.\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\n/** Convert byte array to hex string. */\nconst bytesToHex = (bytes) => {\n let hex = '';\n for (const byte of abytes(bytes))\n hex += padh(byte, 2);\n return hex;\n};\n/** Convert hex string to byte array. */\nconst hexToBytes = (hex) => {\n const e = 'hex invalid'; // Strict ASCII hex only, with one generic error for parse failures.\n if (typeof hex !== 'string')\n throw new TypeError(e);\n if (hex.length % 2 || !/^[\\da-f]*$/i.test(hex))\n throw new RangeError(e);\n const array = new Uint8Array(hex.length / 2);\n for (let ai = 0, hi = 0; ai < array.length; ai++, hi += 2) {\n const n1 = hex.charCodeAt(hi);\n const n2 = hex.charCodeAt(hi + 1);\n // Regex guarantees ASCII. For 0..9/A..F/a..f, this maps char codes to 0..15.\n array[ai] = ((n1 & 15) + (n1 >> 6) * 9) * 16 + (n2 & 15) + (n2 >> 6) * 9;\n }\n return array;\n};\n// WebCrypto is available in all modern environments\n/** Copies several Uint8Arrays into one. */\nconst concatBytes = (...arrays) => {\n let sum = 0;\n for (const a of arrays)\n sum += abytes(a).length;\n const res = new Uint8Array(sum);\n let pad = 0;\n for (const a of arrays) {\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n};\n/**\n * WebCrypto OS-level CSPRNG (random number generator).\n * Will throw when not available; large-request ceilings are delegated to getRandomValues().\n */\nconst randomBytes = (len = LEN) => {\n const c = globalThis?.crypto;\n if (typeof c?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined, consider polyfill');\n return c.getRandomValues(new Uint8Array(len));\n};\n/** Inclusive-lower, exclusive-upper bigint range assertion. */\nconst arange = (n, min, max, msg = 'bad number: out of range') => {\n if (typeof n !== 'bigint')\n throw new TypeError(msg);\n if (min <= n && n < max)\n return n;\n throw new RangeError(msg);\n};\n/** Canonical modular reduction. Callers must provide a positive modulus. */\nconst mod = (a, b = P) => ((a %= b) >= 0n ? a : b + a);\n// Low-255-bit mask used by the `2^255 - 19` fast reduction in `modP(...)`.\nconst P_MASK = (1n << 255n) - 1n;\n// Fast reduction for the special prime `2^255 - 19`. This path assumes nonnegative inputs; the\n// generic fallback would simply be `mod(num, P)`.\nconst modP = (num) => {\n if (num < 0n)\n throw new RangeError('negative coordinate');\n let r = (num >> 255n) * 19n + (num & P_MASK);\n r = (r >> 255n) * 19n + (r & P_MASK);\n return r % P;\n};\n// Reduce modulo the subgroup order stored in implementation constant `N` (RFC 8032's `L`).\nconst modN = (a) => mod(a, N);\n/** Modular inversion using extended euclidean GCD. Variable-time (non-CT). */\nconst invert = (number, modulo) => {\n if (number === 0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= 1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`.\n let a = mod(number, modulo);\n let b = modulo;\n // Only the Bézout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = 0n, u = 1n;\n while (a !== 0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== 1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n};\n// Dynamic lookup keeps sync/async hash providers configurable at runtime. Both exported slots are\n// caller-owned and may be unset; wrapper helpers use this lookup first and then enforce the digest\n// contract instead of trusting provider output.\nconst _hash = (name) => {\n // @ts-ignore\n const fn = hashes[name];\n if (typeof fn !== 'function')\n throw new Error('hashes.' + name + ' not set');\n return fn;\n};\n// All exported provider slots are caller-configurable and may be unset or return arbitrary values,\n// so wrapper helpers must enforce the exact 64-byte SHA-512 digest contract instead of trusting providers.\nconst callHash = (name, ...m) => abytes(_hash(name)(concatBytes(...m)), 64, 'digest');\nconst callHashAsync = async (name, ...m) => abytes(await _hash(name)(concatBytes(...m)), 64, 'digest');\n/**\n * SHA-512 helper used by the synchronous API.\n * @param msg - Message bytes to hash.\n * @returns 64-byte SHA-512 digest.\n * @example\n * Hash message bytes after wiring the synchronous SHA-512 implementation.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const digest = ed.hash(new Uint8Array([1, 2, 3]));\n * ```\n */\n// Public helper validates the message boundary explicitly; the configured provider is still looked\n// up dynamically and its output is checked with `callHash(...)`.\nconst hash = (msg) => callHash('sha512', abytes(msg, undefined, 'message'));\n// Runtime class guard: this is `instanceof Point`, so cross-realm / duplicate-bundle Point objects\n// are rejected even if they are structurally identical.\nconst apoint = (p) => {\n if (p instanceof Point)\n return p;\n throw new TypeError('Point expected');\n};\n// ## End of Helpers\n// -----------------\n// Exclusive upper bound `2^256` used by 32-byte decode/serialization range checks.\nconst B256 = 2n ** 256n;\n/**\n * Point in XYZT extended coordinates.\n * @param X - X coordinate.\n * @param Y - Y coordinate.\n * @param Z - Projective Z coordinate.\n * @param T - Cached cross-product term.\n * @example\n * Do point arithmetic with the built-in base point and encode the result as hex.\n *\n * ```ts\n * const hex = Point.BASE.double().toHex();\n * ```\n */\nclass Point {\n static BASE;\n static ZERO;\n X;\n Y;\n Z;\n T;\n // Constructor only bounds-checks and freezes XYZT coordinates; it does not prove the point is\n // on-curve or that T matches X*Y/Z.\n constructor(X, Y, Z, T) {\n const max = B256;\n this.X = arange(X, 0n, max);\n this.Y = arange(Y, 0n, max);\n this.Z = arange(Z, 1n, max);\n this.T = arange(T, 0n, max);\n freeze(this);\n }\n static CURVE() {\n return ed25519_CURVE;\n }\n static fromAffine(p) {\n return new Point(p.x, p.y, 1n, modP(p.x * p.y));\n }\n /** RFC8032 5.1.3: Uint8Array to Point. */\n static fromBytes(bytes, zip215 = false) {\n const normed = snapshotBytes(bytes, 'point', LEN); // owned copy: sign-bit mask below mutates it\n // adjust first LE byte = last BE byte\n const lastByte = normed[31];\n normed[31] = lastByte & ~0x80;\n const y = bytesToNumberLE(normed);\n // After clearing the sign bit, parsed `y` is always < 2^255. ZIP-215 still accepts the full\n // post-mask range here, while strict RFC8032 decoding further requires `y < p`.\n if (!zip215)\n arange(y, 0n, P);\n const y2 = modP(y * y); // y²\n const u = mod(y2 - 1n); // u=y²-1\n const v = modP(_d * y2 + 1n); // v=dy²+1\n let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (!isValid)\n throw new Error('bad point: y not sqrt'); // not square root: bad point\n const isLastByteOdd = !!(lastByte & 0x80); // x_0, last bit\n // ZIP-215-compatible decoding keeps the x=0 / sign-bit=1 encoding accepted; strict RFC 8032\n // rejects it, but the vendored ZIP-215 compliance vectors include this form in A/R bytes.\n if (!zip215 && x === 0n && isLastByteOdd)\n throw new Error('bad point: x==0, isLastByteOdd'); // x=0, x_0=1\n if (isLastByteOdd !== !!(x & 1n))\n x = mod(-x); // adjust sign of x coordinate\n return new Point(x, y, 1n, modP(x * y)); // Z=1, T=xy\n }\n static fromHex(hex, zip215) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /** Checks if the point is valid and on-curve. */\n assertValidity() {\n const a = _a;\n const d = _d;\n const p = this;\n // Intentional stricter-than-on-curve policy: reject ZERO by default because many protocols\n // require a non-zero point, and silently accepting identity points is a common caller mistake.\n if (p.is0())\n throw new Error('bad point: ZERO');\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * (aX2 + Y2)); // (aX² + Y²)Z²\n const right = mod(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return this;\n }\n /** Equality check: compare points P&Q. */\n equals(other) {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = apoint(other); // checks class equality\n return modP(X1 * Z2) === modP(X2 * Z1) && modP(Y1 * Z2) === modP(Y2 * Z1);\n }\n is0() {\n return this.equals(I);\n }\n /** Flip point over y coordinate. */\n negate() {\n return new Point(mod(-this.X), this.Y, this.Z, mod(-this.T));\n }\n /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */\n double() {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const a = _a;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n const A = modP(X1 * X1);\n const B = modP(Y1 * Y1);\n const C = modP(2n * Z1 * Z1);\n const D = modP(a * A);\n const x1y1 = mod(X1 + Y1);\n const E = mod(modP(x1y1 * x1y1) - A - B);\n const G = mod(D + B);\n const F = mod(G - C);\n const H = mod(D - B);\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n /** Point addition. Complete formula. Cost: `9M + 1*a + 1*d + 7add`. */\n add(other) {\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other); // doesn't check if other on-curve\n const a = _a;\n const d = _d;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n const A = modP(X1 * X2);\n const B = modP(Y1 * Y2);\n const C = modP(modP(T1 * d) * T2);\n const D = modP(Z1 * Z2);\n const E = mod(modP(mod(X1 + Y1) * mod(X2 + Y2)) - A - B);\n const F = mod(D - C);\n const G = mod(D + C);\n const H = mod(B - modP(a * A));\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(apoint(other).negate());\n }\n /**\n * Point-by-scalar multiplication. Safe mode requires `1 <= n < CURVE.n`.\n * Unsafe mode additionally permits `n = 0` and returns the identity point for that case.\n * Uses {@link wNAF} for base point.\n * Uses fake point to mitigate side-channel leakage.\n * @param n - scalar by which point is multiplied\n * @param safe - safe mode guards against timing attacks; unsafe mode is faster\n */\n multiply(n, safe = true) {\n // Mirror noble-curves: unsafe mode still validates scalar range first, but intentionally keeps\n // `n = 0` as the one extra accepted case used by verification-style callers.\n if (!safe && n === 0n)\n return I;\n arange(n, 1n, N);\n if (!safe && this.is0())\n return I;\n if (n === 1n)\n return this;\n if (this.equals(G))\n return wNAF(n).p;\n // init result point & fake point\n let p = I;\n let f = G;\n let d = this;\n // Safe mode always runs 256 iterations so ladder length can't leak the scalar's\n // leading zero bits; unsafe mode stops at the top set bit for speed.\n for (let i = 0; safe ? i < 256 : n > 0n; i++) {\n // if bit is present, add to point\n // if not present, add to fake, for timing safety\n if (n & 1n)\n p = p.add(d);\n else if (safe)\n f = f.add(d);\n d = d.double();\n n >>= 1n;\n }\n return p;\n }\n multiplyUnsafe(scalar) {\n return this.multiply(scalar, false);\n }\n /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */\n toAffine() {\n const { X, Y, Z } = this;\n // Fast-path only for the identity point; all other inputs still go through inversion.\n if (this.equals(I))\n return { x: 0n, y: 1n };\n const iz = invert(Z, P);\n // (Z * Z^-1) must be 1, otherwise bad math\n if (modP(Z * iz) !== 1n)\n throw new Error('invalid inverse');\n // x = X*Z^-1; y = Y*Z^-1\n return { x: modP(X * iz), y: modP(Y * iz) };\n }\n toBytes() {\n const { x, y } = this.toAffine();\n const b = numTo32bLE(y);\n // store sign in first LE byte\n b[31] |= x & 1n ? 0x80 : 0;\n return b;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n clearCofactor() {\n return this.multiply(8n, false); // h = 8\n }\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n isTorsionFree() {\n // Multiply by big number N. We can't `mul(N)` because of checks. Instead, we `mul(N/2)*2+1`;\n // N is odd, so N/2 truncates and the final `add(this)` is always needed.\n return this.multiply(N / 2n, false)\n .double()\n .add(this)\n .is0();\n }\n}\n/** Generator / base point */\nconst G = new Point(Gx, Gy, 1n, mod(Gx * Gy));\n/** Identity / zero point */\nconst I = new Point(0n, 1n, 1n, 0n);\n// Static aliases\nPoint.BASE = G;\nPoint.ZERO = I;\nconst numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), 64)).reverse();\n// Caller-enforced width: some sites require 32-byte RFC encodings, while others intentionally feed\n// wider SHA-512 output chunks through the same little-endian parser.\nconst bytesToNumberLE = (b) => BigInt('0x' + bytesToHex(Uint8Array.from(abytes(b)).reverse()));\nconst pow2 = (x, power) => {\n // pow2(x, 4) == x^(2^4)\n // Negative `power` values are not rejected here and currently leave `x` unchanged.\n let r = x;\n while (power-- > 0) {\n r = modP(r * r);\n }\n return r;\n};\n// prettier-ignore\nconst pow_2_252_3 = (x) => {\n const x2 = modP(x * x); // x^2, bits 1\n const b2 = modP(x2 * x); // x^3, bits 11\n const b4 = modP(pow2(b2, 2) * b2); // x^(2^4-1), bits 1111\n const b5 = modP(pow2(b4, 1) * x); // x^(2^5-1), bits 11111\n const b10 = modP(pow2(b5, 5) * b5); // x^(2^10-1)\n const b20 = modP(pow2(b10, 10) * b10); // x^(2^20-1)\n const b40 = modP(pow2(b20, 20) * b20); // x^(2^40-1)\n const b80 = modP(pow2(b40, 40) * b40); // x^(2^80-1)\n const b160 = modP(pow2(b80, 80) * b80); // x^(2^160-1)\n const b240 = modP(pow2(b160, 80) * b80); // x^(2^240-1)\n const b250 = modP(pow2(b240, 10) * b10); // x^(2^250-1)\n return modP(pow2(b250, 2) * x); // x^((p-5)/8), used by RFC8032 point decode\n};\nconst RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n; // 2^((p-1)/4) = sqrt(-1)\n// RFC8032 §5.1.3 square-root helper for point decompression. `value` is only meaningful when\n// `isValid` is true; callers are also expected to pass canonical field elements with non-zero `v`.\n// prettier-ignore\nconst uvRatio = (u, v) => {\n const v3 = modP(v * modP(v * v)); // v³\n const v7 = modP(modP(v3 * v3) * v); // v⁷\n const pow = pow_2_252_3(modP(u * v7)); // (uv⁷)^(p-5)/8\n let x = modP(u * modP(v3 * pow)); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = modP(v * modP(x * x)); // vx²\n const root1 = x; // First root candidate\n const root2 = modP(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n)\n x = mod(-x); // edIsNegative\n return { isValid: useRoot1 || useRoot2, value: x };\n};\n// Reduce a little-endian byte string modulo the subgroup order `N` (RFC 8032's `L`); the `hash`\n// param name reflects the common caller shape, not an input restriction.\nconst modL_LE = (hash) => modN(bytesToNumberLE(hash));\n// RFC8032 5.1.5. Split the 64-byte hashed seed into the clamped scalar half and nonce prefix.\nconst hashedToExtK = (hashed) => {\n // slice creates a copy, unlike subarray\n const copy = snapshotBytes(hashed);\n const head = copy.slice(0, 32);\n head[0] &= 248; // Clamp bits: 0b1111_1000\n head[31] &= 127; // 0b0111_1111\n head[31] |= 64; // 0b0100_0000\n const prefix = copy.slice(32); // secret key \"prefix\"\n // RFC words this as `[s]B`; reducing the clamped little-endian scalar modulo `N` is equivalent\n // for base-point multiplication because `G` already has subgroup order `N`.\n const scalar = modL_LE(head);\n const point = G.multiply(scalar); // public key point\n const pointBytes = point.toBytes(); // point serialized to Uint8Array\n return { head, prefix, scalar, point, pointBytes };\n};\n// RFC8032 5.1.5; getPublicKey async, sync. Hash secret key and extract point.\nconst getExtendedPublicKeyAsync = (secretKey) => callHashAsync('sha512Async', abytes(secretKey, LEN, 'secretKey')).then(hashedToExtK);\nconst getExtendedPublicKey = (secretKey) => hashedToExtK(callHash('sha512', abytes(secretKey, LEN, 'secretKey')));\n/**\n * Creates a 32-byte Ed25519 public key from the RFC 8032 32-byte secret-key seed. Async.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 32-byte public key.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Derive the public key bytes for a newly generated signer secret.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const publicKey = await ed.getPublicKeyAsync(secretKey);\n * ```\n */\nconst getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);\n/**\n * Creates a 32-byte Ed25519 public key from the RFC 8032 32-byte secret-key seed.\n * To use, set `hashes.sha512` first.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 32-byte public key.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Derive the public key entirely through the synchronous API.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const secretKey = ed.utils.randomSecretKey();\n * const publicKey = ed.getPublicKey(secretKey);\n * ```\n */\nconst getPublicKey = (secretKey) => getExtendedPublicKey(secretKey).pointBytes;\nconst hashFinishAsync = async (res) => res[1](await callHashAsync('sha512Async', res[0]));\nconst hashFinishSync = (res) => res[1](callHash('sha512', res[0]));\n// Code, shared between sync & async sign\nconst _sign = (e, rBytes, msg) => {\n const { pointBytes: A, scalar: s } = e;\n const r = modL_LE(rBytes); // r was created outside, reduce it modulo L\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero SHA-512 provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = G.multiply(r).toBytes(); // R = [r]B\n const hashable = concatBytes(R, A, msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n const S = modN(r + modL_LE(hashed) * s); // S = (r + k * s) mod L; 0 <= s < l\n return abytes(concatBytes(R, numTo32bLE(S)), 64); // 64-byte sig: 32-byte encoded R point || 32-byte LE(S)\n };\n return [hashable, finish];\n};\n/**\n * Signs message using secret key. Async.\n * Follows RFC8032 5.1.6.\n * @param message - Message bytes to sign.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 64-byte Ed25519 signature.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Sign an arbitrary message with a fresh Ed25519 secret key.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const signature = await ed.signAsync(message, secretKey);\n * ```\n */\nconst signAsync = async (message, secretKey) => {\n const m = snapshotBytes(message, 'message');\n const e = await getExtendedPublicKeyAsync(secretKey);\n // r = SHA512(dom2(F, C) || prefix || PH(M)); then generate R, k, S and the signature.\n return hashFinishAsync(_sign(e, await callHashAsync('sha512Async', e.prefix, m), m));\n};\n/**\n * Signs message using secret key. To use, set `hashes.sha512` first.\n * Follows RFC8032 5.1.6.\n * @param message - Message bytes to sign.\n * @param secretKey - 32-byte RFC 8032 secret-key seed, not a 64-byte expanded secret key.\n * @returns 64-byte Ed25519 signature.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Use the sync API when you've wired a SHA-512 implementation yourself.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const secretKey = ed.utils.randomSecretKey();\n * const signature = ed.sign(new Uint8Array([1, 2, 3]), secretKey);\n * ```\n */\nconst sign = (message, secretKey) => {\n const m = snapshotBytes(message, 'message');\n const e = getExtendedPublicKey(secretKey);\n // r = SHA512(dom2(F, C) || prefix || PH(M)); then generate R, k, S and the signature.\n return hashFinishSync(_sign(e, callHash('sha512', e.prefix, m), m));\n};\n// Exported defaults favor ZIP-215 interoperability semantics; callers must opt into the stricter\n// branch with `{ zip215: false }`.\n// Preserves the exported ZIP-215 default for `{}` / `{ zip215: undefined }`, not just omitted opts.\nconst getZip215 = (options) => {\n if (options === null || typeof options !== 'object')\n throw new TypeError('expected valid options object');\n return options.zip215 ?? true;\n};\nconst _verify = (sig, msg, publicKey, options) => {\n sig = abytes(sig, 64, 'signature'); // Signature hex str/Bytes, must be 64 bytes\n msg = abytes(msg, undefined, 'message'); // Message hex str/Bytes\n publicKey = abytes(publicKey, LEN, 'publicKey');\n const zip215 = getZip215(options);\n // zip215=false keeps the library's stricter branch, which still canonicalizes `R` / `A` before\n // hashing and rejects small-order public keys earlier than pure RFC8032 text would require.\n const r = sig.subarray(0, LEN);\n const s = bytesToNumberLE(sig.subarray(LEN, 64)); // Decode second half as an integer S;\n let A, R, SB;\n let hashable = Uint8Array.of();\n let finished = false;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = G.multiply(s, false); // 0 <= s < l is done inside\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n hashable = concatBytes(r, publicKey, msg); // dom2(F, C) || R || A || PH(M)\n finished = true;\n }\n catch (error) { }\n const finish = (hashed) => {\n if (!finished)\n return false;\n // Policy: strict mode intentionally rejects all small-order public keys, even though the raw RFC\n // equation text is looser here. This matches libsodium and avoids weak / ambiguous verification\n // outcomes where unusual low-order public keys can make distinct key/signature combinations verify.\n if (!zip215 && A.isSmallOrder())\n return false;\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n const k = modL_LE(hashed);\n const RkA = R.add(A.multiply(k, false));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n };\n return [hashable, finish];\n};\n/**\n * Verifies a signature on message and public key. Async.\n * The implementation is based on RFC8032 5.1.7, but default opts use ZIP-215 semantics; pass\n * `{ zip215: false }` for the library's stricter branch.\n * @param signature - 64-byte signature.\n * @param message - Signed message bytes.\n * @param publicKey - 32-byte public key.\n * @param opts - Verification options. Defaults to ZIP-215 semantics. See {@link EdDSAVerifyOpts}.\n * @returns `true` when the signature is valid.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Verify the signature against the same message and derived public key.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const publicKey = await ed.getPublicKeyAsync(secretKey);\n * const signature = await ed.signAsync(message, secretKey);\n * const isValid = await ed.verifyAsync(signature, message, publicKey);\n * ```\n */\nconst verifyAsync = async (signature, message, publicKey, opts = {}) => hashFinishAsync(_verify(signature, message, publicKey, opts));\n/**\n * Verifies a signature on message and public key using the synchronous hash path.\n * The implementation is based on RFC8032 5.1.7, but default opts use ZIP-215 semantics; pass\n * `{ zip215: false }` for the library's stricter branch.\n * @param signature - 64-byte signature.\n * @param message - Signed message bytes.\n * @param publicKey - 32-byte public key.\n * @param opts - Verification options. Defaults to ZIP-215 semantics. See {@link EdDSAVerifyOpts}.\n * @returns `true` when the signature is valid.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Verify a signature entirely through the synchronous API.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const secretKey = ed.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const publicKey = ed.getPublicKey(secretKey);\n * const signature = ed.sign(message, secretKey);\n * const isValid = ed.verify(signature, message, publicKey);\n * ```\n */\nconst verify = (signature, message, publicKey, opts = {}) => hashFinishSync(_verify(signature, message, publicKey, opts));\n/**\n * Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves.\n * Exposes the same low-level field-default `mod` reducer and non-CT `invert` helper used\n * internally.\n * @example\n * Convert bytes to a hex string with the low-level helper namespace.\n *\n * ```ts\n * const hex = etc.bytesToHex(new Uint8Array([1, 2, 3]));\n * ```\n */\nconst etc = /* @__PURE__ */ freeze({\n bytesToHex,\n hexToBytes,\n concatBytes,\n mod,\n invert,\n randomBytes,\n});\n/**\n * Hash implementations used by the synchronous API plus the default async WebCrypto provider.\n * Both slots are configurable API surface; wrapper helpers revalidate that providers still return\n * 64-byte SHA-512 digests.\n * @example\n * Provide a SHA-512 implementation before calling synchronous helpers.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const { publicKey } = ed.keygen();\n * ```\n */\nconst hashes = {\n sha512Async: async (message) => {\n const s = globalThis?.crypto?.subtle;\n if (!s)\n throw new Error('crypto.subtle must be defined, consider polyfill');\n return new Uint8Array(await s.digest('SHA-512', concatBytes(message)));\n },\n sha512: undefined,\n};\n// Returns the final 32-byte Ed25519 secret-key seed verbatim, generating fresh random bytes only\n// when omitted.\nconst randomSecretKey = (seed) => {\n return abytes(seed === undefined ? randomBytes() : seed, LEN, 'seed');\n};\n/**\n * Generates a secret/public keypair.\n * @param seed - Optional 32-byte Ed25519 secret-key seed, returned verbatim as `secretKey`.\n * @returns Keypair with `secretKey` and `publicKey`.\n * @throws If synchronous SHA-512 has not been configured in `hashes`. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new keypair through the synchronous API after wiring SHA-512.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n * import { sha512 } from '@noble/hashes/sha2.js';\n *\n * ed.hashes.sha512 = sha512;\n * const { secretKey, publicKey } = ed.keygen();\n * ```\n */\nconst keygen = (seed) => {\n const secretKey = randomSecretKey(seed);\n const publicKey = getPublicKey(secretKey);\n return { secretKey, publicKey };\n};\n/**\n * Generates a secret/public keypair asynchronously.\n * @param seed - Optional 32-byte Ed25519 secret-key seed, returned verbatim as `secretKey`.\n * @returns Keypair with `secretKey` and `publicKey`.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new keypair through the asynchronous WebCrypto-backed path.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const { secretKey, publicKey } = await ed.keygenAsync();\n * ```\n */\nconst keygenAsync = async (seed) => {\n const secretKey = randomSecretKey(seed);\n const publicKey = await getPublicKeyAsync(secretKey);\n return { secretKey, publicKey };\n};\n/**\n * Ed25519-specific key utilities.\n * `utils.getExtendedPublicKey*` expose secret-derived internals (`head`, `prefix`, `scalar`, and\n * point objects), not just public-key bytes.\n * @example\n * Generate a new Ed25519 secret key and derive the matching public key.\n *\n * ```ts\n * import * as ed from '@noble/ed25519';\n *\n * const secretKey = ed.utils.randomSecretKey();\n * const publicKey = await ed.getPublicKeyAsync(secretKey);\n * ```\n */\nconst utils = /* @__PURE__ */ freeze({\n getExtendedPublicKeyAsync,\n getExtendedPublicKey,\n randomSecretKey,\n});\n// ## Precomputes\n// --------------\n// Fixed W=8 window: 33 windows (ceil(256/8) + 1, NOT 32 - see wNAF loop), 128 points per window.\n// Layout is grouped by window: each block stores the positive multiples `1*base .. 128*base` for\n// that window, and the extra `+1` window absorbs carries from signed-digit recoding.\nconst precompute = () => {\n const points = [];\n let p = G;\n let b;\n for (let w = 0; w < 33; w++) {\n b = p;\n points.push(b);\n for (let i = 1; i < 128; i++) {\n b = b.add(p);\n points.push(b);\n } // i=1, bc we skip 0\n p = b.double();\n }\n return points;\n};\nlet Gpows = undefined; // shared process-wide cache of base-point precomputes\n// Branch-based negate helper used for JS/JIT mitigation symmetry, not a strict constant-time claim.\nconst ctneg = (cnd, p) => {\n const n = p.negate();\n return cnd ? n : p;\n};\n/**\n * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by\n * caching multiples of G (base point). Cache is stored in 32MB of RAM.\n * Any time `G.multiply` is done, precomputes are used.\n * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.\n *\n * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,\n * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.\n * Returns the real accumulator `p` plus a fake accumulator `f`; callers only care about `p`, while\n * `f` exists to keep similar work in zero-digit branches as a JS/JIT side-channel mitigation.\n *\n * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().\n */\nconst wNAF = (n) => {\n const comp = Gpows || (Gpows = precompute());\n let p = I;\n let f = G; // f must be G, or could become I in the end\n for (let w = 0; w < 33; w++) {\n let wbits = Number(n & 255n); // extract W=8 bits.\n n >>= 8n; // shift number by W=8 bits.\n // We use negative indexes to reduce size of precomputed table by 2x.\n // Instead of needing precomputes 0..256, we only calculate them for 0..128.\n // If an index > 128 is found, we do (256-index) - where 256 is next window.\n // Naive: index +127 => 127, +224 => 224\n // Optimized: index +127 => 127, +224 => 256-32\n if (wbits > 128) {\n wbits -= 256;\n n += 1n;\n }\n const off = w * 128; // offset of this window's block; also the fake-add index\n const offP = off + Math.abs(wbits) - 1; // real-add index; both offsets always evaluated\n const isOddW = w % 2 !== 0; // conditions, evaluate both; alternates fake-add sign per window\n const isNeg = wbits < 0;\n if (wbits === 0) {\n // wbits == 0 means the real index would be I: can't add it. Add window offset `off` instead.\n f = f.add(ctneg(isOddW, comp[off])); // bits are 0: add garbage to fake point\n }\n else {\n p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point\n }\n }\n if (n !== 0n)\n throw new Error('invalid wnaf');\n return { p, f }; // return both real and fake points for JIT/leakage-shape symmetry\n};\n// !! Remove the export to easily use in REPL / browser console\nexport { etc, getPublicKey, getPublicKeyAsync, hash, hashes, keygen, keygenAsync, Point, sign, signAsync, utils, verify, verifyAsync, };\n","/**\n * @fileoverview Signed-manifest verification for the Velion CDN bundle.\n *\n * Threat model:\n * The loader is published on npm and embedded in customer pages. The full SDK\n * ships from a CDN at runtime. If the CDN is compromised (BGP hijack, bucket\n * takeover, supply-chain on the build pipeline), an attacker could swap the\n * iframe HTML / JS and exfiltrate KYC documents, selfies, and session tokens.\n *\n * Mitigation: every CDN release ships a `manifest.json` that names the\n * entry HTML with its SHA-384 (`entryIntegrity`) and lists every asset with\n * its SHA-384, plus a detached `manifest.sig` (Ed25519 signature over the\n * exact bytes of `manifest.json`). The loader carries the corresponding\n * Ed25519 *public* key and, before letting the iframe load:\n * 1. verifies the signature;\n * 2. refuses a manifest for another loader major or older than\n * `MIN_RUNTIME_VERSION` (anti-rollback: an old, validly signed release\n * cannot be replayed);\n * 3. downloads the entry HTML and the scripts it references and checks them\n * against `entryIntegrity` and the HTML's own SRI attributes.\n * A compromised CDN cannot forge a manifest without the private key, which\n * lives in Cloud KMS and is only usable by the release workflow through\n * Workload Identity Federation.\n *\n * Residual: the iframe navigates to the entry URL itself, so a CDN that serves\n * different bytes to the loader's verification fetch and to the iframe\n * navigation is not caught here. Loading the verified bytes through `srcdoc` or\n * a `blob:` URL would close that gap but would run the runtime with the HOST\n * page's origin (sandbox `allow-same-origin`) or an opaque one, breaking the\n * origin isolation, the API's CORS/Origin checks and camera permissions. See\n * docs/THREAT_MODEL.md (T1).\n *\n * Rotation:\n * The public key is embedded in the loader bundle published to npm. Rotation\n * means publishing a new loader version with the new public key. Old loaders\n * still verify against the previous key while customers upgrade.\n *\n * Browser support:\n * WebCrypto Ed25519 ships enabled by default only in Chrome/Edge 137+,\n * Firefox 130+ and Safari 17+. On older engines `importKey` rejects the\n * algorithm, so the loader falls back to `@noble/ed25519` (pure JS, SHA-512\n * via `crypto.subtle.digest`) with the same key, bytes and verdict. The\n * fallback swaps the verifier, never the policy: a signature that does not\n * verify is still fatal. Only when neither path can run (no `crypto.subtle`,\n * e.g. an insecure context) is the result `unsupported_browser`.\n */\n\nimport { verifyAsync as nobleVerifyAsync } from '@noble/ed25519';\n\n/**\n * Ed25519 public key used to verify `manifest.sig`, base64-encoded raw bytes.\n *\n * Empty string means \"verification disabled\" — accepted only as a transitional\n * mode while the signing pipeline is being deployed. Production loaders MUST\n * ship with this populated before being published to npm.\n *\n * Each environment signs with its own Cloud KMS key. `DEV_MANIFEST_PUBKEY_B64` is\n * the development key (`VELION_MANIFEST_PUBKEY_B64_DEV`), so a local build verifies\n * the dev CDN; CI always injects the environment's key at build time. Update it\n * when the development key is rotated, or local builds and the e2e suite fail\n * with `INTEGRITY_FAILED`.\n */\nconst DEV_MANIFEST_PUBKEY_B64 = 'oX1GwUEjM7Zj9ShtUekgNRXuAUhwgQP5Gf5yYn/xpx4=';\n\ndeclare const __VELION_MANIFEST_PUBKEY__: string | undefined;\n\nexport const VELION_MANIFEST_PUBKEY_B64: string =\n (typeof __VELION_MANIFEST_PUBKEY__ === 'string' && __VELION_MANIFEST_PUBKEY__) ||\n DEV_MANIFEST_PUBKEY_B64;\n\n/**\n * Oldest runtime (`manifest.appVersion`) this loader accepts from a signed manifest.\n *\n * Anti-rollback floor: a signed manifest stays valid forever, so without a floor an\n * attacker who controls the CDN could serve an old release with a known flaw. Raise\n * it whenever a runtime release fixes a security issue; every loader published\n * afterwards then refuses the vulnerable runtimes. `1.1.0-beta.7` is the first\n * runtime whose manifest carries `entryIntegrity` and whose entry pins its scripts\n * with SRI (OSDKW-32).\n */\nexport const MIN_RUNTIME_VERSION = '1.1.0-beta.7';\n\n/** Schema of the signed `manifest.json` emitted by the CDN build pipeline. */\nexport interface VelionCdnManifest {\n /** Loader-major path token, e.g. `\"v1\"`. Must match the loader's `LOADER_MAJOR_VERSION`. */\n version: string;\n /** ISO-8601 timestamp of the build. */\n buildTime: string;\n /** Path to the iframe entry HTML, relative to `cdnUrl`. */\n entry: string;\n /**\n * SHA-384 of the entry HTML (`sha384-<base64>`). Required in a signed manifest:\n * the loader checks the downloaded entry against it before mounting the iframe.\n */\n entryIntegrity?: string;\n /** Runtime version (the app's `package.json`). Required in a signed manifest (anti-rollback). */\n appVersion?: string;\n /** Every shipped asset with its SHA-384 digest. */\n assets?: Array<{ url: string; integrity: string }>;\n}\n\n/** Why a well-signed manifest is still refused, or why the entry did not verify. */\nexport type IntegrityFailure = {\n ok: false;\n reason: 'policy' | 'integrity' | 'unavailable';\n detail: string;\n};\n\n/**\n * Distinguishes \"manifest absent\" (legacy CDN) from \"manifest invalid\" (compromised),\n * and both from \"this browser cannot verify a signature at all\" (`unsupported_browser`).\n */\nexport type ManifestLoadResult =\n | { ok: true; manifest: VelionCdnManifest; signed: boolean }\n | {\n ok: false;\n reason: 'unavailable' | 'invalid_signature' | 'malformed' | 'unsupported_browser';\n detail?: string;\n };\n\nfunction base64ToArrayBuffer(b64: string): ArrayBuffer {\n const bin = atob(b64);\n const buf = new ArrayBuffer(bin.length);\n const view = new Uint8Array(buf);\n for (let i = 0; i < bin.length; i++) {\n view[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n/**\n * Whether a WebCrypto rejection means \"algorithm not implemented\" rather than a bad\n * key or signature. Chromium throws `NotSupportedError` (\"Algorithm: Unrecognized\n * name\"); Firefox and Safari throw `NotSupportedError` too.\n */\nfunction isAlgorithmUnsupported(err: unknown): boolean {\n if (err instanceof Error && err.name === 'NotSupportedError') return true;\n const message = err instanceof Error ? err.message : String(err);\n return /unrecognized|not supported|unsupported/i.test(message);\n}\n\n/** Outcome of the native attempt: a verdict, \"engine lacks Ed25519\", or a hard error. */\ntype WebCryptoOutcome =\n | { kind: 'verdict'; valid: boolean }\n | { kind: 'unsupported' }\n | { kind: 'error'; detail: string };\n\nasync function verifyWithWebCrypto(\n pubKey: ArrayBuffer,\n signature: ArrayBuffer,\n data: ArrayBuffer,\n): Promise<WebCryptoOutcome> {\n let key: CryptoKey;\n try {\n key = await crypto.subtle.importKey(\n 'raw',\n pubKey,\n { name: 'Ed25519' } as AlgorithmIdentifier,\n false,\n ['verify'],\n );\n } catch (err) {\n if (isAlgorithmUnsupported(err)) return { kind: 'unsupported' };\n return { kind: 'error', detail: `pubkey import failed: ${(err as Error).message}` };\n }\n try {\n const valid = await crypto.subtle.verify(\n { name: 'Ed25519' } as AlgorithmIdentifier,\n key,\n signature,\n data,\n );\n return { kind: 'verdict', valid };\n } catch (err) {\n if (isAlgorithmUnsupported(err)) return { kind: 'unsupported' };\n return { kind: 'error', detail: (err as Error).message };\n }\n}\n\n/**\n * Pure-JS Ed25519 verification for engines without WebCrypto Ed25519. Uses RFC 8032\n * strict semantics (`zip215: false`) to match what WebCrypto accepts.\n */\nasync function verifyWithNoble(\n pubKey: ArrayBuffer,\n signature: ArrayBuffer,\n data: ArrayBuffer,\n): Promise<boolean> {\n return nobleVerifyAsync(new Uint8Array(signature), new Uint8Array(data), new Uint8Array(pubKey), {\n zip215: false,\n });\n}\n\n/**\n * Verifies with native WebCrypto when available, otherwise with the JS fallback.\n * Either way a signature that does not verify returns `invalid_signature`.\n */\nasync function verifySignature(\n pubKeyB64: string,\n signature: ArrayBuffer,\n data: ArrayBuffer,\n): Promise<ManifestLoadResult | null> {\n if (typeof globalThis.crypto?.subtle?.digest !== 'function') {\n return {\n ok: false,\n reason: 'unsupported_browser',\n detail:\n 'crypto.subtle is unavailable (insecure context or very old browser); ' +\n 'the manifest signature cannot be verified.',\n };\n }\n const pubKey = base64ToArrayBuffer(pubKeyB64);\n\n const native = await verifyWithWebCrypto(pubKey, signature, data);\n if (native.kind === 'error') {\n return { ok: false, reason: 'invalid_signature', detail: native.detail };\n }\n let valid: boolean;\n if (native.kind === 'verdict') {\n valid = native.valid;\n } else {\n try {\n valid = await verifyWithNoble(pubKey, signature, data);\n } catch (err) {\n // noble throws on malformed input (wrong signature / key length), i.e. a bad signature.\n return { ok: false, reason: 'invalid_signature', detail: (err as Error).message };\n }\n }\n return valid ? null : { ok: false, reason: 'invalid_signature' };\n}\n\n/**\n * Fetches `${cdnUrl}/manifest.json` (and `manifest.sig` when verification is enabled).\n *\n * Returns:\n * - `{ ok:true, signed:true }` when the signature verifies against the embedded pubkey.\n * - `{ ok:true, signed:false }` when the manifest exists but verification is disabled\n * (transitional dev/staging mode where `VELION_MANIFEST_PUBKEY_B64` is empty).\n * - `{ ok:false, reason:'unavailable' }` when the CDN has no manifest yet — the\n * loader treats this as legacy mode and may proceed if explicitly allowed.\n * - `{ ok:false, reason:'invalid_signature' | 'malformed' }` when the manifest\n * is present but tampered or syntactically invalid. The loader MUST refuse\n * to mount the iframe in this case.\n * - `{ ok:false, reason:'unsupported_browser' }` when the browser cannot verify\n * any signature (no `crypto.subtle`). Also fatal, but not a tampering signal.\n */\nexport async function loadAndVerifyManifest(\n cdnUrl: string,\n pubKeyB64: string = VELION_MANIFEST_PUBKEY_B64,\n): Promise<ManifestLoadResult> {\n let manifestBuffer: ArrayBuffer;\n let manifestText: string;\n try {\n const resp = await fetch(`${cdnUrl}/manifest.json`, {\n credentials: 'omit',\n cache: 'no-cache',\n redirect: 'error',\n });\n if (resp.status === 404) {\n return { ok: false, reason: 'unavailable' };\n }\n if (!resp.ok) {\n return { ok: false, reason: 'unavailable', detail: `HTTP ${resp.status}` };\n }\n manifestBuffer = await resp.arrayBuffer();\n manifestText = new TextDecoder().decode(manifestBuffer);\n } catch (err) {\n return { ok: false, reason: 'unavailable', detail: (err as Error).message };\n }\n\n let manifest: VelionCdnManifest;\n try {\n manifest = JSON.parse(manifestText) as VelionCdnManifest;\n if (\n typeof manifest.version !== 'string' ||\n typeof manifest.entry !== 'string' ||\n typeof manifest.buildTime !== 'string'\n ) {\n return { ok: false, reason: 'malformed' };\n }\n } catch (err) {\n return { ok: false, reason: 'malformed', detail: (err as Error).message };\n }\n\n if (!pubKeyB64) {\n // Pubkey not yet provisioned on this loader release. Accept the manifest\n // unsigned but flag it so the caller can decide whether to proceed.\n return { ok: true, manifest, signed: false };\n }\n\n let sigBuffer: ArrayBuffer;\n try {\n const sigResp = await fetch(`${cdnUrl}/manifest.sig`, {\n credentials: 'omit',\n cache: 'no-cache',\n redirect: 'error',\n });\n if (!sigResp.ok) {\n return { ok: false, reason: 'invalid_signature', detail: `sig HTTP ${sigResp.status}` };\n }\n const sigText = (await sigResp.text()).trim();\n sigBuffer = base64ToArrayBuffer(sigText);\n } catch (err) {\n return { ok: false, reason: 'invalid_signature', detail: (err as Error).message };\n }\n\n const failure = await verifySignature(pubKeyB64, sigBuffer, manifestBuffer);\n if (failure) {\n return failure;\n }\n\n return { ok: true, manifest, signed: true };\n}\n\n/** Numeric-aware comparison of SemVer strings, including pre-release identifiers. */\nexport function compareVersions(a: string, b: string): number {\n const parse = (v: string): { core: number[]; pre: string[] } | null => {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/.exec(v.trim());\n if (!m) return null;\n return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split('.') : [] };\n };\n const pa = parse(a);\n const pb = parse(b);\n if (!pa || !pb) return Number.NaN;\n for (let i = 0; i < 3; i++) {\n const d = (pa.core[i] ?? 0) - (pb.core[i] ?? 0);\n if (d !== 0) return Math.sign(d);\n }\n // A release ranks above any of its pre-releases.\n if (pa.pre.length === 0 || pb.pre.length === 0) return Math.sign(pb.pre.length - pa.pre.length);\n for (let i = 0; i < Math.max(pa.pre.length, pb.pre.length); i++) {\n const x = pa.pre[i];\n const y = pb.pre[i];\n if (x === undefined) return -1;\n if (y === undefined) return 1;\n const xn = /^\\d+$/.test(x);\n const yn = /^\\d+$/.test(y);\n if (xn && yn) {\n const d = Number(x) - Number(y);\n if (d !== 0) return Math.sign(d);\n } else if (xn !== yn) {\n return xn ? -1 : 1;\n } else if (x !== y) {\n return x < y ? -1 : 1;\n }\n }\n return 0;\n}\n\n/**\n * Policy a SIGNED manifest must satisfy on top of a valid signature: built for this\n * loader's major, not older than `minRuntimeVersion`, and naming its entry's digest.\n * Returns `null` when the manifest is acceptable.\n */\nexport function checkSignedManifestPolicy(\n manifest: VelionCdnManifest,\n expectedMajor: string,\n minRuntimeVersion: string = MIN_RUNTIME_VERSION,\n): IntegrityFailure | null {\n if (manifest.version !== expectedMajor) {\n return {\n ok: false,\n reason: 'policy',\n detail: `manifest is for loader major \"${manifest.version}\", this loader is \"${expectedMajor}\"`,\n };\n }\n if (typeof manifest.appVersion !== 'string') {\n return { ok: false, reason: 'policy', detail: 'manifest has no appVersion' };\n }\n const cmp = compareVersions(manifest.appVersion, minRuntimeVersion);\n if (Number.isNaN(cmp)) {\n return { ok: false, reason: 'policy', detail: `unparseable appVersion \"${manifest.appVersion}\"` };\n }\n if (cmp < 0) {\n return {\n ok: false,\n reason: 'policy',\n detail: `runtime ${manifest.appVersion} is older than the minimum ${minRuntimeVersion} (rollback refused)`,\n };\n }\n if (typeof manifest.entryIntegrity !== 'string' || !manifest.entryIntegrity.startsWith('sha384-')) {\n return { ok: false, reason: 'policy', detail: 'manifest does not name the entry digest (entryIntegrity)' };\n }\n return null;\n}\n\nasync function sha384Base64(buf: ArrayBuffer): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-384', buf));\n let bin = '';\n for (let i = 0; i < digest.length; i++) bin += String.fromCharCode(digest[i] ?? 0);\n return `sha384-${btoa(bin)}`;\n}\n\n/** True when `actual` (`sha384-…`) is one of the SHA-384 values of an SRI attribute. */\nfunction matchesIntegrity(expected: string, actual: string): boolean {\n return expected\n .trim()\n .split(/\\s+/)\n .some((token) => token.split('?')[0] === actual);\n}\n\nasync function fetchBytes(url: string, noCache: boolean): Promise<ArrayBuffer | IntegrityFailure> {\n try {\n const resp = await fetch(url, {\n credentials: 'omit',\n redirect: 'error',\n ...(noCache && { cache: 'no-cache' as RequestCache }),\n });\n if (!resp.ok) return { ok: false, reason: 'unavailable', detail: `HTTP ${resp.status} for ${url}` };\n return await resp.arrayBuffer();\n } catch (err) {\n return { ok: false, reason: 'unavailable', detail: `${url}: ${(err as Error).message}` };\n }\n}\n\n/**\n * Downloads the iframe entry and every script / stylesheet / modulepreload it\n * references, and checks them before the iframe is pointed at the entry:\n *\n * - the entry HTML must hash to `manifest.entryIntegrity`;\n * - every referenced resource must be same-origin with the CDN and carry an SRI\n * `integrity` attribute (the build adds them), and its bytes must match it.\n *\n * The browser enforces the same SRI attributes again when the iframe loads, so this\n * is what turns a tampered script into an immediate `INTEGRITY_FAILED` instead of a\n * runtime that silently never boots.\n *\n * Returns `null` when everything matches, `reason: 'integrity'` on any mismatch and\n * `reason: 'unavailable'` when a file could not be downloaded.\n */\nexport async function verifyEntry(\n cdnUrl: string,\n manifest: VelionCdnManifest,\n): Promise<IntegrityFailure | null> {\n if (typeof manifest.entryIntegrity !== 'string') {\n return { ok: false, reason: 'integrity', detail: 'manifest does not name the entry digest' };\n }\n if (typeof globalThis.crypto?.subtle?.digest !== 'function') {\n return { ok: false, reason: 'unavailable', detail: 'crypto.subtle is unavailable' };\n }\n const entryPath = manifest.entry.startsWith('/') ? manifest.entry : `/${manifest.entry}`;\n const entryUrl = `${cdnUrl}${entryPath}`;\n const cdnOrigin = new URL(cdnUrl).origin;\n\n const html = await fetchBytes(entryUrl, true);\n if (!(html instanceof ArrayBuffer)) return html;\n const htmlDigest = await sha384Base64(html);\n if (!matchesIntegrity(manifest.entryIntegrity, htmlDigest)) {\n return {\n ok: false,\n reason: 'integrity',\n detail: `${entryPath} does not match the signed manifest (got ${htmlDigest})`,\n };\n }\n\n // Parsed only after its digest matched, so this is the signed document.\n const doc = new DOMParser().parseFromString(new TextDecoder().decode(html), 'text/html');\n const refs: Array<{ url: string; integrity: string | null }> = [];\n doc.querySelectorAll('script[src]').forEach((el) => {\n refs.push({ url: el.getAttribute('src') ?? '', integrity: el.getAttribute('integrity') });\n });\n doc.querySelectorAll('link[href]').forEach((el) => {\n const rel = (el.getAttribute('rel') ?? '').toLowerCase().split(/\\s+/);\n if (rel.includes('modulepreload') || rel.includes('stylesheet') || rel.includes('preload')) {\n refs.push({ url: el.getAttribute('href') ?? '', integrity: el.getAttribute('integrity') });\n }\n });\n\n for (const ref of refs) {\n let url: URL;\n try {\n url = new URL(ref.url, entryUrl);\n } catch {\n return { ok: false, reason: 'integrity', detail: `invalid resource URL \"${ref.url}\" in the entry` };\n }\n if (url.origin !== cdnOrigin) {\n return { ok: false, reason: 'integrity', detail: `entry loads ${url.href} from another origin` };\n }\n if (!ref.integrity) {\n return { ok: false, reason: 'integrity', detail: `entry loads ${url.pathname} without SRI` };\n }\n const bytes = await fetchBytes(url.href, false);\n if (!(bytes instanceof ArrayBuffer)) return bytes;\n const digest = await sha384Base64(bytes);\n if (!matchesIntegrity(ref.integrity, digest)) {\n return {\n ok: false,\n reason: 'integrity',\n detail: `${url.pathname} does not match its SRI digest (got ${digest})`,\n };\n }\n }\n return null;\n}\n","/**\n * Thin client (loader) for Velion Onboarding.\n * Creates an iframe pointing to the CDN app and bridges config/events via postMessage.\n * Follows the same pattern as Sumsub WebSDK: init → iframe loads → postMessage config → events.\n *\n * Before the iframe is pointed at the CDN the loader verifies the signed manifest, the\n * anti-rollback floor and the entry HTML + scripts (see `manifest.ts`). `VELION_INIT`,\n * which carries the session token, is posted exactly once, to the document that\n * loaded after that verification.\n */\n\nimport type {\n VelionConfig,\n OnboardingResult,\n SdkError,\n SdkStatus,\n OnboardingStep,\n} from './types';\nimport {\n SdkErrorCode,\n VELION_MSG_INIT,\n VELION_MSG_READY,\n VELION_MSG_SUCCESS,\n VELION_MSG_ERROR,\n VELION_MSG_STEP_CHANGE,\n VELION_MSG_STEP_COMPLETE,\n VELION_MSG_TOKEN_EXPIRED,\n VELION_MSG_EXIT,\n VELION_MSG_LIVENESS_VIDEO_UPLOADED,\n VELION_MSG_TOKEN,\n type VelionMessage,\n type OnboardingExit,\n type LivenessVideoRef,\n} from './types';\nimport {\n checkSignedManifestPolicy,\n loadAndVerifyManifest,\n verifyEntry,\n VELION_MANIFEST_PUBKEY_B64,\n type VelionCdnManifest,\n} from './manifest';\n\n/**\n * Product slug under the shared `static.velion.la/sdk/` namespace. This identity\n * SDK lives at `sdk/onboarding/`; future Velion SDKs (e.g. payments, auth) get\n * their own slug so they can be deployed independently from the same CDN.\n */\nexport const LOADER_PRODUCT = 'onboarding' as const;\n\n/**\n * Major version of this loader. Locked into the CDN path so a breaking change\n * to the loader↔app postMessage contract requires publishing loader-`v2`\n * against `/sdk/onboarding/v2/`. Customers can keep older loaders for as long\n * as the matching CDN path is served.\n */\nexport const LOADER_MAJOR_VERSION = 'v1' as const;\n\n/** Default CDN base URL for the onboarding app (no trailing slash). */\nexport const DEFAULT_CDN_URL =\n `https://static.velion.la/sdk/${LOADER_PRODUCT}/${LOADER_MAJOR_VERSION}`;\n\n/**\n * Used only while the host container has no laid-out height yet (e.g. `display: none`\n * or first paint). Replaced by a pixel height as soon as `container.clientHeight > 0`.\n */\nconst IFRAME_FALLBACK_HEIGHT_CSS = 'min(85vh, 880px)';\n\n/** Loader config: VelionConfig plus optional CDN URL and token refresh callback. */\nexport interface VelionLoaderConfig extends VelionConfig {\n /**\n * Base URL of the CDN where the onboarding app is served (e.g. https://static.velion.la/sdk).\n * The loader fetches `${cdnUrl}/manifest.json` (signed with Ed25519), verifies the\n * signature against the loader's embedded public key, and only then loads the\n * iframe entry named in the manifest.\n * @default 'https://static.velion.la/sdk'\n */\n cdnUrl?: string;\n\n /**\n * When `true`, lets the loader proceed against a CDN that does not yet expose a\n * signed `manifest.json` — for staging or migration windows. Has NO effect when\n * the loader carries an embedded pubkey AND the manifest exists but signature\n * verification fails (that case is always fatal).\n *\n * Default `false`: production loaders refuse to mount the iframe without a\n * verified manifest once the pubkey has been provisioned.\n *\n * @default false\n */\n allowUnverifiedCdn?: boolean;\n\n /**\n * Called when the iframe requests a new session token (e.g. after SESSION_EXPIRED).\n * Return the new token and optional expiresAt; the CDN app will continue the flow.\n */\n onTokenExpired?: () => Promise<{ sessionToken: string; expiresAt?: string }>;\n\n /**\n * How long to wait, after the iframe document loaded, for the runtime to\n * report `VELION_READY`. Past it the loader emits `RUNTIME_LOAD_FAILED`\n * instead of leaving the host with a blank iframe and no callback (e.g.\n * when the CDN entry points at assets that 404).\n *\n * @default 30000\n */\n runtimeReadyTimeoutMs?: number;\n}\n\nconst DEFAULT_RUNTIME_READY_TIMEOUT_MS = 30_000;\n\nfunction parseOriginFromUrl(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return '';\n }\n}\n\n/**\n * Allows `https:` and `wss:` everywhere, plus plain `http:`/`ws:` only when the host\n * is a loopback / `.local` address (developer machines and CI). Used to prevent\n * accidental cleartext bearer-token transmission to a misconfigured `apiUrl`/`cdnUrl`.\n */\nfunction isLocalhostHost(host: string): boolean {\n return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.endsWith('.local');\n}\n\nexport function isSecureHttpUrl(url: string): boolean {\n try {\n const u = new URL(url);\n if (u.protocol === 'https:') return true;\n if (u.protocol === 'http:') return isLocalhostHost(u.hostname);\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * True while the iframe still holds the `about:blank` document it was created with.\n * That document is same-origin with the host, so its location is readable; the CDN\n * runtime is cross-origin and reading its location throws.\n */\nfunction isInitialBlankDocument(iframe: HTMLIFrameElement): boolean {\n try {\n return iframe.contentWindow?.location.href === 'about:blank';\n } catch {\n return false;\n }\n}\n\n/** Keys of VelionConfig that are safe to send via postMessage (no functions). */\nconst SERIALIZABLE_CONFIG_KEYS: (keyof VelionConfig)[] = [\n 'containerId',\n 'sessionId',\n 'sessionToken',\n 'apiUrl',\n 'expiresAt',\n 'theme',\n 'colorMode',\n 'locale',\n 'allowEmbedded',\n 'livenessShowIntro',\n 'livenessShowBackButton',\n 'fingerprintEndpoint',\n 'debug',\n 'googleMapsApiKey',\n 'showFinalResultScreen',\n 'showProgressBar',\n 'finalResultScreenTexts',\n 'routingTimeoutMs',\n];\n\nfunction buildSerializableConfig(\n config: Readonly<VelionLoaderConfig>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {\n containerId: 'velion-sdk-root',\n allowEmbedded: true,\n };\n for (const key of SERIALIZABLE_CONFIG_KEYS) {\n if (key === 'containerId' || key === 'allowEmbedded') continue;\n const value = config[key as keyof typeof config];\n if (value !== undefined && typeof value !== 'function') {\n out[key] = value;\n }\n }\n return out;\n}\n\nexport class VelionOnboarding {\n private readonly config: Readonly<VelionLoaderConfig>;\n private status: SdkStatus = 'IDLE';\n private iframe: HTMLIFrameElement | null = null;\n private container: HTMLElement | null = null;\n private messageHandler: ((e: MessageEvent) => void) | null = null;\n private containerResizeObserver: ResizeObserver | null = null;\n private iframeHeightWindowResizeHandler: (() => void) | null = null;\n private cdnOrigin = '';\n /** Armed when VELION_INIT is sent; cleared by VELION_READY or destroy(). */\n private readyTimer: ReturnType<typeof setTimeout> | null = null;\n /** Set once VELION_INIT (and with it the session token) has been posted. */\n private initSent = false;\n /**\n * Set when the iframe loads a second document after INIT. From then on nothing\n * from the iframe is trusted: it is no longer the document the loader verified.\n */\n private iframeReloaded = false;\n\n private clearReadyTimer(): void {\n if (this.readyTimer !== null) {\n clearTimeout(this.readyTimer);\n this.readyTimer = null;\n }\n }\n\n private armReadyTimer(cdnUrl: string): void {\n this.clearReadyTimer();\n const ms = this.config.runtimeReadyTimeoutMs ?? DEFAULT_RUNTIME_READY_TIMEOUT_MS;\n if (!(ms > 0)) return;\n this.readyTimer = setTimeout(() => {\n this.readyTimer = null;\n if (this.status !== 'RUNNING') return; // already READY-progressed, errored or destroyed\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.RUNTIME_LOAD_FAILED,\n message:\n `The onboarding runtime at ${cdnUrl} did not become ready within ${ms} ms. ` +\n 'Check that the CDN serves the assets referenced by its index.html and that the host ' +\n \"page's Content-Security-Policy allows the runtime scripts.\",\n });\n }, ms);\n }\n\n constructor(config: VelionLoaderConfig) {\n this.config = Object.freeze({ ...config });\n }\n\n async start(): Promise<void> {\n if (this.status === 'DESTROYED') {\n this.config.onError?.({\n code: SdkErrorCode.INSTANCE_DESTROYED,\n message:\n 'This VelionOnboarding instance has been destroyed. Create a new instance to retry.',\n });\n return;\n }\n\n if (this.status !== 'IDLE') {\n this.config.onError?.({\n code: SdkErrorCode.ALREADY_STARTED,\n message:\n 'start() was called on an already-running SDK instance. Call destroy() before re-starting.',\n });\n return;\n }\n\n const container = document.getElementById(this.config.containerId);\n if (!container) {\n this.config.onError?.({\n code: SdkErrorCode.CONTAINER_NOT_FOUND,\n message: `No DOM element found with id=\"${this.config.containerId}\". Ensure the element exists before calling start().`,\n });\n return;\n }\n\n const cdnUrl = (this.config.cdnUrl ?? DEFAULT_CDN_URL).replace(/\\/$/, '');\n if (!isSecureHttpUrl(cdnUrl)) {\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Insecure cdnUrl: \"${cdnUrl}\". Must be https:// (http:// is allowed only for localhost).`,\n });\n return;\n }\n if (this.config.apiUrl && !isSecureHttpUrl(this.config.apiUrl)) {\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Insecure apiUrl: \"${this.config.apiUrl}\". Must be https:// (http:// is allowed only for localhost).`,\n });\n return;\n }\n this.cdnOrigin = parseOriginFromUrl(cdnUrl);\n if (!this.cdnOrigin) {\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Invalid cdnUrl: ${cdnUrl}. Must be a valid absolute URL.`,\n });\n return;\n }\n\n this.container = container;\n this.status = 'INITIALIZING';\n\n const iframe = document.createElement('iframe');\n iframe.setAttribute('title', 'Velion Onboarding');\n // The SDK only needs the camera. Microphone and geolocation are intentionally not granted.\n iframe.setAttribute('allow', 'camera');\n // Sandbox limits blast radius of a CDN compromise. Tokens we keep:\n // allow-scripts — the iframe is a JS app\n // allow-same-origin — needed for fetch to same-origin assets and for postMessage to behave\n // allow-forms — file pickers and form submissions for OCR upload flows\n // allow-popups — Google Maps / Places attribution links open in new tab\n // allow-modals — getUserMedia permission prompts and document picker\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-modals',\n );\n // Avoid leaking host page paths to the CDN logs.\n iframe.setAttribute('referrerpolicy', 'no-referrer');\n iframe.style.width = '100%';\n iframe.style.border = 'none';\n iframe.style.display = 'block';\n /* Height is applied in attachIframeHeightSync (pixel match + internal fallback). */\n\n const messageHandler = (e: MessageEvent): void => {\n // Origin AND source must match: a sibling iframe from the same CDN origin\n // (e.g. opened by the host page) must not be able to spoof events.\n if (e.origin !== this.cdnOrigin) return;\n if (e.source !== this.iframe?.contentWindow) return;\n if (this.iframeReloaded) return;\n const msg = e.data as VelionMessage | undefined;\n if (!msg || typeof msg.type !== 'string') return;\n\n // Any message that passed the origin+source check came from a running\n // runtime, so none of them may be followed by RUNTIME_LOAD_FAILED. READY is\n // the expected first message, but a runtime that reports a step or an\n // error first is alive just the same.\n this.clearReadyTimer();\n\n switch (msg.type) {\n case VELION_MSG_READY:\n this.status = 'RUNNING';\n break;\n case VELION_MSG_SUCCESS:\n this.status = 'COMPLETED';\n this.config.onSuccess?.(msg.payload as OnboardingResult);\n break;\n case VELION_MSG_ERROR:\n this.status = 'ERROR';\n this.config.onError?.(msg.payload as SdkError);\n break;\n case VELION_MSG_STEP_CHANGE: {\n const p = msg.payload as { step: OnboardingStep; stepIndex: number };\n this.config.onStepChange?.(p.step, p.stepIndex);\n break;\n }\n case VELION_MSG_STEP_COMPLETE: {\n const p = msg.payload as { step: OnboardingStep };\n this.config.onStepComplete?.(p.step);\n break;\n }\n case VELION_MSG_EXIT: {\n // User backed out of the first reversible step: the flow ended without\n // a verdict. Forward to the host so it can dismiss the SDK surface.\n this.status = 'EXITED';\n this.config.onExit?.(msg.payload as OnboardingExit);\n break;\n }\n case VELION_MSG_LIVENESS_VIDEO_UPLOADED: {\n // Evidence signal from the LIVENESS_MATCH step (OSDKW-11). Informational\n // only: the flow never depends on it, so no status change.\n this.config.onLivenessVideoUploaded?.(msg.payload as LivenessVideoRef);\n break;\n }\n case VELION_MSG_TOKEN_EXPIRED: {\n const refresh = this.config.onTokenExpired;\n if (refresh) {\n refresh().then(\n (t) => this.sendToIframe({ type: VELION_MSG_TOKEN, payload: t }),\n () => {\n this.config.onError?.({\n code: SdkErrorCode.SESSION_EXPIRED,\n message: 'Token refresh failed.',\n });\n }\n );\n } else {\n this.config.onError?.({\n code: SdkErrorCode.SESSION_EXPIRED,\n message: 'Session token expired. Provide onTokenExpired in config to refresh.',\n });\n }\n break;\n }\n default:\n break;\n }\n };\n\n window.addEventListener('message', messageHandler);\n this.messageHandler = messageHandler;\n this.iframe = iframe;\n\n container.replaceChildren(iframe);\n this.attachIframeHeightSync(container, iframe);\n\n // ── Verify the CDN manifest and the entry before mounting the iframe ───\n const resolved = await this.resolveManifest(cdnUrl);\n if (!resolved) {\n // resolveManifest already invoked onError. Stop here so we don't load\n // an unverified bundle.\n return;\n }\n const { manifest } = resolved;\n if (!(await this.verifyRuntime(cdnUrl, resolved))) return;\n if (this.status !== 'INITIALIZING') return; // destroyed while verifying\n const entryPath = manifest.entry.startsWith('/') ? manifest.entry : `/${manifest.entry}`;\n\n return new Promise<void>((resolve) => {\n iframe.onload = (): void => {\n if (isInitialBlankDocument(iframe)) {\n // The empty document a freshly inserted iframe starts with. Some engines\n // fire its `load` asynchronously, after `src` is already set; it is not\n // the runtime and must neither receive INIT nor count as a reload.\n return;\n }\n if (this.initSent) {\n // A second document loaded in the iframe (reload, or the runtime\n // navigated away). It was not verified, so it does not get the token.\n this.handleIframeReload();\n return;\n }\n if (!this.iframe?.contentWindow) {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: 'Iframe failed to load.',\n });\n resolve();\n return;\n }\n // postMessage cannot clone functions. Sumsub-style: send only JSON-serializable config.\n // Clone via JSON so no function can slip through (e.g. from cached bundle or nested props).\n const initPayload = buildSerializableConfig(this.config);\n let payloadForPostMessage: unknown;\n try {\n payloadForPostMessage = JSON.parse(JSON.stringify(initPayload));\n } catch {\n payloadForPostMessage = initPayload;\n }\n this.sendToIframe({ type: VELION_MSG_INIT, payload: payloadForPostMessage });\n this.initSent = true;\n this.status = 'RUNNING';\n // The document loaded, but a 200 index.html whose scripts 404 (or a CSP\n // that blocks them) never answers VELION_INIT. Bound the wait so the\n // host gets an error instead of a silent blank iframe.\n this.armReadyTimer(cdnUrl);\n resolve();\n };\n\n iframe.onerror = (): void => {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.UNKNOWN,\n message: `Failed to load onboarding app from ${cdnUrl}. Check cdnUrl and network.`,\n });\n resolve();\n };\n\n iframe.src = `${cdnUrl}${entryPath}`;\n });\n }\n\n /**\n * Reacts to a second `load` of the iframe after `VELION_INIT` was posted.\n *\n * The session is not restarted: that would mean posting the session token to a\n * document the loader never verified (the integrity check covers the bytes it\n * downloaded before the first navigation, not whatever a reload brings). Failing\n * costs little, because the backend owns the session state: a new instance\n * re-verifies the CDN and resumes from the current step.\n */\n private handleIframeReload(): void {\n this.iframeReloaded = true;\n this.clearReadyTimer();\n if (this.status !== 'RUNNING') return; // already finished, failed or destroyed\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.RUNTIME_LOAD_FAILED,\n message:\n 'The onboarding iframe reloaded after the session started. The loader does not resend ' +\n 'the session token to a document it did not verify; call destroy() and start a new ' +\n 'instance to resume from the current step.',\n });\n }\n\n /**\n * Applies the anti-rollback policy to a signed manifest and verifies the entry HTML\n * and its scripts. Emits onError and returns `false` when the runtime must not be\n * mounted.\n */\n private async verifyRuntime(\n cdnUrl: string,\n resolved: { manifest: VelionCdnManifest; signed: boolean; synthesized: boolean },\n ): Promise<boolean> {\n const { manifest, signed, synthesized } = resolved;\n if (synthesized) return true; // legacy CDN without manifest, explicitly tolerated\n if (signed) {\n const policy = checkSignedManifestPolicy(manifest, LOADER_MAJOR_VERSION);\n if (policy) {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `CDN manifest at \"${cdnUrl}/manifest.json\" is signed but not acceptable: ${policy.detail}. ` +\n 'Refusing to load the iframe.',\n });\n return false;\n }\n } else if (typeof manifest.entryIntegrity !== 'string') {\n return true; // unsigned transitional mode and nothing to check against\n }\n let failure;\n try {\n failure = await verifyEntry(cdnUrl, manifest);\n } catch (err) {\n failure = { ok: false as const, reason: 'integrity' as const, detail: (err as Error).message };\n }\n if (!failure) return true;\n this.status = 'ERROR';\n if (failure.reason === 'unavailable') {\n this.config.onError?.({\n code: SdkErrorCode.RUNTIME_LOAD_FAILED,\n message:\n `Could not download the onboarding runtime from ${cdnUrl} to verify it (${failure.detail}). ` +\n 'Check the CDN deploy and the network.',\n });\n } else {\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `The onboarding runtime at ${cdnUrl} failed its integrity check: ${failure.detail}. ` +\n 'Refusing to load the iframe to protect the user.',\n });\n }\n return false;\n }\n\n /**\n * Fetches and verifies the CDN manifest. Returns `null` and emits onError when\n * the manifest is missing in production mode, or when the signature is invalid.\n * `synthesized` marks the stand-in used for a legacy CDN without a manifest.\n */\n private async resolveManifest(\n cdnUrl: string,\n ): Promise<{ manifest: VelionCdnManifest; signed: boolean; synthesized: boolean } | null> {\n let result;\n try {\n result = await loadAndVerifyManifest(cdnUrl);\n } catch (err) {\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message: `Manifest verification crashed unexpectedly: ${(err as Error).message}`,\n });\n return null;\n }\n if (result.ok) {\n if (!result.signed && VELION_MANIFEST_PUBKEY_B64) {\n // Should not happen — pubkey is set, manifest exists, yet not signed.\n // loadAndVerifyManifest only marks `signed:false` when pubkey is empty.\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message: 'Internal: manifest reported as unsigned despite pubkey being set.',\n });\n return null;\n }\n return { manifest: result.manifest, signed: result.signed, synthesized: false };\n }\n if (result.reason === 'unavailable') {\n // Manifest endpoint is missing. Permitted only when the loader is configured\n // to tolerate it OR when the loader was published without a pubkey (transitional).\n const tolerateMissing =\n this.config.allowUnverifiedCdn === true || !VELION_MANIFEST_PUBKEY_B64;\n if (tolerateMissing) {\n return {\n manifest: {\n version: 'legacy',\n buildTime: new Date().toISOString(),\n entry: '/index.html',\n },\n signed: false,\n synthesized: true,\n };\n }\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `CDN at \"${cdnUrl}\" did not expose /manifest.json. The loader is configured ` +\n 'to require a signed manifest. If the CDN is migrating, set `allowUnverifiedCdn: true` ' +\n 'on the loader config — but only as a temporary measure.',\n });\n return null;\n }\n if (result.reason === 'unsupported_browser') {\n // Fatal too, but reported apart: nothing was tampered with, the browser just\n // cannot verify a signature. allowUnverifiedCdn does not bypass it.\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.UNSUPPORTED_BROWSER,\n message:\n 'This browser cannot verify the signature of the Velion CDN manifest, so the ' +\n 'onboarding cannot start. It needs a secure context (https) and WebCrypto ' +\n '(Chrome/Edge 67+, Firefox 68+, Safari 14+). ' +\n (result.detail ? `Detail: ${result.detail}` : ''),\n });\n return null;\n }\n // 'invalid_signature' or 'malformed' — always fatal, even when allowUnverifiedCdn is true.\n this.status = 'ERROR';\n this.config.onError?.({\n code: SdkErrorCode.INTEGRITY_FAILED,\n message:\n `CDN manifest at \"${cdnUrl}/manifest.json\" failed integrity check (${result.reason}). ` +\n 'Refusing to load the iframe to protect the user. ' +\n ('detail' in result && result.detail ? `Detail: ${result.detail}` : ''),\n });\n return null;\n }\n\n /**\n * Keep the iframe exactly as tall as the host container so integrators do not need\n * `height: 100%` on the iframe or flex hacks—only a definite block-size on the\n * container (e.g. `height: 700px` or `height: 100vh`), similar to Sumsub WebSDK.\n *\n * Until the container has a non-zero `clientHeight`, apply an internal fallback\n * height so the SDK is usable even before layout or if only `min-height` is set.\n */\n private attachIframeHeightSync(\n container: HTMLElement,\n iframe: HTMLIFrameElement,\n ): void {\n const sync = (): void => {\n if (this.iframe !== iframe || this.container !== container) return;\n const h = container.clientHeight;\n if (h > 0) {\n iframe.style.height = `${h}px`;\n iframe.style.minHeight = '';\n } else {\n iframe.style.height = IFRAME_FALLBACK_HEIGHT_CSS;\n iframe.style.minHeight = '';\n }\n };\n sync();\n requestAnimationFrame(sync);\n requestAnimationFrame(() => {\n requestAnimationFrame(sync);\n });\n if (typeof ResizeObserver !== 'undefined') {\n this.containerResizeObserver = new ResizeObserver(sync);\n this.containerResizeObserver.observe(container);\n } else {\n this.iframeHeightWindowResizeHandler = sync;\n window.addEventListener('resize', sync);\n }\n }\n\n private detachIframeHeightSync(): void {\n if (this.containerResizeObserver) {\n this.containerResizeObserver.disconnect();\n this.containerResizeObserver = null;\n }\n if (this.iframeHeightWindowResizeHandler) {\n window.removeEventListener('resize', this.iframeHeightWindowResizeHandler);\n this.iframeHeightWindowResizeHandler = null;\n }\n }\n\n private sendToIframe(msg: VelionMessage): void {\n if (this.iframe?.contentWindow) {\n this.iframe.contentWindow.postMessage(msg, this.cdnOrigin);\n }\n }\n\n getStatus(): SdkStatus {\n return this.status;\n }\n\n static getVersion(): string {\n return typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0';\n }\n\n destroy(): void {\n if (this.status === 'DESTROYED') return;\n this.clearReadyTimer();\n this.detachIframeHeightSync();\n if (this.messageHandler) {\n window.removeEventListener('message', this.messageHandler);\n this.messageHandler = null;\n }\n if (this.iframe && this.container) {\n this.iframe.remove();\n this.container.replaceChildren();\n }\n this.iframe = null;\n this.container = null;\n this.status = 'DESTROYED';\n }\n}\n","/**\n * @fileoverview Public API of the Velion Onboarding SDK (thin client / loader).\n *\n * This package is the loader only: it creates an iframe that loads the full\n * onboarding app from the CDN (e.g. https://static.velion.la/sdk) and bridges\n * config and events via postMessage. No React, OpenCV, or Fingerprint\n * are bundled here — minimal size, same API as before.\n */\n\nexport { VelionOnboarding, DEFAULT_CDN_URL, type VelionLoaderConfig } from './velion-loader';\n\n/**\n * No-op when using the loader: OpenCV is loaded inside the CDN app.\n * Kept for API compatibility; configure OpenCV in the CDN app build if needed.\n */\nexport function setOpenCVBaseUrl(_url: string): void {}\n\nexport {\n SdkErrorCode,\n CameraErrorCode,\n VELION_MSG_INIT,\n VELION_MSG_READY,\n VELION_MSG_SUCCESS,\n VELION_MSG_ERROR,\n VELION_MSG_STEP_CHANGE,\n VELION_MSG_STEP_COMPLETE,\n VELION_MSG_TOKEN_EXPIRED,\n VELION_MSG_EXIT,\n VELION_MSG_LIVENESS_VIDEO_UPLOADED,\n VELION_MSG_TOKEN,\n type VelionConfig,\n type VelionTheme,\n type VelionFinalResultStatusCopy,\n type VelionFinalResultScreenTexts,\n type VelionSessionDeclinedReasonMessages,\n type VelionSessionDeclinedReasonTexts,\n type VelionRetryStepTexts,\n type VelionCallbacks,\n type OnboardingExit,\n type OnboardingStep,\n type OnboardingStepStatus,\n type OnboardingType,\n type DocumentSide,\n type DocumentCaptureMode,\n type DocumentsConfig,\n type TaxInfoConfig,\n type TaxInfoOption,\n type DocumentsInitRequest,\n type DocumentsInitResponse,\n type SessionState,\n type OnboardingResult,\n type OnboardingStepDto,\n type StepFieldRule,\n type HumanBasicInfoStepConfig,\n type HumanExtendedInfoStepConfig,\n type TaxInfoStepConfig,\n type AddressInfoStepConfig,\n type SwornDeclarationStepConfig,\n type DocumentsOcrStepConfig,\n type TermsAndConditionsStepConfig,\n type StepConfigMap,\n type SdkError,\n type SdkStatus,\n type LivenessSessionResponse,\n type VideoUpload,\n type LivenessVerifyVideoMeta,\n type LivenessVideoRef,\n type SessionCreationResponse,\n type HumanBasicInfoPayload,\n type LegalBasicInfoPayload,\n type TermsAndConditionsItem,\n type TaxInfoPayload,\n type HumanExtendedInfoPayload,\n type LegalExtendedInfoPayload,\n type AddressInfoPayload,\n type SwornDeclarationPayload,\n type EconomicActivityItem,\n type EconomicActivityStepConfig,\n type EconomicActivitySelectionPayload,\n type EmailContactPayload,\n type PhoneContactPayload,\n type TermsAndConditionsSubmitPayload,\n type TermsAndConditionsAcceptancePayload,\n type OnboardingSessionEvent,\n type OnboardingDtoResponse,\n type VelionMessage,\n type VelionMessageType,\n type VelionInitPayload,\n type VelionStepChangePayload,\n type VelionStepCompletePayload,\n type VelionExitPayload,\n type VelionLivenessVideoUploadedPayload,\n type VelionTokenPayload,\n} from './types';\n"],"names":["CameraErrorCode","SdkErrorCode","VELION_MSG_INIT","VELION_MSG_READY","VELION_MSG_SUCCESS","VELION_MSG_ERROR","VELION_MSG_STEP_CHANGE","VELION_MSG_STEP_COMPLETE","VELION_MSG_TOKEN_EXPIRED","VELION_MSG_EXIT","VELION_MSG_LIVENESS_VIDEO_UPLOADED","VELION_MSG_TOKEN","freeze","Object","P","N","_d","Gx","Gy","_a","ed25519_CURVE","p","n","h","a","d","isBytes","Uint8Array","ArrayBuffer","isView","constructor","name","BYTES_PER_ELEMENT","abytes","value","length","title","bytes","message","TypeError","RangeError","padh","pad","toString","padStart","bytesToHex","hex","byte","hexToBytes","e","test","array","ai","hi","n1","charCodeAt","n2","concatBytes","arrays","sum","res","set","arange","min","max","msg","mod","b","P_MASK","modP","num","r","callHashAsync","async","m","fn","hashes","Error","_hash","apoint","Point","B256","_Point","X","Y","Z","T","__publicField","this","CURVE","fromAffine","x","y","fromBytes","zip215","normed","from","snapshotBytes","lastByte","bytesToNumberLE","y2","u","v","isValid","uvRatio","isLastByteOdd","fromHex","toAffine","assertValidity","is0","X2","Y2","Z2","Z4","aX2","equals","other","X1","Y1","Z1","I","negate","double","A","B","C","D","x1y1","E","G","F","H","X3","Y3","T3","Z3","add","T1","T2","subtract","multiply","safe","wNAF","f","i","multiplyUnsafe","scalar","iz","number","modulo","q","invert","toBytes","numTo32bLE","toHex","clearCofactor","isSmallOrder","isTorsionFree","BASE","ZERO","reverse","BigInt","pow2","power","RM1","v3","v7","pow","x2","b2","b4","b5","b10","b20","b40","b80","b160","b240","b250","pow_2_252_3","vx2","root1","root2","useRoot1","useRoot2","noRoot","modL_LE","hash","modN","_verify","sig","publicKey","options","getZip215","subarray","s","R","SB","hashable","of","finished","error","hashed","k","verifyAsync","signature","opts","hashFinishAsync","sha512Async","globalThis","crypto","subtle","digest","sha512","Gpows","ctneg","cnd","comp","points","w","push","precompute","wbits","Number","off","offP","Math","abs","isOddW","isNeg","VELION_MANIFEST_PUBKEY_B64","base64ToArrayBuffer","b64","bin","atob","buf","view","isAlgorithmUnsupported","err","String","verifySignature","pubKeyB64","data","ok","reason","detail","pubKey","native","key","importKey","kind","valid","verify","verifyWithWebCrypto","nobleVerifyAsync","verifyWithNoble","checkSignedManifestPolicy","manifest","expectedMajor","minRuntimeVersion","version","appVersion","cmp","parse","exec","trim","core","pre","split","pa","pb","NaN","sign","xn","yn","compareVersions","isNaN","entryIntegrity","startsWith","sha384Base64","fromCharCode","btoa","matchesIntegrity","expected","actual","some","token","fetchBytes","url","noCache","resp","fetch","credentials","redirect","cache","arrayBuffer","status","DEFAULT_CDN_URL","isSecureHttpUrl","URL","protocol","host","hostname","endsWith","SERIALIZABLE_CONFIG_KEYS","VelionOnboarding","config","iframe","container","messageHandler","containerResizeObserver","iframeHeightWindowResizeHandler","cdnOrigin","readyTimer","initSent","iframeReloaded","clearReadyTimer","clearTimeout","armReadyTimer","cdnUrl","ms","runtimeReadyTimeoutMs","setTimeout","onError","code","RUNTIME_LOAD_FAILED","start","INSTANCE_DESTROYED","ALREADY_STARTED","document","getElementById","containerId","CONTAINER_NOT_FOUND","replace","UNKNOWN","apiUrl","origin","parseOriginFromUrl","createElement","setAttribute","style","width","border","display","source","contentWindow","type","onSuccess","payload","onStepChange","step","stepIndex","onStepComplete","onExit","onLivenessVideoUploaded","refresh","onTokenExpired","then","t","sendToIframe","SESSION_EXPIRED","window","addEventListener","replaceChildren","attachIframeHeightSync","resolved","resolveManifest","verifyRuntime","entryPath","entry","Promise","resolve","onload","location","href","isInitialBlankDocument","handleIframeReload","initPayload","out","allowEmbedded","buildSerializableConfig","payloadForPostMessage","JSON","stringify","onerror","src","signed","synthesized","policy","INTEGRITY_FAILED","failure","entryUrl","html","htmlDigest","doc","DOMParser","parseFromString","TextDecoder","decode","refs","querySelectorAll","forEach","el","getAttribute","integrity","rel","toLowerCase","includes","ref","pathname","verifyEntry","result","manifestBuffer","manifestText","sigBuffer","buildTime","sigResp","text","loadAndVerifyManifest","allowUnverifiedCdn","Date","toISOString","UNSUPPORTED_BROWSER","sync","clientHeight","height","minHeight","requestAnimationFrame","ResizeObserver","observe","detachIframeHeightSync","disconnect","removeEventListener","postMessage","getStatus","getVersion","destroy","remove","setOpenCVBaseUrl","_url"],"mappings":"0JAoSYA,kBAAAA,IAEVA,EAAA,kBAAoB,2BAEpBA,EAAA,iBAAmB,0BAKnBA,EAAA,oBAAsB,6BAKtBA,EAAA,iBAAmB,0BAMnBA,EAAA,eAAiB,wBAEjBA,EAAA,cAAgB,uBAKhBA,EAAA,gBAAkB,yBAElBA,EAAA,iBAAmB,0BAEnBA,EAAA,QAAU,uBA/BAA,IAAAA,GAAA,CAAA,GAqCAC,kBAAAA,IAGVA,EAAA,gBAAkB,kBAElBA,EAAA,gBAAkB,kBAElBA,EAAA,qBAAuB,uBAEvBA,EAAA,iBAAmB,mBASnBA,EAAA,kBAAoB,oBAQpBA,EAAA,gBAAkB,kBAIlBA,EAAA,mBAAqB,qBAErBA,EAAA,uBAAyB,yBAEzBA,EAAA,gBAAkB,kBAElBA,EAAA,qBAAuB,uBAMvBA,EAAA,6BAA+B,+BAO/BA,EAAA,aAAe,eAIfA,EAAA,cAAgB,gBAEhBA,EAAA,UAAY,YAIZA,EA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